diff options
author | Rohan Rathi <rohanrathi08@gmail.com> | 2018-06-20 19:59:44 +0300 |
---|---|---|
committer | Rohan Rathi <rohanrathi08@gmail.com> | 2018-06-20 19:59:44 +0300 |
commit | c73a6b0d42f5ee16bb2af7d585035463854f4024 (patch) | |
tree | c366aeac74491653e0ba516b745116bfa6475f94 /source/blender | |
parent | dd752476b97aa3b35d1359422ca42e33d99ac851 (diff) | |
parent | 82dc5f91e86351e1a26769ec86d9054437eb77d6 (diff) |
Merge branch 'blender2.8' into soc-2018-bevel
Diffstat (limited to 'source/blender')
955 files changed, 16527 insertions, 15524 deletions
diff --git a/source/blender/alembic/intern/abc_exporter.cc b/source/blender/alembic/intern/abc_exporter.cc index c766720d6cd..45e2b68f94d 100644 --- a/source/blender/alembic/intern/abc_exporter.cc +++ b/source/blender/alembic/intern/abc_exporter.cc @@ -401,7 +401,7 @@ void AbcExporter::exploreTransform(Base *ob_base, Object *parent, Object *dupliO DupliObject *link = static_cast<DupliObject *>(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) { @@ -568,7 +568,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 e1507bedd01..fd6de1001ae 100644 --- a/source/blender/alembic/intern/abc_mesh.h +++ b/source/blender/alembic/intern/abc_mesh.h @@ -78,7 +78,7 @@ private: void writeArbGeoParams(struct Mesh *mesh); void getGeoGroups(struct Mesh *mesh, std::map<std::string, std::vector<int32_t> > &geoGroups); - + /* fluid surfaces support */ void getVelocities(struct Mesh *mesh, std::vector<Imath::V3f> &vels); diff --git a/source/blender/avi/AVI_avi.h b/source/blender/avi/AVI_avi.h index 5e9fe378c38..210195234be 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 5009bd2a30b..d019863faa5 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 6695998fd35..2d8a0b0038f 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_mjpeg.c b/source/blender/avi/intern/avi_mjpeg.c index 258426809fb..3146aebb0d0 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 47c18831cbd..f6da824a9f7 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; diff --git a/source/blender/avi/intern/avi_rgb.c b/source/blender/avi/intern/avi_rgb.c index f0baf7c6c14..6997a0d8be4 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 051fdba1cd2..f5f48b9eeb4 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/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index 79b0e5eb95f..02410f624da 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -264,12 +264,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); @@ -278,7 +278,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 diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h index 8ec75bda538..7567adc50dc 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); @@ -185,7 +185,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); @@ -195,7 +195,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); diff --git a/source/blender/blenkernel/BKE_addon.h b/source/blender/blenkernel/BKE_addon.h index e631d1d6537..3af6d3b61bf 100644 --- a/source/blender/blenkernel/BKE_addon.h +++ b/source/blender/blenkernel/BKE_addon.h @@ -51,7 +51,8 @@ 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); 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 326c25e8899..b16e8c17a12 100644 --- a/source/blender/blenkernel/BKE_animsys.h +++ b/source/blender/blenkernel/BKE_animsys.h @@ -76,21 +76,23 @@ struct AnimData *BKE_animdata_copy(struct Main *bmain, struct AnimData *adt, con bool BKE_animdata_copy_id(struct Main *bmain, struct ID *id_to, struct ID *id_from, const bool do_action, const bool do_id_user); /* Copy AnimData Actions */ -void BKE_animdata_copy_id_action(struct ID *id, const bool set_newid); +void BKE_animdata_copy_id_action(struct Main *bmain, struct ID *id, const bool set_newid); /* Merge copies of data from source AnimData block */ 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; -void BKE_animdata_merge_copy(struct ID *dst_id, struct ID *src_id, eAnimData_MergeCopy_Modes action_mode, bool fix_drivers); +void BKE_animdata_merge_copy( + struct Main *bmain, struct ID *dst_id, struct ID *src_id, + eAnimData_MergeCopy_Modes action_mode, bool fix_drivers); /* ************************************* */ /* KeyingSets API */ @@ -141,7 +143,8 @@ void BKE_animdata_fix_paths_remove(struct ID *id, const char *path); /* -------------------------------------- */ /* Move animation data from src to destination if it's paths are based on basepaths */ -void BKE_animdata_separate_by_basepath(struct ID *srcID, struct ID *dstID, struct ListBase *basepaths); +void BKE_animdata_separate_by_basepath( + struct Main *bmain, struct ID *srcID, struct ID *dstID, struct ListBase *basepaths); /* Move F-Curves from src to destination if it's path is based on basepath */ void action_move_fcurves_by_basepath(struct bAction *srcAct, struct bAction *dstAct, const char basepath[]); diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h index 57d70afcb8b..23014accc3f 100644 --- a/source/blender/blenkernel/BKE_armature.h +++ b/source/blender/blenkernel/BKE_armature.h @@ -55,10 +55,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 */ diff --git a/source/blender/blenkernel/BKE_blender_version.h b/source/blender/blenkernel/BKE_blender_version.h index a1212322983..def7dfd753b 100644 --- a/source/blender/blenkernel/BKE_blender_version.h +++ b/source/blender/blenkernel/BKE_blender_version.h @@ -28,10 +28,10 @@ * and keep comment above the defines. * Use STRINGIFY() rather than defining with quotes */ #define BLENDER_VERSION 280 -#define BLENDER_SUBVERSION 17 -/* Several breakages with 270, e.g. constraint deg vs rad */ -#define BLENDER_MINVERSION 270 -#define BLENDER_MINSUBVERSION 6 +#define BLENDER_SUBVERSION 19 +/* Several breakages with 280, e.g. collections vs layers */ +#define BLENDER_MINVERSION 280 +#define BLENDER_MINSUBVERSION 0 /* used by packaging tools */ /* can be left blank, otherwise a,b,c... etc with no quotes */ diff --git a/source/blender/blenkernel/BKE_cloth.h b/source/blender/blenkernel/BKE_cloth.h index d598923edbc..f0d8e1a1d84 100644 --- a/source/blender/blenkernel/BKE_cloth.h +++ b/source/blender/blenkernel/BKE_cloth.h @@ -68,7 +68,7 @@ typedef struct ClothHairData { typedef struct ClothSolverResult { int status; - + int max_iterations, min_iterations; float avg_iterations; float max_error, min_error, avg_error; @@ -139,7 +139,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]; } @@ -204,7 +204,7 @@ struct CollPair; typedef struct ColliderContacts { struct Object *ob; struct CollisionModifierData *collmd; - + struct CollPair *collisions; int totcollisions; } ColliderContacts; diff --git a/source/blender/blenkernel/BKE_collection.h b/source/blender/blenkernel/BKE_collection.h index fc5b19ccb4f..7dce3b2c703 100644 --- a/source/blender/blenkernel/BKE_collection.h +++ b/source/blender/blenkernel/BKE_collection.h @@ -90,14 +90,13 @@ void BKE_collections_child_remove_nulls(struct Main *bmain, struct Collection *o bool BKE_collection_is_in_scene(struct Collection *collection); void BKE_collections_after_lib_link(struct Main *bmain); bool BKE_collection_object_cyclic_check(struct Main *bmain, struct Object *object, struct Collection *collection); -bool BKE_collection_is_animated(struct Collection *collection, struct Object *parent); /* Object list cache. */ struct ListBase BKE_collection_object_cache_get(struct Collection *collection); void BKE_collection_object_cache_free(struct Collection *collection); -struct Base *BKE_collection_or_layer_objects(struct Depsgraph *depsgraph, +struct Base *BKE_collection_or_layer_objects(const struct Depsgraph *depsgraph, const struct Scene *scene, const struct ViewLayer *view_layer, struct Collection *collection); @@ -139,13 +138,21 @@ void BKE_scene_objects_callback(struct Scene *scene, BKE_scene_objects_Cb callba /* Iteratorion over objects in collection. */ -#define FOREACH_COLLECTION_BASE_RECURSIVE_BEGIN(_collection, _base) \ - for (Base *_base = (Base*)BKE_collection_object_cache_get(_collection).first; \ - _base; \ - _base = _base->next) \ - { - -#define FOREACH_COLLECTION_BASE_RECURSIVE_END \ +#define FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(_collection, _object, _mode) \ + { \ + int _base_flag = (_mode == DAG_EVAL_VIEWPORT) ? \ + BASE_VISIBLE_VIEWPORT : BASE_VISIBLE_RENDER; \ + int _base_id = 0; \ + for (Base *_base = (Base*)BKE_collection_object_cache_get(_collection).first; \ + _base; \ + _base = _base->next, _base_id++) \ + { \ + if (_base->flag & _base_flag) { \ + Object *_object = _base->object; \ + +#define FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END \ + } \ + } \ } #define FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(_collection, _object) \ diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h index 98ba0f6f2a4..2bc71c114b7 100644 --- a/source/blender/blenkernel/BKE_constraint.h +++ b/source/blender/blenkernel/BKE_constraint.h @@ -53,10 +53,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; @@ -85,7 +85,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); @@ -95,13 +95,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 Depsgraph *depsgraph, struct bConstraint *con, struct bConstraintOb *cob, struct bConstraintTarget *ct, float ctime); diff --git a/source/blender/blenkernel/BKE_context.h b/source/blender/blenkernel/BKE_context.h index e224863a27f..2ea940b8fee 100644 --- a/source/blender/blenkernel/BKE_context.h +++ b/source/blender/blenkernel/BKE_context.h @@ -330,6 +330,6 @@ struct Depsgraph *CTX_data_depsgraph_on_load(const bContext *C); #ifdef __cplusplus } #endif - + #endif diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h index 85c894864d5..dc9bbf9336e 100644 --- a/source/blender/blenkernel/BKE_customdata.h +++ b/source/blender/blenkernel/BKE_customdata.h @@ -227,8 +227,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 @@ -354,9 +354,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( diff --git a/source/blender/blenkernel/BKE_displist.h b/source/blender/blenkernel/BKE_displist.h index 6dd40b7a651..034f9b2b6a8 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 0a759629930..acb5e63d32f 100644 --- a/source/blender/blenkernel/BKE_dynamicpaint.h +++ b/source/blender/blenkernel/BKE_dynamicpaint.h @@ -55,7 +55,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 39986129c61..690a42894f2 100644 --- a/source/blender/blenkernel/BKE_editmesh.h +++ b/source/blender/blenkernel/BKE_editmesh.h @@ -57,7 +57,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 d45ecf9e3d8..379ab3e81b5 100644 --- a/source/blender/blenkernel/BKE_effect.h +++ b/source/blender/blenkernel/BKE_effect.h @@ -99,7 +99,7 @@ typedef struct EffectorCache { struct Object *ob; struct ParticleSystem *psys; struct SurfaceModifierData *surmd; - + struct PartDeflect *pd; /* precalculated for guides */ @@ -171,10 +171,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; diff --git a/source/blender/blenkernel/BKE_fcurve.h b/source/blender/blenkernel/BKE_fcurve.h index 09f5ecce050..c0bbf146afd 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 \ } @@ -108,7 +108,8 @@ bool driver_get_variable_property( struct ChannelDriver *driver, struct DriverTarget *dtar, struct PointerRNA *r_ptr, struct PropertyRNA **r_prop, int *r_index); -float evaluate_driver(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver, const float evaltime); +float evaluate_driver(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver, + struct ChannelDriver *driver_orig, const float evaltime); /* ************** F-Curve Modifiers *************** */ @@ -133,7 +134,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 +144,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 +230,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); @@ -282,7 +283,8 @@ void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2]); /* evaluate fcurve */ float evaluate_fcurve(struct FCurve *fcu, float evaltime); -float evaluate_fcurve_driver(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, float evaltime); +float evaluate_fcurve_driver(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, + struct ChannelDriver *driver_orig, float evaltime); /* evaluate fcurve and store value */ float calculate_fcurve(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, float evaltime); @@ -290,7 +292,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 +305,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_font.h b/source/blender/blenkernel/BKE_font.h index e5eea4423c9..d13cd4adff9 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); @@ -86,13 +86,13 @@ struct VFont *BKE_vfont_load_exists(struct Main *bmain, const char *filepath); void BKE_vfont_make_local(struct Main *bmain, struct VFont *vfont, const bool lib_local); -bool BKE_vfont_to_curve_ex(struct Main *bmain, struct Object *ob, struct Curve *cu, int mode, +bool BKE_vfont_to_curve_ex(struct Object *ob, struct Curve *cu, int mode, struct ListBase *r_nubase, const wchar_t **r_text, int *r_text_len, bool *r_text_free, struct CharTrans **r_chartransdata); -bool BKE_vfont_to_curve_nubase(struct Main *bmain, struct Object *ob, int mode, +bool BKE_vfont_to_curve_nubase(struct Object *ob, int mode, struct ListBase *r_nubase); -bool BKE_vfont_to_curve(struct Main *bmain, struct Object *ob, int mode); +bool BKE_vfont_to_curve(struct Object *ob, int mode); int BKE_vfont_select_get(struct Object *ob, int *r_start, int *r_end); void BKE_vfont_select_clamp(struct Object *ob); diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h index c5ad91c81fd..82afbdefeab 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 */ @@ -218,5 +218,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 b6de922c245..3a951b7860d 100644 --- a/source/blender/blenkernel/BKE_gpencil.h +++ b/source/blender/blenkernel/BKE_gpencil.h @@ -56,7 +56,7 @@ void BKE_gpencil_stroke_sync_selection(struct bGPDstroke *gps); struct bGPDframe *BKE_gpencil_frame_addnew(struct bGPDlayer *gpl, int cframe); struct bGPDframe *BKE_gpencil_frame_addcopy(struct bGPDlayer *gpl, int cframe); struct bGPDlayer *BKE_gpencil_layer_addnew(struct bGPdata *gpd, const char *name, bool setactive); -struct bGPdata *BKE_gpencil_data_addnew(const char name[]); +struct bGPdata *BKE_gpencil_data_addnew(struct Main *bmain, const char name[]); struct bGPDframe *BKE_gpencil_frame_duplicate(const struct bGPDframe *gpf_src); struct bGPDlayer *BKE_gpencil_layer_duplicate(const struct bGPDlayer *gpl_src); @@ -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 94630eaa7b0..6df31db7b83 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 fc018dbfe81..badcd5012de 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 */ @@ -271,7 +271,7 @@ bool BKE_image_scale(struct Image *image, int width, int height); bool BKE_image_has_alpha(struct Image *image); /* check if texture has gpu texture code */ -bool BKE_image_has_bindcode(struct Image *ima); +bool BKE_image_has_opengl_texture(struct Image *ima); void BKE_image_get_size(struct Image *image, struct ImageUser *iuser, int *width, int *height); void BKE_image_get_size_fl(struct Image *image, struct ImageUser *iuser, float size[2]); @@ -296,6 +296,12 @@ void BKE_image_file_format_set(struct Image *image, int ftype, const struct ImbF bool BKE_image_has_loaded_ibuf(struct Image *image); struct ImBuf *BKE_image_get_ibuf_with_name(struct Image *image, const char *name); struct ImBuf *BKE_image_get_first_ibuf(struct Image *image); + +struct RenderSlot *BKE_image_add_renderslot(struct Image *ima, const char *name); +bool BKE_image_remove_renderslot(struct Image *ima, struct ImageUser *iuser, int slot); +struct RenderSlot *BKE_image_get_renderslot(struct Image *ima, int slot); +bool BKE_image_clear_renderslot(struct Image *ima, struct ImageUser *iuser, int slot); + #ifdef __cplusplus } #endif diff --git a/source/blender/blenkernel/BKE_key.h b/source/blender/blenkernel/BKE_key.h index 5eef44ef896..2f953e57d71 100644 --- a/source/blender/blenkernel/BKE_key.h +++ b/source/blender/blenkernel/BKE_key.h @@ -50,7 +50,7 @@ extern "C" { void BKE_key_free(struct Key *sc); void BKE_key_free_nolib(struct Key *key); -struct Key *BKE_key_add(struct ID *id); +struct Key *BKE_key_add(struct Main *bmain, struct ID *id); void BKE_key_copy_data(struct Main *bmain, struct Key *key_dst, const struct Key *key_src, const int flag); struct Key *BKE_key_copy(struct Main *bmain, const struct Key *key); struct Key *BKE_key_copy_nolib(struct Key *key); diff --git a/source/blender/blenkernel/BKE_lattice.h b/source/blender/blenkernel/BKE_lattice.h index b722b7da6a0..c2ac5e98f76 100644 --- a/source/blender/blenkernel/BKE_lattice.h +++ b/source/blender/blenkernel/BKE_lattice.h @@ -41,7 +41,6 @@ struct Main; struct Mesh; struct Object; struct Scene; -struct DerivedMesh; struct BPoint; struct MDeformVert; struct Depsgraph; diff --git a/source/blender/blenkernel/BKE_layer.h b/source/blender/blenkernel/BKE_layer.h index 60204d177f2..9e89033894d 100644 --- a/source/blender/blenkernel/BKE_layer.h +++ b/source/blender/blenkernel/BKE_layer.h @@ -104,8 +104,15 @@ bool BKE_view_layer_has_collection( bool BKE_scene_has_object( struct Scene *scene, struct Object *ob); +/* selection and hiding */ + bool BKE_layer_collection_objects_select( struct ViewLayer *view_layer, struct LayerCollection *lc, bool deselect); +bool BKE_layer_collection_has_selected_objects( + struct ViewLayer *view_layer, struct LayerCollection *lc); + +void BKE_base_set_visible(struct Scene *scene, struct ViewLayer *view_layer, struct Base *base, bool extend); +void BKE_layer_collection_set_visible(struct Scene *scene, struct ViewLayer *view_layer, struct LayerCollection *lc, bool extend); /* override */ diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h index 3d70ef75a7c..1fd6fe1adae 100644 --- a/source/blender/blenkernel/BKE_mesh.h +++ b/source/blender/blenkernel/BKE_mesh.h @@ -64,7 +64,6 @@ struct MDeformVert; struct MDisps; struct Object; struct CustomData; -struct DerivedMesh; struct Scene; struct MLoopUV; struct ReportList; diff --git a/source/blender/blenkernel/BKE_mesh_iterators.h b/source/blender/blenkernel/BKE_mesh_iterators.h new file mode 100644 index 00000000000..cbf156b8052 --- /dev/null +++ b/source/blender/blenkernel/BKE_mesh_iterators.h @@ -0,0 +1,65 @@ +/* + * ***** 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: all of this file. + * + * Contributor(s): Blender Foundation + * + * ***** END GPL LICENSE BLOCK ***** + */ +#ifndef __BKE_MESH_ITERATORS_H__ +#define __BKE_MESH_ITERATORS_H__ + +/** \file BKE_MESH_ITERATORS.h + * \ingroup bke + */ + +struct Mesh; +struct MVert; +struct MEdge; +struct MPoly; +struct MLoop; +struct MLoopUV; +struct MLoopTri; + +typedef enum MeshForeachFlag { + MESH_FOREACH_NOP = 0, + MESH_FOREACH_USE_NORMAL = (1 << 0), /* foreachMappedVert, foreachMappedLoop, foreachMappedFaceCenter */ +} MeshForeachFlag; + + +void BKE_mesh_foreach_mapped_vert( + struct Mesh *mesh, + void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]), + void *userData, + MeshForeachFlag flag); +void BKE_mesh_foreach_mapped_edge( + struct Mesh *mesh, + void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]), + void *userData); +void BKE_mesh_foreach_mapped_loop( + struct Mesh *mesh, + void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]), + void *userData, + MeshForeachFlag flag); +void BKE_mesh_foreach_mapped_face_center( + struct Mesh *mesh, + void (*func)(void *userData, int index, const float cent[3], const float no[3]), + void *userData, + MeshForeachFlag flag); + +#endif /* __BKE_MESH_ITERATORS_H__ */ diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h index b40d32203f6..8a9e2f44604 100644 --- a/source/blender/blenkernel/BKE_modifier.h +++ b/source/blender/blenkernel/BKE_modifier.h @@ -202,7 +202,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 modifier may reuse the derivedData argument (i.e. return it in * modified form), but must not release it. @@ -212,7 +212,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. @@ -253,7 +253,7 @@ typedef struct ModifierTypeInfo { * * The mesh argument should always be non-NULL; the modifier * should read the object data from the mesh object instead of the - * actual object data. + * actual object data. * * The modifier may reuse the mesh argument (i.e. return it in * modified form), but must not release it. @@ -263,7 +263,7 @@ typedef struct ModifierTypeInfo { /* Like applyModifier but called during editmode (for supporting * modifiers). - * + * * The mesh object that is returned must support the operations that * are expected from editmode objects. The same qualifications regarding * mesh apply as for applyModifier. @@ -277,7 +277,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); @@ -323,7 +323,7 @@ typedef struct ModifierTypeInfo { */ void (*updateDepsgraph)(struct ModifierData *md, const ModifierUpdateDepsgraphContext *ctx); - + /* Should return true if the modifier needs to be recalculated on time * changes. * @@ -335,7 +335,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. * */ diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h index 851f2360f51..cecea927e8a 100644 --- a/source/blender/blenkernel/BKE_multires.h +++ b/source/blender/blenkernel/BKE_multires.h @@ -97,14 +97,6 @@ int multiresModifier_reshapeFromDeformMod(struct Depsgraph *depsgraph, struct Sc void multires_stitch_grids(struct Object *); -/*switch mdisp data in dm between tangent and object space*/ -enum { - MULTIRES_SPACE_TANGENT, - MULTIRES_SPACE_OBJECT, - MULTIRES_SPACE_ABSOLUTE -}; -void multires_set_space(struct DerivedMesh *dm, struct Object *ob, int from, int to); - /* Related to the old multires */ void multires_free(struct Multires *mr); void multires_load_old(struct Object *ob, struct Mesh *me); diff --git a/source/blender/blenkernel/BKE_nla.h b/source/blender/blenkernel/BKE_nla.h index 4509d374b02..6f0b6d59984 100644 --- a/source/blender/blenkernel/BKE_nla.h +++ b/source/blender/blenkernel/BKE_nla.h @@ -34,6 +34,7 @@ */ struct AnimData; +struct Main; struct NlaStrip; struct NlaTrack; struct bAction; @@ -50,9 +51,9 @@ void BKE_nlastrip_free(ListBase *strips, struct NlaStrip *strip); void BKE_nlatrack_free(ListBase *tracks, struct NlaTrack *nlt); void BKE_nla_tracks_free(ListBase *tracks); -struct NlaStrip *BKE_nlastrip_copy(struct NlaStrip *strip, const bool use_same_action); -struct NlaTrack *BKE_nlatrack_copy(struct NlaTrack *nlt, const bool use_same_actions); -void BKE_nla_tracks_copy(ListBase *dst, ListBase *src); +struct NlaStrip *BKE_nlastrip_copy(struct Main *bmain, struct NlaStrip *strip, const bool use_same_action); +struct NlaTrack *BKE_nlatrack_copy(struct Main *bmain, struct NlaTrack *nlt, const bool use_same_actions); +void BKE_nla_tracks_copy(struct Main *bmain, ListBase *dst, ListBase *src); struct NlaTrack *BKE_nlatrack_add(struct AnimData *adt, struct NlaTrack *prev); struct NlaStrip *BKE_nlastrip_new(struct bAction *act); diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h index d271252ceef..63398ec9f5e 100644 --- a/source/blender/blenkernel/BKE_node.h +++ b/source/blender/blenkernel/BKE_node.h @@ -100,7 +100,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 */ @@ -111,21 +111,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; @@ -142,23 +142,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); @@ -184,41 +184,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); /* can this node be added to a node tree */ int (*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; @@ -279,7 +279,7 @@ 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); @@ -297,11 +297,11 @@ typedef struct bNodeTreeType { /* Tree update. Overrides nodetype->updatetreefunc! */ void (*update)(struct bNodeTree *ntree); - + int (*validate_link)(struct bNodeTree *ntree, struct bNodeLink *link); void (*node_add_init)(struct bNodeTree *ntree, struct bNode *bnode); - + /* RNA integration */ ExtensionRNA ext; } bNodeTreeType; diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h index 482d39b5e68..ab8327d354a 100644 --- a/source/blender/blenkernel/BKE_object.h +++ b/source/blender/blenkernel/BKE_object.h @@ -279,7 +279,7 @@ struct Mesh *BKE_object_get_original_mesh(struct Object *object); int BKE_object_insert_ptcache(struct Object *ob); void BKE_object_delete_ptcache(struct Object *ob, int index); -struct KeyBlock *BKE_object_shapekey_insert(struct Object *ob, const char *name, const bool from_mix); +struct KeyBlock *BKE_object_shapekey_insert(struct Main *bmain, struct Object *ob, const char *name, const bool from_mix); bool BKE_object_shapekey_remove(struct Main *bmain, struct Object *ob, struct KeyBlock *kb); bool BKE_object_shapekey_free(struct Main *bmain, struct Object *ob); diff --git a/source/blender/blenkernel/BKE_ocean.h b/source/blender/blenkernel/BKE_ocean.h index 7a4c7d67040..3ea104e656a 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_paint.h b/source/blender/blenkernel/BKE_paint.h index 2ba6446c18f..6ade14b275c 100644 --- a/source/blender/blenkernel/BKE_paint.h +++ b/source/blender/blenkernel/BKE_paint.h @@ -184,7 +184,7 @@ typedef struct SculptSession { int totvert, totpoly; struct KeyBlock *kb; float *vmask; - + /* Mesh connectivity */ struct MeshElemMap *pmap; int *pmap_mem; @@ -210,7 +210,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 d87d63454f0..11aa67d7f25 100644 --- a/source/blender/blenkernel/BKE_particle.h +++ b/source/blender/blenkernel/BKE_particle.h @@ -61,7 +61,7 @@ struct LinkNode; struct KDTree; struct RNG; struct BVHTreeRay; -struct BVHTreeRayHit; +struct BVHTreeRayHit; struct EdgeHash; struct Depsgraph; struct ViewLayer; @@ -90,6 +90,8 @@ typedef struct ParticleSimulationData { * maximum value per time step is important. Only sph_integrate makes use of * this at the moment. Other solvers could, too. */ float courant_num; + /* Only valid during dynamics_step(). */ + struct RNG *rng; } ParticleSimulationData; typedef struct SPHData { @@ -196,7 +198,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]; @@ -316,6 +318,9 @@ void BKE_particlesettings_free(struct ParticleSettings *part); void psys_free_path_cache(struct ParticleSystem *psys, struct PTCacheEdit *edit); void psys_free(struct Object *ob, struct ParticleSystem *psys); +/* Copy. */ +void psys_copy_particles(struct ParticleSystem *psys_dst, struct ParticleSystem *psys_src); + bool psys_render_simplify_params(struct ParticleSystem *psys, struct ChildParticle *cpa, float *params); void psys_interpolate_uvs(const struct MTFace *tface, int quad, const float w[4], float uvco[2]); @@ -329,9 +334,10 @@ void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr float utan[3], float vtan[3], float orco[3]); struct ParticleSystemModifierData *psys_get_modifier(struct Object *ob, struct ParticleSystem *psys); -struct ModifierData *object_add_particle_system(struct Scene *scene, struct Object *ob, const char *name); -void object_remove_particle_system(struct Scene *scene, struct Object *ob); -struct ParticleSettings *BKE_particlesettings_add(struct Main *main, const char *name); +struct ModifierData *object_add_particle_system( + struct Main *bmain, struct Scene *scene, struct Object *ob, const char *name); +void object_remove_particle_system(struct Main *bmain, struct Scene *scene, struct Object *ob); +struct ParticleSettings *BKE_particlesettings_add(struct Main *bmain, const char *name); void BKE_particlesettings_copy_data( struct Main *bmain, struct ParticleSettings *part_dst, const struct ParticleSettings *part_src, const int flag); diff --git a/source/blender/blenkernel/BKE_pointcache.h b/source/blender/blenkernel/BKE_pointcache.h index 89f1aa5eadd..21673213db1 100644 --- a/source/blender/blenkernel/BKE_pointcache.h +++ b/source/blender/blenkernel/BKE_pointcache.h @@ -185,7 +185,7 @@ typedef struct PTCacheID { } PTCacheID; typedef struct PTCacheBaker { - struct Main *main; + struct Main *bmain; struct Scene *scene; struct ViewLayer *view_layer; struct Depsgraph *depsgraph; @@ -246,13 +246,25 @@ typedef struct PTCacheUndo { size_t undo_size; } PTCacheUndo; +enum { + /* Modifier stack got evaluated during particle edit mode, need to copy + * new evaluated particles to the edit struct. + */ + PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL = (1 << 0), +}; + typedef struct PTCacheEdit { + int flags; + PTCacheEditPoint *points; struct PTCacheID pid; /* particles stuff */ struct ParticleSystem *psys; + struct ParticleSystem *psys_eval; + struct ParticleSystemModifierData *psmd; + struct ParticleSystemModifierData *psmd_eval; struct KDTree *emitter_field; float *emitter_cosnos; /* localspace face centers and normals (average of its verts), from the derived mesh */ int *mirror_cache; @@ -278,7 +290,8 @@ void BKE_ptcache_id_from_dynamicpaint(PTCacheID *pid, struct Object *ob, struct void BKE_ptcache_id_from_rigidbody(PTCacheID *pid, struct Object *ob, struct RigidBodyWorld *rbw); PTCacheID BKE_ptcache_id_find(struct Object *ob, struct Scene *scene, struct PointCache *cache); -void BKE_ptcache_ids_from_object(struct ListBase *lb, struct Object *ob, struct Scene *scene, int duplis); +void BKE_ptcache_ids_from_object( + struct ListBase *lb, struct Object *ob, struct Scene *scene, int duplis); /***************** Global funcs ****************************/ void BKE_ptcache_remove(void); diff --git a/source/blender/blenkernel/BKE_report.h b/source/blender/blenkernel/BKE_report.h index 70feff17151..2a79c7f5d58 100644 --- a/source/blender/blenkernel/BKE_report.h +++ b/source/blender/blenkernel/BKE_report.h @@ -74,6 +74,6 @@ bool BKE_report_write_file(const char *filepath, ReportList *reports, const char #ifdef __cplusplus } #endif - + #endif diff --git a/source/blender/blenkernel/BKE_rigidbody.h b/source/blender/blenkernel/BKE_rigidbody.h index 016a531db95..b7d27cc7101 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__ @@ -80,7 +80,7 @@ void BKE_rigidbody_calc_center_of_mass(struct Object *ob, float r_center[3]); /* Utilities */ struct RigidBodyWorld *BKE_rigidbody_get_world(struct Scene *scene); -void BKE_rigidbody_remove_object(struct Scene *scene, struct Object *ob); +void BKE_rigidbody_remove_object(struct Main *bmain, struct Scene *scene, struct Object *ob); void BKE_rigidbody_remove_constraint(struct Scene *scene, struct Object *ob); /* -------------- */ diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h index 0606108a23b..270ab60c02b 100644 --- a/source/blender/blenkernel/BKE_scene.h +++ b/source/blender/blenkernel/BKE_scene.h @@ -83,7 +83,7 @@ void BKE_scene_free(struct Scene *sce); void BKE_scene_init(struct Scene *sce); struct Scene *BKE_scene_add(struct Main *bmain, const char *name); -void BKE_scene_remove_rigidbody_object(struct Scene *scene, struct Object *ob); +void BKE_scene_remove_rigidbody_object(struct Main *bmain, struct Scene *scene, struct Object *ob); bool BKE_scene_object_find(struct Scene *scene, struct Object *ob); struct Object *BKE_scene_object_find_by_name(struct Scene *scene, const char *name); diff --git a/source/blender/blenkernel/BKE_screen.h b/source/blender/blenkernel/BKE_screen.h index 0b95152ad8e..1b42ce97940 100644 --- a/source/blender/blenkernel/BKE_screen.h +++ b/source/blender/blenkernel/BKE_screen.h @@ -216,6 +216,8 @@ typedef struct PanelType { int (*poll)(const struct bContext *C, struct PanelType *pt); /* draw header (optional) */ void (*draw_header)(const struct bContext *C, struct Panel *pa); + /* draw header preset (optional) */ + void (*draw_header_preset)(const struct bContext *C, struct Panel *pa); /* draw entirely, view changes should be handled here */ void (*draw)(const struct bContext *C, struct Panel *pa); @@ -305,6 +307,7 @@ typedef struct Menu { /* spacetypes */ struct SpaceType *BKE_spacetype_from_id(int spaceid); +struct ARegionType *BKE_regiontype_from_id_or_first(struct SpaceType *st, int regionid); struct ARegionType *BKE_regiontype_from_id(struct SpaceType *st, int regionid); const struct ListBase *BKE_spacetypes_list(void); void BKE_spacetype_register(struct SpaceType *st); diff --git a/source/blender/blenkernel/BKE_sequencer.h b/source/blender/blenkernel/BKE_sequencer.h index 63c91ef9635..51f61c8352c 100644 --- a/source/blender/blenkernel/BKE_sequencer.h +++ b/source/blender/blenkernel/BKE_sequencer.h @@ -138,38 +138,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); @@ -276,7 +276,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. */ @@ -495,6 +495,6 @@ struct ImBuf *BKE_sequencer_render_mask_input( int cfra, int fra_offset, bool make_float); void BKE_sequencer_color_balance_apply(struct StripColorBalance *cb, struct ImBuf *ibuf, float mul, bool make_float, struct ImBuf *mask_input); -void BKE_sequencer_all_free_anim_ibufs(int cfra); +void BKE_sequencer_all_free_anim_ibufs(struct Main *bmain, int cfra); #endif /* __BKE_SEQUENCER_H__ */ diff --git a/source/blender/blenkernel/BKE_shrinkwrap.h b/source/blender/blenkernel/BKE_shrinkwrap.h index 8a809b606f1..c92b0fd1272 100644 --- a/source/blender/blenkernel/BKE_shrinkwrap.h +++ b/source/blender/blenkernel/BKE_shrinkwrap.h @@ -47,7 +47,6 @@ */ struct Object; -struct DerivedMesh; struct Mesh; struct MVert; struct MDeformVert; diff --git a/source/blender/blenkernel/BKE_studiolight.h b/source/blender/blenkernel/BKE_studiolight.h index 5e386fde528..af7ef9a383e 100644 --- a/source/blender/blenkernel/BKE_studiolight.h +++ b/source/blender/blenkernel/BKE_studiolight.h @@ -34,6 +34,8 @@ * Studio lighting for the 3dview */ +#include "BKE_context.h" + #include "BLI_sys_types.h" #include "DNA_space_types.h" @@ -51,13 +53,36 @@ #define STUDIOLIGHT_Y_NEG 3 #define STUDIOLIGHT_Z_POS 4 #define STUDIOLIGHT_Z_NEG 5 -#define STUDIOLIGHT_ICON_ID_TYPE_RADIANCE 0 -#define STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE 1 + +#define STUDIOLIGHT_ICON_ID_TYPE_RADIANCE (1 << 0) +#define STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE (1 << 1) +#define STUDIOLIGHT_ICON_ID_TYPE_MATCAP (1 << 2) +#define STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED (1 << 3) + +#define STUDIOLIGHT_ICON_SIZE 96 + +#define STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL 2 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_MAX_COMPONENTS 9 + + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 0 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS 1 +#endif + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 1 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS 4 +#endif + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 2 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS 9 +#endif struct GPUTexture; +struct StudioLight; +/* StudioLight.flag */ enum StudioLightFlag { - STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED = (1 << 0), + STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED = (1 << 0), STUDIOLIGHT_LIGHT_DIRECTION_CALCULATED = (1 << 1), STUDIOLIGHT_INTERNAL = (1 << 2), STUDIOLIGHT_EXTERNAL_FILE = (1 << 3), @@ -72,26 +97,43 @@ enum StudioLightFlag { STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED = (1 << 11), STUDIOLIGHT_UI_EXPANDED = (1 << 13), } StudioLightFlag; + #define STUDIOLIGHT_FLAG_ALL (STUDIOLIGHT_INTERNAL | STUDIOLIGHT_EXTERNAL_FILE) #define STUDIOLIGHT_FLAG_ORIENTATIONS (STUDIOLIGHT_ORIENTATION_CAMERA | STUDIOLIGHT_ORIENTATION_WORLD | STUDIOLIGHT_ORIENTATION_VIEWNORMAL) #define STUDIOLIGHT_ORIENTATIONS_MATERIAL_MODE (STUDIOLIGHT_INTERNAL | STUDIOLIGHT_ORIENTATION_WORLD) #define STUDIOLIGHT_ORIENTATIONS_SOLID (STUDIOLIGHT_INTERNAL | STUDIOLIGHT_ORIENTATION_CAMERA | STUDIOLIGHT_ORIENTATION_WORLD) +typedef void StudioLightFreeFunction(struct StudioLight *, void *data); + typedef struct StudioLight { struct StudioLight *next, *prev; + + int index; int flag; char name[FILE_MAXFILE]; char path[FILE_MAX]; - int irradiance_icon_id; - int radiance_icon_id; - int index; - float diffuse_light[6][3]; + char *path_irr_cache; + char *path_sh_cache; + int icon_id_irradiance; + int icon_id_radiance; + int icon_id_matcap; + int icon_id_matcap_flipped; + float spherical_harmonics_coefs[STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS][3]; float light_direction[3]; ImBuf *equirectangular_radiance_buffer; ImBuf *equirectangular_irradiance_buffer; ImBuf *radiance_cubemap_buffers[6]; struct GPUTexture *equirectangular_radiance_gputexture; struct GPUTexture *equirectangular_irradiance_gputexture; + float *gpu_matcap_3components; /* 3 channel buffer for GPU_R11F_G11F_B10F */ + + /* + Free function to clean up the running icons previews (wmJob) the usage is in + interface_icons. Please be aware that this was build to handle only one free function + that cleans up all icons. just to keep the code simple. + */ + StudioLightFreeFunction *free_function; + void* free_function_data; } StudioLight; void BKE_studiolight_init(void); @@ -99,9 +141,11 @@ void BKE_studiolight_free(void); struct StudioLight *BKE_studiolight_find(const char *name, int flag); struct StudioLight *BKE_studiolight_findindex(int index, int flag); struct StudioLight *BKE_studiolight_find_first(int flag); -unsigned int *BKE_studiolight_preview(StudioLight *sl, int icon_size, int icon_id_type); +void BKE_studiolight_preview(uint* icon_buffer, StudioLight *sl, int icon_id_type); struct ListBase *BKE_studiolight_listbase(void); void BKE_studiolight_ensure_flag(StudioLight *sl, int flag); void BKE_studiolight_refresh(void); +void BKE_studiolight_set_free_function(StudioLight *sl, StudioLightFreeFunction *free_function, void *data); +void BKE_studiolight_unset_icon_id(StudioLight *sl, int icon_id); #endif /* __BKE_STUDIOLIGHT_H__ */ diff --git a/source/blender/blenkernel/BKE_undo_system.h b/source/blender/blenkernel/BKE_undo_system.h index 05093deec70..a75606a17cb 100644 --- a/source/blender/blenkernel/BKE_undo_system.h +++ b/source/blender/blenkernel/BKE_undo_system.h @@ -135,6 +135,7 @@ extern const UndoType *BKE_UNDOSYS_TYPE_TEXT; UndoStack *BKE_undosys_stack_create(void); void BKE_undosys_stack_destroy(UndoStack *ustack); void BKE_undosys_stack_clear(UndoStack *ustack); +void BKE_undosys_stack_clear_active(UndoStack *ustack); bool BKE_undosys_stack_has_undo(UndoStack *ustack, const char *name); void BKE_undosys_stack_init_from_main(UndoStack *ustack, struct Main *bmain); void BKE_undosys_stack_init_from_context(UndoStack *ustack, struct bContext *C); diff --git a/source/blender/blenkernel/BKE_workspace.h b/source/blender/blenkernel/BKE_workspace.h index 5442fd43ce5..03d24ac53d1 100644 --- a/source/blender/blenkernel/BKE_workspace.h +++ b/source/blender/blenkernel/BKE_workspace.h @@ -44,6 +44,7 @@ struct WorkSpaceInstanceHook *BKE_workspace_instance_hook_create(const struct Ma void BKE_workspace_instance_hook_free(const struct Main *bmain, struct WorkSpaceInstanceHook *hook); struct WorkSpaceLayout *BKE_workspace_layout_add( + struct Main *bmain, struct WorkSpace *workspace, struct bScreen *screen, const char *name) ATTR_NONNULL(); diff --git a/source/blender/blenkernel/BKE_writeavi.h b/source/blender/blenkernel/BKE_writeavi.h index ca295c51f5d..3bd0689a93a 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; diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index 867b5884114..94d762214f2 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -140,6 +140,7 @@ set(SRC intern/mesh.c intern/mesh_convert.c intern/mesh_evaluate.c + intern/mesh_iterators.c intern/mesh_mapping.c intern/mesh_merge.c intern/mesh_remap.c @@ -272,6 +273,7 @@ set(SRC BKE_mball.h BKE_mball_tessellate.h BKE_mesh.h + BKE_mesh_iterators.h BKE_mesh_mapping.h BKE_mesh_remap.h BKE_mesh_tangent.h diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c index 68bcfa878ac..81b1afa3621 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/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index c081bb0799f..5a4dc479c10 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -136,7 +136,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 @@ -144,7 +144,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); @@ -346,7 +346,7 @@ void DM_init( dm->numPolyData = numPolys; DM_init_funcs(dm); - + dm->needsFree = 1; dm->dirty = 0; @@ -754,7 +754,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) { @@ -780,7 +780,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)) { @@ -861,18 +861,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); } @@ -1146,10 +1146,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); } @@ -1170,7 +1170,7 @@ DerivedMesh *mesh_create_derived_for_modifier( ModifierEvalContext mectx = {depsgraph, ob, 0}; md->scene = scene; - + if (!(md->mode & eModifierMode_Realtime)) { return NULL; } @@ -1178,11 +1178,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); @@ -1192,7 +1192,7 @@ DerivedMesh *mesh_create_derived_for_modifier( if (build_shapekey_layers) add_shapekey_layers(dm, me, ob); - + MEM_freeN(deformedVerts); } else { @@ -1200,7 +1200,7 @@ DerivedMesh *mesh_create_derived_for_modifier( if (build_shapekey_layers) add_shapekey_layers(tdm, me, ob); - + dm = modwrap_applyModifier(md, &mectx, tdm); ASSERT_IS_VALID_DM(dm); @@ -1220,13 +1220,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; } @@ -1490,7 +1490,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)) { @@ -1871,35 +1871,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); } @@ -1910,12 +1910,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); @@ -2051,6 +2051,7 @@ static void mesh_calc_modifiers( ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0; ModifierApplyFlag deform_app_flags = app_flags; + BLI_assert((me->id.tag & LIB_TAG_COPIED_ON_WRITE_EVAL_RESULT) == 0); if (useCache) app_flags |= MOD_APPLY_USECACHE; @@ -2095,13 +2096,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; } @@ -2119,7 +2120,7 @@ static void mesh_calc_modifiers( else { break; } - + /* grab modifiers until index i */ if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index)) break; @@ -2142,7 +2143,7 @@ static void mesh_calc_modifiers( BLI_assert(!build_shapekey_layers); //if (build_shapekey_layers) // add_shapekey_layers(*r_deform_mesh, me, ob); - + if (deformedVerts) { BKE_mesh_apply_vert_coords(*r_deform_mesh, deformedVerts); } @@ -2158,7 +2159,7 @@ static void mesh_calc_modifiers( /* Now apply all remaining modifiers. If useDeform is off then skip - * OnlyDeform ones. + * OnlyDeform ones. */ Mesh *mesh = NULL; Mesh *orco_mesh = NULL; @@ -2317,7 +2318,7 @@ static void mesh_calc_modifiers( } } - + /* set the Mesh to only copy needed data */ mask = curr->mask; /* needMapping check here fixes bug [#28112], otherwise it's @@ -2584,7 +2585,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; } @@ -2646,7 +2647,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; } @@ -3016,8 +3017,9 @@ static void mesh_build_data( if ((ob->mode & OB_MODE_ALL_SCULPT) && ob->sculpt) { /* create PBVH immediately (would be created on the fly too, * but this avoids waiting on first stroke) */ - - BKE_sculpt_update_mesh_elements(depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); + /* XXX Disabled for now. + * This can create horrible nasty bugs by generating re-entrant call of mesh_get_eval_final! */ +// BKE_sculpt_update_mesh_elements(depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); } BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS)); @@ -3054,14 +3056,14 @@ static void editbmesh_build_data( static CustomDataMask object_get_datamask(const Depsgraph *depsgraph, Object *ob, bool *r_need_mapping) { ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - Object *actob = view_layer->basact ? view_layer->basact->object : NULL; + Object *actob = view_layer->basact ? DEG_get_original_object(view_layer->basact->object) : NULL; CustomDataMask mask = ob->customdata_mask; if (r_need_mapping) { *r_need_mapping = false; } - if (ob == actob) { + if (DEG_get_original_object(ob) == actob) { bool editing = BKE_paint_select_face_test(ob); /* weight paint and face select need original indices because of selection buffer drawing */ @@ -3193,7 +3195,7 @@ Mesh *mesh_get_eval_deform(struct Depsgraph *depsgraph, Scene *scene, Object *ob DerivedMesh *mesh_create_derived_render(struct Depsgraph *depsgraph, Scene *scene, Object *ob, CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers_dm( depsgraph, scene, ob, NULL, 1, false, dataMask, -1, false, false, false, NULL, &final); @@ -3238,7 +3240,7 @@ DerivedMesh *mesh_create_derived_no_deform( float (*vertCos)[3], CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers_dm( depsgraph, scene, ob, vertCos, 0, false, dataMask, -1, false, false, false, NULL, &final); @@ -3352,13 +3354,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); @@ -3371,7 +3373,7 @@ DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob) dm->getVertNo(dm, a, v_co_no->no); } } - + dm->release(dm); return vertexcosnos; } diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index 01f6eab261f..9f5b81a8915 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -32,7 +32,7 @@ #include <string.h> #include <math.h> #include <stdlib.h> -#include <stddef.h> +#include <stddef.h> #include "MEM_guardedalloc.h" @@ -88,11 +88,11 @@ bAction *BKE_action_add(Main *bmain, const char name[]) { bAction *act; - + act = BKE_libblock_alloc(bmain, ID_AC, name, 0); - + return act; -} +} /* .................................. */ @@ -106,15 +106,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); } @@ -179,14 +179,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; } @@ -194,11 +194,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)) @@ -217,7 +217,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 { @@ -243,69 +243,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, @@ -319,18 +319,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) @@ -338,11 +338,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); @@ -360,10 +360,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); } @@ -374,7 +374,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)); } @@ -383,11 +383,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; @@ -403,10 +403,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)); } @@ -421,19 +421,19 @@ 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)); + chan = BKE_pose_channel_find_name(pose, name); if (chan) { return chan; } /* 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; @@ -442,20 +442,22 @@ 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); - + if (pose->chanhash) { + BLI_ghash_insert(pose->chanhash, chan->name, chan); + } + return chan; } @@ -495,7 +497,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; } @@ -544,11 +546,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... @@ -557,12 +559,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); @@ -586,7 +588,7 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const /* XXX: This is needed for motionpath drawing to work. Dunno why it was setting to null before... */ pchan->mpath = animviz_copy_motionpath(pchan->mpath); } - + if (pchan->prop) { pchan->prop = IDP_CopyProperty_ex(pchan->prop, flag); } @@ -598,7 +600,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; } @@ -646,7 +648,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) { @@ -675,18 +677,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); @@ -742,7 +744,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; @@ -751,7 +753,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; @@ -780,7 +782,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); @@ -802,11 +804,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); } @@ -883,7 +885,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; @@ -921,31 +923,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) @@ -956,10 +958,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) */ @@ -968,7 +970,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; } } @@ -980,7 +982,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. */ @@ -989,14 +991,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; } } @@ -1009,18 +1011,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; } @@ -1030,13 +1032,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 @@ -1066,7 +1068,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) { @@ -1080,7 +1082,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) { @@ -1088,7 +1090,7 @@ bool action_has_motion(const bAction *act) return true; } } - + /* nothing found */ return false; } @@ -1105,7 +1107,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 @@ -1113,26 +1115,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); } @@ -1144,7 +1146,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) @@ -1152,22 +1154,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; } @@ -1177,7 +1179,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) @@ -1186,7 +1188,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); @@ -1194,37 +1196,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 @@ -1234,53 +1236,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; @@ -1288,10 +1290,10 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, } } } - + /* free basePath */ MEM_freeN(basePath); - + /* return flags found */ return flags; } @@ -1302,26 +1304,26 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, 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); } } @@ -1330,7 +1332,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; @@ -1347,16 +1349,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; @@ -1367,7 +1369,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; @@ -1387,27 +1389,27 @@ void BKE_pose_tag_recalc(Main *bmain, bPose *pose) DEG_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; @@ -1415,7 +1417,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. @@ -1432,27 +1434,27 @@ 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<ConstrWorkOb>", 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, 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 689e0fb5ee6..a9bb193a7a1 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)); diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c index c7730d8877b..07b8b69bc70 100644 --- a/source/blender/blenkernel/intern/anim.c +++ b/source/blender/blenkernel/intern/anim.c @@ -104,12 +104,12 @@ 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); @@ -117,13 +117,13 @@ void animviz_free_motionpath_cache(bMotionPath *mpath) GWN_VERTBUF_DISCARD_SAFE(mpath->points_vbo); GWN_BATCH_DISCARD_SAFE(mpath->batch_line); GWN_BATCH_DISCARD_SAFE(mpath->batch_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) @@ -131,10 +131,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); } @@ -174,11 +174,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 */ @@ -206,9 +206,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 */ @@ -227,13 +227,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 @@ -249,10 +249,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; } @@ -262,20 +262,19 @@ 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 */ DLRBT_Tree keys; /* temp, to know where the keyframes are */ - + /* Original (Source Objects) */ Object *ob; /* source object */ bPoseChannel *pchan; /* source posechannel (if applicable) */ - + /* "Evaluated" Copies (these come from the background COW copie * that provide all the coordinates we want to save off) */ Object *ob_eval; /* evaluated object */ - bPoseChannel *pchan_eval; /* evaluated posechannel (if applicable) */ } MPathTarget; /* ........ */ @@ -287,28 +286,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; @@ -342,27 +341,33 @@ static void motionpaths_calc_update_scene(Main *bmain, 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; - - Object *ob_eval = mpt->ob_eval; - bPoseChannel *pchan_eval = mpt->pchan_eval; - - /* 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); - + + Object *ob_eval = mpt->ob_eval; + + /* Lookup evaluated pose channel, here because the depsgraph + * evaluation can change them so they are not cached in mpt. */ + bPoseChannel *pchan_eval = NULL; + if (mpt->pchan) { + pchan_eval = BKE_pose_channel_find_name(ob_eval->pose, mpt->pchan->name); + } + /* pose-channel or object path baking? */ - if (mpt->pchan_eval) { + if (pchan_eval) { /* heads or tails */ if (mpath->flag & MOTIONPATH_FLAG_BHEAD) { copy_v3_v3(mpv->co, pchan_eval->pose_head); @@ -370,7 +375,7 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) else { copy_v3_v3(mpv->co, pchan_eval->pose_tail); } - + /* result must be in worldspace */ mul_m4_v3(ob_eval->obmat, mpv->co); } @@ -388,7 +393,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 @@ -399,15 +404,15 @@ static void motionpaths_calc_bake_targets(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?) */ @@ -417,17 +422,14 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) efra = MAX2(efra, mpt->mpath->end_frame); } if (efra <= sfra) return; - - + + /* get copies of objects/bones to get the calculated results from * (for copy-on-write evaluation), so that we actually get some results */ // TODO: Create a copy of background depsgraph that only contain these entities, and only evaluates them.. for (mpt = targets->first; mpt; mpt = mpt->next) { mpt->ob_eval = DEG_get_evaluated_object(depsgraph, mpt->ob); - if (mpt->pchan) { - mpt->pchan_eval = BKE_pose_channel_find_name(mpt->ob_eval->pose, mpt->pchan->name); - } AnimData *adt = BKE_animdata_from_id(&mpt->ob_eval->id); @@ -469,23 +471,23 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) /* perform baking for targets */ motionpaths_calc_bake_targets(scene, targets); } - + /* reset original environment */ // XXX: Soon to be obsolete CFRA = cfra; motionpaths_calc_update_scene(bmain, depsgraph); - + /* clear recalc flags from targets */ for (mpt = targets->first; mpt; mpt = mpt->next) { bAnimVizSettings *avs; bMotionPath *mpath = mpt->mpath; - + /* 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; @@ -502,7 +504,7 @@ static void motionpaths_calc_bake_targets(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] */ @@ -512,7 +514,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) @@ -525,17 +527,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) { @@ -545,18 +547,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 */ @@ -569,13 +571,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"); @@ -590,11 +592,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)) { @@ -620,10 +622,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); } @@ -667,7 +669,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; @@ -678,7 +680,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 e5a68fa7476..fd7497f9ba1 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -105,7 +105,7 @@ bool id_type_can_have_animdata(const short id_type) case ID_GD: case ID_CF: return true; - + /* no AnimData */ default: return false; @@ -121,13 +121,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 */ @@ -139,33 +139,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; } @@ -176,14 +176,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)) { @@ -191,11 +191,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 */ @@ -218,7 +218,7 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) adt->action = NULL; ok = true; } - + return ok; } @@ -227,13 +227,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) { @@ -244,19 +244,19 @@ 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 driver array cache */ MEM_SAFE_FREE(adt->driver_array); - + /* free overrides */ /* TODO... */ - + /* free animdata now */ MEM_freeN(adt); iat->adt = NULL; @@ -270,12 +270,12 @@ void BKE_animdata_free(ID *id, const bool do_id_user) AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action, const bool do_id_user) { 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); @@ -288,15 +288,15 @@ AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action, co } /* duplicate NLA data */ - BKE_nla_tracks_copy(&dadt->nla_tracks, &adt->nla_tracks); - + BKE_nla_tracks_copy(bmain, &dadt->nla_tracks, &adt->nla_tracks); + /* duplicate drivers (F-Curves) */ copy_fcurves(&dadt->drivers, &adt->drivers); dadt->driver_array = NULL; - + /* don't copy overrides */ BLI_listbase_clear(&dadt->overrides); - + /* return */ return dadt; } @@ -319,78 +319,80 @@ bool BKE_animdata_copy_id(Main *bmain, ID *id_to, ID *id_from, const bool do_act return true; } -void BKE_animdata_copy_id_action(ID *id, const bool set_newid) +void BKE_animdata_copy_id_action(Main *bmain, ID *id, const bool set_newid) { AnimData *adt = BKE_animdata_from_id(id); if (adt) { if (adt->action) { id_us_min((ID *)adt->action); - adt->action = set_newid ? ID_NEW_SET(adt->action, BKE_action_copy(G.main, adt->action)) : - BKE_action_copy(G.main, adt->action); + adt->action = set_newid ? ID_NEW_SET(adt->action, BKE_action_copy(bmain, adt->action)) : + BKE_action_copy(bmain, adt->action); } if (adt->tmpact) { id_us_min((ID *)adt->tmpact); - adt->tmpact = set_newid ? ID_NEW_SET(adt->tmpact, BKE_action_copy(G.main, adt->tmpact)) : - BKE_action_copy(G.main, adt->tmpact); + adt->tmpact = set_newid ? ID_NEW_SET(adt->tmpact, BKE_action_copy(bmain, adt->tmpact)) : + BKE_action_copy(bmain, adt->tmpact); } } } /* Merge copies of the data from the src AnimData into the destination AnimData */ -void BKE_animdata_merge_copy(ID *dst_id, ID *src_id, eAnimData_MergeCopy_Modes action_mode, bool fix_drivers) +void BKE_animdata_merge_copy( + Main *bmain, ID *dst_id, ID *src_id, + eAnimData_MergeCopy_Modes action_mode, bool fix_drivers) { 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 */ - dst->action = BKE_action_copy(G.main, src->action); - dst->tmpact = BKE_action_copy(G.main, src->tmpact); + dst->action = BKE_action_copy(bmain, src->action); + dst->tmpact = BKE_action_copy(bmain, src->tmpact); } else if (action_mode == ADT_MERGECOPY_SRC_REF) { /* 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(&tracks, &src->nla_tracks); + + 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) { @@ -402,7 +404,7 @@ void BKE_animdata_merge_copy(ID *dst_id, ID *src_id, eAnimData_MergeCopy_Modes a } } } - + BLI_movelisttolist(&dst->drivers, &drivers); } } @@ -422,7 +424,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 @@ -431,7 +433,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) { @@ -440,56 +442,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 @@ -508,69 +510,70 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha * animation data is based off "basepath", creating new AnimData and * associated data as necessary */ -void BKE_animdata_separate_by_basepath(ID *srcID, ID *dstID, ListBase *basepaths) +void BKE_animdata_separate_by_basepath( + Main *bmain, ID *srcID, ID *dstID, ListBase *basepaths) { 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 */ if (dstAdt->action == NULL) { - dstAdt->action = BKE_action_add(G.main, srcAdt->action->id.name + 2); + dstAdt->action = BKE_action_add(bmain, srcAdt->action->id.name + 2); } 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(G.main, dstAdt->action->id.name + 2); + 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; } @@ -628,15 +631,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) @@ -645,7 +648,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 */ @@ -660,20 +663,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)) { @@ -687,31 +690,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)); } @@ -725,27 +728,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)) && @@ -762,18 +765,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); } @@ -794,13 +797,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 */ @@ -818,21 +821,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. @@ -844,11 +847,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 */ @@ -866,10 +869,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); @@ -884,11 +887,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 */ @@ -906,16 +909,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); @@ -1005,7 +1008,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); } @@ -1015,13 +1018,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); } @@ -1032,18 +1035,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); @@ -1051,20 +1054,20 @@ static void adt_apply_all_fcurves_cb(ID *id, AnimData *adt, void *wrapper_data) } /* apply the given callback function on all F-Curves attached to data in main database */ -void BKE_fcurves_main_cb(Main *mainptr, ID_FCurve_Edit_Callback func, void *user_data) +void BKE_fcurves_main_cb(Main *bmain, ID_FCurve_Edit_Callback func, void *user_data) { /* 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(mainptr, adt_apply_all_fcurves_cb, &wrapper); + BKE_animdata_main_cb(bmain, adt_apply_all_fcurves_cb, &wrapper); } /* Whole Database Ops -------------------------------------------- */ /* apply the given callback function on all data in main database */ -void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *user_data) +void BKE_animdata_main_cb(Main *bmain, ID_AnimData_Edit_Callback func, void *user_data) { ID *id; @@ -1074,7 +1077,7 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u 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) { \ @@ -1086,69 +1089,69 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u } \ if (adt) func(id, adt, user_data); \ } (void)0 - + /* nodes */ - ANIMDATA_IDS_CB(mainptr->nodetree.first); - + ANIMDATA_IDS_CB(bmain->nodetree.first); + /* textures */ - ANIMDATA_NODETREE_IDS_CB(mainptr->tex.first, Tex); - + ANIMDATA_NODETREE_IDS_CB(bmain->tex.first, Tex); + /* lamps */ - ANIMDATA_NODETREE_IDS_CB(mainptr->lamp.first, Lamp); - + ANIMDATA_NODETREE_IDS_CB(bmain->lamp.first, Lamp); + /* materials */ - ANIMDATA_NODETREE_IDS_CB(mainptr->mat.first, Material); - + ANIMDATA_NODETREE_IDS_CB(bmain->mat.first, Material); + /* cameras */ - ANIMDATA_IDS_CB(mainptr->camera.first); - + ANIMDATA_IDS_CB(bmain->camera.first); + /* shapekeys */ - ANIMDATA_IDS_CB(mainptr->key.first); - + ANIMDATA_IDS_CB(bmain->key.first); + /* metaballs */ - ANIMDATA_IDS_CB(mainptr->mball.first); - + ANIMDATA_IDS_CB(bmain->mball.first); + /* curves */ - ANIMDATA_IDS_CB(mainptr->curve.first); - + ANIMDATA_IDS_CB(bmain->curve.first); + /* armatures */ - ANIMDATA_IDS_CB(mainptr->armature.first); - + ANIMDATA_IDS_CB(bmain->armature.first); + /* lattices */ - ANIMDATA_IDS_CB(mainptr->latt.first); - + ANIMDATA_IDS_CB(bmain->latt.first); + /* meshes */ - ANIMDATA_IDS_CB(mainptr->mesh.first); - + ANIMDATA_IDS_CB(bmain->mesh.first); + /* particles */ - ANIMDATA_IDS_CB(mainptr->particle.first); + ANIMDATA_IDS_CB(bmain->particle.first); /* speakers */ - ANIMDATA_IDS_CB(mainptr->speaker.first); + ANIMDATA_IDS_CB(bmain->speaker.first); /* movie clips */ - ANIMDATA_IDS_CB(mainptr->movieclip.first); + ANIMDATA_IDS_CB(bmain->movieclip.first); /* objects */ - ANIMDATA_IDS_CB(mainptr->object.first); + ANIMDATA_IDS_CB(bmain->object.first); /* masks */ - ANIMDATA_IDS_CB(mainptr->mask.first); - + ANIMDATA_IDS_CB(bmain->mask.first); + /* worlds */ - ANIMDATA_NODETREE_IDS_CB(mainptr->world.first, World); + ANIMDATA_NODETREE_IDS_CB(bmain->world.first, World); /* scenes */ - ANIMDATA_NODETREE_IDS_CB(mainptr->scene.first, Scene); + ANIMDATA_NODETREE_IDS_CB(bmain->scene.first, Scene); /* line styles */ - ANIMDATA_IDS_CB(mainptr->linestyle.first); - + ANIMDATA_IDS_CB(bmain->linestyle.first); + /* grease pencil */ - ANIMDATA_IDS_CB(mainptr->gpencil.first); + ANIMDATA_IDS_CB(bmain->gpencil.first); /* cache files */ - ANIMDATA_IDS_CB(mainptr->cachefiles.first); + ANIMDATA_IDS_CB(bmain->cachefiles.first); } /* Fix all RNA-Paths throughout the database (directly access the Global.main version) @@ -1158,11 +1161,11 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u /* TODO: use BKE_animdata_main_cb for looping over all data */ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const char *oldName, const char *newName) { - Main *mainptr = G.main; + 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) \ @@ -1170,7 +1173,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) { \ @@ -1182,72 +1185,72 @@ 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(mainptr->nodetree.first); - + RENAMEFIX_ANIM_IDS(bmain->nodetree.first); + /* textures */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->tex.first, Tex); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->tex.first, Tex); + /* lamps */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->lamp.first, Lamp); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->lamp.first, Lamp); + /* materials */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->mat.first, Material); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->mat.first, Material); + /* cameras */ - RENAMEFIX_ANIM_IDS(mainptr->camera.first); - + RENAMEFIX_ANIM_IDS(bmain->camera.first); + /* shapekeys */ - RENAMEFIX_ANIM_IDS(mainptr->key.first); - + RENAMEFIX_ANIM_IDS(bmain->key.first); + /* metaballs */ - RENAMEFIX_ANIM_IDS(mainptr->mball.first); - + RENAMEFIX_ANIM_IDS(bmain->mball.first); + /* curves */ - RENAMEFIX_ANIM_IDS(mainptr->curve.first); - + RENAMEFIX_ANIM_IDS(bmain->curve.first); + /* armatures */ - RENAMEFIX_ANIM_IDS(mainptr->armature.first); - + RENAMEFIX_ANIM_IDS(bmain->armature.first); + /* lattices */ - RENAMEFIX_ANIM_IDS(mainptr->latt.first); - + RENAMEFIX_ANIM_IDS(bmain->latt.first); + /* meshes */ - RENAMEFIX_ANIM_IDS(mainptr->mesh.first); - + RENAMEFIX_ANIM_IDS(bmain->mesh.first); + /* particles */ - RENAMEFIX_ANIM_IDS(mainptr->particle.first); + RENAMEFIX_ANIM_IDS(bmain->particle.first); /* speakers */ - RENAMEFIX_ANIM_IDS(mainptr->speaker.first); + RENAMEFIX_ANIM_IDS(bmain->speaker.first); /* movie clips */ - RENAMEFIX_ANIM_IDS(mainptr->movieclip.first); + RENAMEFIX_ANIM_IDS(bmain->movieclip.first); /* objects */ - RENAMEFIX_ANIM_IDS(mainptr->object.first); + RENAMEFIX_ANIM_IDS(bmain->object.first); /* masks */ - RENAMEFIX_ANIM_IDS(mainptr->mask.first); - + RENAMEFIX_ANIM_IDS(bmain->mask.first); + /* worlds */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->world.first, World); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->world.first, World); + /* linestyles */ - RENAMEFIX_ANIM_IDS(mainptr->linestyle.first); - + RENAMEFIX_ANIM_IDS(bmain->linestyle.first); + /* grease pencil */ - RENAMEFIX_ANIM_IDS(mainptr->gpencil.first); + RENAMEFIX_ANIM_IDS(bmain->gpencil.first); /* cache files */ - RENAMEFIX_ANIM_IDS(mainptr->cachefiles.first); - + RENAMEFIX_ANIM_IDS(bmain->cachefiles.first); + /* scenes */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->scene.first, Scene); + RENAMEFIX_ANIM_NODETREE_IDS(bmain->scene.first, Scene); } -/* *********************************** */ +/* *********************************** */ /* KeyingSet API */ /* Finding Tools --------------------------- */ @@ -1257,50 +1260,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"); @@ -1310,16 +1313,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; } @@ -1330,55 +1333,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) @@ -1400,12 +1403,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); } @@ -1417,11 +1420,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; @@ -1433,12 +1436,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) { @@ -1451,7 +1454,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 * @@ -1754,14 +1757,14 @@ static void animsys_evaluate_fcurves( 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 */ @@ -1776,13 +1779,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; } } } @@ -1798,13 +1801,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) @@ -1828,17 +1831,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 */ @@ -1859,9 +1862,9 @@ static void animsys_evaluate_action_ex( /* 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(depsgraph, ptr, &act->curves, remap, ctime); } @@ -1880,7 +1883,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 */ @@ -1902,14 +1905,14 @@ static void nlastrip_evaluate_controls(Depsgraph *depsgraph, NlaStrip *strip, fl /* 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(depsgraph, &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. @@ -1934,7 +1937,7 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li 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 */ @@ -1944,53 +1947,53 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li 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 */ @@ -2000,8 +2003,8 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li 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? */ @@ -2009,12 +2012,12 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li nlastrip_evaluate_controls(depsgraph, 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; @@ -2023,51 +2026,51 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li /* 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(depsgraph, estrip->prev, estrip->start); nlastrip_evaluate_controls(depsgraph, 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; } @@ -2078,9 +2081,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)) { @@ -2119,15 +2122,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"); @@ -2138,27 +2141,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; } @@ -2169,7 +2172,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) { @@ -2180,36 +2183,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); @@ -2221,19 +2224,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 */ @@ -2244,7 +2247,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); } @@ -2256,7 +2259,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) { @@ -2270,15 +2273,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; } @@ -2288,17 +2291,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; @@ -2314,48 +2317,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 */ @@ -2379,11 +2382,11 @@ static void nlastrip_evaluate_transition( 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... @@ -2398,8 +2401,8 @@ static void nlastrip_evaluate_transition( 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, @@ -2407,23 +2410,23 @@ static void nlastrip_evaluate_transition( * 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(depsgraph, ptr, &tmp_channels, &tmp_modifiers, &tmp_nes); - + /* second strip */ tmp_nes.strip_mode = NES_TIME_TRANSITION_END; tmp_nes.strip = s2; nlastrip_evaluate(depsgraph, 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); } @@ -2436,32 +2439,32 @@ static void nlastrip_evaluate_meta( 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(depsgraph, 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(depsgraph, 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); } @@ -2470,7 +2473,7 @@ static void nlastrip_evaluate_meta( void nlastrip_evaluate(Depsgraph *depsgraph, 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 */ @@ -2478,7 +2481,7 @@ void nlastrip_evaluate(Depsgraph *depsgraph, PointerRNA *ptr, ListBase *channels 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 */ @@ -2490,11 +2493,11 @@ void nlastrip_evaluate(Depsgraph *depsgraph, PointerRNA *ptr, ListBase *channels case NLASTRIP_TYPE_META: /* meta */ nlastrip_evaluate_meta(depsgraph, ptr, channels, modifiers, nes); break; - + default: /* do nothing */ break; } - + /* clear temp recursion safe-check */ strip->flag &= ~NLASTRIP_FLAG_EDIT_TOUCHED; } @@ -2503,18 +2506,18 @@ void nlastrip_evaluate(Depsgraph *depsgraph, PointerRNA *ptr, ListBase *channels 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: @@ -2559,19 +2562,19 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin 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 */ @@ -2581,24 +2584,24 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin } 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(depsgraph, &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))) { @@ -2606,9 +2609,9 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin 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)); @@ -2618,20 +2621,20 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin /* 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(depsgraph, &estrips, &dummy_trackslist, -1, ctime); } @@ -2639,27 +2642,27 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin /* 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(depsgraph, 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(depsgraph, ptr, echannels, NULL, nes); - + /* 3. free temporary evaluation data that's not used elsewhere */ BLI_freelistN(&estrips); } -/* 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. */ @@ -2672,15 +2675,15 @@ static void animsys_calculate_nla(Depsgraph *depsgraph, PointerRNA *ptr, AnimDat /* evaluate the NLA stack, obtaining a set of values to flush */ animsys_evaluate_nla(depsgraph, &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 */ @@ -2700,7 +2703,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; @@ -2744,7 +2747,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 @@ -2753,14 +2756,14 @@ static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, 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 @@ -2769,7 +2772,7 @@ void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, Scene *scene, ID *id, A 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(depsgraph, &id_ptr, adt, ctime); @@ -2777,13 +2780,13 @@ void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, Scene *scene, ID *id, A /* evaluate Active Action only */ else if (adt->action) animsys_evaluate_action_ex(depsgraph, &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... */ @@ -2793,22 +2796,22 @@ void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, Scene *scene, ID *id, A { 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; } @@ -2826,10 +2829,10 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene 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) \ @@ -2840,8 +2843,8 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene } \ } (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 @@ -2858,10 +2861,10 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene BKE_animsys_evaluate_animdata(depsgraph, 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 @@ -2870,46 +2873,46 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene 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); @@ -2918,31 +2921,31 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene /* 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 */ @@ -3017,7 +3020,7 @@ void BKE_animsys_eval_driver(Depsgraph *depsgraph, PathResolvedRNA anim_rna; if (animsys_store_rna_setting(&id_ptr, NULL, fcu->rna_path, fcu->array_index, &anim_rna)) { const float ctime = DEG_get_ctime(depsgraph); - const float curval = calculate_fcurve(&anim_rna, fcu, ctime); + const float curval = evaluate_fcurve_driver(&anim_rna, fcu, driver_orig, ctime); ok = animsys_write_rna_setting(&anim_rna, curval); if (ok && DEG_is_active(depsgraph)) { animsys_write_orig_anim_rna(&id_ptr, NULL, fcu, curval); diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index 3b2534eae73..ccff6216cb3 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 8dbfc35c774..ba45b5acb5d 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -632,17 +632,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 @@ -650,14 +650,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; @@ -673,39 +673,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); } - + } } @@ -764,10 +764,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); @@ -1811,7 +1811,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 */ @@ -1819,7 +1819,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; @@ -1835,13 +1835,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 @@ -1853,29 +1853,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 ce99da87c74..628f92c7803 100644 --- a/source/blender/blenkernel/intern/armature_update.c +++ b/source/blender/blenkernel/intern/armature_update.c @@ -117,7 +117,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(depsgraph, 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); */ @@ -427,21 +427,21 @@ static void splineik_evaluate_bone( { /* 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); } } @@ -449,15 +449,15 @@ static void splineik_evaluate_bone( 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); } @@ -465,7 +465,7 @@ static void splineik_evaluate_bone( /* 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 3f78b096115..c366d822648 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -62,6 +62,7 @@ #include "BKE_scene.h" #include "BKE_screen.h" #include "BKE_sequencer.h" +#include "BKE_studiolight.h" #include "DEG_depsgraph.h" @@ -81,23 +82,25 @@ char versionstr[48] = ""; /* only to be called on exit blender */ void BKE_blender_free(void) { - /* samples are in a global list..., also sets G.main->sound->sample NULL */ - BKE_main_free(G.main); - G.main = NULL; + /* samples are in a global list..., also sets G_MAIN->sound->sample NULL */ + + BKE_studiolight_free(); /* needs to run before main free as wm is still referenced for icons preview jobs */ + BKE_main_free(G_MAIN); + G_MAIN = NULL; if (G.log.file != NULL) { fclose(G.log.file); } BKE_spacetypes_free(); /* after free main, it uses space callbacks */ - + IMB_exit(); BKE_cachefiles_exit(); BKE_images_exit(); DEG_free_node_types(); BKE_brush_system_exit(); - RE_texture_rng_exit(); + RE_texture_rng_exit(); BLI_callback_global_finalize(); @@ -122,10 +125,10 @@ void BKE_blender_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(); + G_MAIN = BKE_main_new(); strcpy(G.ima, "//"); @@ -142,9 +145,9 @@ void BKE_blender_globals_init(void) void BKE_blender_globals_clear(void) { - BKE_main_free(G.main); /* free all lib data */ + BKE_main_free(G_MAIN); /* free all lib data */ - G.main = NULL; + G_MAIN = NULL; } /***/ @@ -325,7 +328,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/blendfile.c b/source/blender/blenkernel/intern/blendfile.c index 597c69408b5..27b5089b092 100644 --- a/source/blender/blenkernel/intern/blendfile.c +++ b/source/blender/blenkernel/intern/blendfile.c @@ -116,7 +116,7 @@ static void setup_app_data( bContext *C, BlendFileData *bfd, const char *filepath, ReportList *reports) { - Main *bmain = G.main; /* Valid usage */ + Main *bmain = G_MAIN; Scene *curscene = NULL; const bool is_startup = (bfd->filename[0] == '\0'); const bool recover = (G.fileflags & G_FILE_RECOVER) != 0; @@ -207,7 +207,7 @@ static void setup_app_data( win->scene = curscene; } - /* BKE_blender_globals_clear will free G.main, here we can still restore pointers */ + /* BKE_blender_globals_clear will free G_MAIN, here we can still restore pointers */ blo_lib_link_restore(bfd->main, CTX_wm_manager(C), curscene, cur_view_layer); if (win) { curscene = win->scene; @@ -230,14 +230,14 @@ static void setup_app_data( } } - /* free G.main Main database */ + /* free G_MAIN Main database */ // CTX_wm_manager_set(C, NULL); BKE_blender_globals_clear(); /* clear old property update cache, in case some old references are left dangling */ RNA_property_update_cache_free(); - bmain = G.main = bfd->main; + bmain = G_MAIN = bfd->main; CTX_data_main_set(C, bmain); diff --git a/source/blender/blenkernel/intern/bmfont.c b/source/blender/blenkernel/intern/bmfont.c index 8018629ef2a..c99894bfbaf 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 eb5cdd02fe5..8fdaf183b06 100644 --- a/source/blender/blenkernel/intern/boids.c +++ b/source/blender/blenkernel/intern/boids.c @@ -277,7 +277,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 */ @@ -287,7 +287,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); @@ -327,7 +327,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 */ @@ -337,7 +337,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); @@ -395,7 +395,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); @@ -497,13 +497,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) { @@ -560,13 +560,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; } @@ -612,7 +612,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); @@ -622,7 +622,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) @@ -662,7 +662,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; n<neighbors; n++) { @@ -776,7 +776,7 @@ static Object *boid_find_ground(BoidBrainData *bbd, ParticleData *pa, float grou if (bpa->data.mode == eBoidMode_Climbing) { SurfaceModifierData *surmd = NULL; float x[3], v[3]; - + surmd = (SurfaceModifierData *)modifiers_findByType(bpa->ground, eModifierType_Surface ); /* take surface velocity into account */ @@ -869,10 +869,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; @@ -1050,7 +1050,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]; @@ -1166,7 +1166,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; @@ -1227,7 +1227,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 @@ -1274,7 +1274,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. */ @@ -1289,7 +1289,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); @@ -1468,7 +1468,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); diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index 7f50e521e63..42cd7968321 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/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c index e8328139d64..1a7c4e2a4a0 100644 --- a/source/blender/blenkernel/intern/bvhutils.c +++ b/source/blender/blenkernel/intern/bvhutils.c @@ -79,7 +79,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]; @@ -110,7 +110,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; @@ -194,7 +194,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) @@ -287,7 +287,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; diff --git a/source/blender/blenkernel/intern/cachefile.c b/source/blender/blenkernel/intern/cachefile.c index 74c0dca6279..c7d7a3a98eb 100644 --- a/source/blender/blenkernel/intern/cachefile.c +++ b/source/blender/blenkernel/intern/cachefile.c @@ -217,7 +217,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 b1b4f18a6d5..d1ab559515b 100644 --- a/source/blender/blenkernel/intern/camera.c +++ b/source/blender/blenkernel/intern/camera.c @@ -161,7 +161,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 7bcc05b0e37..72a1f941c26 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -284,7 +284,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 @@ -305,7 +305,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, @@ -434,7 +434,7 @@ static void cdDM_foreachMappedFaceCenter( else { orig = i; } - + ml = &cddm->mloop[mp->loopstart]; BKE_mesh_calc_poly_center(mp, ml, mvert, cent); @@ -723,7 +723,7 @@ static void loops_to_customdata_corners( for (i = 0; i < numUV; i++) { texface = CustomData_get_n(facedata, CD_MTFACE, cdindex, i); - + for (j = 0; j < 3; j++) { l = l3[j]; mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPUV, i); @@ -733,7 +733,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); @@ -780,18 +780,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; @@ -882,7 +882,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) { @@ -1585,7 +1585,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) { @@ -1622,7 +1622,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 */ @@ -1663,7 +1663,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 */ @@ -1867,7 +1867,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 */ @@ -1878,11 +1878,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++) { @@ -1896,7 +1896,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++) { @@ -1906,19 +1906,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)); @@ -1946,7 +1946,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 @@ -1966,7 +1966,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); @@ -2212,7 +2212,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 cc1c7260cbc..c5d9472ca4b 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -80,7 +80,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh ); * 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; @@ -91,7 +91,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; @@ -107,7 +107,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; @@ -155,27 +155,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; } @@ -194,10 +194,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; @@ -218,23 +218,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++) { @@ -257,25 +257,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; @@ -304,7 +304,7 @@ void bvhselftree_update_from_cloth(ClothModifierData *clmd, bool moving) break; } } - + BLI_bvhtree_update_tree(bvhtree); } } @@ -312,13 +312,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); } @@ -335,13 +335,13 @@ static int do_init_cloth(Object *ob, ClothModifierData *clmd, Mesh *result, int 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; @@ -387,7 +387,7 @@ static int do_step_cloth(struct Depsgraph *depsgraph, Object *ob, ClothModifierD cloth_update_spring_lengths ( clmd, result ); cloth_update_springs( clmd ); - + // TIMEIT_START(cloth_step) /* call the solver. */ @@ -398,7 +398,7 @@ static int do_step_cloth(struct Depsgraph *depsgraph, Object *ob, ClothModifierD pdEndEffectors(&effectors); // printf ( "%f\n", ( float ) tval() ); - + return ret; } @@ -429,7 +429,7 @@ void clothModifier_do(ClothModifierData *clmd, struct Depsgraph *depsgraph, Scen 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; @@ -507,13 +507,13 @@ void clothModifier_do(ClothModifierData *clmd, struct Depsgraph *depsgraph, Scen void cloth_free_modifier(ClothModifierData *clmd ) { Cloth *cloth = NULL; - + if ( !clmd ) return; cloth = clmd->clothObject; - + if ( cloth ) { BPH_cloth_solver_free(clmd); @@ -529,12 +529,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; } @@ -544,7 +544,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 ); @@ -554,8 +554,8 @@ void cloth_free_modifier(ClothModifierData *clmd ) if (cloth->edgeset) BLI_edgeset_free(cloth->edgeset); - - + + /* if (clmd->clothObject->facemarks) MEM_freeN(clmd->clothObject->facemarks); @@ -571,12 +571,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"); @@ -610,7 +610,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 ); @@ -660,11 +660,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) || @@ -693,7 +693,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh ) mvert_num = mesh->totvert; verts = clothObj->verts; - + if (cloth_uses_vgroup(clmd)) { for (i = 0; i < mvert_num; i++, verts++) { @@ -717,21 +717,21 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh ) 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; } @@ -786,7 +786,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl 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) @@ -837,9 +837,9 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl 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 ) @@ -859,7 +859,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl 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, mesh); @@ -870,19 +870,19 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl 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 < mesh->totvert; 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; @@ -958,17 +958,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; @@ -981,10 +981,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 @@ -992,17 +992,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) { @@ -1013,39 +1013,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; } } @@ -1056,10 +1056,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 @@ -1067,17 +1067,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) { @@ -1088,18 +1088,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; } } @@ -1148,10 +1148,10 @@ static void cloth_update_springs( ClothModifierData *clmd ) spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE; } } - + search = search->next; } - + cloth_hair_update_bending_targets(clmd); } @@ -1243,10 +1243,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); } @@ -1268,7 +1268,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) LinkNodePair *edgelist; EdgeSet *edgeset = NULL; LinkNode *search = NULL, *search2 = NULL; - + // error handling if ( numedges==0 ) return 0; @@ -1282,7 +1282,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) cloth->edgeset = NULL; edgelist = MEM_callocN(sizeof(*edgelist) * mvert_num, "cloth_edgelist_alloc" ); - + if (!edgelist) return 0; @@ -1314,7 +1314,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) spring->flags = 0; struct_springs++; - + BLI_linklist_prepend ( &cloth->springs, spring ); } else { @@ -1325,7 +1325,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) 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); @@ -1415,15 +1415,15 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) 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; @@ -1431,10 +1431,10 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) 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; } @@ -1452,33 +1452,33 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) 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) */ @@ -1492,10 +1492,10 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) 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 diff --git a/source/blender/blenkernel/intern/collection.c b/source/blender/blenkernel/intern/collection.c index ab0ec8b0491..eef4a6210c8 100644 --- a/source/blender/blenkernel/intern/collection.c +++ b/source/blender/blenkernel/intern/collection.c @@ -297,20 +297,6 @@ void BKE_collection_new_name_get(Collection *collection_parent, char *rname) MEM_freeN(name); } -/************************* Dependencies ****************************/ - -bool BKE_collection_is_animated(Collection *collection, Object *UNUSED(parent)) -{ - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, object) - { - if (object->proxy) { - return true; - } - } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; - return false; -} - /* **************** Object List Cache *******************/ static void collection_object_cache_fill(ListBase *lb, Collection *collection, int parent_restrict) @@ -323,20 +309,21 @@ static void collection_object_cache_fill(ListBase *lb, Collection *collection, i if (base == NULL) { base = MEM_callocN(sizeof(Base), "Object Base"); base->object = cob->ob; + BLI_addtail(lb, base); + } - if ((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) { - base->flag |= BASE_VISIBLED | BASE_VISIBLE_VIEWPORT; - - if ((child_restrict & COLLECTION_RESTRICT_SELECT) == 0) { - base->flag |= BASE_SELECTABLED; - } - } + int object_restrict = base->object->restrictflag; - if ((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) { - base->flag |= BASE_VISIBLE_RENDER; - } + if (((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) && + ((object_restrict & OB_RESTRICT_VIEW) == 0)) + { + base->flag |= BASE_VISIBLE_VIEWPORT; + } - BLI_addtail(lb, base); + if (((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) && + ((object_restrict & OB_RESTRICT_RENDER) == 0)) + { + base->flag |= BASE_VISIBLE_RENDER; } } @@ -377,7 +364,7 @@ void BKE_collection_object_cache_free(Collection *collection) collection_object_cache_free(collection); } -Base *BKE_collection_or_layer_objects(Depsgraph *depsgraph, +Base *BKE_collection_or_layer_objects(const Depsgraph *depsgraph, const Scene *scene, const ViewLayer *view_layer, Collection *collection) @@ -623,7 +610,7 @@ static bool scene_collections_object_remove(Main *bmain, Scene *scene, Object *o { bool removed = false; - BKE_scene_remove_rigidbody_object(scene, ob); + BKE_scene_remove_rigidbody_object(bmain, scene, ob); FOREACH_SCENE_COLLECTION_BEGIN(scene, collection) { diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c index b23b1b2dbed..38cb1a1de16 100644 --- a/source/blender/blenkernel/intern/collision.c +++ b/source/blender/blenkernel/intern/collision.c @@ -446,7 +446,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, @@ -489,14 +489,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)++; } @@ -515,13 +515,13 @@ 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, Collection *collection, unsigned int *numcollobj, unsigned int modifier_type, bool dupli) { Object **objs; unsigned int numobj= 0, maxobj= 100; int level = dupli ? 0 : 1; - + objs= MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray"); /* gather all collision objects */ @@ -566,7 +566,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"); @@ -595,7 +595,7 @@ static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, ListBase *get_collider_cache(Scene *scene, Object *self, Collection *collection) { ListBase *objs= NULL; - + /* add object in same layer in scene */ if (collection) { FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, object) @@ -633,7 +633,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; @@ -650,10 +650,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 */ @@ -699,7 +699,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; @@ -711,9 +711,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; @@ -731,31 +731,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; @@ -765,11 +765,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); @@ -789,8 +789,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 //////////////////////////////////////////////////////////// @@ -799,15 +799,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); @@ -817,12 +817,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 ) ) @@ -836,20 +836,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 ); @@ -861,7 +861,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; @@ -871,10 +871,10 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa // check for approximated time collisions } } - + if ( overlap ) MEM_freeN ( overlap ); - + } } //////////////////////////////////////////////////////////// @@ -893,7 +893,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); @@ -910,14 +910,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); @@ -930,7 +930,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]; @@ -984,20 +984,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)); @@ -1007,10 +1007,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; @@ -1028,21 +1028,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 */ @@ -1099,7 +1099,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); @@ -1107,7 +1107,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; @@ -1115,20 +1115,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; } @@ -1163,7 +1163,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; @@ -1182,11 +1182,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++) { @@ -1196,13 +1196,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; } @@ -1218,32 +1218,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]; @@ -1257,12 +1257,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]; @@ -1270,35 +1270,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); @@ -1320,7 +1320,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); @@ -1336,53 +1336,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; @@ -1391,46 +1391,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) { @@ -1438,11 +1438,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 6c97380b9ca..ff4795afe87 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 fe60d53a9a2..ac47a9e0756 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -30,7 +30,7 @@ */ -#include <stdio.h> +#include <stdio.h> #include <stddef.h> #include <string.h> #include <math.h> @@ -122,14 +122,14 @@ void BKE_constraint_unique_name(bConstraint *con, ListBase *list) bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, 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; cob->depsgraph = depsgraph; - + /* based on type of available data */ switch (datatype) { case CONSTRAINT_OBTYPE_OBJECT: @@ -138,7 +138,7 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O 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 @@ -156,7 +156,7 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O } else unit_m4(cob->matrix); - + copy_m4_m4(cob->startmat, cob->matrix); break; } @@ -167,7 +167,7 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O 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; @@ -176,13 +176,13 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O /* 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; } @@ -199,11 +199,11 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O 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 @@ -211,7 +211,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: @@ -220,7 +220,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); } @@ -232,21 +232,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. */ @@ -255,12 +255,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 */ @@ -270,7 +270,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 */ @@ -306,7 +306,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 */ @@ -321,7 +321,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 */ @@ -342,7 +342,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 @@ -357,7 +357,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); } @@ -370,7 +370,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... */ @@ -379,7 +379,7 @@ void BKE_constraint_mat_convertspace( normalize_m4(diff_mat); } zero_v3(diff_mat[3]); - + mul_m4_m4m4(mat, diff_mat, mat); } } @@ -398,10 +398,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; @@ -413,18 +413,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; @@ -448,22 +448,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]); @@ -475,12 +475,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); @@ -490,25 +490,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. */ @@ -523,17 +523,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); } @@ -549,7 +549,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. * @@ -567,7 +567,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 @@ -583,22 +583,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); @@ -607,45 +607,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); } @@ -656,7 +656,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 @@ -685,7 +685,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(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *UNUSED(cob), bConstraintTarget *ct, float UNUSED(ctime)) @@ -696,7 +696,7 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint 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) @@ -729,8 +729,8 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint \ 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) @@ -769,7 +769,7 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint 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) @@ -795,7 +795,7 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint 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); @@ -805,7 +805,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); } @@ -815,13 +815,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; } @@ -830,7 +830,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); } @@ -844,16 +844,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); @@ -862,19 +862,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; @@ -885,22 +885,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. */ @@ -932,15 +932,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); } @@ -950,13 +950,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; } @@ -965,7 +965,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); } @@ -975,14 +975,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; } @@ -1038,14 +1038,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 */ @@ -1059,14 +1059,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; @@ -1077,12 +1077,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); @@ -1110,7 +1110,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; @@ -1121,10 +1121,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); } @@ -1134,14 +1134,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; } @@ -1150,7 +1150,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); @@ -1160,13 +1160,13 @@ static void kinematic_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void kinematic_get_tarmat(struct Depsgraph *UNUSED(depsgraph), 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); } @@ -1203,7 +1203,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; @@ -1213,7 +1213,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); } @@ -1223,13 +1223,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; } @@ -1238,7 +1238,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); } @@ -1249,7 +1249,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), 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; @@ -1258,7 +1258,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), 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) */ if (ct->tar->curve_cache && ct->tar->curve_cache->path && ct->tar->curve_cache->path->data) { @@ -1267,9 +1267,9 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), /* 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 @@ -1292,7 +1292,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), /* 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); @@ -1301,7 +1301,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), #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]); @@ -1322,9 +1322,9 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), 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); } } @@ -1336,27 +1336,27 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), 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]); @@ -1389,7 +1389,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; @@ -1407,7 +1407,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) { @@ -1439,37 +1439,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); } @@ -1495,40 +1495,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]); } @@ -1552,14 +1552,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); } @@ -1569,13 +1569,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; } @@ -1584,7 +1584,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); } @@ -1594,28 +1594,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]; } @@ -1642,14 +1642,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); } @@ -1659,13 +1659,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; } @@ -1674,7 +1674,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); } @@ -1684,50 +1684,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); @@ -1754,14 +1754,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); } @@ -1771,13 +1771,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; } @@ -1786,7 +1786,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); } @@ -1796,13 +1796,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); @@ -1850,7 +1850,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); } @@ -1860,13 +1860,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; } @@ -1875,7 +1875,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); } @@ -1884,7 +1884,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); @@ -1925,12 +1925,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: @@ -1968,20 +1968,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); } @@ -1989,7 +1989,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; @@ -1999,13 +1999,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; } @@ -2013,11 +2013,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); } @@ -2041,7 +2041,7 @@ static void pycon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), * 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) @@ -2059,19 +2059,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 */ @@ -2097,7 +2097,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; } @@ -2105,10 +2105,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); } @@ -2118,13 +2118,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; } @@ -2133,7 +2133,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); } @@ -2142,18 +2142,18 @@ static void actcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), 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) @@ -2176,21 +2176,21 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint * 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); @@ -2201,21 +2201,21 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint * 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); } @@ -2229,10 +2229,10 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint * 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. */ @@ -2261,15 +2261,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); } @@ -2279,13 +2279,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; } @@ -2294,7 +2294,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); } @@ -2304,14 +2304,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) { @@ -2324,10 +2324,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; @@ -2338,10 +2338,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; @@ -2353,10 +2353,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; @@ -2368,10 +2368,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; @@ -2393,7 +2393,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]); @@ -2407,10 +2407,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; @@ -2422,10 +2422,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; @@ -2437,10 +2437,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; @@ -2462,10 +2462,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; @@ -2476,10 +2476,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; @@ -2491,10 +2491,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; @@ -2506,10 +2506,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; @@ -2536,14 +2536,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); } @@ -2569,14 +2569,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); } @@ -2586,13 +2586,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; } @@ -2601,7 +2601,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); } @@ -2611,19 +2611,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 */ @@ -2650,7 +2650,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; } } @@ -2661,12 +2661,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); } @@ -2693,10 +2693,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; @@ -2705,7 +2705,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); } @@ -2715,13 +2715,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; } @@ -2730,7 +2730,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); } @@ -2740,51 +2740,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); } } @@ -2792,15 +2792,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: @@ -2823,7 +2823,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; @@ -2834,10 +2834,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) { @@ -2846,10 +2846,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); @@ -2859,16 +2859,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); } } @@ -2893,7 +2893,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); @@ -2903,7 +2903,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); } @@ -2913,13 +2913,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; } @@ -2928,7 +2928,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); } @@ -2938,16 +2938,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); @@ -2955,7 +2955,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]; @@ -2990,7 +2990,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) { @@ -3037,7 +3037,7 @@ static bConstraintTypeInfo CTI_MINMAX = { static void clampto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bClampToConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3047,13 +3047,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; } @@ -3062,7 +3062,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); } @@ -3083,33 +3083,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. @@ -3121,15 +3121,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 */ @@ -3165,19 +3165,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]); } @@ -3203,7 +3203,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; @@ -3212,7 +3212,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); } @@ -3222,13 +3222,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; } @@ -3237,7 +3237,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); } @@ -3247,21 +3247,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. @@ -3283,12 +3283,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++) { @@ -3308,8 +3308,8 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sval[i] = 0.0f; } } - - + + /* apply transforms */ switch (data->to) { case TRANS_SCALE: @@ -3340,7 +3340,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); } @@ -3366,7 +3366,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); } @@ -3384,12 +3384,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; } @@ -3399,7 +3399,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); } } @@ -3408,22 +3408,22 @@ static void shrinkwrap_flush_tars(bConstraint *con, ListBase *list, bool no_copy static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), 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: @@ -3438,16 +3438,16 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai 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 */ @@ -3474,7 +3474,7 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai 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. */ @@ -3505,14 +3505,14 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai 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); @@ -3523,7 +3523,7 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai 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]); @@ -3550,14 +3550,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); } @@ -3567,13 +3567,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; } @@ -3582,7 +3582,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); } @@ -3598,60 +3598,60 @@ 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); - + 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); - + /* 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); } @@ -3677,17 +3677,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); } @@ -3705,7 +3705,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); } @@ -3715,13 +3715,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; } @@ -3730,7 +3730,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); } @@ -3767,7 +3767,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); } @@ -3777,13 +3777,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; } @@ -3792,7 +3792,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); } @@ -3802,20 +3802,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) */ @@ -3828,7 +3828,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 */ @@ -3845,7 +3845,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); @@ -4413,7 +4413,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)) @@ -4424,10 +4424,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. */ @@ -4444,7 +4444,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 */ @@ -4462,17 +4462,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); } @@ -4487,11 +4487,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); } @@ -4547,11 +4547,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); } @@ -4560,10 +4560,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; } @@ -4573,27 +4573,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); } @@ -4612,7 +4612,7 @@ static bConstraint *add_new_constraint(Object *ob, bPoseChannel *pchan, const ch break; } } - + return con; } @@ -4623,7 +4623,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); } @@ -4639,10 +4639,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); @@ -4733,7 +4733,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) { @@ -4741,7 +4741,7 @@ bConstraint *BKE_constraints_active_get(ListBase *list) return con; } } - + /* no active constraint found */ return NULL; } @@ -4750,12 +4750,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; } } @@ -4767,11 +4767,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); @@ -4787,7 +4787,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; @@ -4797,7 +4797,7 @@ bool BKE_constraints_proxylocked_owner(Object *ob, bPoseChannel *pchan) return true; } } - + return false; } @@ -4816,7 +4816,7 @@ void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, Scene *scene, ListBase targets = {NULL, NULL}; bConstraintOb *cob; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { /* make 'constraint-ob' */ cob = MEM_callocN(sizeof(bConstraintOb), "tempConstraintOb"); @@ -4853,19 +4853,19 @@ void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, Scene *scene, 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(depsgraph, 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); @@ -4881,17 +4881,17 @@ void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, Scene *scene, void BKE_constraint_targets_for_solving_get(struct Depsgraph *depsgraph, 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) { @@ -4904,7 +4904,7 @@ void BKE_constraint_targets_for_solving_get(struct Depsgraph *depsgraph, bConstr } } } - + /* ---------- Evaluation ----------- */ /* This function is called whenever constraints need to be evaluated. Currently, all @@ -4922,12 +4922,12 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, ListBase *conlist, bCons /* 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; @@ -4935,37 +4935,37 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, ListBase *conlist, bCons 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(depsgraph, 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 6314486d809..ee907fa496f 100644 --- a/source/blender/blenkernel/intern/context.c +++ b/source/blender/blenkernel/intern/context.c @@ -84,7 +84,7 @@ struct bContext { struct bContextStore *store; const char *operator_poll_msg; /* reason for poll failing */ } wm; - + /* data context */ struct { struct Main *main; @@ -94,7 +94,7 @@ struct bContext { int py_init; /* true if python is initialized */ void *py_context; } data; - + /* data evaluation */ #if 0 struct { @@ -108,7 +108,7 @@ struct bContext { bContext *CTX_create(void) { bContext *C; - + C = MEM_callocN(sizeof(bContext), "bContext"); return C; @@ -424,7 +424,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; } @@ -465,13 +465,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); diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c index 01da9857864..f6dd630e077 100644 --- a/source/blender/blenkernel/intern/curve.c +++ b/source/blender/blenkernel/intern/curve.c @@ -1028,7 +1028,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' */ @@ -2138,7 +2138,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; } @@ -2148,7 +2148,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); @@ -2683,10 +2683,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 */ @@ -4962,7 +4962,7 @@ bool BKE_curve_minmax(Curve *cu, bool use_radius, float min[3], float max[3]) */ if (is_font) { nurb_lb = &temp_nurb_lb; - BKE_vfont_to_curve_ex(G.main, NULL, cu, FO_EDIT, nurb_lb, + BKE_vfont_to_curve_ex(NULL, cu, FO_EDIT, nurb_lb, NULL, NULL, NULL, NULL); use_radius = false; } diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c index aa67eafaa98..b9328051699 100644 --- a/source/blender/blenkernel/intern/customdata.c +++ b/source/blender/blenkernel/intern/customdata.c @@ -526,7 +526,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; } @@ -631,7 +631,7 @@ static void layerCopy_grid_paint_mask(const void *source, void *dest, int count) d[i].data = NULL; d[i].level = 0; } - + } } @@ -742,7 +742,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; @@ -1005,7 +1005,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; @@ -1033,7 +1033,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); @@ -1078,7 +1078,7 @@ static void layerInterp_bweight( float f; float **in = (float **)sources; int i; - + if (count <= 0) return; f = 0.0f; @@ -1129,7 +1129,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; @@ -1224,18 +1224,18 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL}, /* 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, @@ -1480,10 +1480,10 @@ bool CustomData_merge( 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; @@ -1562,7 +1562,7 @@ void CustomData_free(CustomData *data, int totelem) if (data->layers) MEM_freeN(data->layers); - + CustomData_external_free(data); CustomData_reset(data); } @@ -1866,7 +1866,7 @@ static CustomDataLayer *customData_add_layer__internal( return NULL; } } - + data->totlayer++; /* keep layers ordered by type */ @@ -1896,7 +1896,7 @@ static CustomDataLayer *customData_add_layer__internal( data->layers[index].active_clone = 0; data->layers[index].active_mask = 0; } - + customData_update_offsets(data); return &data->layers[index]; @@ -1908,7 +1908,7 @@ void *CustomData_add_layer( { CustomDataLayer *layer; const LayerTypeInfo *typeInfo = layerType_getInfo(type); - + layer = customData_add_layer__internal(data, type, alloctype, layerdata, totelem, typeInfo->defaultname); CustomData_update_typemap(data); @@ -1925,7 +1925,7 @@ void *CustomData_add_layer_named( void *layerdata, int totelem, const char *name) { CustomDataLayer *layer; - + layer = customData_add_layer__internal(data, type, alloctype, layerdata, totelem, name); CustomData_update_typemap(data); @@ -2010,7 +2010,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; } @@ -2229,7 +2229,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 @@ -2367,7 +2367,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 */ @@ -2446,9 +2446,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; } @@ -2836,7 +2836,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) { @@ -2878,7 +2878,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; @@ -2889,7 +2889,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; @@ -2908,13 +2908,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; } @@ -3187,7 +3187,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) { @@ -3389,7 +3389,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; @@ -3402,7 +3402,7 @@ static bool cd_layer_find_dupe(CustomData *data, const char *name, int type, int } } } - + return false; } @@ -3413,7 +3413,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); @@ -3483,7 +3483,7 @@ bool CustomData_verify_versions(struct CustomData *data, int index) static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external) { BLI_strncpy(filename, external->filename, FILE_MAX); - BLI_path_abs(filename, ID_BLEND_PATH(G.main, id)); + BLI_path_abs(filename, ID_BLEND_PATH_FROM_GLOBAL(id)); } void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem) @@ -3519,7 +3519,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 d17c9ef5cc6..aa762865a2a 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; } diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c index d4ff9bd5c0c..2da157d5b88 100644 --- a/source/blender/blenkernel/intern/deform.c +++ b/source/blender/blenkernel/intern/deform.c @@ -1192,7 +1192,12 @@ bool data_transfer_layersmapping_vgroups( if (fromlayers >= 0) { idx_src = fromlayers; - BLI_assert(idx_src < BLI_listbase_count(&ob_src->defbase)); + if (idx_src >= BLI_listbase_count(&ob_src->defbase)) { + /* This can happen when vgroups are removed from source object... + * Remapping would be really tricky here, we'd need to go over all objects in Main everytime we delete + * a vgroup... for now, simpler and safer to abort. */ + return false; + } } else if ((idx_src = ob_src->actdef - 1) == -1) { return false; diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c index 5e812d4e5d0..ad055a727a9 100644 --- a/source/blender/blenkernel/intern/displist.c +++ b/source/blender/blenkernel/intern/displist.c @@ -1573,7 +1573,7 @@ static void do_makeDispListCurveTypes( } if (ob->type == OB_FONT) { - BKE_vfont_to_curve_nubase(G.main, ob, FO_EDIT, &nubase); + BKE_vfont_to_curve_nubase(ob, FO_EDIT, &nubase); } else { BKE_nurbList_duplicate(&nubase, BKE_curve_nurbs_get(cu)); diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c index 0b2c65a7b8d..ed2566c9bb5 100644 --- a/source/blender/blenkernel/intern/dynamicpaint.c +++ b/source/blender/blenkernel/intern/dynamicpaint.c @@ -490,9 +490,9 @@ static void scene_setSubframe(Scene *scene, float subframe) scene->r.subframe = subframe; } -static int surface_getBrushFlags(DynamicPaintSurface *surface, const ViewLayer *view_layer) +static int surface_getBrushFlags(DynamicPaintSurface *surface, const Depsgraph *depsgraph) { - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, surface->brush_group); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, surface->brush_group); Object *brushObj = NULL; ModifierData *md = NULL; @@ -5758,7 +5758,7 @@ static void dynamic_paint_generate_bake_data_cb( } } -static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const ViewLayer *view_layer, Object *ob) +static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const Depsgraph *depsgraph, Object *ob) { PaintSurfaceData *sData = surface->data; PaintBakeData *bData = sData->bData; @@ -5766,7 +5766,7 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const Vie int index; bool new_bdata = false; const bool do_velocity_data = ((surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) || - (surface_getBrushFlags(surface, view_layer) & BRUSH_USES_VELOCITY)); + (surface_getBrushFlags(surface, depsgraph) & BRUSH_USES_VELOCITY)); const bool do_accel_data = (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) != 0; int canvasNumOfVerts = dm->getNumVerts(dm); @@ -5912,8 +5912,7 @@ static int dynamicPaint_doStep( { Object *brushObj = NULL; ModifierData *md = NULL; - ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, surface->brush_group); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, surface->brush_group); /* backup current scene frame */ int scene_frame = scene->r.cfra; @@ -6051,8 +6050,7 @@ int dynamicPaint_calculateFrame( dynamicPaint_applySurfaceDisplace(surface, surface->canvas->dm); /* update bake data */ - ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - dynamicPaint_generateBakeData(surface, view_layer, cObject); + dynamicPaint_generateBakeData(surface, depsgraph, cObject); /* don't do substeps for first frame */ if (surface->substeps && (frame != surface->start_frame)) { diff --git a/source/blender/blenkernel/intern/editmesh_bvh.c b/source/blender/blenkernel/intern/editmesh_bvh.c index e68f11f6274..c1121d5b1ea 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) { diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c index bdf6e84a3b1..7e506570b7e 100644 --- a/source/blender/blenkernel/intern/effect.c +++ b/source/blender/blenkernel/intern/effect.c @@ -219,10 +219,6 @@ ListBase *pdInitEffectors( ListBase *effectors = NULL; for (; base; base = base->next) { - if ((base->flag & BASE_VISIBLED) == 0) { - continue; - } - if (base->object->pd && base->object->pd->forcefield) { add_object_to_effectors(&effectors, depsgraph, scene, weights, base->object, ob_src, for_simulation); } @@ -318,7 +314,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; @@ -377,7 +373,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; @@ -391,7 +387,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; @@ -403,7 +399,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; @@ -426,7 +422,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; } @@ -435,7 +431,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect if (!colliders) free_collider_cache(&colls); - + return visibility; } @@ -446,11 +442,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; } @@ -543,7 +539,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); @@ -625,7 +621,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); @@ -698,9 +694,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 @@ -862,10 +858,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); } @@ -893,7 +889,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 */ @@ -998,7 +994,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! */ @@ -1007,7 +1003,7 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we for (; p<tot; p+=step) { if (get_effector_data(eff, &efd, point, 0)) { efd.falloff= effector_falloff(eff, &efd, point, weights); - + if (efd.falloff > 0.0f) efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point); @@ -1022,7 +1018,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); @@ -1135,14 +1131,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; @@ -1162,7 +1158,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); } @@ -1171,7 +1167,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); } @@ -1180,7 +1176,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); } @@ -1188,17 +1184,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 0de04e31be9..e63d99a35ee 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -29,7 +29,7 @@ * \ingroup bke */ - + #include <math.h> #include <stdio.h> @@ -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,33 +1904,34 @@ 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; } /* Evaluate an Channel-Driver to get a 'time' value to use instead of "evaltime" * - "evaltime" is the frame at which F-Curve is being evaluated * - has to return a float value + * - driver_orig is where we cache Python expressions, in case of COW */ -float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const float evaltime) +float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, ChannelDriver *driver_orig, const float evaltime) { DriverVar *dvar; - + /* check if driver can be evaluated */ - if (driver->flag & DRIVER_FLAG_INVALID) + if (driver_orig->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 +1946,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 +1965,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 +1990,7 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl value = tmp_val; } } - + /* store value in driver */ driver->curval = value; break; @@ -1998,8 +1999,8 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl { #ifdef WITH_PYTHON /* check for empty or invalid expression */ - if ( (driver->expression[0] == '\0') || - (driver->flag & DRIVER_FLAG_INVALID) ) + if ( (driver_orig->expression[0] == '\0') || + (driver_orig->flag & DRIVER_FLAG_INVALID) ) { driver->curval = 0.0f; } @@ -2009,7 +2010,7 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl */ BLI_mutex_lock(&python_driver_lock); - driver->curval = BPY_driver_exec(anim_rna, driver, evaltime); + driver->curval = BPY_driver_exec(anim_rna, driver, driver_orig, evaltime); BLI_mutex_unlock(&python_driver_lock); } @@ -2020,14 +2021,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 +2042,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 +2058,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 +2087,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 +2097,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 +2121,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 +2136,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 +2159,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 +2167,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 +2218,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 +2234,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 +2243,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 +2260,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 +2272,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 +2286,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 +2295,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 +2312,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 +2324,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 +2333,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 +2343,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 +2358,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 +2375,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 +2396,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 +2409,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 +2422,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 +2440,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 +2458,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 +2476,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 +2494,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 +2512,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 +2530,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 +2548,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 +2566,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 +2584,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 +2602,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 +2620,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 +2630,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 +2646,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 +2674,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 +2694,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; } @@ -2705,7 +2706,7 @@ float evaluate_fcurve(FCurve *fcu, float evaltime) return evaluate_fcurve_ex(fcu, evaltime, 0.0); } -float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime) +float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, ChannelDriver *driver_orig, float evaltime) { BLI_assert(fcu->driver != NULL); float cvalue = 0.0f; @@ -2715,7 +2716,7 @@ float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evalt */ if (fcu->driver) { /* evaltime now serves as input for the curve */ - evaltime = evaluate_driver(anim_rna, fcu->driver, evaltime); + evaltime = evaluate_driver(anim_rna, fcu->driver, driver_orig, evaltime); /* only do a default 1-1 mapping if it's unlikely that anything else will set a value... */ if (fcu->totvert == 0) { @@ -2753,7 +2754,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)) || @@ -2762,7 +2763,7 @@ float calculate_fcurve(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime) /* calculate and set curval (evaluates driver too if necessary) */ float curval; if (fcu->driver) { - curval = evaluate_fcurve_driver(anim_rna, fcu, evaltime); + curval = evaluate_fcurve_driver(anim_rna, fcu, fcu->driver, evaltime); } else { curval = evaluate_fcurve(fcu, evaltime); diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c index f3d0a5fe085..b69bce088d2 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 f7ab5415d1c..36633663f9d 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -148,12 +148,12 @@ 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); } } -static VFontData *vfont_get_data(Main *bmain, VFont *vfont) +static VFontData *vfont_get_data(VFont *vfont) { if (vfont == NULL) { return NULL; @@ -188,10 +188,10 @@ static VFontData *vfont_get_data(Main *bmain, VFont *vfont) } } else { - pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id)); + pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH_FROM_GLOBAL(&vfont->id)); if (vfont->temp_pf == NULL) { - vfont->temp_pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id)); + vfont->temp_pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH_FROM_GLOBAL(&vfont->id)); } } if (!pf) { @@ -205,7 +205,7 @@ static VFontData *vfont_get_data(Main *bmain, 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,14 +348,14 @@ 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) { + + 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); + + return BKE_vfont_load(G_MAIN, FO_BUILTIN_NAME); } static VChar *find_vfont_char(VFontData *vfd, unsigned int character) @@ -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; @@ -423,7 +423,7 @@ static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect, mul_v2_fl(bp[3].vec, cu->fsize); } -static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int character, CharInfo *info, +static void buildchar(Curve *cu, ListBase *nubase, unsigned int character, CharInfo *info, float ofsx, float ofsy, float rot, int charidx) { BezTriple *bezt1, *bezt2; @@ -433,7 +433,7 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha VChar *che = NULL; int i; - vfd = vfont_get_data(bmain, which_vfont(cu, info)); + vfd = vfont_get_data(which_vfont(cu, info)); if (!vfd) return; #if 0 @@ -454,7 +454,7 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha 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(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha } 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(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha 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); @@ -635,7 +635,7 @@ struct TempLineInfo { int wspace_nr; /* number of whitespaces of line */ }; -bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBase *r_nubase, +bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, const wchar_t **r_text, int *r_text_len, bool *r_text_free, struct CharTrans **r_chartransdata) { @@ -677,11 +677,11 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBas if (cu->str == NULL) return ok; if (vfont == NULL) return ok; - vfd = vfont_get_data(bmain, vfont); + vfd = vfont_get_data(vfont); /* 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(Main *bmain, Object *ob, Curve *cu, int mode, ListBas /* 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); @@ -770,7 +770,7 @@ makebreak: if (vfont == NULL) break; if (vfont != oldvfont) { - vfd = vfont_get_data(bmain, vfont); + vfd = vfont_get_data(vfont); oldvfont = vfont; } @@ -886,7 +886,7 @@ makebreak: } else if (ascii == 9) { /* TAB */ float tabfac; - + ct->xof = xof; ct->yof = yof; ct->linenr = lnr; @@ -911,27 +911,27 @@ makebreak: 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 @@ makebreak: 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 @@ makebreak: 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 @@ makebreak: } 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 @@ makebreak: } che = find_vfont_char(vfd, ascii); - + twidth = char_width(cu, che, info); dtime = distfac * 0.5f * twidth; @@ -1156,16 +1156,16 @@ makebreak: /* 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 @@ makebreak: } } } - + /* 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 @@ makebreak: 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]; @@ -1274,7 +1274,7 @@ makebreak: } /* We do not want to see any character for \n or \r */ if (cha != '\n') - buildchar(bmain, cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i); + buildchar(cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i); if ((info->flag & CU_CHINFO_UNDERLINE) && (cha != '\n')) { float ulwidth, uloverlap = 0.0f; @@ -1340,19 +1340,19 @@ finally: } -bool BKE_vfont_to_curve_nubase(Main *bmain, Object *ob, int mode, ListBase *r_nubase) +bool BKE_vfont_to_curve_nubase(Object *ob, int mode, ListBase *r_nubase) { BLI_assert(ob->type == OB_FONT); - return BKE_vfont_to_curve_ex(bmain, ob, ob->data, mode, r_nubase, + return BKE_vfont_to_curve_ex(ob, ob->data, mode, r_nubase, NULL, NULL, NULL, NULL); } -bool BKE_vfont_to_curve(Main *bmain, Object *ob, int mode) +bool BKE_vfont_to_curve(Object *ob, int mode) { Curve *cu = ob->data; - return BKE_vfont_to_curve_ex(bmain, ob, ob->data, mode, &cu->nurb, NULL, NULL, NULL, NULL); + return BKE_vfont_to_curve_ex(ob, ob->data, mode, &cu->nurb, NULL, NULL, NULL, NULL); } diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index ee0d0b41898..e89508fd6c0 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -27,7 +27,7 @@ * \ingroup bke */ - + #include <stdio.h> #include <string.h> #include <stdlib.h> @@ -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; } @@ -622,21 +622,21 @@ bGPDpalettecolor *BKE_gpencil_palettecolor_addnew(bGPDpalette *palette, const ch } /* add a new gp-datablock */ -bGPdata *BKE_gpencil_data_addnew(const char name[]) +bGPdata *BKE_gpencil_data_addnew(Main *bmain, const char name[]) { bGPdata *gpd; - + /* allocate memory for a new block */ - gpd = BKE_libblock_alloc(G.main, ID_GD, name, 0); - + 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; } @@ -805,6 +805,7 @@ bGPdata *BKE_gpencil_data_duplicate(Main *bmain, const bGPdata *gpd_src, bool in return gpd_dst; } else { + BLI_assert(bmain != NULL); bGPdata *gpd_copy; BKE_id_copy_ex(bmain, &gpd_src->id, (ID **)&gpd_copy, 0, false); return gpd_copy; @@ -823,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; @@ -848,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); @@ -873,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" @@ -883,7 +884,7 @@ bool gpencil_layer_is_editable(const bGPDlayer *gpl) return true; } } - + /* Something failed */ return false; } @@ -892,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 */ @@ -901,7 +902,7 @@ bGPDframe *BKE_gpencil_layer_find_frame(bGPDlayer *gpl, int cframe) return gpf; } } - + return NULL; } @@ -913,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) { @@ -942,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)) @@ -964,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)) @@ -984,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) { @@ -1003,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)) @@ -1028,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; } @@ -1037,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; } @@ -1061,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; } @@ -1080,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; } @@ -1097,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); @@ -1280,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) { @@ -1294,7 +1295,7 @@ void BKE_gpencil_palettecolor_changename(bGPdata *gpd, char *oldname, const char } } } - + } /* Delete all strokes of the color */ @@ -1303,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/icons.c b/source/blender/blenkernel/intern/icons.c index e409f8c91f0..37f53e81236 100644 --- a/source/blender/blenkernel/intern/icons.c +++ b/source/blender/blenkernel/intern/icons.c @@ -119,7 +119,7 @@ static void icon_free(void *val) } } -static void icon_free_data(Icon *icon) +static void icon_free_data(int icon_id, Icon *icon) { if (icon->obj_type == ICON_DATA_ID) { ((ID *)(icon->obj))->icon_id = 0; @@ -130,6 +130,12 @@ static void icon_free_data(Icon *icon) else if (icon->obj_type == ICON_DATA_GEOM) { ((struct Icon_Geom *)(icon->obj))->icon_id = 0; } + else if (icon->obj_type == ICON_DATA_STUDIOLIGHT) { + StudioLight *sl = icon->obj; + if (sl != NULL) { + BKE_studiolight_unset_icon_id(sl, icon_id); + } + } else { BLI_assert(0); } @@ -145,7 +151,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++; @@ -243,7 +249,7 @@ void BKE_previewimg_freefunc(void *link) if (prv->gputexture[i]) GPU_texture_free(prv->gputexture[i]); } - + MEM_freeN(prv); } } @@ -509,11 +515,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); @@ -640,7 +646,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; @@ -699,7 +705,7 @@ bool BKE_icon_delete(const int icon_id) Icon *icon = BLI_ghash_popkey(gIcons, SET_INT_IN_POINTER(icon_id), NULL); if (icon) { - icon_free_data(icon); + icon_free_data(icon_id, icon); icon_free(icon); return true; } @@ -722,7 +728,7 @@ bool BKE_icon_delete_unmanaged(const int icon_id) return false; } else { - icon_free_data(icon); + icon_free_data(icon_id, icon); icon_free(icon); return true; } diff --git a/source/blender/blenkernel/intern/idcode.c b/source/blender/blenkernel/intern/idcode.c index 4860f5a896d..0edeaab8900 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; @@ -101,7 +101,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); @@ -120,7 +120,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 0c5078e3e36..ae9236e35fe 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; @@ -1051,7 +1051,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; } diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index c1ecabcfb5a..b5abdcae2d4 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -342,19 +342,18 @@ void BKE_image_free_buffers(Image *ima) /** Free (or release) any data used by this image (does not free the image itself). */ void BKE_image_free(Image *ima) { - int a; - /* Also frees animdata. */ BKE_image_free_buffers(ima); image_free_packedfiles(ima); - for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) { - if (ima->renders[a]) { - RE_FreeRenderResult(ima->renders[a]); - ima->renders[a] = NULL; + LISTBASE_FOREACH(RenderSlot *, slot, &ima->renderslots) { + if (slot->render) { + RE_FreeRenderResult(slot->render); + slot->render = NULL; } } + BLI_freelistN(&ima->renderslots); BKE_image_free_views(ima); MEM_SAFE_FREE(ima->stereo3d_format); @@ -380,6 +379,12 @@ static void image_init(Image *ima, short source, short type) if (source == IMA_SRC_VIEWER) ima->flag |= IMA_VIEW_AS_RENDER; + if (type == IMA_TYPE_R_RESULT) { + for (int i = 0; i < 8; i++) { + BKE_image_add_renderslot(ima, NULL); + } + } + BKE_color_managed_colorspace_settings_init(&ima->colorspace_settings); ima->stereo3d_format = MEM_callocN(sizeof(Stereo3dFormat), "Image Stereo Format"); } @@ -466,14 +471,15 @@ void BKE_image_copy_data(Main *UNUSED(bmain), Image *ima_dst, const Image *ima_s /* Cleanup stuff that cannot be copied. */ ima_dst->cache = NULL; ima_dst->rr = NULL; - for (int i = 0; i < IMA_MAX_RENDER_SLOT; i++) { - ima_dst->renders[i] = NULL; + + BLI_duplicatelist(&ima_dst->renderslots, &ima_src->renderslots); + LISTBASE_FOREACH(RenderSlot *, slot, &ima_dst->renderslots) { + slot->render = NULL; } BLI_listbase_clear(&ima_dst->anims); for (int i = 0; i < TEXTARGET_COUNT; i++) { - ima_dst->bindcode[i] = 0; ima_dst->gputexture[i] = NULL; } @@ -538,16 +544,14 @@ bool BKE_image_scale(Image *image, int width, int height) return (ibuf != NULL); } -bool BKE_image_has_bindcode(Image *ima) +bool BKE_image_has_opengl_texture(Image *ima) { - bool has_bindcode = false; for (int i = 0; i < TEXTARGET_COUNT; i++) { - if (ima->bindcode[i]) { - has_bindcode = true; - break; + if (ima->gputexture[i]) { + return true; } } - return has_bindcode; + return false; } static void image_init_color_management(Image *ima) @@ -572,7 +576,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 { @@ -603,7 +607,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); @@ -930,21 +934,6 @@ void BKE_image_tag_time(Image *ima) ima->lastused = PIL_check_seconds_timer_i(); } -#if 0 -static void tag_all_images_time(Main *bmain) -{ - Image *ima; - int ctime = PIL_check_seconds_timer_i(); - - ima = bmain->image.first; - while (ima) { - if (ima->bindcode || ima->repbind || ima->ibufs.first) { - ima->lastused = ctime; - } - } -} -#endif - static uintptr_t image_mem_size(Image *image) { uintptr_t size = 0; @@ -1363,63 +1352,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 @@ -1427,35 +1416,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); } } @@ -3015,7 +3004,7 @@ RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima) if (ima->render_slot == ima->last_render_slot) rr = RE_AcquireResultRead(RE_GetSceneRender(scene)); else - rr = ima->renders[ima->render_slot]; + rr = BKE_image_get_renderslot(ima, ima->render_slot)->render; /* set proper views */ image_init_multilayer_multiview(ima, rr); @@ -3039,7 +3028,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); @@ -3049,27 +3038,39 @@ bool BKE_image_is_openexr(struct Image *ima) void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot) { - /* called right before rendering, ima->renders contains render + /* called right before rendering, ima->renderslots contains render * result pointers for everything but the current render */ Render *re = RE_GetSceneRender(scene); - int slot = ima->render_slot, last = ima->last_render_slot; - if (slot != last) { - ima->renders[last] = NULL; - RE_SwapResult(re, &ima->renders[last]); + /* Ensure we always have a valid render slot. */ + if (!ima->renderslots.first) { + BKE_image_add_renderslot(ima, NULL); + ima->render_slot = 0; + ima->last_render_slot = 0; + } + else if (ima->render_slot >= BLI_listbase_count(&ima->renderslots)) { + ima->render_slot = 0; + ima->last_render_slot = 0; + } + + RenderSlot *last_slot = BKE_image_get_renderslot(ima, ima->last_render_slot); + RenderSlot *cur_slot = BKE_image_get_renderslot(ima, ima->render_slot); - if (ima->renders[slot]) { + if (last_slot && ima->render_slot != ima->last_render_slot) { + last_slot->render = NULL; + RE_SwapResult(re, &last_slot->render); + + if (cur_slot->render) { if (free_current_slot) { - RE_FreeRenderResult(ima->renders[slot]); - ima->renders[slot] = NULL; + BKE_image_clear_renderslot(ima, NULL, ima->render_slot); } else { - RE_SwapResult(re, &ima->renders[slot]); + RE_SwapResult(re, &cur_slot->render); } } } - ima->last_render_slot = slot; + ima->last_render_slot = ima->render_slot; } /**************************** multiview load openexr *********************************/ @@ -3687,11 +3688,12 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc if (BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO)) actview = iuser->multiview_eye; + RenderSlot *slot; if (from_render) { RE_AcquireResultImage(re, &rres, actview); } - else if (ima->renders[ima->render_slot]) { - rres = *(ima->renders[ima->render_slot]); + else if ((slot = BKE_image_get_renderslot(ima, ima->render_slot))->render) { + rres = *(slot->render); rres.have_combined = ((RenderView *)rres.views.first)->rectf != NULL; } else @@ -4721,3 +4723,97 @@ static void image_update_views_format(Image *ima, ImageUser *iuser) } } } + +/**************************** Render Slots ***************************/ + +RenderSlot *BKE_image_add_renderslot(Image *ima, const char *name) +{ + RenderSlot *slot = MEM_callocN(sizeof(RenderSlot), "Image new Render Slot"); + if (name && name[0]) { + BLI_strncpy(slot->name, name, sizeof(slot->name)); + } + else { + int n = BLI_listbase_count(&ima->renderslots) + 1; + BLI_snprintf(slot->name, sizeof(slot->name), "Slot %d", n); + } + BLI_addtail(&ima->renderslots, slot); + return slot; +} + +bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int index) +{ + int num_slots = BLI_listbase_count(&ima->renderslots); + if (index >= num_slots || num_slots == 1) { + return false; + } + + RenderSlot *remove_slot = BLI_findlink(&ima->renderslots, index); + RenderSlot *current_slot = BLI_findlink(&ima->renderslots, ima->render_slot); + RenderSlot *current_last_slot = BLI_findlink(&ima->renderslots, ima->last_render_slot); + + RenderSlot *next_slot; + if (current_slot == remove_slot) { + next_slot = BLI_findlink(&ima->renderslots, (index == num_slots - 1) ? index - 1 : index + 1); + } + else { + next_slot = current_slot; + } + + /* If the slot to be removed is the slot with the last render, make another slot the last render slot. */ + if (remove_slot == current_last_slot) { + /* Choose the currently selected slot unless that one is being removed, in that case take the next one. */ + RenderSlot *next_last_slot; + if (current_slot == remove_slot) + next_last_slot = next_slot; + else + next_last_slot = current_slot; + + if (!iuser) return false; + Render *re = RE_GetSceneRender(iuser->scene); + if (!re) return false; + RE_SwapResult(re, ¤t_last_slot->render); + RE_SwapResult(re, &next_last_slot->render); + current_last_slot = next_last_slot; + } + + current_slot = next_slot; + + BLI_remlink(&ima->renderslots, remove_slot); + + ima->render_slot = BLI_findindex(&ima->renderslots, current_slot); + ima->last_render_slot = BLI_findindex(&ima->renderslots, current_last_slot); + + if (remove_slot->render) { + RE_FreeRenderResult(remove_slot->render); + } + MEM_freeN(remove_slot); + + return true; +} + +bool BKE_image_clear_renderslot(Image *ima, ImageUser *iuser, int index) +{ + if (index == ima->last_render_slot) { + if (!iuser) return false; + if (G.is_rendering) return false; + Render *re = RE_GetSceneRender(iuser->scene); + if (!re) return false; + RE_ClearResult(re); + return true; + } + else { + RenderSlot *slot = BLI_findlink(&ima->renderslots, index); + if (!slot) return false; + if (slot->render) { + RE_FreeRenderResult(slot->render); + slot->render = NULL; + } + return true; + } +} + +RenderSlot *BKE_image_get_renderslot(Image *ima, int index) +{ + /* Can be NULL for images without render slots. */ + return BLI_findlink(&ima->renderslots, index); +} diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index 82178096b46..eeb09931211 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -37,7 +37,7 @@ * * -- Joshua Leung, Jan 2009 */ - + #include <math.h> #include <stdio.h> #include <string.h> @@ -92,18 +92,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); } @@ -162,7 +162,7 @@ static AdrBit2Path *adrcode_bitmaps_to_paths(int blocktype, int adrcode, int *to RET_ABP(ob_layer_bits); } // XXX TODO: add other types... - + /* Normal curve */ return NULL; } @@ -176,7 +176,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: @@ -191,7 +191,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: @@ -204,7 +204,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: @@ -246,18 +246,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: @@ -268,21 +268,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: @@ -290,7 +290,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; @@ -301,7 +301,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: @@ -309,18 +309,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") */ @@ -330,7 +330,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 */ @@ -349,7 +349,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]"; @@ -369,7 +369,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) { @@ -404,7 +404,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); @@ -419,26 +419,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"; @@ -454,15 +454,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; @@ -477,20 +477,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; } @@ -499,7 +499,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: @@ -508,73 +508,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; } @@ -583,7 +583,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: @@ -591,29 +591,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; } @@ -623,39 +623,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; } @@ -665,7 +665,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: @@ -680,7 +680,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; } @@ -690,7 +690,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: @@ -705,10 +705,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: @@ -717,11 +717,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; } @@ -730,7 +730,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: @@ -761,7 +761,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 @@ -811,64 +811,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: @@ -885,28 +885,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 { @@ -948,24 +948,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; } @@ -983,21 +983,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; } @@ -1007,10 +1007,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 */ @@ -1022,24 +1022,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; @@ -1051,7 +1051,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; @@ -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 single target */ dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; @@ -1074,12 +1074,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) @@ -1091,7 +1091,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; @@ -1099,7 +1099,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 */ @@ -1116,14 +1116,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; @@ -1136,7 +1136,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 @@ -1147,21 +1147,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 */ @@ -1174,12 +1174,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; @@ -1188,20 +1188,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 @@ -1210,46 +1210,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; @@ -1262,80 +1262,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 @@ -1343,27 +1343,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; } @@ -1374,7 +1374,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); } @@ -1389,16 +1389,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 <builtin> 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... */ @@ -1408,10 +1408,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) { @@ -1427,23 +1427,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); } @@ -1459,44 +1459,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); } @@ -1509,12 +1509,12 @@ static void action_to_animato(ID *id, bAction *act, ListBase *groups, ListBase * * This assumes that AnimData has been added already. Separation of drivers * from animation data is accomplished here too... */ -static void ipo_to_animdata(ID *id, Ipo *ipo, char actname[], char constname[], Sequence *seq) +static void ipo_to_animdata(Main *bmain, ID *id, Ipo *ipo, char actname[], char constname[], Sequence *seq) { AnimData *adt = BKE_animdata_from_id(id); ListBase anim = {NULL, NULL}; ListBase drivers = {NULL, NULL}; - + /* sanity check */ if (ELEM(NULL, id, ipo)) return; @@ -1522,36 +1522,36 @@ static void ipo_to_animdata(ID *id, Ipo *ipo, char actname[], char constname[], 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 : "<None>", (constname) ? constname : "<None>", (seq) ? (seq->name + 2) : "<None>", 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(G.main, nameBuf); + + 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"); @@ -1566,18 +1566,18 @@ static void ipo_to_animdata(ID *id, Ipo *ipo, char actname[], char constname[], 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); } @@ -1595,25 +1595,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; @@ -1642,25 +1642,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); } @@ -1679,147 +1679,147 @@ 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... -void do_versions_ipos_to_animato(Main *main) +// XXX currently done after all file reading... +void do_versions_ipos_to_animato(Main *bmain) { ListBase drivers = {NULL, NULL}; ID *id; - - if (main == NULL) { + + if (bmain == NULL) { printf("Argh! Main is NULL in do_versions_ipos_to_animato()\n"); return; } - + /* only convert if version is right */ - if (main->versionfile >= 250) { - printf("WARNING: Animation data too new to convert (Version %d)\n", main->versionfile); + if (bmain->versionfile >= 250) { + printf("WARNING: Animation data too new to convert (Version %d)\n", bmain->versionfile); return; } else if (G.debug & G_DEBUG) printf("INFO: Converting to Animato...\n"); - + /* ----------- Animation Attached to Data -------------- */ - + /* objects */ - for (id = main->object.first; id; id = id->next) { + 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(id, ob->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, ob->ipo, NULL, NULL, NULL); + id_us_min(&ob->ipo->id); 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(id, ob->ipo, NULL, NULL, NULL); + ipo_to_animdata(bmain, id, ob->ipo, NULL, NULL, NULL); id_us_min(&ob->ipo->id); ob->ipo = NULL; } } - + /* 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(id, con->ipo, pchan->name, con->name, NULL); + ipo_to_animdata(bmain, id, con->ipo, pchan->name, con->name, NULL); id_us_min(&con->ipo->id); con->ipo = NULL; } } } } - + /* 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(id, con->ipo, NULL, con->name, NULL); + 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(id, conchan->ipo, NULL, conchan->name, NULL); + 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); @@ -1827,100 +1827,100 @@ void do_versions_ipos_to_animato(Main *main) adt->action->idroot = ID_OB; } } - + /* shapekeys */ - for (id = main->key.first; id; id = id->next) { + 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(id, key->ipo, NULL, NULL, NULL); - + 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 = main->mat.first; id; id = id->next) { + 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(id, ma->ipo, NULL, NULL, NULL); - + 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 = main->world.first; id; id = id->next) { + 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(id, wo->ipo, NULL, NULL, NULL); - + 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 = main->scene.first; id; id = id->next) { + 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) { @@ -1936,13 +1936,13 @@ void do_versions_ipos_to_animato(Main *main) break; } icu->adrcode = adrcode; - + /* convert IPO */ - ipo_to_animdata((ID *)scene, seq->ipo, NULL, NULL, seq); - + 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; } @@ -1952,142 +1952,142 @@ void do_versions_ipos_to_animato(Main *main) /* textures */ - for (id = main->tex.first; id; id = id->next) { + 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(id, te->ipo, NULL, NULL, NULL); - + 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 = main->camera.first; id; id = id->next) { + 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(id, ca->ipo, NULL, NULL, NULL); - + 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 = main->lamp.first; id; id = id->next) { + 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(id, la->ipo, NULL, NULL, NULL); - + 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 = main->curve.first; id; id = id->next) { + 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(id, cu->ipo, NULL, NULL, NULL); - + 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 = main->action.first; id; id = id->next) { + 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 = main->ipo.first; id; id = id->next) { + 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(main, id->name + 2); + 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 fd42556067e..4689575655e 100644 --- a/source/blender/blenkernel/intern/key.c +++ b/source/blender/blenkernel/intern/key.c @@ -102,18 +102,18 @@ void BKE_key_free_nolib(Key *key) } } -Key *BKE_key_add(ID *id) /* common function */ +Key *BKE_key_add(Main *bmain, ID *id) /* common function */ { Key *key; char *el; - - key = BKE_libblock_alloc(G.main, ID_KE, "Key", 0); - + + 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(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 158d2954100..0e81e6570e2 100644 --- a/source/blender/blenkernel/intern/lamp.c +++ b/source/blender/blenkernel/intern/lamp.c @@ -89,7 +89,7 @@ void BKE_lamp_init(Lamp *la) la->contact_spread = 0.2f; la->contact_thickness = 0.5f; la->spec_fac = 1.0f; - + curvemapping_initialize(la->curfalloff); } @@ -152,7 +152,7 @@ Lamp *BKE_lamp_localize(Lamp *la) if (la->nodetree) lan->nodetree = ntreeLocalize(la->nodetree); - + lan->preview = NULL; return lan; @@ -175,7 +175,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; diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c index b5b62de57ec..a885495f2bf 100644 --- a/source/blender/blenkernel/intern/lattice.c +++ b/source/blender/blenkernel/intern/lattice.c @@ -152,13 +152,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--; @@ -203,7 +203,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; @@ -240,9 +240,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]); } @@ -255,9 +255,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) { @@ -556,7 +556,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; @@ -568,14 +568,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); @@ -641,7 +641,7 @@ static bool calc_curve_deform(Object *par, float co[3], } } } - + if (where_on_path_deform(par, fac, loc, dir, new_quat, &radius)) { /* returns OK */ float quat[4], cent[3]; @@ -687,7 +687,7 @@ static bool calc_curve_deform(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); @@ -731,7 +731,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. */ @@ -804,12 +804,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(cuOb, vertexCos[a], defaxis, &cd, NULL); @@ -827,7 +827,7 @@ void curve_deform_vector(Object *cuOb, Object *target, { CurveDeform cd; float quat[4]; - + if (cuOb->type != OB_CURVE) { unit_m3(mat); return; @@ -835,21 +835,21 @@ void curve_deform_vector(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(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); } @@ -937,11 +937,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 */ @@ -949,41 +949,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 { @@ -1004,9 +1004,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); } @@ -1046,7 +1046,7 @@ void BKE_lattice_modifiers_calc(struct Depsgraph *depsgraph, Scene *scene, Objec 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; @@ -1072,7 +1072,7 @@ void BKE_lattice_modifiers_calc(struct Depsgraph *depsgraph, Scene *scene, Objec dl->parts = 1; dl->nr = numVerts; dl->verts = (float *) vertexCos; - + BLI_addtail(&ob->curve_cache->disp, dl); } } @@ -1154,7 +1154,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; diff --git a/source/blender/blenkernel/intern/layer.c b/source/blender/blenkernel/intern/layer.c index c7bb24cdcee..db9ce76b30c 100644 --- a/source/blender/blenkernel/intern/layer.c +++ b/source/blender/blenkernel/intern/layer.c @@ -439,7 +439,9 @@ static LayerCollection *collection_from_index(ListBase *lb, const int number, in } (*i)++; + } + for (LayerCollection *lc = lb->first; lc; lc = lc->next) { LayerCollection *lc_nested = collection_from_index(&lc->layer_collections, number, i); if (lc_nested) { return lc_nested; @@ -537,7 +539,9 @@ static int index_from_collection(ListBase *lb, const LayerCollection *lc, int *i } (*i)++; + } + for (LayerCollection *lcol = lb->first; lcol; lcol = lcol->next) { int i_nested = index_from_collection(&lcol->layer_collections, lc, i); if (i_nested != -1) { return i_nested; @@ -567,7 +571,7 @@ int BKE_layer_collection_findindex(ViewLayer *view_layer, const LayerCollection * in at least one layer collection. That list is also synchronized here, and * stores state like selection. */ -static void layer_collection_sync( +static int layer_collection_sync( ViewLayer *view_layer, const ListBase *lb_scene, ListBase *lb_layer, ListBase *new_object_bases, int parent_exclude, int parent_restrict) @@ -594,6 +598,7 @@ static void layer_collection_sync( /* Add layer collections for any new scene collections, and ensure order is the same. */ ListBase new_lb_layer = {NULL, NULL}; + int runtime_flag = 0; for (const CollectionChild *child = lb_scene->first; child; child = child->next) { Collection *collection = child->collection; @@ -615,15 +620,19 @@ static void layer_collection_sync( } /* Sync child collections. */ - layer_collection_sync( + int child_runtime_flag = layer_collection_sync( view_layer, &collection->children, &lc->layer_collections, new_object_bases, lc->flag, child_restrict); /* Layer collection exclude is not inherited. */ if (lc->flag & LAYER_COLLECTION_EXCLUDE) { + lc->runtime_flag = 0; continue; } + else { + lc->runtime_flag = child_runtime_flag; + } /* Sync objects, except if collection was excluded. */ for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) { @@ -645,22 +654,50 @@ static void layer_collection_sync( BLI_ghash_insert(view_layer->object_bases_hash, base->object, base); } - if ((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) { + int object_restrict = base->object->restrictflag; + + if (((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) && + ((object_restrict & OB_RESTRICT_VIEW) == 0)) + { base->flag |= BASE_VISIBLED | BASE_VISIBLE_VIEWPORT; - if ((child_restrict & COLLECTION_RESTRICT_SELECT) == 0) { + if (((child_restrict & COLLECTION_RESTRICT_SELECT) == 0) && + ((object_restrict & OB_RESTRICT_SELECT) == 0)) + { base->flag |= BASE_SELECTABLED; } } - if ((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) { + + if (((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) && + ((object_restrict & OB_RESTRICT_RENDER) == 0)) + + { base->flag |= BASE_VISIBLE_RENDER; } + + /* Update runtime flags used for display and tools. */ + if (base->flag & BASE_VISIBLED) { + lc->runtime_flag |= LAYER_COLLECTION_HAS_ENABLED_OBJECTS; + } + + if (base->flag & BASE_HIDE) { + view_layer->runtime_flag |= VIEW_LAYER_HAS_HIDE; + } + else if (base->flag & BASE_VISIBLED) { + lc->runtime_flag |= LAYER_COLLECTION_HAS_VISIBLE_OBJECTS; + } + + lc->runtime_flag |= LAYER_COLLECTION_HAS_OBJECTS; } + + runtime_flag |= lc->runtime_flag; } /* Replace layer collection list with new one. */ *lb_layer = new_lb_layer; BLI_assert(BLI_listbase_count(lb_scene) == BLI_listbase_count(lb_layer)); + + return runtime_flag; } /** @@ -688,6 +725,8 @@ void BKE_layer_collection_sync(const Scene *scene, ViewLayer *view_layer) base->flag &= ~(BASE_VISIBLED | BASE_SELECTABLED | BASE_VISIBLE_VIEWPORT | BASE_VISIBLE_RENDER); } + view_layer->runtime_flag = 0; + /* Generate new layer connections and object bases when collections changed. */ CollectionChild child = {NULL, NULL, scene->master_collection}; const ListBase collections = {&child, &child}; @@ -759,6 +798,7 @@ void BKE_main_collection_sync_remap(const Main *bmain) for (Collection *collection = bmain->collection.first; collection; collection = collection->id.next) { BKE_collection_object_cache_free(collection); + DEG_id_tag_update_ex((Main *)bmain, &collection->id, DEG_TAG_COPY_ON_WRITE); } BKE_main_collection_sync(bmain); @@ -808,6 +848,107 @@ bool BKE_layer_collection_objects_select(ViewLayer *view_layer, LayerCollection return changed; } +bool BKE_layer_collection_has_selected_objects(ViewLayer *view_layer, LayerCollection *lc) +{ + if (lc->collection->flag & COLLECTION_RESTRICT_SELECT) { + return false; + } + + if (!(lc->flag & LAYER_COLLECTION_EXCLUDE)) { + for (CollectionObject *cob = lc->collection->gobject.first; cob; cob = cob->next) { + Base *base = BKE_view_layer_base_find(view_layer, cob->ob); + + if (base && (base->flag & BASE_SELECTED)) { + return true; + } + } + } + + for (LayerCollection *iter = lc->layer_collections.first; iter; iter = iter->next) { + if (BKE_layer_collection_has_selected_objects(view_layer, iter)) { + return true; + } + } + + return false; +} + +/* ---------------------------------------------------------------------- */ + +/* Test base visibility when BASE_VISIBLED has not been set yet. */ +static bool base_is_visible(Base *base, eEvaluationMode mode) +{ + if (mode == DAG_EVAL_VIEWPORT) { + return ((base->flag & BASE_VISIBLE_VIEWPORT) != 0) && + ((base->flag & BASE_HIDE) == 0); + } + else { + return ((base->flag & BASE_VISIBLE_RENDER) != 0); + } +} + +/* Update after toggling visibility of an object base. */ +void BKE_base_set_visible(Scene *scene, ViewLayer *view_layer, Base *base, bool extend) +{ + if (!extend) { + /* Make only one base visible. */ + for (Base *other = view_layer->object_bases.first; other; other = other->next) { + other->flag |= BASE_HIDE; + } + + base->flag &= ~BASE_HIDE; + } + else { + /* Toggle visibility of one base. */ + base->flag ^= BASE_HIDE; + } + + BKE_layer_collection_sync(scene, view_layer); +} + +void BKE_layer_collection_set_visible(Scene *scene, ViewLayer *view_layer, LayerCollection *lc, bool extend) +{ + if (!extend) { + /* Make only objects from one collection visible. */ + for (Base *base = view_layer->object_bases.first; base; base = base->next) { + base->flag |= BASE_HIDE; + } + + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(lc->collection, ob) + { + Base *base = BLI_ghash_lookup(view_layer->object_bases_hash, ob); + + if (base) { + base->flag &= ~BASE_HIDE; + } + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + + BKE_layer_collection_activate(view_layer, lc); + } + else { + /* Toggle visibility of objects from collection. */ + bool hide = (lc->runtime_flag & LAYER_COLLECTION_HAS_VISIBLE_OBJECTS) != 0; + + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(lc->collection, ob) + { + Base *base = BLI_ghash_lookup(view_layer->object_bases_hash, ob); + + if (base) { + if (hide) { + base->flag |= BASE_HIDE; + } + else { + base->flag &= ~BASE_HIDE; + } + } + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + } + + BKE_layer_collection_sync(scene, view_layer); +} + /* ---------------------------------------------------------------------- */ static LayerCollection *find_layer_collection_by_scene_collection(LayerCollection *lc, const Collection *collection) @@ -1234,21 +1375,8 @@ void BKE_layer_eval_view_layer( { DEG_debug_print_eval(depsgraph, __func__, view_layer->name, view_layer); - /* Set visibility based on depsgraph mode. */ + /* Visibility based on depsgraph mode. */ const eEvaluationMode mode = DEG_get_mode(depsgraph); - const int base_flag = (mode == DAG_EVAL_VIEWPORT) ? BASE_VISIBLE_VIEWPORT : BASE_VISIBLE_RENDER; - - for (Base *base = view_layer->object_bases.first; base != NULL; base = base->next) { - if (base->flag & base_flag) { - base->flag |= BASE_VISIBLED; - } - else { - base->flag &= ~BASE_VISIBLED; - } - } - - /* TODO(sergey): Is it always required? */ - view_layer->flag |= VIEW_LAYER_ENGINE_DIRTY; /* Create array of bases, for fast index-based lookup. */ const int num_object_bases = BLI_listbase_count(&view_layer->object_bases); @@ -1257,15 +1385,26 @@ void BKE_layer_eval_view_layer( num_object_bases, sizeof(Base *), "view_layer->object_bases_array"); int base_index = 0; for (Base *base = view_layer->object_bases.first; base; base = base->next) { - /* if base is not selectabled, clear select. */ + /* Set visibility. */ + if (base_is_visible(base, mode)) { + base->flag |= BASE_VISIBLED; + } + else { + base->flag &= ~(BASE_VISIBLED | BASE_SELECTABLED); + } + + /* If base is not selectabled, clear select. */ if ((base->flag & BASE_SELECTABLED) == 0) { base->flag &= ~BASE_SELECTED; } - /* Store base in the array. */ + view_layer->object_bases_array[base_index++] = base; } + + + /* Flush back base flag to the original view layer for editing. */ + ViewLayer *view_layer_orig = DEG_get_input_view_layer(depsgraph); if (view_layer == DEG_get_evaluated_view_layer(depsgraph)) { - ViewLayer *view_layer_orig = DEG_get_input_view_layer(depsgraph); Base *base_orig = view_layer_orig->object_bases.first; const Base *base_eval = view_layer->object_bases.first; while (base_orig != NULL) { @@ -1274,6 +1413,14 @@ void BKE_layer_eval_view_layer( base_eval = base_eval->next; } } + + /* Hidden objects can't be active. */ + if (view_layer->basact && !(view_layer->basact->flag & BASE_VISIBLED)) { + view_layer->basact = NULL; + } + if (view_layer_orig->basact && !(view_layer_orig->basact->flag & BASE_VISIBLED)) { + view_layer_orig->basact = NULL; + } } void BKE_layer_eval_view_layer_indexed( diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c index a885f22b739..c45903aa1fa 100644 --- a/source/blender/blenkernel/intern/library.c +++ b/source/blender/blenkernel/intern/library.c @@ -142,7 +142,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 */ @@ -768,13 +768,14 @@ 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)) { - if (id_copy(CTX_data_main(C), id, &newid, false) && newid) { + Main *bmain = CTX_data_main(C); + if (id_copy(bmain, id, &newid, false) && newid) { /* copy animation actions too */ - BKE_animdata_copy_id_action(id, false); + BKE_animdata_copy_id_action(bmain, id, false); /* us is 1 by convention, but RNA_property_pointer_set * will also increment it, so set it to zero */ newid->us = 0; @@ -783,12 +784,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; } @@ -1078,9 +1079,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); @@ -1113,7 +1114,7 @@ int set_listbasepointers(Main *main, ListBase **lb) lb[INDEX_ID_WS] = &(main->workspaces); /* before wm, so it's freed after it! */ lb[INDEX_ID_WM] = &(main->wm); lb[INDEX_ID_MSK] = &(main->mask); - + lb[INDEX_ID_NULL] = NULL; return (MAX_LIBARRAY - 1); @@ -1408,7 +1409,7 @@ void *BKE_id_new_nomain(const short type, const char *name) 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, true); /* could be set to false, need to investigate */ @@ -1527,7 +1528,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); @@ -1766,11 +1767,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)) { @@ -1784,7 +1785,7 @@ void id_sort_by_name(ListBase *lb, ID *id) BLI_addtail(lb, id); } } - + } /** @@ -1794,9 +1795,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 */ @@ -1805,7 +1806,7 @@ static ID *is_dupid(ListBase *lb, ID *id, const char *name) } } } - + return idtest; } @@ -1894,8 +1895,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') { @@ -1906,7 +1907,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); @@ -1914,7 +1915,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; @@ -1977,7 +1978,7 @@ bool new_id(ListBase *lb, ID *id, const char *tname) #endif id_sort_by_name(lb, id); - + return result; } @@ -2492,7 +2493,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); diff --git a/source/blender/blenkernel/intern/library_query.c b/source/blender/blenkernel/intern/library_query.c index 37b5b62b06e..f23d8720a65 100644 --- a/source/blender/blenkernel/intern/library_query.c +++ b/source/blender/blenkernel/intern/library_query.c @@ -352,10 +352,6 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call #define CALLBACK_INVOKE(check_id_super, cb_flag) \ FOREACH_CALLBACK_INVOKE(&data, check_id_super, cb_flag) - if (id->override_static != NULL) { - CALLBACK_INVOKE_ID(id->override_static->reference, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE); - } - for (; id != NULL; id = (flag & IDWALK_RECURSE) ? BLI_LINKSTACK_POP(data.ids_todo) : NULL) { data.self_id = id; data.cb_flag = ID_IS_LINKED(id) ? IDWALK_CB_INDIRECT_USAGE : 0; @@ -372,6 +368,11 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call continue; } + if (id->override_static != NULL) { + CALLBACK_INVOKE_ID(id->override_static->reference, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE); + CALLBACK_INVOKE_ID(id->override_static->storage, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE); + } + library_foreach_idproperty_ID_link(&data, id->properties, IDWALK_CB_USER); AnimData *adt = BKE_animdata_from_id(id); diff --git a/source/blender/blenkernel/intern/library_remap.c b/source/blender/blenkernel/intern/library_remap.c index e3c10175feb..f34a2ff7f84 100644 --- a/source/blender/blenkernel/intern/library_remap.c +++ b/source/blender/blenkernel/intern/library_remap.c @@ -195,8 +195,10 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0; #ifdef DEBUG_PRINT - printf("In %s: Remapping %s (%p) to %s (%p) (is_indirect: %d, skip_indirect: %d)\n", - id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, is_indirect, skip_indirect); + printf("In %s (lib %p): Remapping %s (%p) to %s (%p) " + "(is_indirect: %d, skip_indirect: %d, is_reference: %d, skip_reference: %d)\n", + id->name, id->lib, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, + is_indirect, skip_indirect, is_reference, skip_reference); #endif if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_CB_NEVER_NULL)) { @@ -239,7 +241,7 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id else { if (!is_never_null) { *id_p = new_id; - DEG_id_tag_update_ex(id_remap_data->bmain, id_self, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); + DEG_id_tag_update_ex(id_remap_data->bmain, id_self, DEG_TAG_TRANSFORM | DEG_TAG_TIME | DEG_TAG_GEOMETRY); } if (cb_flag & IDWALK_CB_USER) { id_us_min(old_id); @@ -1015,7 +1017,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 collections when deleting an object. @@ -1031,7 +1033,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 1ea2f170922..21b2ab6b454 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,10 +90,10 @@ void init_def_material(void) void BKE_material_free(Material *ma) { BKE_animdata_free((ID *)ma, false); - + /* Free gpu material before the ntree */ GPU_material_free(&ma->gpumaterial); - + /* is no lib link block, but material extension */ if (ma->nodetree) { ntreeFreeTree(ma->nodetree); @@ -117,7 +117,7 @@ void BKE_material_init(Material *ma) ma->spec = 0.5; ma->roughness = 0.25f; - + ma->pr_lamp = 3; /* two lamps, is bits */ ma->pr_type = MA_SPHERE; @@ -131,9 +131,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; } @@ -218,7 +218,7 @@ Material ***give_matarar(Object *ob) Mesh *me; Curve *cu; MetaBall *mb; - + if (ob->type == OB_MESH) { me = ob->data; return &(me->mat); @@ -239,7 +239,7 @@ short *give_totcolp(Object *ob) Mesh *me; Curve *cu; MetaBall *mb; - + if (ob->type == OB_MESH) { me = ob->data; return &(me->totcol); @@ -413,7 +413,7 @@ Material *BKE_material_pop_id(Main *bmain, ID *id, int index_i, bool update_data DEG_relations_tag_update(bmain); } } - + return ret; } @@ -447,7 +447,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; @@ -473,12 +473,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; } @@ -621,18 +621,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"); @@ -676,7 +676,7 @@ void assign_material(Main *bmain, Object *ob, Material *ma, short act, int assig break; } } - + /* do it */ ob->matbits[act - 1] = bit; @@ -811,14 +811,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; @@ -831,7 +831,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; @@ -844,7 +844,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; } @@ -858,10 +858,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); @@ -873,21 +873,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) { @@ -900,14 +900,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); @@ -932,7 +932,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; @@ -944,7 +944,7 @@ static bNode *nodetree_uv_node_recursive(bNode *node) } } } - + return NULL; } @@ -967,7 +967,7 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) ma->paint_clone_slot = 0; return; } - + bNode *node, *active_node; if (!(ma->nodetree)) { @@ -995,10 +995,10 @@ 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 */ bNode *uvnode = nodetree_uv_node_recursive(node); - + if (uvnode) { NodeShaderUVMap *storage = (NodeShaderUVMap *)uvnode->storage; ma->texpaintslot[index].uvname = storage->uv_map; @@ -1014,8 +1014,8 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) } ma->tot_slots = count; - - + + if (ma->paint_active_slot >= count) { ma->paint_active_slot = count - 1; } @@ -1042,7 +1042,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]; diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c index 3afaf2d569e..2ff69c5ee6d 100644 --- a/source/blender/blenkernel/intern/mball.c +++ b/source/blender/blenkernel/intern/mball.c @@ -89,7 +89,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; @@ -201,7 +201,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 b325d8d02d9..f502d7e394f 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -107,7 +107,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_MDEFORMVERT)) @@ -126,7 +126,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; @@ -144,52 +144,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; @@ -200,7 +200,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; @@ -210,22 +210,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; @@ -237,14 +237,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; @@ -254,7 +254,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 } } } - + return 0; } @@ -267,22 +267,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); @@ -294,7 +294,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; } @@ -440,7 +440,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); @@ -728,8 +728,9 @@ BMesh *BKE_mesh_to_bmesh( Mesh *BKE_bmesh_to_mesh_nomain(BMesh *bm, const struct BMeshToMeshParams *params) { + BLI_assert(params->calc_object_remap == false); Mesh *mesh = BKE_id_new_nomain(ID_ME, NULL); - BM_mesh_bm_to_me(bm, mesh, params); + BM_mesh_bm_to_me(NULL, bm, mesh, params); return mesh; } @@ -823,13 +824,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; @@ -837,11 +838,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; @@ -1036,7 +1037,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; @@ -1047,9 +1048,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) @@ -1057,7 +1058,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); @@ -1127,7 +1128,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; @@ -1142,7 +1143,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]; @@ -1184,7 +1185,7 @@ int poly_find_loop_from_vert( if (loopstart->v == vert) return j; } - + return -1; } @@ -1201,7 +1202,7 @@ int poly_get_adj_loops_from_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]; @@ -1237,7 +1238,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); } @@ -1280,7 +1281,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) { diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.c index 4e1297043d0..3062cd13f5f 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.c +++ b/source/blender/blenkernel/intern/mesh_evaluate.c @@ -179,7 +179,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 { @@ -192,7 +192,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)) { @@ -203,7 +203,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)) { @@ -402,14 +402,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); @@ -2325,19 +2325,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); @@ -2346,9 +2346,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; } @@ -2368,18 +2368,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++) { @@ -2387,7 +2387,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; @@ -2399,7 +2399,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. diff --git a/source/blender/blenkernel/intern/mesh_iterators.c b/source/blender/blenkernel/intern/mesh_iterators.c new file mode 100644 index 00000000000..48f6b1820f8 --- /dev/null +++ b/source/blender/blenkernel/intern/mesh_iterators.c @@ -0,0 +1,154 @@ +/* + * ***** 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): Blender Foundation + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/blenkernel/intern/mesh_iterators.c + * \ingroup bke + * + * Functions for iterating mesh features. + */ + +#include "DNA_mesh_types.h" +#include "DNA_meshdata_types.h" + +#include "BKE_customdata.h" +#include "BKE_mesh.h" +#include "BKE_mesh_iterators.h" + + +/* Copied from cdDM_foreachMappedVert */ +void BKE_mesh_foreach_mapped_vert( + Mesh *mesh, + void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]), + void *userData, + MeshForeachFlag flag) +{ + MVert *mv = mesh->mvert; + const int *index = CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX); + int i; + + if (index) { + for (i = 0; i < mesh->totvert; i++, mv++) { + const short *no = (flag & MESH_FOREACH_USE_NORMAL) ? mv->no : NULL; + const int orig = *index++; + if (orig == ORIGINDEX_NONE) continue; + func(userData, orig, mv->co, NULL, no); + } + } + else { + for (i = 0; i < mesh->totvert; i++, mv++) { + const short *no = (flag & MESH_FOREACH_USE_NORMAL) ? mv->no : NULL; + func(userData, i, mv->co, NULL, no); + } + } +} + +/* Copied from cdDM_foreachMappedEdge */ +void BKE_mesh_foreach_mapped_edge( + Mesh *mesh, + void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]), + void *userData) +{ + MVert *mv = mesh->mvert; + MEdge *med = mesh->medge; + int i, orig, *index = CustomData_get_layer(&mesh->edata, CD_ORIGINDEX); + + for (i = 0; i < mesh->totedge; i++, med++) { + if (index) { + orig = *index++; + if (orig == ORIGINDEX_NONE) continue; + func(userData, orig, mv[med->v1].co, mv[med->v2].co); + } + else + func(userData, i, mv[med->v1].co, mv[med->v2].co); + } +} + +/* Copied from cdDM_foreachMappedLoop */ +void BKE_mesh_foreach_mapped_loop( + Mesh *mesh, + void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]), + void *userData, + MeshForeachFlag flag) +{ + /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would + * return loop data from bmesh itself. */ + const float (*lnors)[3] = (flag & MESH_FOREACH_USE_NORMAL) ? CustomData_get_layer(&mesh->ldata, CD_NORMAL) : NULL; + + const MVert *mv = mesh->mvert; + const MLoop *ml = mesh->mloop; + const MPoly *mp = mesh->mpoly; + const int *v_index = CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX); + const int *f_index = CustomData_get_layer(&mesh->pdata, CD_ORIGINDEX); + int p_idx, i; + + for (p_idx = 0; p_idx < mesh->totpoly; ++p_idx, ++mp) { + for (i = 0; i < mp->totloop; ++i, ++ml) { + const int v_idx = v_index ? v_index[ml->v] : ml->v; + const int f_idx = f_index ? f_index[p_idx] : p_idx; + const float *no = lnors ? *lnors++ : NULL; + if (!ELEM(ORIGINDEX_NONE, v_idx, f_idx)) { + func(userData, v_idx, f_idx, mv[ml->v].co, no); + } + } + } +} + +/* Copied from cdDM_foreachMappedFaceCenter */ +void BKE_mesh_foreach_mapped_face_center( + Mesh *mesh, + void (*func)(void *userData, int index, const float cent[3], const float no[3]), + void *userData, + MeshForeachFlag flag) +{ + MVert *mvert = mesh->mvert; + MPoly *mp; + MLoop *ml; + int i, orig, *index; + + index = CustomData_get_layer(&mesh->pdata, CD_ORIGINDEX); + mp = mesh->mpoly; + for (i = 0; i < mesh->totpoly; i++, mp++) { + float cent[3]; + float *no, _no[3]; + + if (index) { + orig = *index++; + if (orig == ORIGINDEX_NONE) continue; + } + else { + orig = i; + } + + ml = &mesh->mloop[mp->loopstart]; + BKE_mesh_calc_poly_center(mp, ml, mvert, cent); + + if (flag & MESH_FOREACH_USE_NORMAL) { + BKE_mesh_calc_poly_normal(mp, ml, mvert, (no = _no)); + } + else { + no = NULL; + } + + func(userData, orig, cent, no); + } + +} diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index 0b904caf375..835b78e2a78 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -130,7 +130,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)); @@ -489,7 +489,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; } @@ -505,7 +505,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); @@ -614,7 +614,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) { @@ -623,10 +623,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; } @@ -659,7 +659,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) { @@ -668,10 +668,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; } @@ -683,7 +683,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) { @@ -692,10 +692,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; } diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c index fc236cc2ad0..98586a5c2f5 100644 --- a/source/blender/blenkernel/intern/movieclip.c +++ b/source/blender/blenkernel/intern/movieclip.c @@ -171,7 +171,7 @@ static void get_sequence_fname(const MovieClip *clip, BLI_strncpy(name, clip->name, sizeof(clip->name)); } - BLI_path_abs(name, ID_BLEND_PATH(G.main, &clip->id)); + BLI_path_abs(name, ID_BLEND_PATH_FROM_GLOBAL(&clip->id)); } /* supposed to work with sequences only */ @@ -261,7 +261,7 @@ static void movieclip_open_anim_file(MovieClip *clip) if (!clip->anim) { BLI_strncpy(str, clip->name, FILE_MAX); - BLI_path_abs(str, ID_BLEND_PATH(G.main, &clip->id)); + BLI_path_abs(str, ID_BLEND_PATH_FROM_GLOBAL(&clip->id)); /* FIXME: make several stream accessible in image editor, too */ clip->anim = openanim(str, IB_rect, 0, clip->colorspace_settings.name); @@ -1300,7 +1300,7 @@ void BKE_movieclip_reload(Main *bmain, MovieClip *clip) */ { Scene *scene; - for (scene = G.main->scene.first; scene; scene = scene->id.next) { + for (scene = bmain->scene.first; scene; scene = scene->id.next) { if (scene->nodetree) { nodeUpdateID(scene->nodetree, &clip->id); } @@ -1568,7 +1568,7 @@ void BKE_movieclip_filename_for_frame(MovieClip *clip, MovieClipUser *user, char } else { BLI_strncpy(name, clip->name, FILE_MAX); - BLI_path_abs(name, ID_BLEND_PATH(G.main, &clip->id)); + BLI_path_abs(name, ID_BLEND_PATH_FROM_GLOBAL(&clip->id)); } } diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c index 39a472241bc..5bd4a1a0475 100644 --- a/source/blender/blenkernel/intern/multires.c +++ b/source/blender/blenkernel/intern/multires.c @@ -190,7 +190,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); } } @@ -205,7 +205,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++) { @@ -213,7 +213,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); @@ -227,7 +227,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 */ @@ -238,7 +238,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; @@ -251,7 +251,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; @@ -475,7 +475,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; @@ -485,9 +485,9 @@ static int get_levels_from_disps(Object *ob) totlvl--; else totlvl++; - + } - + break; } } @@ -538,7 +538,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); @@ -736,7 +736,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); } @@ -802,7 +802,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; @@ -828,18 +828,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); @@ -854,7 +854,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); @@ -943,7 +943,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); @@ -956,7 +956,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); @@ -1129,7 +1129,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); @@ -1141,7 +1141,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); @@ -1215,7 +1215,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; @@ -1312,7 +1312,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]; @@ -1326,131 +1326,11 @@ void multires_modifier_update_hidden(DerivedMesh *dm) md->hidden); if (md->hidden) MEM_freeN(md->hidden); - - md->hidden = gh; - } - } - } -} - -void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) -{ - DerivedMesh *ccgdm = NULL, *subsurf = NULL; - CCGElem **gridData, **subGridData = NULL; - CCGKey key; - MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY); - MDisps *mdisps; - 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) { - goto cleanup; - } - - 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); - numGrids = subsurf->getNumGrids(subsurf); - gridSize = subsurf->getGridSize(subsurf); - gridData = subsurf->getGridData(subsurf); - subsurf->getGridKey(subsurf, &key); - - subGridData = MEM_calloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*"); - - for (i = 0; i < numGrids; i++) { - 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); - gridOffset = ccgdm->getGridOffset((DerivedMesh *)ccgdm); - - dGridSize = multires_side_tot[totlvl]; - dSkip = (dGridSize - 1) / (gridSize - 1); - - k = 0; /*current loop/mdisp index within the mloop array*/ - - /* TODO: Use BLI_task parallel range for that one too? */ - 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 */ - CCGElem *subgrid = subGridData[gIndex]; - float (*dispgrid)[3] = NULL; - - /* when adding new faces in edit mode, need to allocate disps */ - if (!mdisp->disps) { - mdisp->totdisp = gridSize * gridSize; - mdisp->level = totlvl; - mdisp->disps = MEM_calloc_arrayN(mdisp->totdisp, 3 * sizeof(float), "disp in multires_set_space"); - } - - dispgrid = mdisp->disps; - - for (y = 0; y < gridSize; y++) { - for (x = 0; x < gridSize; x++) { - 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); - - /* convert to absolute coordinates in space */ - if (from == MULTIRES_SPACE_TANGENT) { - mul_v3_m3v3(dco, mat, data); - add_v3_v3(dco, co); - } - else if (from == MULTIRES_SPACE_OBJECT) { - add_v3_v3v3(dco, co, data); - } - 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); - - sub_v3_v3(dco, co); - mul_v3_m3v3(data, mat, dco); - } - else if (to == MULTIRES_SPACE_OBJECT) { - sub_v3_v3(dco, co); - mul_v3_m3v3(data, mat, dco); - } - else if (to == MULTIRES_SPACE_ABSOLUTE) { - copy_v3_v3(data, dco); - } - } + md->hidden = gh; } } } - -cleanup: - if (subsurf) { - subsurf->needsFree = 1; - subsurf->release(subsurf); - } - - if (ccgdm) { - ccgdm->needsFree = 1; - ccgdm->release(ccgdm); - } } void multires_stitch_grids(Object *ob) @@ -1545,10 +1425,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) @@ -1565,7 +1445,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; @@ -1640,7 +1520,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); @@ -1649,7 +1529,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; @@ -1710,11 +1590,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) { @@ -1729,11 +1609,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) { @@ -1854,7 +1734,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); @@ -2085,7 +1965,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; @@ -2164,7 +2044,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 b91887e6815..91340997532 100644 --- a/source/blender/blenkernel/intern/nla.c +++ b/source/blender/blenkernel/intern/nla.c @@ -54,9 +54,10 @@ #include "BKE_action.h" #include "BKE_fcurve.h" -#include "BKE_nla.h" #include "BKE_global.h" #include "BKE_library.h" +#include "BKE_main.h" +#include "BKE_nla.h" #ifdef WITH_AUDASPACE # include <AUD_Special.h> @@ -78,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); @@ -116,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); @@ -140,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); } @@ -162,19 +163,19 @@ void BKE_nla_tracks_free(ListBase *tracks) * * \param use_same_action When true, the existing action is used (instead of being duplicated) */ -NlaStrip *BKE_nlastrip_copy(NlaStrip *strip, const bool use_same_action) +NlaStrip *BKE_nlastrip_copy(Main *bmain, NlaStrip *strip, const bool use_same_action) { 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) { @@ -183,104 +184,104 @@ NlaStrip *BKE_nlastrip_copy(NlaStrip *strip, const bool use_same_action) } else { /* use a copy of the action instead (user count shouldn't have changed yet) */ - strip_d->act = BKE_action_copy(G.main, strip_d->act); + 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(cs, use_same_action); + cs_d = BKE_nlastrip_copy(bmain, cs, use_same_action); BLI_addtail(&strip_d->strips, cs_d); } - + /* return the strip */ return strip_d; } /* Copy NLA Track */ -NlaTrack *BKE_nlatrack_copy(NlaTrack *nlt, const bool use_same_actions) +NlaTrack *BKE_nlatrack_copy(Main *bmain, NlaTrack *nlt, const bool use_same_actions) { 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(strip, use_same_actions); + strip_d = BKE_nlastrip_copy(bmain, strip, use_same_actions); BLI_addtail(&nlt_d->strips, strip_d); } - + /* return the copy */ return nlt_d; } /* Copy all NLA data */ -void BKE_nla_tracks_copy(ListBase *dst, ListBase *src) +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 */ // XXX: we need to fix this sometime - nlt_d = BKE_nlatrack_copy(nlt, true); + nlt_d = BKE_nlatrack_copy(bmain, nlt, true); BLI_addtail(dst, nlt_d); } } /* 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; } @@ -289,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 @@ -305,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; } @@ -331,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; } @@ -361,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 @@ -379,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; } @@ -406,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? */ @@ -430,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 */ @@ -453,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 */ @@ -475,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) @@ -506,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); @@ -523,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 */ @@ -545,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); } @@ -568,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; @@ -576,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 @@ -584,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) { @@ -629,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 */ @@ -669,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; } @@ -685,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) { @@ -701,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; } @@ -736,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 */ @@ -749,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); } @@ -761,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 */ @@ -790,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 */ @@ -832,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) @@ -841,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 */ @@ -850,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; @@ -891,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); } @@ -916,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; } @@ -939,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)) { @@ -953,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 : "<None>", nlt, nlt->name); } } } - + /* Not found! */ return NULL; } @@ -970,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; @@ -996,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; @@ -1019,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) @@ -1044,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) @@ -1057,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); } @@ -1072,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; } @@ -1101,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; } @@ -1121,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) { @@ -1143,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 @@ -1164,7 +1165,7 @@ bool BKE_nlastrip_within_bounds(NlaStrip *strip, float min, float max) { return false; } - + /* should be ok! */ return true; } @@ -1177,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 @@ -1197,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; @@ -1210,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; @@ -1218,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 @@ -1244,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; @@ -1257,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; @@ -1273,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); } @@ -1301,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) { @@ -1320,7 +1321,7 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) return false; } } - + /* should be first now */ return true; } @@ -1331,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; } @@ -1350,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; } @@ -1369,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? */ } } @@ -1432,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; } @@ -1465,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. @@ -1475,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) { @@ -1497,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)); @@ -1526,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 @@ -1534,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) { @@ -1546,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... */ @@ -1572,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; @@ -1580,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)) { @@ -1601,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) ) @@ -1618,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) @@ -1675,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) { @@ -1684,7 +1685,7 @@ bool BKE_nla_action_is_stashed(AnimData *adt, bAction *act) } } } - + return false; } @@ -1696,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; } @@ -1766,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)) @@ -1780,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] @@ -1800,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 @@ -1815,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 @@ -1828,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); } @@ -1841,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 */ @@ -1860,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 */ @@ -1877,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; @@ -1893,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"); @@ -1901,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) { @@ -1913,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)) @@ -1921,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 @@ -1940,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; } @@ -1950,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); } @@ -1981,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 @@ -2018,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 72a34d35715..9de31205504 100644 --- a/source/blender/blenkernel/intern/node.c +++ b/source/blender/blenkernel/intern/node.c @@ -94,7 +94,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++; } } @@ -102,7 +102,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++; } } @@ -117,11 +117,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; @@ -136,7 +136,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) @@ -149,17 +149,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; } @@ -167,13 +167,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; } } @@ -185,19 +185,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; } } @@ -206,10 +206,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); @@ -217,7 +217,7 @@ static void node_socket_set_typeinfo(bNodeTree *ntree, bNodeSocket *sock, bNodeS } else { sock->typeinfo = &NodeSocketTypeUndefined; - + ntree->init &= ~NTREE_TYPE_INIT; } } @@ -227,21 +227,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)) @@ -250,7 +250,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)) @@ -271,20 +271,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) @@ -314,7 +314,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 */ @@ -322,7 +324,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); } @@ -371,12 +375,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); } @@ -386,10 +392,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) @@ -425,8 +433,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); } @@ -434,7 +444,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) @@ -479,7 +491,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)); @@ -490,21 +502,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; } @@ -533,12 +545,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; } @@ -547,12 +559,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; } @@ -683,12 +695,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; @@ -699,12 +711,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; @@ -716,7 +728,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); } @@ -724,21 +736,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; } @@ -746,14 +758,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); @@ -767,7 +779,7 @@ void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node) MEM_freeN(sock); } BLI_listbase_clear(&node->outputs); - + node->update |= NODE_UPDATE; } @@ -784,7 +796,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++) { @@ -800,7 +812,7 @@ int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockin if (sockindex) *sockindex = index; return 1; } - + *nodep = NULL; return 0; } @@ -892,22 +904,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 @@ -1024,11 +1036,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) @@ -1048,10 +1060,10 @@ bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, link->tonode = fromnode; link->tosock = fromsock; } - + if (ntree) ntree->update |= NTREE_UPDATE_LINKS; - + return link; } @@ -1064,7 +1076,7 @@ void nodeRemLink(bNodeTree *ntree, bNodeLink *link) if (link->tosock) link->tosock->link = NULL; MEM_freeN(link); - + if (ntree) ntree->update |= NTREE_UPDATE_LINKS; } @@ -1072,14 +1084,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; } @@ -1091,15 +1103,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) { @@ -1109,13 +1121,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 @@ -1125,11 +1137,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); } @@ -1179,7 +1191,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); @@ -1188,7 +1200,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); @@ -1209,7 +1221,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. */ @@ -1221,15 +1233,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; } @@ -1360,7 +1372,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) { @@ -1370,11 +1382,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) { @@ -1382,14 +1394,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; } @@ -1413,14 +1425,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); } @@ -1430,10 +1442,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); } @@ -1442,10 +1454,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); } @@ -1455,11 +1467,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); } @@ -1467,7 +1479,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; @@ -1483,10 +1495,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); @@ -1497,7 +1509,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; @@ -1511,15 +1523,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); } @@ -1531,27 +1543,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; @@ -1559,7 +1571,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) @@ -1568,7 +1580,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); } @@ -1593,10 +1605,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); @@ -1605,7 +1617,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) @@ -1615,7 +1627,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); } @@ -1638,10 +1650,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) @@ -1677,30 +1689,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]; @@ -1713,7 +1725,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); @@ -1744,7 +1756,7 @@ static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdat } MEM_freeN(node); - + if (ntree) ntree->update |= NTREE_UPDATE_NODES; } @@ -1760,7 +1772,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); } @@ -1768,7 +1780,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 @@ -1776,7 +1788,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; @@ -1789,7 +1801,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; @@ -1811,15 +1822,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); @@ -1836,7 +1847,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); @@ -1844,12 +1855,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); } } @@ -1857,7 +1865,7 @@ void ntreeFreeTree(bNodeTree *ntree) void ntreeFreeCache(bNodeTree *ntree) { if (ntree == NULL) return; - + if (ntree->typeinfo->free_cache) ntree->typeinfo->free_cache(ntree); } @@ -1871,7 +1879,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; @@ -1879,9 +1887,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) && @@ -1909,12 +1917,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) { @@ -1928,7 +1936,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... */ } @@ -2055,7 +2063,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); } @@ -2080,7 +2088,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 */ @@ -2107,13 +2115,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; } @@ -2129,7 +2137,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); @@ -2139,7 +2147,7 @@ bNodeSocket *ntreeAddSocketInterface(bNodeTree *ntree, int in_out, const char *i BLI_addtail(&ntree->outputs, iosock); ntree->update |= NTREE_UPDATE_GROUP_OUT; } - + return iosock; } @@ -2147,7 +2155,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); @@ -2157,7 +2165,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; } @@ -2186,10 +2194,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; } @@ -2216,7 +2224,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); } @@ -2227,20 +2235,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; @@ -2259,20 +2267,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); @@ -2283,7 +2291,7 @@ StructRNA *ntreeInterfaceTypeGet(bNodeTree *ntree, int create) else if (create) { ntree_interface_type_create(ntree); } - + return ntree->interface_type; } @@ -2344,7 +2352,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; @@ -2358,7 +2366,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++; @@ -2369,9 +2377,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; @@ -2402,7 +2410,7 @@ static bNode *node_get_active_id_recursive(bNodeInstanceKey active_key, bNodeIns } } } - + return NULL; } @@ -2451,9 +2459,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; @@ -2466,9 +2474,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; @@ -2491,11 +2499,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; @@ -2503,7 +2511,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; @@ -2559,13 +2567,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); @@ -2603,7 +2611,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) { @@ -2684,25 +2693,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; } @@ -2773,10 +2782,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; } } @@ -2790,7 +2799,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; @@ -2807,19 +2816,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); } @@ -2832,9 +2841,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) { @@ -2845,7 +2854,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) @@ -2853,21 +2862,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; @@ -2877,9 +2886,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) { @@ -2892,12 +2901,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) { @@ -2911,7 +2920,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) { @@ -2921,12 +2930,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; } @@ -2937,7 +2946,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) { @@ -2948,14 +2957,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) @@ -2971,7 +2980,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); @@ -2981,31 +2990,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); @@ -3014,28 +3023,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; } @@ -3045,15 +3054,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; } @@ -3061,15 +3070,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; @@ -3080,11 +3089,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; } @@ -3092,7 +3101,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); } @@ -3159,14 +3168,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; @@ -3193,7 +3202,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)) { @@ -3201,7 +3210,7 @@ static bool unique_socket_template_identifier_check(void *arg, const char *name) } } } - + return false; } @@ -3217,16 +3226,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, '_'); @@ -3236,7 +3245,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, '_'); @@ -3343,14 +3352,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; @@ -3360,7 +3369,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(); @@ -3368,13 +3377,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(); @@ -3385,13 +3394,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(); @@ -3402,7 +3411,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(); @@ -3417,7 +3426,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(); @@ -3458,7 +3467,7 @@ static void registerCompositNodes(void) register_node_type_cmp_cornerpin(); } -static void registerShaderNodes(void) +static void registerShaderNodes(void) { register_node_type_sh_group(); @@ -3552,7 +3561,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(); @@ -3566,26 +3575,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(); @@ -3598,7 +3607,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"); @@ -3617,13 +3626,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 f55925f64f5..5ca9b9d2203 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -148,7 +148,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; @@ -436,9 +436,9 @@ void BKE_object_free(Object *ob) animviz_free_motionpath(ob->mpath); ob->mpath = NULL; } - + BKE_constraints_free_ex(&ob->constraints, false); - + free_partdeflect(ob->pd); BKE_rigidbody_free_object(ob); BKE_rigidbody_free_constraint(ob); @@ -478,7 +478,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) @@ -486,25 +486,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; } @@ -628,9 +628,9 @@ bool BKE_object_is_visible(Object *ob, const eObjectVisibilityCheck mode) 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; @@ -692,12 +692,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; @@ -709,7 +709,7 @@ 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); @@ -725,7 +725,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; @@ -739,7 +739,7 @@ void BKE_object_init(Object *ob) ob->fluidsimSettings = NULL; BLI_listbase_clear(&ob->pc_ids); - + /* Animation Visualization defaults */ animviz_settings_init(&ob->avs); @@ -830,9 +830,9 @@ Object *BKE_object_add_from( 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) { @@ -858,10 +858,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); @@ -874,38 +874,9 @@ SoftBody *copy_softbody(const SoftBody *sb, const int flag) ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int flag) { - ParticleSystem *psysn; - ParticleData *pa; - int p; - - psysn = MEM_dupallocN(psys); - psysn->particles = MEM_dupallocN(psys->particles); - psysn->child = MEM_dupallocN(psys->child); - - if (psys->part->type == PART_HAIR) { - for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) - pa->hair = MEM_dupallocN(pa->hair); - } - - if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) { - ParticleKey *key = psysn->particles->keys; - BoidParticle *boid = psysn->particles->boid; - - 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++; - if (key) { - pa->keys = key; - key += pa->totkey; - } - } - } + ParticleSystem *psysn = MEM_dupallocN(psys); + + psys_copy_particles(psysn, psys); if (psys->clmd) { psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth); @@ -923,10 +894,10 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int f psysn->tree = NULL; psysn->bvhtree = NULL; psysn->batch_cache = NULL; - + BLI_listbase_clear(&psysn->pathcachebufs); BLI_listbase_clear(&psysn->childcachebufs); - + psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, flag); /* XXX - from reading existing code this seems correct but intended usage of @@ -975,7 +946,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) @@ -998,31 +969,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); } @@ -1191,11 +1162,11 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ } if (ob_src->iuser) ob_dst->iuser = MEM_dupallocN(ob_src->iuser); - + if (ob_src->bb) ob_dst->bb = MEM_dupallocN(ob_src->bb); - + 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)); @@ -1227,7 +1198,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; @@ -1239,7 +1210,7 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ ob_dst->mpath = animviz_copy_motionpath(ob_src->mpath); copy_object_lod(ob_dst, ob_src, flag_subdata); - + /* Do not copy runtime curve data. */ ob_dst->curve_cache = NULL; @@ -1335,34 +1306,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) @@ -1393,14 +1364,14 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *cob) printf("cannot make proxy\n"); return; } - + ob->proxy = target; ob->proxy_group = cob; id_lib_extern(&target->id); - + DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); DEG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); - + /* copy transform * - cob means this proxy comes from a collection, just apply the matrix * so the object wont move from its dupli-transform. @@ -1422,13 +1393,13 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *cob) 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; @@ -1445,24 +1416,24 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *cob) 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) { @@ -1546,7 +1517,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 */ @@ -1565,14 +1536,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); @@ -1696,7 +1667,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); @@ -1708,9 +1679,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); @@ -1760,7 +1731,7 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, /* 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 @@ -1784,10 +1755,10 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, if (cu->pathlen) { ctime /= cu->pathlen; } - + CLAMP(ctime, 0.0f, 1.0f); } - + unit_m4(mat); /* vec: 4 items! */ @@ -1797,7 +1768,7 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, #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]); @@ -1812,7 +1783,7 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, 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); @@ -1821,22 +1792,22 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, } 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) { @@ -1864,14 +1835,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); @@ -2047,16 +2018,16 @@ void BKE_object_get_parent_matrix(Depsgraph *depsgraph, Scene *scene, Object *ob 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); @@ -2064,10 +2035,10 @@ void BKE_object_get_parent_matrix(Depsgraph *depsgraph, Scene *scene, Object *ob 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; @@ -2085,22 +2056,22 @@ static void solve_parenting(Depsgraph *depsgraph, 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(depsgraph, 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) { @@ -2138,18 +2109,18 @@ void BKE_object_where_is_calc_time_ex( RigidBodyWorld *rbw, float r_originmat[3][3]) { if (ob == NULL) return; - + /* execute drivers only, as animation has already been done */ BKE_animsys_evaluate_animdata(depsgraph, 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(depsgraph, 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) { @@ -2165,7 +2136,7 @@ void BKE_object_where_is_calc_time_ex( 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; @@ -2173,7 +2144,7 @@ void BKE_object_where_is_calc_time_ex( BKE_constraints_solve(depsgraph, &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; @@ -2195,9 +2166,9 @@ void BKE_object_where_is_calc_mat4(Depsgraph *depsgraph, Scene *scene, Object *o float slowmat[4][4]; Object *par = ob->parent; - + solve_parenting(depsgraph, scene, ob, par, obmat, slowmat, NULL, false); - + if (ob->partype & PARSLOW) where_is_object_parslow(ob, obmat, slowmat); } @@ -2227,7 +2198,7 @@ void BKE_object_workob_calc_parent(Depsgraph *depsgraph, Scene *scene, Object *o { Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); BKE_object_workob_clear(workob); - + unit_m4(workob->obmat); unit_m4(workob->parentinv); unit_m4(workob->constinv); @@ -2237,7 +2208,7 @@ void BKE_object_workob_calc_parent(Depsgraph *depsgraph, Scene *scene, Object *o workob->trackflag = ob_eval->trackflag; workob->upflag = ob_eval->upflag; - + workob->partype = ob_eval->partype; workob->par1 = ob_eval->par1; workob->par2 = ob_eval->par2; @@ -2303,7 +2274,7 @@ BoundBox *BKE_boundbox_alloc_unit(void) bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox"); BKE_boundbox_init_from_minmax(bb, min, max); - + return bb; } @@ -2311,7 +2282,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]; @@ -2346,7 +2317,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); } @@ -2378,13 +2349,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]); @@ -2397,17 +2368,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]; @@ -2419,7 +2390,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: @@ -2767,7 +2738,7 @@ void BKE_object_handle_update_ex(Depsgraph *depsgraph, object_handle_update_proxy(depsgraph, 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 @@ -2812,10 +2783,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: { @@ -2919,7 +2890,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; @@ -2944,18 +2915,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; } @@ -2969,7 +2940,7 @@ void BKE_object_delete_ptcache(Object *ob, int index) /* shape key utility function */ /************************* Mesh ************************/ -static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mix) +static KeyBlock *insert_meshkey(Main *bmain, Object *ob, const char *name, const bool from_mix) { Mesh *me = ob->data; Key *key = me->key; @@ -2977,7 +2948,7 @@ static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mi int newkey = 0; if (key == NULL) { - key = me->key = BKE_key_add((ID *)me); + key = me->key = BKE_key_add(bmain, (ID *)me); key->type = KEY_RELATIVE; newkey = 1; } @@ -3001,7 +2972,7 @@ static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mi return kb; } /************************* Lattice ************************/ -static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mix) +static KeyBlock *insert_lattkey(Main *bmain, Object *ob, const char *name, const bool from_mix) { Lattice *lt = ob->data; Key *key = lt->key; @@ -3009,7 +2980,7 @@ static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mi int newkey = 0; if (key == NULL) { - key = lt->key = BKE_key_add((ID *)lt); + key = lt->key = BKE_key_add(bmain, (ID *)lt); key->type = KEY_RELATIVE; newkey = 1; } @@ -3039,7 +3010,7 @@ static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mi return kb; } /************************* Curve ************************/ -static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_mix) +static KeyBlock *insert_curvekey(Main *bmain, Object *ob, const char *name, const bool from_mix) { Curve *cu = ob->data; Key *key = cu->key; @@ -3048,7 +3019,7 @@ static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_m int newkey = 0; if (key == NULL) { - key = cu->key = BKE_key_add((ID *)cu); + key = cu->key = BKE_key_add(bmain, (ID *)cu); key->type = KEY_RELATIVE; newkey = 1; } @@ -3079,16 +3050,16 @@ static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_m return kb; } -KeyBlock *BKE_object_shapekey_insert(Object *ob, const char *name, const bool from_mix) -{ +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(ob, name, from_mix); + return insert_meshkey(bmain, ob, name, from_mix); case OB_CURVE: case OB_SURF: - return insert_curvekey(ob, name, from_mix); + return insert_curvekey(bmain, ob, name, from_mix); case OB_LATTICE: - return insert_lattkey(ob, name, from_mix); + return insert_lattkey(bmain, ob, name, from_mix); default: return NULL; } diff --git a/source/blender/blenkernel/intern/object_deform.c b/source/blender/blenkernel/intern/object_deform.c index fb2e824b299..2de81864512 100644 --- a/source/blender/blenkernel/intern/object_deform.c +++ b/source/blender/blenkernel/intern/object_deform.c @@ -133,7 +133,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")); } diff --git a/source/blender/blenkernel/intern/object_dupli.c b/source/blender/blenkernel/intern/object_dupli.c index e9b1e79dc67..b7748039f62 100644 --- a/source/blender/blenkernel/intern/object_dupli.c +++ b/source/blender/blenkernel/intern/object_dupli.c @@ -124,7 +124,7 @@ static void init_context( static void copy_dupli_context(DupliContext *r_ctx, const DupliContext *ctx, Object *ob, float mat[4][4], int index) { *r_ctx = *ctx; - + /* XXX annoying, previously was done by passing an ID* argument, this at least is more explicit */ if (ctx->gen->type == OB_DUPLICOLLECTION) r_ctx->collection = ctx->object->dup_group; @@ -233,13 +233,12 @@ static void make_child_duplis(const DupliContext *ctx, void *userdata, MakeChild Object *parent = ctx->object; if (ctx->collection) { - int collectionid = 0; - FOREACH_COLLECTION_BASE_RECURSIVE_BEGIN(ctx->collection, base) + eEvaluationMode mode = DEG_get_mode(ctx->depsgraph); + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(ctx->collection, ob, mode) { - Object *ob = base->object; - if ((base->flag & BASE_VISIBLED) && ob != ctx->obedit && is_child(ob, parent)) { + if ((ob != ctx->obedit) && is_child(ob, parent)) { DupliContext pctx; - copy_dupli_context(&pctx, ctx, ctx->object, NULL, collectionid); + copy_dupli_context(&pctx, ctx, ctx->object, NULL, _base_id); /* mballs have a different dupli handling */ if (ob->type != OB_MBALL) { @@ -247,9 +246,8 @@ static void make_child_duplis(const DupliContext *ctx, void *userdata, MakeChild } make_child_duplis_cb(&pctx, userdata, ob); } - collectionid++; } - FOREACH_COLLECTION_BASE_RECURSIVE_END + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } else { int baseid = 0; @@ -278,9 +276,7 @@ static void make_duplis_collection(const DupliContext *ctx) { Object *ob = ctx->object; Collection *collection; - Base *base; float collection_mat[4][4]; - int id; if (ob->dup_group == NULL) return; collection = ob->dup_group; @@ -291,20 +287,22 @@ static void make_duplis_collection(const DupliContext *ctx) mul_m4_m4m4(collection_mat, ob->obmat, collection_mat); /* don't access 'ob->obmat' from now on. */ - const ListBase dup_collection_objects = BKE_collection_object_cache_get(collection); - for (base = dup_collection_objects.first, id = 0; base; base = base->next, id++) { - if (base->object != ob && (base->flag & BASE_VISIBLED)) { + eEvaluationMode mode = DEG_get_mode(ctx->depsgraph); + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(collection, cob, mode) + { + if (cob != ob) { float mat[4][4]; /* collection dupli offset, should apply after everything else */ - mul_m4_m4m4(mat, collection_mat, base->object->obmat); + mul_m4_m4m4(mat, collection_mat, cob->obmat); - make_dupli(ctx, base->object, mat, id); + make_dupli(ctx, cob, mat, _base_id); /* recursion */ - make_recursive_duplis(ctx, base->object, collection_mat, id); + make_recursive_duplis(ctx, cob, collection_mat, _base_id); } } + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } static const DupliGenerator gen_dupli_collection = { @@ -540,7 +538,7 @@ static const DupliGenerator gen_dupli_verts = { }; /* OB_DUPLIVERTS - FONT */ -static Object *find_family_object(const char *family, size_t family_len, unsigned int ch, GHash *family_gh) +static Object *find_family_object(Main *bmain, const char *family, size_t family_len, unsigned int ch, GHash *family_gh) { Object **ob_pt; Object *ob; @@ -557,7 +555,7 @@ static Object *find_family_object(const char *family, size_t family_len, unsigne ch_utf8[ch_utf8_len] = '\0'; ch_utf8_len += 1; /* compare with null terminator */ - for (ob = G.main->object.first; ob; ob = ob->id.next) { + for (ob = bmain->object.first; ob; ob = ob->id.next) { if (STREQLEN(ob->id.name + 2 + family_len, ch_utf8, ch_utf8_len)) { if (STREQLEN(ob->id.name + 2, family, family_len)) { break; @@ -593,7 +591,7 @@ static void make_duplis_font(const DupliContext *ctx) /* in par the family name is stored, use this to find the other objects */ - BKE_vfont_to_curve_ex(G.main, par, par->data, FO_DUPLI, NULL, + BKE_vfont_to_curve_ex(par, par->data, FO_DUPLI, NULL, &text, &text_len, &text_free, &chartransdata); if (text == NULL || chartransdata == NULL) { @@ -614,7 +612,9 @@ static void make_duplis_font(const DupliContext *ctx) /* advance matching BLI_strncpy_wchar_from_utf8 */ for (a = 0; a < text_len; a++, ct++) { - ob = find_family_object(cu->family, family_len, (unsigned int)text[a], family_gh); + /* XXX That G.main is *really* ugly, but not sure what to do here... + * Definitively don't think it would be safe to put back Main *bmain pointer in DupliContext as done in 2.7x? */ + ob = find_family_object(G.main, cu->family, family_len, (unsigned int)text[a], family_gh); if (ob) { vec[0] = fsize * (ct->xof - xof); vec[1] = fsize * (ct->yof - yof); @@ -820,7 +820,8 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem { Scene *scene = ctx->scene; Object *par = ctx->object; - bool for_render = DEG_get_mode(ctx->depsgraph) == DAG_EVAL_RENDER; + eEvaluationMode mode = DEG_get_mode(ctx->depsgraph); + bool for_render = mode == DAG_EVAL_RENDER; bool use_texcoords = for_render; Object *ob = NULL, **oblist = NULL, obcopy, *obcopylist = NULL; @@ -836,6 +837,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem float (*obmat)[4]; int a, b, hair = 0; int totpart, totchild, totcollection = 0 /*, pa_num */; + RNG *rng; int no_draw_flag = PARS_UNEXIST; @@ -846,7 +848,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem if (part == NULL) return; - if (!psys_check_enabled(par, psys, (DEG_get_mode(ctx->depsgraph) == DAG_EVAL_RENDER))) + if (!psys_check_enabled(par, psys, for_render)) return; if (!for_render) @@ -857,7 +859,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem totpart = psys->totpart; totchild = psys->totchild; - BLI_srandom((unsigned int)(31415926 + psys->seed)); + rng = BLI_rng_new_srandom(31415926u + (unsigned int)psys->seed); if ((for_render || part->draw_as == PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) { ParticleSimulationData sim = {NULL}; @@ -910,12 +912,12 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem totcollection += dw->count; } else { - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object) + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(part->dup_group, object, mode) { (void) object; totcollection++; } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } /* we also copy the actual objects to restore afterwards, since @@ -935,7 +937,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem } else { a = 0; - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object) + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(part->dup_group, object, mode) { oblist[a] = object; obcopylist[a] = *object; @@ -945,7 +947,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem continue; } } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } } else { @@ -992,7 +994,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem /* for collections, pick the object based on settings */ if (part->draw & PART_DRAW_RAND_GR) - b = BLI_rand() % totcollection; + b = BLI_rng_get_int(rng) % totcollection; else b = a % totcollection; @@ -1035,7 +1037,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem if (part->ren_as == PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) { b = 0; - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object) + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(part->dup_group, object, mode) { copy_m4_m4(tmat, oblist[b]->obmat); @@ -1060,7 +1062,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem b++; } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } else { /* to give ipos in object correct offset */ @@ -1131,6 +1133,8 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem end_latt_deform(psys->lattice_deform_data); psys->lattice_deform_data = NULL; } + + BLI_rng_free(rng); } static void make_duplis_particles(const DupliContext *ctx) @@ -1249,7 +1253,7 @@ DupliApplyData *duplilist_apply(Depsgraph *depsgraph, Object *ob, Scene *scene, { DupliApplyData *apply_data = NULL; int num_objects = BLI_listbase_count(duplilist); - + if (num_objects > 0) { DupliObject *dob; int i; @@ -1270,7 +1274,7 @@ DupliApplyData *duplilist_apply(Depsgraph *depsgraph, Object *ob, Scene *scene, /* 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; @@ -1290,7 +1294,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/object_update.c b/source/blender/blenkernel/intern/object_update.c index f0f31eebfbd..4c38940b11d 100644 --- a/source/blender/blenkernel/intern/object_update.c +++ b/source/blender/blenkernel/intern/object_update.c @@ -242,7 +242,6 @@ void BKE_object_handle_data_update( if (!(ob->mode & OB_MODE_EDIT) && ob->particlesystem.first) { const bool use_render_params = (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER); ParticleSystem *tpsys, *psys; - DerivedMesh *dm; ob->transflag &= ~OB_DUPLIPARTS; psys = ob->particlesystem.first; while (psys) { @@ -267,18 +266,6 @@ void BKE_object_handle_data_update( else psys = psys->next; } - - if (use_render_params && ob->transflag & OB_DUPLIPARTS) { - /* this is to make sure we get render level duplis in groups: - * the derivedmesh must be created before init_render_mesh, - * since object_duplilist does dupliparticles before that */ - CustomDataMask data_mask = CD_MASK_BAREMESH | CD_MASK_MFACE | CD_MASK_MTFACE | CD_MASK_MCOL; - dm = mesh_create_derived_render(depsgraph, scene, ob, data_mask); - dm->release(dm); - - for (psys = ob->particlesystem.first; psys; psys = psys->next) - psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated; - } } /* quick cache removed */ @@ -417,6 +404,12 @@ void BKE_object_eval_flush_base_flags(Depsgraph *depsgraph, object->base_flag &= ~(BASE_SELECTED | BASE_SELECTABLED); } + /* Copy to original object datablock if needed. */ + if (DEG_is_active(depsgraph)) { + Object *object_orig = DEG_get_original_object(object); + object_orig->base_flag = object->base_flag; + } + if (object->mode == OB_MODE_PARTICLE_EDIT) { for (ParticleSystem *psys = object->particlesystem.first; psys != NULL; diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index 2d8527f23d6..7f3f916964a 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 07cd28da556..da455faaa86 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -34,7 +34,7 @@ #include <fcntl.h> #include <sys/stat.h> -#ifndef WIN32 +#ifndef WIN32 #include <unistd.h> #else #include <io.h> @@ -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 20d68ee2a58..c1c3cbf1ca3 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -164,7 +164,7 @@ Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer) { if (sce && view_layer) { ToolSettings *ts = sce->toolsettings; - + if (view_layer->basact && view_layer->basact->object) { switch (view_layer->basact->object->mode) { case OB_MODE_SCULPT: @@ -607,7 +607,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)]; } @@ -709,7 +709,7 @@ static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder) } if (reorder) BM_log_mesh_elems_reorder(ss->bm, ss->bm_log); - BM_mesh_bm_to_me(ss->bm, ob->data, (&(struct BMeshToMeshParams){0})); + BM_mesh_bm_to_me(NULL, ss->bm, ob->data, (&(struct BMeshToMeshParams){.calc_object_remap = false})); } } } diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index 8c322f0c853..693d6ac587e 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -100,19 +100,19 @@ float PSYS_FRAND_BASE[PSYS_FRAND_COUNT]; void psys_init_rng(void) { - int i; - BLI_srandom(5831); /* arbitrary */ - for (i = 0; i < PSYS_FRAND_COUNT; ++i) { - PSYS_FRAND_BASE[i] = BLI_frand(); - PSYS_FRAND_SEED_OFFSET[i] = (unsigned int)BLI_rand(); - PSYS_FRAND_SEED_MULTIPLIER[i] = (unsigned int)BLI_rand(); + RNG *rng = BLI_rng_new_srandom(5831); /* arbitrary */ + for (int i = 0; i < PSYS_FRAND_COUNT; ++i) { + PSYS_FRAND_BASE[i] = BLI_rng_get_float(rng); + PSYS_FRAND_SEED_OFFSET[i] = (unsigned int)BLI_rng_get_int(rng); + PSYS_FRAND_SEED_MULTIPLIER[i] = (unsigned int)BLI_rng_get_int(rng); } + BLI_rng_free(rng); } static void get_child_modifier_parameters(ParticleSettings *part, ParticleThreadContext *ctx, ChildParticle *cpa, short cpa_from, int cpa_num, float *cpa_fuv, float *orco, ParticleTexture *ptex); static void get_cpa_texture(Mesh *mesh, ParticleSystem *psys, ParticleSettings *part, ParticleData *par, - int child_index, int face_index, const float fw[4], float *orco, ParticleTexture *ptex, int event, float cfra); + int child_index, int face_index, const float fw[4], float *orco, ParticleTexture *ptex, int event, float cfra); /* few helpers for countall etc. */ int count_particles(ParticleSystem *psys) @@ -201,7 +201,7 @@ ParticleSystem *psys_get_current(Object *ob) if (psys->flag & PSYS_CURRENT) return psys; } - + return NULL; } short psys_get_current_num(Object *ob) @@ -214,7 +214,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) @@ -426,7 +426,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). */ @@ -435,7 +435,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]); } @@ -446,7 +446,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); @@ -477,7 +477,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); } @@ -556,10 +556,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); @@ -594,11 +594,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); @@ -613,7 +613,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) { @@ -631,7 +631,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); @@ -653,6 +653,51 @@ void psys_free(Object *ob, ParticleSystem *psys) } } +void psys_copy_particles(ParticleSystem *psys_dst, ParticleSystem *psys_src) +{ + /* Free existing particles. */ + if (psys_dst->particles != psys_src->particles) { + psys_free_particles(psys_dst); + } + if (psys_dst->child != psys_src->child) { + psys_free_children(psys_dst); + } + /* Restore counters. */ + psys_dst->totpart = psys_src->totpart; + psys_dst->totchild = psys_src->totchild; + /* Copy particles and children. */ + psys_dst->particles = MEM_dupallocN(psys_src->particles); + psys_dst->child = MEM_dupallocN(psys_src->child); + if (psys_dst->part->type == PART_HAIR) { + ParticleData *pa; + int p; + for (p = 0, pa = psys_dst->particles; p < psys_dst->totpart; p++, pa++) { + pa->hair = MEM_dupallocN(pa->hair); + } + } + if (psys_dst->particles && (psys_dst->particles->keys || psys_dst->particles->boid)) { + ParticleKey *key = psys_dst->particles->keys; + BoidParticle *boid = psys_dst->particles->boid; + ParticleData *pa; + int p; + if (key != NULL) { + key = MEM_dupallocN(key); + } + if (boid != NULL) { + boid = MEM_dupallocN(boid); + } + for (p = 0, pa = psys_dst->particles; p < psys_dst->totpart; p++, pa++) { + if (boid != NULL) { + pa->boid = boid++; + } + if (key != NULL) { + pa->keys = key; + key += pa->totkey; + } + } + } +} + /************************************************/ /* Interpolation */ /************************************************/ @@ -665,7 +710,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; } @@ -918,7 +963,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) { @@ -1079,7 +1124,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) { @@ -1099,7 +1144,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) { @@ -1199,7 +1244,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]; @@ -1230,7 +1275,7 @@ static float psys_interpolate_value_from_verts(Mesh *mesh, short from, int index MFace *mf = &mesh->mface[index]; return interpolate_particle_value(values[mf->v1], values[mf->v2], values[mf->v3], values[mf->v4], fw, mf->v4); } - + } return 0.0f; } @@ -1253,7 +1298,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); @@ -1336,7 +1381,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]; @@ -1516,7 +1561,7 @@ float psys_particle_value_from_verts(Mesh *mesh, short from, ParticleData *pa, f if (!psys_map_index_on_dm(mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw)) return 0.0f; - + return psys_interpolate_value_from_verts(mesh, from, mapindex, mapfw, values); } @@ -1590,13 +1635,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; } @@ -1640,10 +1685,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); - + 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) { @@ -1681,22 +1726,22 @@ int do_guides(Depsgraph *depsgraph, ParticleSettings *part, ListBase *effectors, 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; @@ -1705,14 +1750,14 @@ int do_guides(Depsgraph *depsgraph, ParticleSettings *part, ListBase *effectors, 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); @@ -1720,52 +1765,52 @@ int do_guides(Depsgraph *depsgraph, ParticleSettings *part, ListBase *effectors, 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(depsgraph, 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); @@ -1922,7 +1967,7 @@ static bool psys_thread_context_init_path( if (totchild && part->childtype == PART_CHILD_FACES) { totparent = (int)(totchild * part->parents * 0.3f); - + if (use_render_params && part->child_nbr && part->ren_child_nbr) totparent *= (float)part->child_nbr / (float)part->ren_child_nbr; @@ -1996,7 +2041,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); } @@ -2104,7 +2149,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; @@ -2253,14 +2298,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); - + psys_apply_child_modifiers(ctx, &modifiers, cpa, &ptex, orco, hairmat, child_keys, par, par_orco); } else @@ -2298,57 +2343,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); } @@ -2404,15 +2449,15 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re ParticleCacheKey *ca, **cache; Mesh *hair_mesh = (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS) ? psys->hair_out_mesh : 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}; @@ -2449,7 +2494,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->mesh_final, psys, PSYS_VG_EFFECTOR); - + if (!psys->totchild) vg_length = psys_cache_vgroup(psmd->mesh_final, psys, PSYS_VG_LENGTH); } @@ -2524,7 +2569,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); } @@ -2598,204 +2643,235 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re if (vg_length) MEM_freeN(vg_length); } -void psys_cache_edit_paths(Depsgraph *depsgraph, Scene *scene, Object *ob, PTCacheEdit *edit, float cfra, const bool use_render_params) -{ - ParticleCacheKey *ca, **cache = edit->pathcache; - ParticleEditSettings *pset = &scene->toolsettings->particle; - - PTCacheEditPoint *point = NULL; - PTCacheEditKey *ekey = NULL; - - ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); - ParticleData *pa = psys ? psys->particles : NULL; - - 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}; - int k, i; - int segments = 1 << pset->draw_step; - int totpart = edit->totpoint, recalc_set = 0; +typedef struct CacheEditrPathsIterData { + Object *object; + PTCacheEdit *edit; + ParticleSystemModifierData *psmd; + ParticleData *pa; + int segments; + bool use_weight; float sel_col[3]; float nosel_col[3]; +} CacheEditrPathsIterData; - segments = MAX2(segments, 4); - - if (!cache || edit->totpoint != edit->totcached) { - /* clear out old and create new empty path cache */ - psys_free_path_cache(edit->psys, edit); - cache = edit->pathcache = psys_alloc_path_cache_buffers(&edit->pathcachebufs, totpart, segments + 1); - - /* set flag for update (child particles check this too) */ - for (i = 0, point = edit->points; i < totpart; i++, point++) - point->flag |= PEP_EDIT_RECALC; - recalc_set = 1; +static void psys_cache_edit_paths_iter( + void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + CacheEditrPathsIterData *iter_data = (CacheEditrPathsIterData *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if (edit->totcached && !(point->flag & PEP_EDIT_RECALC)) { + return; + } + if (point->totkey == 0) { + return; } + Object *ob = iter_data->object; + ParticleSystem *psys = edit->psys; + ParticleCacheKey **cache = edit->pathcache; + ParticleSystemModifierData *psmd = iter_data->psmd; + ParticleData *pa = iter_data->pa ? iter_data->pa + iter : NULL; + PTCacheEditKey *ekey = point->keys; + const int segments = iter_data->segments; + const bool use_weight = iter_data->use_weight; - /* frs_sec = (psys || edit->pid.flag & PTCACHE_VEL_PER_SEC) ? 25.0f : 1.0f; */ /* UNUSED */ + float birthtime = 0.0f, dietime = 0.0f; + float hairmat[4][4], rotmat[3][3], prev_tangent[3] = {0.0f, 0.0f, 0.0f}; - const bool use_weight = (pset->brushtype == PE_BRUSH_WEIGHT) && (psys != NULL) && (psys->particles != NULL); + ParticleInterpolationData pind; + pind.keyed = 0; + pind.cache = NULL; + pind.epoint = point; + pind.bspline = psys ? (psys->part->flag & PART_HAIR_BSPLINE) : 0; + pind.mesh = NULL; + /* should init_particle_interpolation set this ? */ if (use_weight) { - ; /* use weight painting colors now... */ - } - else { - sel_col[0] = (float)edit->sel_col[0] / 255.0f; - sel_col[1] = (float)edit->sel_col[1] / 255.0f; - sel_col[2] = (float)edit->sel_col[2] / 255.0f; - nosel_col[0] = (float)edit->nosel_col[0] / 255.0f; - nosel_col[1] = (float)edit->nosel_col[1] / 255.0f; - nosel_col[2] = (float)edit->nosel_col[2] / 255.0f; + pind.hkey[0] = NULL; + /* pa != NULL since the weight brush is only available for hair */ + pind.hkey[0] = pa->hair; + pind.hkey[1] = pa->hair + 1; } - /*---first main loop: create all actual particles' paths---*/ - for (i = 0, point = edit->points; i < totpart; i++, pa += pa ? 1 : 0, point++) { - if (edit->totcached && !(point->flag & PEP_EDIT_RECALC)) - continue; + memset(cache[iter], 0, sizeof(*cache[iter]) * (segments + 1)); - if (point->totkey == 0) - continue; + cache[iter]->segments = segments; - ekey = point->keys; + /*--get the first data points--*/ + init_particle_interpolation(ob, psys, pa, &pind); - pind.keyed = 0; - pind.cache = NULL; - pind.epoint = point; - pind.bspline = psys ? (psys->part->flag & PART_HAIR_BSPLINE) : 0; - pind.mesh = NULL; + if (psys) { + psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, pa, hairmat); + copy_v3_v3(rotmat[0], hairmat[2]); + copy_v3_v3(rotmat[1], hairmat[1]); + copy_v3_v3(rotmat[2], hairmat[0]); + } + birthtime = pind.birthtime; + dietime = pind.dietime; - /* should init_particle_interpolation set this ? */ - if (use_weight) { - pind.hkey[0] = NULL; - /* pa != NULL since the weight brush is only available for hair */ - pind.hkey[0] = pa->hair; - pind.hkey[1] = pa->hair + 1; - } + if (birthtime >= dietime) { + cache[iter]->segments = -1; + return; + } + /*--interpolate actual path from data points--*/ + ParticleCacheKey *ca; + int k; + float t, time = 0.0f, keytime = 0.0f; + for (k = 0, ca = cache[iter]; k <= segments; k++, ca++) { + time = (float)k / (float)segments; + t = birthtime + time * (dietime - birthtime); + ParticleKey result; + result.time = -t; + do_particle_interpolation(psys, iter, pa, t, &pind, &result); + copy_v3_v3(ca->co, result.co); + + /* non-hair points are already in global space */ + if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { + mul_m4_v3(hairmat, ca->co); - memset(cache[i], 0, sizeof(*cache[i]) * (segments + 1)); + if (k) { + cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k); - cache[i]->segments = segments; + if (k == segments) + copy_qt_qt(ca->rot, (ca - 1)->rot); - /*--get the first data points--*/ - init_particle_interpolation(ob, psys, pa, &pind); + /* set velocity */ + sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co); - if (psys) { - psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, pa, hairmat); - copy_v3_v3(rotmat[0], hairmat[2]); - copy_v3_v3(rotmat[1], hairmat[1]); - copy_v3_v3(rotmat[2], hairmat[0]); + if (k == 1) + copy_v3_v3((ca - 1)->vel, ca->vel); + } } - - birthtime = pind.birthtime; - dietime = pind.dietime; - - if (birthtime >= dietime) { - cache[i]->segments = -1; - continue; + else { + ca->vel[0] = ca->vel[1] = 0.0f; + ca->vel[2] = 1.0f; } - /*--interpolate actual path from data points--*/ - for (k = 0, ca = cache[i]; k <= segments; k++, ca++) { - time = (float)k / (float)segments; - t = birthtime + time * (dietime - birthtime); - result.time = -t; - do_particle_interpolation(psys, i, pa, t, &pind, &result); - copy_v3_v3(ca->co, result.co); - - /* non-hair points are already in global space */ - if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { - mul_m4_v3(hairmat, ca->co); - - if (k) { - cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k); - - if (k == segments) - copy_qt_qt(ca->rot, (ca - 1)->rot); - - /* set velocity */ - sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co); - - if (k == 1) - copy_v3_v3((ca - 1)->vel, ca->vel); - } + /* selection coloring in edit mode */ + if (use_weight) { + if (k == 0) { + weight_to_rgb(ca->col, pind.hkey[1]->weight); } else { - ca->vel[0] = ca->vel[1] = 0.0f; - ca->vel[2] = 1.0f; - } - - /* selection coloring in edit mode */ - if (use_weight) { - if (k == 0) { - weight_to_rgb(ca->col, pind.hkey[1]->weight); + /* warning: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */ + float real_t; + if (result.time < 0.0f) { + real_t = -result.time; } else { - /* warning: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */ - float real_t; - if (result.time < 0.0f) { - real_t = -result.time; - } - else { - real_t = pind.hkey[0]->time + t * (pind.hkey[0][pa->totkey - 1].time - pind.hkey[0]->time); - } + real_t = pind.hkey[0]->time + t * (pind.hkey[0][pa->totkey - 1].time - pind.hkey[0]->time); + } - while (pind.hkey[1]->time < real_t) { - pind.hkey[1]++; - } - pind.hkey[0] = pind.hkey[1] - 1; - /* end copy */ + while (pind.hkey[1]->time < real_t) { + pind.hkey[1]++; + } + pind.hkey[0] = pind.hkey[1] - 1; + /* end copy */ - float w1[3], w2[3]; - keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); + float w1[3], w2[3]; + keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); - weight_to_rgb(w1, pind.hkey[0]->weight); - weight_to_rgb(w2, pind.hkey[1]->weight); + weight_to_rgb(w1, pind.hkey[0]->weight); + weight_to_rgb(w2, pind.hkey[1]->weight); - interp_v3_v3v3(ca->col, w1, w2, keytime); + interp_v3_v3v3(ca->col, w1, w2, keytime); + } + } + else { + if ((ekey + (pind.ekey[0] - point->keys))->flag & PEK_SELECT) { + if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { + copy_v3_v3(ca->col, iter_data->sel_col); + } + else { + keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); + interp_v3_v3v3(ca->col, iter_data->sel_col, iter_data->nosel_col, keytime); } } else { - if ((ekey + (pind.ekey[0] - point->keys))->flag & PEK_SELECT) { - if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { - copy_v3_v3(ca->col, sel_col); - } - else { - keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); - interp_v3_v3v3(ca->col, sel_col, nosel_col, keytime); - } + if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { + keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); + interp_v3_v3v3(ca->col, iter_data->nosel_col, iter_data->sel_col, keytime); } else { - if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { - keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); - interp_v3_v3v3(ca->col, nosel_col, sel_col, keytime); - } - else { - copy_v3_v3(ca->col, nosel_col); - } + copy_v3_v3(ca->col, iter_data->nosel_col); } } - - ca->time = t; } - if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { - /* First rotation is based on emitting face orientation. - * This is way better than having flipping rotations resulting - * from using a global axis as a rotation pole (vec_to_quat()). - * It's not an ideal solution though since it disregards the - * initial tangent, but taking that in to account will allow - * the possibility of flipping again. -jahka - */ - mat3_to_quat_is_ok(cache[i]->rot, rotmat); + + ca->time = t; + } + if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { + /* First rotation is based on emitting face orientation. + * This is way better than having flipping rotations resulting + * from using a global axis as a rotation pole (vec_to_quat()). + * It's not an ideal solution though since it disregards the + * initial tangent, but taking that in to account will allow + * the possibility of flipping again. -jahka + */ + mat3_to_quat_is_ok(cache[iter]->rot, rotmat); + } +} + +void psys_cache_edit_paths(Depsgraph *depsgraph, Scene *scene, Object *ob, PTCacheEdit *edit, float cfra, const bool use_render_params) +{ + ParticleCacheKey **cache = edit->pathcache; + ParticleEditSettings *pset = &scene->toolsettings->particle; + + ParticleSystem *psys = edit->psys; + + ParticleData *pa = psys ? psys->particles : NULL; + + int segments = 1 << pset->draw_step; + int totpart = edit->totpoint, recalc_set = 0; + + segments = MAX2(segments, 4); + + if (!cache || edit->totpoint != edit->totcached) { + /* Clear out old and create new empty path cache. */ + psys_free_path_cache(edit->psys, edit); + cache = edit->pathcache = psys_alloc_path_cache_buffers(&edit->pathcachebufs, totpart, segments + 1); + /* Set flag for update (child particles check this too). */ + int i; + PTCacheEditPoint *point; + for (i = 0, point = edit->points; i < totpart; i++, point++) { + point->flag |= PEP_EDIT_RECALC; } + recalc_set = 1; } + const bool use_weight = (pset->brushtype == PE_BRUSH_WEIGHT) && (psys != NULL) && (psys->particles != NULL); + + CacheEditrPathsIterData iter_data; + iter_data.object = ob; + iter_data.edit = edit; + iter_data.psmd = edit->psmd_eval; + iter_data.pa = pa; + iter_data.segments = segments; + iter_data.use_weight = use_weight; + + if (use_weight) { + ; /* use weight painting colors now... */ + } + else { + iter_data.sel_col[0] = (float)edit->sel_col[0] / 255.0f; + iter_data.sel_col[1] = (float)edit->sel_col[1] / 255.0f; + iter_data.sel_col[2] = (float)edit->sel_col[2] / 255.0f; + iter_data.nosel_col[0] = (float)edit->nosel_col[0] / 255.0f; + iter_data.nosel_col[1] = (float)edit->nosel_col[1] / 255.0f; + iter_data.nosel_col[2] = (float)edit->nosel_col[2] / 255.0f; + } + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, psys_cache_edit_paths_iter, &settings); + edit->totcached = totpart; if (psys) { @@ -2804,15 +2880,18 @@ void psys_cache_edit_paths(Depsgraph *depsgraph, Scene *scene, Object *ob, PTCac sim.scene = scene; sim.ob = ob; sim.psys = psys; - sim.psmd = psys_get_modifier(ob, psys); + sim.psmd = edit->psmd_eval; psys_cache_child_paths(&sim, cfra, true, use_render_params); } /* clear recalc flag if set here */ if (recalc_set) { - for (i = 0, point = edit->points; i < totpart; i++, point++) + PTCacheEditPoint *point; + int i; + for (i = 0, point = edit->points; i < totpart; i++, point++) { point->flag &= ~PEP_EDIT_RECALC; + } } } /************************************************/ @@ -2889,7 +2968,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]); } @@ -2906,7 +2985,7 @@ static void psys_face_mat(Object *ob, Mesh *mesh, ParticleData *pa, float mat[4] mface = &mesh->mface[i]; osface = CustomData_get(&mesh->fdata, i, CD_ORIGSPACE); - + if (orco && (orcodata = CustomData_get_layer(&mesh->vdata, CD_ORCO))) { copy_v3_v3(v[0], orcodata[mface->v1]); copy_v3_v3(v[1], orcodata[mface->v2]); @@ -2935,7 +3014,7 @@ void psys_mat_hair_to_object(Object *UNUSED(ob), Mesh *mesh, short from, Particl unit_m4(hairmat); return; } - + psys_face_mat(0, mesh, pa, hairmat, 0); psys_particle_on_dm(mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0); copy_v3_v3(hairmat[3], vec); @@ -2975,7 +3054,7 @@ void psys_mat_hair_to_global(Object *ob, Mesh *mesh, short from, ParticleData *p /************************************************/ /* ParticleSettings handling */ /************************************************/ -ModifierData *object_add_particle_system(Scene *scene, Object *ob, const char *name) +ModifierData *object_add_particle_system(Main *bmain, Scene *scene, Object *ob, const char *name) { ParticleSystem *psys; ModifierData *md; @@ -2992,7 +3071,7 @@ ModifierData *object_add_particle_system(Scene *scene, Object *ob, const char *n psys->pointcache = BKE_ptcache_add(&psys->ptcaches); BLI_addtail(&ob->particlesystem, psys); - psys->part = BKE_particlesettings_add(NULL, DATA_("ParticleSettings")); + psys->part = BKE_particlesettings_add(bmain, DATA_("ParticleSettings")); if (BLI_listbase_count_at_most(&ob->particlesystem, 2) > 1) BLI_snprintf(psys->name, sizeof(psys->name), DATA_("ParticleSystem %i"), BLI_listbase_count(&ob->particlesystem)); @@ -3015,12 +3094,12 @@ ModifierData *object_add_particle_system(Scene *scene, Object *ob, const char *n psys->flag = PSYS_CURRENT; psys->cfra = BKE_scene_frame_get_from_ctime(scene, CFRA + 1); - DEG_relations_tag_update(G.main); + DEG_relations_tag_update(bmain); DEG_id_tag_update(&ob->id, OB_RECALC_DATA); return md; } -void object_remove_particle_system(Scene *UNUSED(scene), Object *ob) +void object_remove_particle_system(Main *bmain, Scene *UNUSED(scene), Object *ob) { ParticleSystem *psys = psys_get_current(ob); ParticleSystemModifierData *psmd; @@ -3061,9 +3140,9 @@ void object_remove_particle_system(Scene *UNUSED(scene), Object *ob) else ob->mode &= ~OB_MODE_PARTICLE_EDIT; - DEG_relations_tag_update(G.main); + DEG_relations_tag_update(bmain); DEG_id_tag_update(&ob->id, OB_RECALC_DATA); - + /* Flush object mode. */ DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE); } @@ -3087,7 +3166,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; @@ -3155,15 +3234,12 @@ static void default_particle_settings(ParticleSettings *part) } -ParticleSettings *BKE_particlesettings_add(Main *main, const char *name) +ParticleSettings *BKE_particlesettings_add(Main *bmain, const char *name) { ParticleSettings *part; - if (main == NULL) - main = G.main; + part = BKE_libblock_alloc(bmain, ID_PA, name, 0); - part = BKE_libblock_alloc(main, ID_PA, name, 0); - default_particle_settings(part); return part; @@ -3172,24 +3248,24 @@ ParticleSettings *BKE_particlesettings_add(Main *main, 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; } @@ -3264,7 +3340,7 @@ static int get_particle_uv(Mesh *mesh, ParticleData *pa, int index, const float MFace *mf; MTFace *tf; int i; - + tf = CustomData_get_layer_named(&mesh->fdata, CD_MTFACE, name); if (tf == NULL) @@ -3461,7 +3537,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); - + if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) { BKE_mesh_texspace_calc(me); } @@ -3557,7 +3633,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; @@ -3694,7 +3770,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) @@ -3971,9 +4047,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)); @@ -3999,7 +4075,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; } } @@ -4037,7 +4113,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); return; } @@ -4249,7 +4325,7 @@ void psys_apply_hair_lattice(Depsgraph *depsgraph, Scene *scene, Object *ob, Par 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_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c index 846afd48064..2e056aa7a3f 100644 --- a/source/blender/blenkernel/intern/particle_distribute.c +++ b/source/blender/blenkernel/intern/particle_distribute.c @@ -85,6 +85,7 @@ static void distribute_simple_children(Scene *scene, Object *ob, Mesh *final_mes int i, p; int child_nbr= psys_get_child_number(scene, psys, use_render_params); int totpart= psys_get_tot_child(scene, psys, use_render_params); + RNG *rng = BLI_rng_new_srandom(31415926 + psys->seed + psys->child_seed); alloc_child_particles(psys, totpart); @@ -93,12 +94,12 @@ static void distribute_simple_children(Scene *scene, Object *ob, Mesh *final_mes for (p=0; p<psys->totpart; 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; - cpa->fuv[1]=2.0f*BLI_frand()-1.0f; - cpa->fuv[2]=2.0f*BLI_frand()-1.0f; + cpa->fuv[0]=2.0f*BLI_rng_get_float(rng)-1.0f; + cpa->fuv[1]=2.0f*BLI_rng_get_float(rng)-1.0f; + cpa->fuv[2]=2.0f*BLI_rng_get_float(rng)-1.0f; length=len_v3(cpa->fuv); } @@ -107,6 +108,8 @@ static void distribute_simple_children(Scene *scene, Object *ob, Mesh *final_mes } /* dmcache must be updated for parent particles if children from faces is used */ psys_calc_dmcache(ob, final_mesh, deform_mesh, psys); + + BLI_rng_free(rng); } static void distribute_grid(Mesh *mesh, ParticleSystem *psys) { @@ -135,7 +138,7 @@ static void distribute_grid(Mesh *mesh, ParticleSystem *psys) /* determine major axis */ axis = axis_dominant_v3_single(delta); - + d = delta[axis]/(float)res; size[axis] = res; @@ -197,7 +200,7 @@ static void distribute_grid(Mesh *mesh, ParticleSystem *psys) totface = mesh->totface; mface = mface_array = mesh->mface; - + for (a=0; a<amax; a++) { if (a==0) { a0mul=res*res; a1mul=res; a2mul=1; } else if (a==1) { a0mul=res; a1mul=1; a2mul=res*res; } @@ -346,13 +349,13 @@ static void init_mv_jit(float *jit, int num, int seed2, float amount) x= 0; num2 = 2 * num; for (i=0; i<num2; i+=2) { - + jit[i] = x + amount*rad1*(0.5f - BLI_rng_get_float(rng)); jit[i+1] = i/(2.0f*num) + amount*rad1*(0.5f - BLI_rng_get_float(rng)); - + jit[i]-= (float)floor(jit[i]); jit[i+1]-= (float)floor(jit[i+1]); - + x+= rad3; x -= (float)floor(x); } @@ -413,10 +416,10 @@ static int distribute_binary_search(float *sum, int n, float value) while (low < high) { mid = (low + high) / 2; - + if ((sum[mid] >= value) && (sum[mid - 1] < value)) return mid; - + if (sum[mid] > value) { high = mid - 1; } @@ -430,7 +433,7 @@ static int distribute_binary_search(float *sum, int n, float value) /* the max number if calls to rng_* funcs within psys_thread_distribute_particle * be sure to keep up to date if this changes */ -#define PSYS_RND_DIST_SKIP 2 +#define PSYS_RND_DIST_SKIP 3 /* note: this function must be thread safe, for from == PART_FROM_CHILD */ #define ONLY_WORKING_WITH_PA_VERTS 0 @@ -468,24 +471,26 @@ 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->mesh,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; w<maxw; w++) { pa->verts[w]=ptn->num; } } #endif - - if (rng_skip_tot > 0) /* should never be below zero */ + + BLI_assert(rng_skip_tot > 0); /* should never be below zero */ + if (rng_skip_tot > 0) { BLI_rng_skip(thread->rng, rng_skip_tot); + } } static void distribute_from_faces_exec(ParticleTask *thread, ParticleData *pa, int p) { @@ -497,10 +502,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 = &mesh->mface[i]; - + switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { @@ -520,14 +525,16 @@ 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_assert(rng_skip_tot > 0); /* should never be below zero */ + if (rng_skip_tot > 0) { BLI_rng_skip(thread->rng, rng_skip_tot); + } } static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, int p) { @@ -538,13 +545,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 = mesh->mvert; - + pa->num = i = ctx->index[p]; mface = &mesh->mface[i]; - + switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { @@ -564,30 +571,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 = mesh->totface; - + psys_interpolate_face(mvert,mface,0,0,pa->fuv,co,nor,0,0,0); - + normalize_v3(nor); negate_v3(nor); - + min_d=FLT_MAX; intersect=0; - + for (i=0, mface=mesh->mface; i<tot; i++,mface++) { if (i==pa->num) 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_d<min_d) { min_d=cur_d; @@ -597,7 +604,7 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, } if (mface->v4) { v4=mvert[mface->v4].co; - + if (isect_ray_tri_v3(co, nor, v4, v1, v3, &cur_d, NULL)) { if (cur_d<min_d) { min_d=cur_d; @@ -615,13 +622,16 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, pa->foffset *= ctx->jit[p % (2 * ctx->jitlevel)]; break; case PART_DISTR_RAND: - pa->foffset *= BLI_frand(); + pa->foffset *= BLI_rng_get_float(thread->rng); + rng_skip_tot--; break; } } - - if (rng_skip_tot > 0) /* should never be below zero */ + + BLI_assert(rng_skip_tot > 0); /* should never be below zero */ + if (rng_skip_tot > 0) { BLI_rng_skip(thread->rng, rng_skip_tot); + } } static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, int p) { @@ -633,40 +643,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 = &mesh->mface[ctx->index[p]]; - + 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(mesh,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,NULL,NULL,orco1); 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<maxw; w++) { parent[w]=ptn[w].index; @@ -676,7 +686,7 @@ static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, i parent[w]=-1; pweight[w]=0.0f; } - + for (w=0,i=0; w<maxw && i<4; w++) { if (parent[w]>=0) { cpa->pa[i]=parent[w]; @@ -689,13 +699,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]; } @@ -711,7 +721,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: @@ -735,13 +745,13 @@ 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) { BLI_rng_skip(task->rng, PSYS_RND_DIST_SKIP); } - + for (; p < task->end; ++p, ++cpa) { distribute_children_exec(task, cpa, p); } @@ -818,21 +828,22 @@ 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]; - + RNG *rng = NULL; + if (ELEM(NULL, ob, psys, psys->part)) return 0; - + part=psys->part; totpart=psys->totpart; if (totpart==0) return 0; - + if (!final_mesh->runtime.deformed_only && !CustomData_get_layer(&final_mesh->fdata, 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. @@ -841,12 +852,11 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti psys_thread_context_init(ctx, sim); const bool use_render_params = (DEG_get_mode(sim->depsgraph) == DAG_EVAL_RENDER); - + /* First handle special cases */ if (from == PART_FROM_CHILD) { /* Simple children */ if (part->childtype != PART_CHILD_FACES) { - BLI_srandom(31415926 + psys->seed + psys->child_seed); distribute_simple_children(scene, ob, final_mesh, sim->psmd->mesh_original, psys, use_render_params); return 0; } @@ -854,8 +864,6 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti else { /* Grid distribution */ if (part->distr==PART_DISTR_GRID && from != PART_FROM_VERT) { - BLI_srandom(31415926 + psys->seed); - if (psys->part->use_modifier_stack) { mesh = final_mesh; } @@ -879,11 +887,11 @@ 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; - BLI_srandom(31415926 + psys->seed + psys->child_seed); + distr = PART_DISTR_RAND; + rng = BLI_rng_new_srandom(31415926 + psys->seed + psys->child_seed); mesh= final_mesh; /* BMESH ONLY */ @@ -906,8 +914,9 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti } else { distr = part->distr; - BLI_srandom(31415926 + psys->seed); - + + rng = BLI_rng_new_srandom(31415926 + psys->seed); + if (psys->part->use_modifier_stack) mesh = final_mesh; else @@ -958,6 +967,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti if (mesh != final_mesh) BKE_id_free(NULL, mesh); BLI_kdtree_free(tree); + BLI_rng_free(rng); return 0; } @@ -971,7 +981,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 = CustomData_get_layer(&mesh->vdata, CD_ORCO); for (i=0; i<totelem; i++) { @@ -1003,7 +1013,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti } cur = mf->v4 ? area_quad_v3(co1, co2, co3, co4) : area_tri_v3(co1, co2, co3); - + if (cur > maxweight) maxweight = cur; @@ -1035,7 +1045,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti for (i=0;i<totelem; i++) { MFace *mf = &mesh->mface[i]; tweight = vweight[mf->v1] + vweight[mf->v2] + vweight[mf->v3]; - + if (mf->v4) { tweight += vweight[mf->v4]; tweight /= 4.0f; @@ -1098,7 +1108,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti for (p = 0; p < totpart; p++) { /* In theory element_sum[totmapped - 1] should be 1.0, * but due to float errors this is not necessarily always true, so scale pos accordingly. */ - const float pos = BLI_frand() * element_sum[totmapped - 1]; + const float pos = BLI_rng_get_float(rng) * element_sum[totmapped - 1]; const int eidx = distribute_binary_search(element_sum, totmapped, pos); particle_element[p] = element_map[eidx]; BLI_assert(pos <= element_sum[eidx]); @@ -1108,7 +1118,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 @@ -1152,17 +1162,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); @@ -1191,6 +1201,8 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti alloc_child_particles(psys, totpart); } + BLI_rng_free(rng); + return 1; } @@ -1198,7 +1210,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); } @@ -1210,19 +1222,19 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) ParticleTask *tasks; Mesh *final_mesh = sim->psmd->mesh_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); @@ -1230,16 +1242,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, final_mesh, sim->psmd->mesh_original, sim->psys); - + if (ctx.mesh != final_mesh) BKE_id_free(NULL, ctx.mesh); - + psys_tasks_free(tasks, numtasks); - + psys_thread_context_free(&ctx); } diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index 8d6991ff9f4..1c50e85668d 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -242,7 +242,7 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) } } } - + if (psys->particles) { totsaved=MIN2(psys->totpart,totpart); /*save old pars*/ @@ -272,7 +272,7 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) MEM_freeN(psys->particles); psys_free_pdd(psys); } - + psys->particles=newpars; psys->totpart=totpart; @@ -317,14 +317,14 @@ void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, Partic { /* 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 (!mesh_final->runtime.deformed_only) { /* Will use later to speed up subsurf/derivedmesh */ @@ -428,7 +428,7 @@ void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, Partic /* 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; } @@ -457,15 +457,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); @@ -475,7 +475,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) @@ -537,7 +537,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)) { @@ -561,7 +561,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; @@ -620,7 +620,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; p<newtotpart; p++, pa++, npa++) { @@ -708,7 +708,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0); else psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0); - + /* get possible textural influence */ psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra); @@ -716,7 +716,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); @@ -734,10 +734,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)) { @@ -758,7 +758,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); @@ -795,7 +795,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); @@ -814,11 +814,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); @@ -847,7 +847,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 */ @@ -886,7 +886,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic use_global_space = true; break; } - + /* create rotation quat */ @@ -995,7 +995,7 @@ static void evaluate_emitter_anim(struct Depsgraph *depsgraph, Scene *scene, Obj { if (ob->parent) evaluate_emitter_anim(depsgraph, scene, ob->parent, cfra); - + /* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */ BKE_animsys_evaluate_animdata(depsgraph, scene, &ob->id, ob->adt, cfra, ADT_RECALC_ANIM); BKE_object_where_is_calc_time(depsgraph, scene, ob, cfra); @@ -1009,7 +1009,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->depsgraph, sim->scene, sim->ob, pa->time); @@ -1086,7 +1086,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; p<totpart; p++, pa++) reset_particle(sim, pa, dtime, cfra); } @@ -1148,7 +1148,7 @@ static void set_keyed_keys(ParticleSimulationData *sim) ksim.depsgraph = sim->depsgraph; ksim.scene = sim->scene; - + /* no proper targets so let's clear and bail out */ if (psys->totkeyed==0) { free_keyed_keys(psys); @@ -1158,16 +1158,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; @@ -1249,17 +1249,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) @@ -1269,9 +1269,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); } } @@ -1365,7 +1365,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); @@ -1498,7 +1498,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; @@ -1591,9 +1591,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); } } @@ -1773,7 +1773,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)); @@ -2061,6 +2061,7 @@ static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, flo ParticleSettings *part = sim->psys->part; ParticleData *pa = efdata->pa; EffectedPoint epoint; + RNG *rng = sim->rng; /* add effectors */ pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint); @@ -2076,9 +2077,9 @@ static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, flo /* brownian force */ if (part->brownfac != 0.0f) { - force[0] += (BLI_frand()-0.5f) * part->brownfac; - force[1] += (BLI_frand()-0.5f) * part->brownfac; - force[2] += (BLI_frand()-0.5f) * part->brownfac; + force[0] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac; + force[1] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac; + force[2] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac; } if (part->flag & PART_ROT_DYN && epoint.ave) @@ -2520,7 +2521,7 @@ static int collision_sphere_to_edges(ParticleCollision *col, float radius, Parti result->uv[0] = u; - + hit = cur; *t = ct; } @@ -2545,7 +2546,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; @@ -2649,16 +2650,17 @@ static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRay return hit->index >= 0; } -static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation) +static int collision_response(ParticleSimulationData *sim, ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation) { ParticleCollisionElement *pce = &col->pce; PartDeflect *pd = col->hit->pd; + RNG *rng = sim->rng; float co[3]; /* point of collision */ float x = hit->dist/col->original_ray_length; /* location factor of collision between this iteration */ float f = col->f + x * (1.0f - col->f); /* time factor of collision between timestep */ float dt1 = (f - col->f) * col->total_time; /* time since previous collision (in seconds) */ float dt2 = (1.0f - f) * col->total_time; /* time left after collision (in seconds) */ - int through = (BLI_frand() < pd->pdef_perm) ? 1 : 0; /* did particle pass through the collision surface? */ + int through = (BLI_rng_get_float(rng) < pd->pdef_perm) ? 1 : 0; /* did particle pass through the collision surface? */ /* calculate exact collision location */ interp_v3_v3v3(co, col->co1, col->co2, x); @@ -2683,8 +2685,8 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR float v0_tan[3];/* tangential component of v0 */ float vc_tan[3];/* tangential component of collision surface velocity */ float v0_dot, vc_dot; - float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_frand() - 0.5f); - float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_frand() - 0.5f); + float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_rng_get_float(rng) - 0.5f); + float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_rng_get_float(rng) - 0.5f); float distance, nor[3], dot; CLAMP(damp,0.0f, 1.0f); @@ -2692,7 +2694,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); @@ -2709,14 +2711,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. @@ -2779,7 +2781,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); @@ -2788,7 +2790,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); @@ -2889,12 +2891,12 @@ 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) collision_fail(pa, &col); - else if (collision_response(pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0) + else if (collision_response(sim, pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0) return; } else @@ -2995,19 +2997,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; k<pa->totkey; k++,key++) { float length = len_v3v3(key->co, (key-1)->co); if (length < min_length) return false; } - + return true; } @@ -3018,7 +3020,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++; } @@ -3040,7 +3042,7 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, in float hairmat[4][4]; float max_length; float hair_radius; - + mesh = *r_mesh; if (!mesh) { *r_mesh = mesh = BKE_mesh_new_nomain(totpoint, totedge, 0, 0, 0); @@ -3050,12 +3052,12 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, in mvert = mesh->mvert; medge = mesh->medge; dvert = mesh->dvert; - + 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 { @@ -3067,12 +3069,12 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, in } } } - + 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 { @@ -3160,7 +3162,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; @@ -3168,7 +3170,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; @@ -3179,7 +3181,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_mesh) { Mesh *mesh = psys->hair_in_mesh; @@ -3189,26 +3191,26 @@ static void do_hair_dynamics(ParticleSimulationData *sim) realloc_roots = true; } } - + if (!psys->hair_in_mesh || !psys->clmd->hairdata || realloc_roots) { if (psys->clmd->hairdata) { MEM_freeN(psys->clmd->hairdata); psys->clmd->hairdata = NULL; } } - + hair_create_input_mesh(sim, totpoint, totedge, &psys->hair_in_mesh, &psys->clmd->hairdata); - + if (psys->hair_out_mesh) BKE_id_free(NULL, psys->hair_out_mesh); - + 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; - + BKE_id_copy_ex( NULL, &psys->hair_in_mesh->id, (ID **)&psys->hair_out_mesh, LIB_ID_CREATE_NO_MAIN | @@ -3219,9 +3221,9 @@ static void do_hair_dynamics(ParticleSimulationData *sim) deformedVerts = BKE_mesh_vertexCos_get(psys->hair_out_mesh, NULL); clothModifier_do(psys->clmd, sim->depsgraph, sim->scene, sim->ob, psys->hair_in_mesh, deformedVerts); BKE_mesh_apply_vert_coords(psys->hair_out_mesh, deformedVerts); - + MEM_freeN(deformedVerts); - + /* restore cloth effector weights */ psys->clmd->sim_parms->effector_weights = clmd_effweights; } @@ -3270,11 +3272,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 */ @@ -3427,7 +3429,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)) { @@ -3502,7 +3504,6 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) { ParticleSystem *psys = sim->psys; ParticleSettings *part=psys->part; - RNG *rng; BoidBrainData bbd; ParticleTexture ptex; PARTICLE_P; @@ -3529,9 +3530,8 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) return; } - BLI_srandom(31415926 + (int)cfra + psys->seed); /* for now do both, boids us 'rng' */ - rng = BLI_rng_new_srandom(31415926 + (int)cfra + psys->seed); + sim->rng = BLI_rng_new_srandom(31415926 + (int)cfra + psys->seed); psys_update_effectors(sim); @@ -3548,7 +3548,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) bbd.cfra = cfra; bbd.dfra = dfra; bbd.timestep = timestep; - bbd.rng = rng; + bbd.rng = sim->rng; psys_update_particle_tree(psys, cfra); @@ -3566,7 +3566,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); @@ -3623,7 +3623,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); @@ -3637,7 +3637,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) { @@ -3744,8 +3744,10 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) } free_collider_cache(&sim->colliders); - BLI_rng_free(rng); + BLI_rng_free(sim->rng); + sim->rng = NULL; } + static void update_children(ParticleSimulationData *sim, const bool use_render_params) { if ((sim->psys->part->type == PART_HAIR) && (sim->psys->flag & PSYS_HAIR_DONE)==0) @@ -3771,7 +3773,7 @@ static void cached_step(ParticleSimulationData *sim, float cfra, const bool use_ float disp, dietime; psys_update_effectors(sim); - + disp= psys_get_current_display_percentage(psys, use_render_params); LOOP_PARTICLES { @@ -3821,7 +3823,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; @@ -3832,7 +3834,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; @@ -3841,7 +3843,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) { @@ -3849,46 +3851,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; p<totpart; p++, pa++) { int ptype=0; - - gzread(gzf, &ptype, sizeof( ptype )); + + gzread(gzf, &ptype, sizeof( ptype )); if (ptype & readMask) { activeParts++; - + gzread(gzf, &(pa->size), sizeof(float)); - + pa->size /= 10.0f; - + for (j=0; j<3; j++) { float wrf; - gzread(gzf, &wrf, sizeof( wrf )); + 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; @@ -3898,18 +3900,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 @@ -3955,7 +3957,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! */ @@ -3964,7 +3966,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); } @@ -4073,7 +4075,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); @@ -4209,7 +4211,9 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o { ParticleSimulationData sim= {0}; ParticleSettings *part = psys->part; + ParticleSystem *psys_orig = psys_orig_get(psys); float cfra; + ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); /* drawdata is outdated after ANY change */ if (psys->pdd) psys->pdd->flag &= ~PARTICLE_DRAW_DATA_UPDATED; @@ -4217,25 +4221,13 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o if (!psys_check_enabled(ob, psys, use_render_params)) return; - if (DEG_is_active(depsgraph)) { - if (psys->orig_psys != NULL && psys->orig_psys->edit != NULL) { - psys_cache_edit_paths( - depsgraph, - (Scene *)DEG_get_original_id(&scene->id), - DEG_get_original_object(ob), - psys->orig_psys->edit, - DEG_get_ctime(depsgraph), - DEG_get_mode(depsgraph) == DAG_EVAL_RENDER); - } - } - cfra = DEG_get_ctime(depsgraph); sim.depsgraph = depsgraph; sim.scene = scene; sim.ob = ob; sim.psys = psys; - sim.psmd = psys_get_modifier(ob, psys); + sim.psmd = psmd; /* system was already updated from modifier stack */ if (sim.psmd->flag & eParticleSystemFlag_psys_updated) { @@ -4280,10 +4272,10 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o free_hair(ob, psys, 0); - if (psys->edit && psys->free_edit) { - psys->free_edit(psys->edit); - psys->edit = NULL; - psys->free_edit = NULL; + if (psys_orig->edit && psys_orig->free_edit) { + psys_orig->free_edit(psys_orig->edit); + psys_orig->edit = NULL; + psys_orig->free_edit = NULL; } /* first step is negative so particles get killed and reset */ @@ -4379,6 +4371,22 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o psys->flag &= ~PSYS_OB_ANIM_RESTORE; } + if (psys_orig->edit) { + psys_orig->edit->flags |= PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL; + } + + if (DEG_is_active(depsgraph)) { + if (psys_orig != psys) { + if (psys_orig->edit != NULL && + psys_orig->edit->psys == psys_orig) + { + psys_orig->edit->psys_eval = psys; + psys_orig->edit->psmd_eval = psmd; + } + psys_orig->flag = psys->flag; + } + } + psys->cfra = cfra; psys->recalc = 0; diff --git a/source/blender/blenkernel/intern/pbvh.c b/source/blender/blenkernel/intern/pbvh.c index 8cc8a8510f2..0a4cd3ec3c1 100644 --- a/source/blender/blenkernel/intern/pbvh.c +++ b/source/blender/blenkernel/intern/pbvh.c @@ -134,7 +134,7 @@ static void update_node_vb(PBVH *bvh, PBVHNode *node) BB vb; BB_reset(&vb); - + if (node->flag & PBVH_Leaf) { PBVHVertexIter vd; @@ -185,10 +185,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++; } @@ -218,7 +218,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; @@ -390,7 +390,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 { @@ -1281,7 +1281,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; @@ -1384,7 +1384,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 @@ -1409,7 +1409,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; @@ -2011,7 +2011,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) { @@ -2023,7 +2023,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) @@ -2039,7 +2039,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; } @@ -2049,7 +2049,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; } @@ -2311,22 +2311,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/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index af13909bf89..3e8e6a69dd8 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -125,7 +125,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 @@ -155,7 +155,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; @@ -166,7 +166,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; @@ -244,7 +244,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); @@ -320,7 +320,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, ×); @@ -498,7 +498,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)); @@ -564,7 +564,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]; } @@ -581,7 +581,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; @@ -593,7 +593,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; @@ -640,7 +640,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; } @@ -683,7 +683,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; } @@ -695,7 +695,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); @@ -709,7 +709,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); @@ -762,7 +762,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) @@ -818,13 +818,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); @@ -1199,7 +1199,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; @@ -1241,7 +1241,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)) { @@ -1286,13 +1286,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); @@ -1309,15 +1309,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)); @@ -1333,23 +1333,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)); @@ -1357,13 +1357,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); } @@ -1372,7 +1372,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; } @@ -1529,7 +1529,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; @@ -1613,9 +1613,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; @@ -1624,29 +1624,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<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_ROTATION); pid->info_types= 0; - + pid->stack_index = pid->cache->index; - + pid->default_step = 1; pid->max_step = 1; pid->file_type = PTCACHE_FILE_PTCACHE; @@ -1688,7 +1688,7 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup 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; @@ -1696,7 +1696,7 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup /* 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; @@ -1732,7 +1732,7 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup } } } - + if (scene && ob->rigidbody_object && scene->rigidbody_world) { pid = MEM_callocN(sizeof(PTCacheID), "PTCacheID"); BKE_ptcache_id_from_rigidbody(pid, ob, scene->rigidbody_world); @@ -1743,16 +1743,15 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup * for baking with linking dupligroups. Once we have better overrides * this can be revisited so users select the local objects directly. */ if (scene && (duplis-- > 0) && (ob->dup_group)) { - Collection *collection = ob->dup_group; - Base *base = BKE_collection_object_cache_get(collection).first; - - for (; base; base = base->next) { - if (base->object != ob) { + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(ob->dup_group, object) + { + if (object != ob) { ListBase lb_dupli_pid; - BKE_ptcache_ids_from_object(&lb_dupli_pid, base->object, scene, duplis); + BKE_ptcache_ids_from_object(&lb_dupli_pid, object, scene, duplis); BLI_movelisttolist(lb, &lb_dupli_pid); } } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } } @@ -1819,20 +1818,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() */ } @@ -1843,9 +1842,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); @@ -1861,8 +1860,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; } @@ -1884,7 +1883,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 */ } @@ -1901,7 +1900,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) { @@ -1995,7 +1994,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; @@ -2005,7 +2004,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); @@ -2015,7 +2014,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; @@ -2051,18 +2050,18 @@ static int ptcache_file_data_read(PTCacheFile *pf) if ((pf->data_types & (1<<i)) && !ptcache_file_read(pf, pf->cur[i], 1, ptcache_data_size[i])) return 0; } - + return 1; } static int ptcache_file_data_write(PTCacheFile *pf) -{ +{ int i; for (i=0; i<BPHYS_TOT_DATA; i++) { if ((pf->data_types & (1<<i)) && !ptcache_file_write(pf, pf->cur[i], 1, ptcache_data_size[i])) return 0; } - + return 1; } static int ptcache_file_header_begin_read(PTCacheFile *pf) @@ -2070,12 +2069,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; @@ -2084,7 +2083,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); @@ -2095,13 +2094,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; } @@ -2382,14 +2381,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); @@ -2404,10 +2403,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; @@ -2463,7 +2462,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"); @@ -2512,7 +2511,7 @@ static int ptcache_read_stream(PTCacheID *pid, int cfra) } ptcache_file_close(pf); - + return error == 0; } @@ -2557,7 +2556,7 @@ static int ptcache_read(PTCacheID *pid, int cfra) } else { pm = pid->cache->mem_cache.first; - + while (pm && pm->frame != cfra) pm = pm->next; } @@ -2582,7 +2581,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); } @@ -2611,7 +2610,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; } @@ -2749,7 +2748,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); @@ -2821,7 +2820,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 @@ -2969,7 +2968,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]; @@ -3002,11 +3001,11 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) 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 @@ -3015,9 +3014,9 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) 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 */ @@ -3034,7 +3033,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) 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) @@ -3063,7 +3062,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } BLI_freelistN(&pid->cache->mem_cache); - if (pid->cache->cached_frames) + if (pid->cache->cached_frames) memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames)); } else { @@ -3085,7 +3084,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } } break; - + case PTCACHE_CLEAR_FRAME: if (pid->cache->flag & PTCACHE_DISK_CACHE) { if (BKE_ptcache_id_exist(pid, cfra)) { @@ -3122,10 +3121,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); @@ -3165,7 +3164,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); } @@ -3203,7 +3202,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]; @@ -3211,9 +3210,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; @@ -3221,7 +3220,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 */ @@ -3329,7 +3328,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; @@ -3387,19 +3386,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 */ @@ -3418,7 +3417,7 @@ void BKE_ptcache_remove(void) else { rmdir = 0; /* path dosnt exist */ } - + if (rmdir) { BLI_delete(path, true, false); } @@ -3528,7 +3527,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 */ @@ -3537,7 +3536,7 @@ void BKE_ptcache_quick_cache_all(Main *bmain, Scene *scene, ViewLayer *view_laye PTCacheBaker baker; memset(&baker, 0, sizeof(baker)); - baker.main = bmain; + baker.bmain = bmain; baker.scene = scene; baker.view_layer = view_layer; baker.bake = 0; @@ -3563,7 +3562,7 @@ static void ptcache_dt_to_str(char *str, double dtime) /* if bake is not given run simulations to current frame */ void BKE_ptcache_bake(PTCacheBaker *baker) { - Main *bmain = baker->main; + Main *bmain = baker->bmain; Scene *scene = baker->scene; ViewLayer *view_layer = baker->view_layer; struct Depsgraph *depsgraph = baker->depsgraph; @@ -3577,7 +3576,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 */ @@ -3769,7 +3768,7 @@ void BKE_ptcache_bake(PTCacheBaker *baker) scene->r.framelen = frameleno; CFRA = cfrao; - + if (bake) { /* already on cfra unless baking */ BKE_scene_graph_update_for_newframe(depsgraph, bmain); } @@ -3851,7 +3850,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); @@ -3871,7 +3870,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]; @@ -3930,7 +3929,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]; @@ -3940,9 +3939,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; @@ -3953,7 +3952,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 */ @@ -4009,7 +4008,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); } } @@ -4087,7 +4086,7 @@ void BKE_ptcache_update_info(PTCacheID *pid) } bytes += sizeof(PTCacheMem); - + totframes++; } diff --git a/source/blender/blenkernel/intern/report.c b/source/blender/blenkernel/intern/report.c index 67b076c0153..a9b36a85602 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 f7628d081a6..2374670b212 100644 --- a/source/blender/blenkernel/intern/rigidbody.c +++ b/source/blender/blenkernel/intern/rigidbody.c @@ -48,13 +48,13 @@ #include "DNA_ID.h" #include "DNA_group_types.h" +#include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_object_types.h" #include "DNA_object_force_types.h" #include "DNA_rigidbody_types.h" #include "DNA_scene_types.h" -#include "BKE_cdderivedmesh.h" #include "BKE_collection.h" #include "BKE_effect.h" #include "BKE_global.h" @@ -62,6 +62,7 @@ #include "BKE_library.h" #include "BKE_library_query.h" #include "BKE_mesh.h" +#include "BKE_mesh_runtime.h" #include "BKE_object.h" #include "BKE_pointcache.h" #include "BKE_rigidbody.h" @@ -235,16 +236,18 @@ RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int UNUSED(f /* Setup Utilities - Validate Sim Instances */ /* get the appropriate DerivedMesh based on rigid body mesh source */ -static DerivedMesh *rigidbody_get_mesh(Object *ob) +static Mesh *rigidbody_get_mesh(Object *ob) { + /* TODO(Sybren): turn this into a switch statement */ if (ob->rigidbody_object->mesh_source == RBO_MESH_DEFORM) { - return ob->derivedDeform; + return ob->runtime.mesh_deform_eval; } else if (ob->rigidbody_object->mesh_source == RBO_MESH_FINAL) { - return ob->derivedFinal; + return ob->runtime.mesh_eval; } else { - return CDDM_from_mesh(ob->data); + BLI_assert(ob->rigidbody_object->mesh_source == RBO_MESH_BASE); + return ob->data; } } @@ -252,14 +255,14 @@ static DerivedMesh *rigidbody_get_mesh(Object *ob) static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, float margin, bool *can_embed) { rbCollisionShape *shape = NULL; - DerivedMesh *dm = NULL; + Mesh *mesh = NULL; MVert *mvert = NULL; int totvert = 0; if (ob->type == OB_MESH && ob->data) { - dm = rigidbody_get_mesh(ob); - mvert = (dm) ? dm->getVertArray(dm) : NULL; - totvert = (dm) ? dm->getNumVerts(dm) : 0; + mesh = rigidbody_get_mesh(ob); + mvert = (mesh) ? mesh->mvert : NULL; + totvert = (mesh) ? mesh->totvert : 0; } else { printf("ERROR: cannot make Convex Hull collision shape for non-Mesh object\n"); @@ -272,9 +275,6 @@ static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, fl printf("ERROR: no vertices to define Convex Hull collision shape with\n"); } - if (dm && ob->rigidbody_object->mesh_source == RBO_MESH_BASE) - dm->release(dm); - return shape; } @@ -286,24 +286,24 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) rbCollisionShape *shape = NULL; if (ob->type == OB_MESH) { - DerivedMesh *dm = NULL; + Mesh *mesh = NULL; MVert *mvert; const MLoopTri *looptri; int totvert; int tottri; const MLoop *mloop; - - dm = rigidbody_get_mesh(ob); + + mesh = rigidbody_get_mesh(ob); /* ensure mesh validity, then grab data */ - if (dm == NULL) + if (mesh == NULL) return NULL; - mvert = dm->getVertArray(dm); - totvert = dm->getNumVerts(dm); - looptri = dm->getLoopTriArray(dm); - tottri = dm->getNumLoopTri(dm); - mloop = dm->getLoopArray(dm); + mvert = mesh->mvert; + totvert = mesh->totvert; + looptri = BKE_mesh_runtime_looptri_ensure(mesh); + tottri = mesh->runtime.looptris.len; + mloop = mesh->mloop; /* sanity checking - potential case when no data will be present */ if ((totvert == 0) || (tottri == 0)) { @@ -315,7 +315,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 @@ -334,7 +334,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 @@ -353,11 +353,6 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) shape = RB_shape_new_gimpact_mesh(mdata); } } - - /* cleanup temp data */ - if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) { - dm->release(dm); - } } else { printf("ERROR: cannot make Triangular Mesh collision shape for non-Mesh object\n"); @@ -520,30 +515,25 @@ void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) case RB_SHAPE_TRIMESH: { if (ob->type == OB_MESH) { - DerivedMesh *dm = rigidbody_get_mesh(ob); + Mesh *mesh = rigidbody_get_mesh(ob); MVert *mvert; const MLoopTri *lt = NULL; int totvert, tottri = 0; const MLoop *mloop = NULL; - + /* ensure mesh validity, then grab data */ - if (dm == NULL) + if (mesh == NULL) return; - - mvert = dm->getVertArray(dm); - totvert = dm->getNumVerts(dm); - lt = dm->getLoopTriArray(dm); - tottri = dm->getNumLoopTri(dm); - mloop = dm->getLoopArray(dm); - + + mvert = mesh->mvert; + totvert = mesh->totvert; + lt = BKE_mesh_runtime_looptri_ensure(mesh); + tottri = mesh->runtime.looptris.len; + mloop = mesh->mloop; + 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); - } } else { /* rough estimate from boundbox as fallback */ @@ -603,30 +593,25 @@ void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) case RB_SHAPE_TRIMESH: { if (ob->type == OB_MESH) { - DerivedMesh *dm = rigidbody_get_mesh(ob); + Mesh *mesh = rigidbody_get_mesh(ob); MVert *mvert; const MLoopTri *looptri; int totvert, tottri; const MLoop *mloop; - + /* ensure mesh validity, then grab data */ - if (dm == NULL) + if (mesh == NULL) return; - - mvert = dm->getVertArray(dm); - totvert = dm->getNumVerts(dm); - looptri = dm->getLoopTriArray(dm); - tottri = dm->getNumLoopTri(dm); - mloop = dm->getLoopArray(dm); - + + mvert = mesh->mvert; + totvert = mesh->totvert; + looptri = BKE_mesh_runtime_looptri_ensure(mesh); + tottri = mesh->runtime.looptris.len; + mloop = mesh->mloop; + 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); - } } break; } @@ -1135,7 +1120,7 @@ RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) return scene->rigidbody_world; } -void BKE_rigidbody_remove_object(Scene *scene, Object *ob) +void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob) { RigidBodyWorld *rbw = scene->rigidbody_world; RigidBodyOb *rbo = ob->rigidbody_object; @@ -1170,6 +1155,7 @@ void BKE_rigidbody_remove_object(Scene *scene, Object *ob) } FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } + BKE_collection_object_remove(bmain, rbw->group, ob, false); } /* remove object's settings */ @@ -1202,17 +1188,20 @@ void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) /* Update object array and rigid body count so they're in sync with the rigid body group */ static void rigidbody_update_ob_array(RigidBodyWorld *rbw) { - const ListBase objects = BKE_collection_object_cache_get(rbw->group); - int i, n; - - n = BLI_listbase_count(&objects); + int n = 0; + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) + { + (void)object; + n++; + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; if (rbw->numbodies != n) { rbw->numbodies = n; rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies); } - i = 0; + int i = 0; FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) { rbw->objects[i] = object; @@ -1241,7 +1230,7 @@ static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw) rigidbody_update_ob_array(rbw); } -static void rigidbody_update_sim_ob(struct Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo) +static void rigidbody_update_sim_ob(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo) { float loc[3]; float rot[4]; @@ -1252,10 +1241,10 @@ static void rigidbody_update_sim_ob(struct Depsgraph *depsgraph, Scene *scene, R return; if (rbo->shape == RB_SHAPE_TRIMESH && rbo->flag & RBO_FLAG_USE_DEFORM) { - DerivedMesh *dm = ob->derivedDeform; - if (dm) { - MVert *mvert = dm->getVertArray(dm); - int totvert = dm->getNumVerts(dm); + Mesh *mesh = ob->runtime.mesh_deform_eval; + if (mesh) { + MVert *mvert = mesh->mvert; + int totvert = mesh->totvert; BoundBox *bb = BKE_object_boundbox_get(ob); RB_shape_trimesh_update(rbo->physics_shape, (float *)mvert, totvert, sizeof(MVert), bb->vec[0], bb->vec[6]); @@ -1330,7 +1319,7 @@ static void rigidbody_update_sim_ob(struct Depsgraph *depsgraph, Scene *scene, R * * \param rebuild Rebuild entire simulation */ -static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, bool rebuild) +static void rigidbody_update_simulation(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, bool rebuild) { /* update world */ if (rebuild) @@ -1340,7 +1329,7 @@ static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scen /* 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) { @@ -1401,7 +1390,7 @@ static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scen } } FOREACH_COLLECTION_OBJECT_RECURSIVE_END; - + /* update constraints */ if (rbw->constraints == NULL) /* no constraints, move on */ return; @@ -1437,8 +1426,10 @@ static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scen FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } -static void rigidbody_update_simulation_post_step(ViewLayer *view_layer, RigidBodyWorld *rbw) +static void rigidbody_update_simulation_post_step(Depsgraph *depsgraph, RigidBodyWorld *rbw) { + ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph); + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, ob) { Base *base = BKE_view_layer_base_find(view_layer, ob); @@ -1567,7 +1558,7 @@ void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) /* Rebuild rigid body world */ /* NOTE: this needs to be called before frame update to work correctly */ -void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, float ctime) +void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime) { RigidBodyWorld *rbw = scene->rigidbody_world; PointCache *cache; @@ -1579,8 +1570,15 @@ void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, floa cache = rbw->pointcache; /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */ - const ListBase objects = BKE_collection_object_cache_get(rbw->group); - if (rbw->physics_world == NULL || rbw->numbodies != BLI_listbase_count(&objects)) { + int n = 0; + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) + { + (void)object; + n++; + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + + if (rbw->physics_world == NULL || rbw->numbodies != n) { cache->flag |= PTCACHE_OUTDATED; } @@ -1596,7 +1594,7 @@ void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, floa } /* Run RigidBody simulation for the specified physics world */ -void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, float ctime) +void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime) { float timestep; RigidBodyWorld *rbw = scene->rigidbody_world; @@ -1634,7 +1632,7 @@ void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, floa } /* advance simulation, we can only step one frame forward */ - if (ctime == rbw->ltime + 1) { + if (compare_ff_relative(ctime, rbw->ltime + 1, FLT_EPSILON, 64)) { /* write cache for first frame when on second frame */ if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) { BKE_ptcache_write(&pid, startframe); @@ -1648,8 +1646,7 @@ void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, floa /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */ RB_dworld_step_simulation(rbw->physics_world, timestep, INT_MAX, 1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f)); - ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph); - rigidbody_update_simulation_post_step(view_layer, rbw); + rigidbody_update_simulation_post_step(depsgraph, rbw); /* write cache for current frame */ BKE_ptcache_validate(cache, (int)ctime); @@ -1680,14 +1677,14 @@ void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFun struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; } struct RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type) { return NULL; } struct RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { return NULL; } -void BKE_rigidbody_remove_object(Scene *scene, Object *ob) {} +void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob) {} void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) {} void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) {} void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) {} bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime) { return false; } void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) {} -void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, float ctime) {} -void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, float ctime) {} +void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime) {} +void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime) {} #if defined(__GNUC__) || defined(__clang__) # pragma GCC diagnostic pop @@ -1695,10 +1692,31 @@ void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, floa #endif /* WITH_BULLET */ + +/* Copy the pointcache from the evaluated to the original scene. + * This allows the re-evaluation of the original scene to use the + * physics cache. + */ +static void rigidbody_copy_cache_to_orig(Scene *scene_eval) +{ + if ((scene_eval->id.tag & LIB_TAG_COPIED_ON_WRITE) == 0) { + /* Scene is already an original, this function is a no-op. */ + return; + } + + Scene *scene_orig = (Scene *)DEG_get_original_id(&scene_eval->id); + RigidBodyWorld *rbw_orig = scene_orig->rigidbody_world; + RigidBodyWorld *rbw_eval = scene_eval->rigidbody_world; + + BKE_ptcache_free_list(&rbw_orig->ptcaches); + rbw_orig->pointcache = BKE_ptcache_copy_list(&rbw_orig->ptcaches, &rbw_eval->ptcaches, LIB_ID_COPY_CACHES); +} + + /* -------------------- */ /* Depsgraph evaluation */ -void BKE_rigidbody_rebuild_sim(struct Depsgraph *depsgraph, +void BKE_rigidbody_rebuild_sim(Depsgraph *depsgraph, Scene *scene) { float ctime = DEG_get_ctime(depsgraph); @@ -1709,18 +1727,26 @@ void BKE_rigidbody_rebuild_sim(struct Depsgraph *depsgraph, } } -void BKE_rigidbody_eval_simulation(struct Depsgraph *depsgraph, +void BKE_rigidbody_eval_simulation(Depsgraph *depsgraph, Scene *scene) { float ctime = DEG_get_ctime(depsgraph); DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime); + /* evaluate rigidbody sim */ - if (BKE_scene_check_rigidbody_active(scene)) { - BKE_rigidbody_do_simulation(depsgraph, scene, ctime); + if (!BKE_scene_check_rigidbody_active(scene)) { + return; + } + BKE_rigidbody_do_simulation(depsgraph, scene, ctime); + + /* Make sure re-evaluation can use the cache from this simulation */ + if (!DEG_is_active(depsgraph)) { + return; } + rigidbody_copy_cache_to_orig(scene); } -void BKE_rigidbody_object_sync_transforms(struct Depsgraph *depsgraph, +void BKE_rigidbody_object_sync_transforms(Depsgraph *depsgraph, Scene *scene, Object *ob) { diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index 63d7942c623..4c81cb057f0 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -110,7 +110,6 @@ #include "bmesh.h" -const char *RE_engine_id_BLENDER_CLAY = "BLENDER_CLAY"; const char *RE_engine_id_BLENDER_EEVEE = "BLENDER_EEVEE"; const char *RE_engine_id_BLENDER_WORKBENCH = "BLENDER_WORKBENCH"; const char *RE_engine_id_CYCLES = "CYCLES"; @@ -137,10 +136,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); @@ -450,9 +449,6 @@ void BKE_scene_free_ex(Scene *sce, const bool do_id_user) { BKE_animdata_free((ID *)sce, false); - /* check all sequences */ - BKE_sequencer_clear_scene_in_allseqs(G.main, sce); - BKE_sequencer_editing_free(sce, do_id_user); BKE_keyingsets_free(&sce->keyingsets); @@ -483,10 +479,10 @@ void BKE_scene_free_ex(Scene *sce, const bool do_id_user) BLI_freelistN(&sce->markers); BLI_freelistN(&sce->transform_spaces); BLI_freelistN(&sce->r.views); - + BKE_toolsettings_free(sce->toolsettings); sce->toolsettings = NULL; - + BKE_scene_free_depsgraph_hash(sce); MEM_SAFE_FREE(sce->fps_info); @@ -536,7 +532,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_OSA; sce->r.cfra = 1; sce->r.sfra = 1; @@ -619,7 +615,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; @@ -632,6 +628,8 @@ void BKE_scene_init(Scene *sce) CURVEMAP_SLOPE_POS_NEG); sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct"); + + sce->toolsettings->object_flag |= SCE_OBJECT_MODE_LOCK; sce->toolsettings->doublimit = 0.001; sce->toolsettings->vgroup_weight = 1.0f; sce->toolsettings->uvcalc_margin = 0.001f; @@ -643,7 +641,7 @@ void BKE_scene_init(Scene *sce) sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX; sce->toolsettings->autokey_mode = U.autokey_mode; - + sce->toolsettings->transform_pivot_point = V3D_AROUND_CENTER_MEAN; sce->toolsettings->snap_mode = SCE_SNAP_MODE_INCREMENT; sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID; @@ -744,22 +742,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; @@ -769,28 +767,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; @@ -808,15 +806,8 @@ void BKE_scene_init(Scene *sce) copy_v3_v3(sce->display.light_direction, (float[3]){-M_SQRT1_3, -M_SQRT1_3, M_SQRT1_3}); sce->display.shadow_shift = 0.1; - sce->display.matcap_icon = 1; - sce->display.matcap_type = CLAY_MATCAP_NONE; - sce->display.matcap_hue = 0.5f; - sce->display.matcap_saturation = 0.5f; - sce->display.matcap_value = 0.5f; sce->display.matcap_ssao_distance = 0.2f; sce->display.matcap_ssao_attenuation = 1.0f; - sce->display.matcap_ssao_factor_cavity = 1.0f; - sce->display.matcap_ssao_factor_edge = 1.0f; sce->display.matcap_ssao_samples = 16; /* SceneEEVEE */ @@ -920,10 +911,10 @@ Object *BKE_scene_object_find_by_name(Scene *scene, const char *name) void BKE_scene_set_background(Main *bmain, Scene *scene) { Object *ob; - + /* check for cyclic sets, for reading old files but also for definite security (py?) */ BKE_scene_validate_setscene(bmain, scene); - + /* deselect objects (for dataselect) */ for (ob = bmain->object.first; ob; ob = ob->id.next) ob->flag &= ~SELECT; @@ -958,7 +949,7 @@ int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter, Scene **scene, int val, Base **base, Object **ob) { bool run_again = true; - + /* init */ if (val == 0) { iter->phase = F_START; @@ -1017,19 +1008,19 @@ int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter, } } } - + if (*base == NULL) { iter->phase = F_START; } else { if (iter->phase != F_DUPLI) { if (depsgraph && (*base)->object->transflag & OB_DUPLI) { - /* collections cannot be duplicated for mballs yet, - * this enters eternal loop because of + /* collections cannot be duplicated for mballs yet, + * this enters eternal loop because of * makeDispListMBall getting called inside of collection_duplilist */ if ((*base)->object->dup_group == NULL) { iter->duplilist = object_duplilist(depsgraph, (*scene), (*base)->object); - + iter->dupob = iter->duplilist->first; if (!iter->dupob) { @@ -1062,13 +1053,13 @@ int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter, else if (iter->phase == F_DUPLI) { iter->phase = F_SCENE; (*base)->flag_legacy &= ~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; @@ -1196,14 +1187,14 @@ char *BKE_scene_find_last_marker_name(Scene *scene, int frame) return best_marker ? best_marker->name : NULL; } -void BKE_scene_remove_rigidbody_object(Scene *scene, Object *ob) +void BKE_scene_remove_rigidbody_object(struct Main *bmain, Scene *scene, Object *ob) { /* remove rigid body constraint from world before removing object */ if (ob->rigidbody_constraint) BKE_rigidbody_remove_constraint(scene, ob); /* remove rigid body object from world before removing object */ if (ob->rigidbody_object) - BKE_rigidbody_remove_object(scene, ob); + BKE_rigidbody_remove_object(bmain, scene, ob); } /* checks for cycle, returns 1 if it's all OK */ @@ -1214,7 +1205,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) { @@ -1241,7 +1232,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; } @@ -1333,7 +1324,7 @@ static void prepare_mesh_for_viewport_render( if (check_rendered_viewport_visible(bmain)) { BMesh *bm = mesh->edit_btmesh->bm; BM_mesh_bm_to_me( - bm, mesh, + bmain, bm, mesh, (&(struct BMeshToMeshParams){ .calc_object_remap = true, })); @@ -1621,7 +1612,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 8cff10902ef..5a6c55a9fcc 100644 --- a/source/blender/blenkernel/intern/screen.c +++ b/source/blender/blenkernel/intern/screen.c @@ -65,7 +65,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); @@ -86,7 +86,7 @@ static void spacetype_free(SpaceType *st) BLI_freelistN(&art->paneltypes); BLI_freelistN(&art->headertypes); } - + BLI_freelistN(&st->regiontypes); BLI_freelistN(&st->toolshelf); @@ -95,18 +95,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,18 +114,30 @@ SpaceType *BKE_spacetype_from_id(int spaceid) return NULL; } -ARegionType *BKE_regiontype_from_id(SpaceType *st, int regionid) +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; } +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; + } + } + return NULL; +} + const ListBase *BKE_spacetypes_list(void) { @@ -135,7 +147,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) { @@ -143,7 +155,7 @@ void BKE_spacetype_register(SpaceType *st) spacetype_free(stype); MEM_freeN(stype); } - + BLI_addtail(&spacetypes, st); } @@ -158,20 +170,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); } @@ -204,7 +216,7 @@ static void panel_list_copy(ListBase *newlb, const ListBase *lb) ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) { ARegion *newar = MEM_dupallocN(ar); - + newar->prev = newar->next = NULL; BLI_listbase_clear(&newar->handlers); BLI_listbase_clear(&newar->uiblocks); @@ -216,25 +228,30 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) newar->regiontimer = NULL; newar->headerstr = NULL; newar->draw_buffer = NULL; - + /* use optional regiondata callback */ if (ar->regiondata) { ARegionType *art = BKE_regiontype_from_id(st, ar->regiontype); - if (art && art->duplicate) + if (art && art->duplicate) { newar->regiondata = art->duplicate(ar->regiondata); - else + } + else if (ar->flag & RGN_FLAG_TEMP_REGIONDATA) { + newar->regiondata = NULL; + } + else { newar->regiondata = MEM_dupallocN(ar->regiondata); + } } if (ar->v2d.tab_offset) newar->v2d.tab_offset = MEM_dupallocN(ar->v2d.tab_offset); - + panel_list_copy(&newar->panels, &ar->panels); BLI_listbase_clear(&newar->ui_previews); BLI_duplicatelist(&newar->ui_previews, &ar->ui_previews); - + return newar; } @@ -243,10 +260,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); @@ -258,17 +275,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); } } @@ -280,14 +297,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; } } @@ -365,16 +382,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; @@ -414,15 +431,15 @@ 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); MEM_SAFE_FREE(sa->global); BLI_freelistN(&sa->regionbase); - + BKE_spacedata_freelist(&sa->spacedata); - + BLI_freelistN(&sa->actionzones); } @@ -444,7 +461,7 @@ 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); @@ -652,7 +669,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 00af9721f07..9105961a3ae 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; @@ -1853,7 +1853,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; @@ -2054,7 +2054,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; @@ -2086,7 +2086,7 @@ static void transform_image( xo = x; yo = y; - + /* Rotate */ s = sinf(rotate); c = cosf(rotate); @@ -2129,7 +2129,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; @@ -2293,7 +2293,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; @@ -2462,12 +2462,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; } @@ -2521,7 +2521,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]; @@ -2554,7 +2554,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]; @@ -2623,7 +2623,7 @@ static ImBuf *do_multicam( else { out = i; } - + return out; } @@ -2698,7 +2698,7 @@ static ImBuf *do_adjustment( else { out = i; } - + return out; } @@ -2877,7 +2877,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 ecd0335fc4e..d857db7e276 100644 --- a/source/blender/blenkernel/intern/sequencer.c +++ b/source/blender/blenkernel/intern/sequencer.c @@ -751,10 +751,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)); @@ -1016,7 +1016,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); } @@ -1280,7 +1280,7 @@ static void multibuf(ImBuf *ibuf, const float fmul) rt_float[1] *= fmul; rt_float[2] *= fmul; rt_float[3] *= fmul; - + rt_float += 4; } } @@ -1311,9 +1311,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); } @@ -1334,7 +1334,7 @@ StripElem *BKE_sequencer_give_stripelem(Sequence *seq, int cfra) if (nr == -1 || se == NULL) return NULL; - + se += nr + seq->anim_startofs; } return se; @@ -1431,7 +1431,7 @@ static int get_shown_sequences(ListBase *seqbasep, int cfra, int chanshown, Sequ } } } - + chanshown = b; for (; b > 0; b--) { @@ -1662,7 +1662,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 @@ -2107,7 +2107,7 @@ void BKE_sequencer_proxy_set(struct Sequence *seq, bool value) } else { seq->flag &= ~SEQ_USE_PROXY; - } + } } /*********************** color balance *************************/ @@ -2207,7 +2207,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; @@ -2559,7 +2559,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); } @@ -3077,7 +3077,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; @@ -3294,7 +3294,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; } @@ -3679,13 +3679,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; } @@ -3762,7 +3762,7 @@ static ImBuf *seq_render_strip_stack( if (out) { return out; } - + if (count == 1) { Sequence *seq = seq_arr[0]; @@ -3887,7 +3887,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)) { @@ -3938,23 +3938,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; @@ -3984,7 +3984,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); @@ -4070,7 +4070,7 @@ ImBuf *BKE_sequencer_give_ibuf_threaded(const SeqRenderData *context, float cfra pthread_mutex_unlock(&frame_done_lock); } } - + return e ? e->ibuf : NULL; } @@ -4186,30 +4186,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; @@ -4219,7 +4219,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) { @@ -4229,11 +4229,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; } @@ -4241,9 +4241,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); } @@ -4500,9 +4500,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; @@ -4961,7 +4961,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); @@ -5215,7 +5215,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"); @@ -5403,7 +5403,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); @@ -5724,10 +5724,10 @@ static void sequencer_all_free_anim_ibufs(ListBase *seqbase, int cfra) } } -void BKE_sequencer_all_free_anim_ibufs(int cfra) +void BKE_sequencer_all_free_anim_ibufs(Main *bmain, int cfra) { BKE_sequencer_cache_cleanup(); - for (Scene *scene = G.main->scene.first; + for (Scene *scene = bmain->scene.first; scene != NULL; scene = scene->id.next) { diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c index a7b233bc042..f8615671384 100644 --- a/source/blender/blenkernel/intern/shrinkwrap.c +++ b/source/blender/blenkernel/intern/shrinkwrap.c @@ -166,7 +166,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/smoke.c b/source/blender/blenkernel/intern/smoke.c index 738be9ded54..6bdce647bd9 100644 --- a/source/blender/blenkernel/intern/smoke.c +++ b/source/blender/blenkernel/intern/smoke.c @@ -1812,7 +1812,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 9aa6c172a90..31644cc2392 100644 --- a/source/blender/blenkernel/intern/softbody.c +++ b/source/blender/blenkernel/intern/softbody.c @@ -75,6 +75,7 @@ variables on the UI for now #include "BKE_curve.h" #include "BKE_effect.h" #include "BKE_global.h" +#include "BKE_layer.h" #include "BKE_modifier.h" #include "BKE_softbody.h" #include "BKE_pointcache.h" @@ -516,19 +517,17 @@ static void ccd_build_deflector_hash_single(GHash *hash, Object *ob) /** * \note collection overrides scene when not NULL. */ -static void ccd_build_deflector_hash(ViewLayer *view_layer, Collection *collection, Object *vertexowner, GHash *hash) +static void ccd_build_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, GHash *hash) { - Object *ob; - if (!hash) return; /* Explicit collision collection. */ - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, collection); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, collection); for (; base; base = base->next) { /* Only proceed for mesh object in same layer. */ if (base->object->type == OB_MESH) { - ob = base->object; + Object *ob = base->object; if (ob == vertexowner) { /* If vertexowner is given we don't want to check collision with owner object. */ continue; @@ -551,19 +550,17 @@ static void ccd_update_deflector_hash_single(GHash *hash, Object *ob) /** * \note collection overrides scene when not NULL. */ -static void ccd_update_deflector_hash(ViewLayer *view_layer, Collection *collection, Object *vertexowner, GHash *hash) +static void ccd_update_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, GHash *hash) { - Object *ob; - if ((!hash) || (!vertexowner)) return; /* Explicit collision collection. */ - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, collection); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, collection); for (; base; base = base->next) { /* Only proceed for mesh object in same layer. */ if (base->object->type == OB_MESH) { - ob = base->object; + Object *ob = base->object; if (ob == vertexowner) { /* If vertexowner is given we don't want to check collision with owner object. */ continue; @@ -974,9 +971,9 @@ static bool are_there_deflectors(Base *first_base) return 0; } -static int query_external_colliders(ViewLayer *view_layer, Collection *collection) +static int query_external_colliders(Depsgraph *depsgraph, Collection *collection) { - return(are_there_deflectors(BKE_collection_or_layer_objects(NULL, NULL, view_layer, collection))); + return(are_there_deflectors(BKE_collection_or_layer_objects(depsgraph, NULL, NULL, collection))); } /* --- dependency information functions*/ @@ -2220,7 +2217,7 @@ static void softbody_calc_forcesEx(struct Depsgraph *depsgraph, Scene *scene, Ob /* gravity = sb->grav * sb_grav_force_scale(ob); */ /* UNUSED */ /* check conditions for various options */ - do_deflector= query_external_colliders(DEG_get_evaluated_view_layer(depsgraph), sb->collision_group); + do_deflector= query_external_colliders(depsgraph, sb->collision_group); /* do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); */ /* UNUSED */ do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL); do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES)); @@ -2284,7 +2281,7 @@ static void softbody_calc_forces(struct Depsgraph *depsgraph, Scene *scene, Obje } /* check conditions for various options */ - do_deflector= query_external_colliders(DEG_get_evaluated_view_layer(depsgraph), sb->collision_group); + do_deflector= query_external_colliders(depsgraph, sb->collision_group); do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL); do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES)); @@ -2839,7 +2836,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; @@ -3495,13 +3492,11 @@ static void softbody_step(struct Depsgraph *depsgraph, Scene *scene, Object *ob, */ if (dtime < 0 || dtime > 10.5f) return; - ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - - ccd_update_deflector_hash(view_layer, sb->collision_group, ob, sb->scratch->colliderhash); + ccd_update_deflector_hash(depsgraph, sb->collision_group, ob, sb->scratch->colliderhash); if (sb->scratch->needstobuildcollider) { - if (query_external_colliders(view_layer, sb->collision_group)) { - ccd_build_deflector_hash(view_layer, sb->collision_group, ob, sb->scratch->colliderhash); + if (query_external_colliders(depsgraph, sb->collision_group)) { + ccd_build_deflector_hash(depsgraph, sb->collision_group, ob, sb->scratch->colliderhash); } sb->scratch->needstobuildcollider=0; } diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index a7f3fc1df9e..ebb23f8d5c6 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -144,7 +144,7 @@ void BKE_sound_free(bSound *sound) } BKE_sound_free_waveform(sound); - + #endif /* WITH_AUDASPACE */ if (sound->spinlock) { BLI_spin_end(sound->spinlock); @@ -774,7 +774,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); } @@ -797,9 +797,9 @@ void BKE_sound_read_waveform(bSound *sound, short *stop) 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; diff --git a/source/blender/blenkernel/intern/studiolight.c b/source/blender/blenkernel/intern/studiolight.c index e4b49656907..62361917f2f 100644 --- a/source/blender/blenkernel/intern/studiolight.c +++ b/source/blender/blenkernel/intern/studiolight.c @@ -42,6 +42,7 @@ #include "BLI_path_util.h" #include "BLI_rand.h" #include "BLI_string.h" +#include "BLI_string_utils.h" #include "DNA_listBase.h" @@ -55,59 +56,88 @@ /* Statics */ static ListBase studiolights; -#define STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE 8 +#define STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE 128 #define STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT 32 #define STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_WIDTH (STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT * 2) +/* + Disable this option so caches are not loaded from disk + Do not checkin with this commented out +*/ +#define STUDIOLIGHT_LOAD_CACHED_FILES + static const char *STUDIOLIGHT_CAMERA_FOLDER = "studiolights/camera/"; static const char *STUDIOLIGHT_WORLD_FOLDER = "studiolights/world/"; static const char *STUDIOLIGHT_MATCAP_FOLDER = "studiolights/matcap/"; /* FUNCTIONS */ +#define IMB_SAFE_FREE(p) do { \ +if (p) { \ + IMB_freeImBuf(p); \ + p = NULL; \ +} \ +} while (0) + +#define GPU_TEXTURE_SAFE_FREE(p) do { \ +if (p) { \ + GPU_texture_free(p); \ + p = NULL; \ +} \ +} while (0) + static void studiolight_free(struct StudioLight *sl) { - for (int index = 0 ; index < 6 ; index ++) { - if (sl->radiance_cubemap_buffers[index] != NULL) { - IMB_freeImBuf(sl->radiance_cubemap_buffers[index]); - sl->radiance_cubemap_buffers[index] = NULL; - } - - if (sl->equirectangular_radiance_gputexture) { - GPU_texture_free(sl->equirectangular_radiance_gputexture); - sl->equirectangular_radiance_gputexture = NULL; - } - - if (sl->equirectangular_irradiance_gputexture) { - GPU_texture_free(sl->equirectangular_irradiance_gputexture); - sl->equirectangular_irradiance_gputexture = NULL; - } - - if (sl->equirectangular_radiance_buffer) { - IMB_freeImBuf(sl->equirectangular_radiance_buffer); - sl->equirectangular_radiance_buffer = NULL; - } +#define STUDIOLIGHT_DELETE_ICON(s) { \ + if (s != 0) { \ + BKE_icon_delete(s); \ + s = 0; \ + } \ +} + if (sl->free_function) { + sl->free_function(sl, sl->free_function_data); + } + STUDIOLIGHT_DELETE_ICON(sl->icon_id_radiance); + STUDIOLIGHT_DELETE_ICON(sl->icon_id_irradiance); + STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap); + STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap_flipped); +#undef STUDIOLIGHT_DELETE_ICON - if (sl->equirectangular_irradiance_buffer) { - IMB_freeImBuf(sl->equirectangular_irradiance_buffer); - sl->equirectangular_irradiance_buffer = NULL; - } + for (int index = 0 ; index < 6 ; index ++) { + IMB_SAFE_FREE(sl->radiance_cubemap_buffers[index]); } - MEM_freeN(sl); + GPU_TEXTURE_SAFE_FREE(sl->equirectangular_radiance_gputexture); + GPU_TEXTURE_SAFE_FREE(sl->equirectangular_irradiance_gputexture); + IMB_SAFE_FREE(sl->equirectangular_radiance_buffer); + IMB_SAFE_FREE(sl->equirectangular_irradiance_buffer); + MEM_SAFE_FREE(sl->path_irr_cache); + MEM_SAFE_FREE(sl->path_sh_cache); + MEM_SAFE_FREE(sl->gpu_matcap_3components); + MEM_SAFE_FREE(sl); } -static struct StudioLight *studiolight_create(void) +static struct StudioLight *studiolight_create(int flag) { struct StudioLight *sl = MEM_callocN(sizeof(*sl), __func__); sl->path[0] = 0x00; sl->name[0] = 0x00; - sl->flag = 0; + sl->path_irr_cache = NULL; + sl->path_sh_cache = NULL; + sl->free_function = NULL; + sl->flag = flag; sl->index = BLI_listbase_count(&studiolights); - sl->radiance_icon_id = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_RADIANCE); - sl->irradiance_icon_id = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE); + if (flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) { + sl->icon_id_matcap = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP); + sl->icon_id_matcap_flipped = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED); + } + else { + sl->icon_id_radiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_RADIANCE); + sl->icon_id_irradiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE); + } for (int index = 0 ; index < 6 ; index ++) { sl->radiance_cubemap_buffers[index] = NULL; } + return sl; } @@ -158,7 +188,7 @@ static void studiolight_calculate_radiance_buffer( } } -static void studiolight_load_equierectangular_image(StudioLight *sl) +static void studiolight_load_equirectangular_image(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { ImBuf *ibuf = NULL; @@ -171,29 +201,47 @@ static void studiolight_load_equierectangular_image(StudioLight *sl) sl->flag |= STUDIOLIGHT_EXTERNAL_IMAGE_LOADED; } -static void studiolight_create_equierectangular_radiance_gputexture(StudioLight *sl) +static void studiolight_create_equirectangular_radiance_gputexture(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { char error[256]; BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED); ImBuf *ibuf = sl->equirectangular_radiance_buffer; - sl->equirectangular_radiance_gputexture = GPU_texture_create_2D(ibuf->x, ibuf->y, GPU_RGBA8, ibuf->rect_float, error); - GPUTexture *tex = sl->equirectangular_radiance_gputexture; - GPU_texture_bind(tex, 0); - GPU_texture_filter_mode(tex, true); - GPU_texture_wrap_mode(tex, true); - GPU_texture_unbind(tex); + + if (sl->flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) { + sl->gpu_matcap_3components = MEM_callocN(sizeof(float[3]) * ibuf->x * ibuf->y, __func__); + + float *offset4 = ibuf->rect_float; + float *offset3 = sl->gpu_matcap_3components; + for (int i = 0 ; i < ibuf->x * ibuf->y; i++) { + copy_v3_v3(offset3, offset4); + offset3 += 3; + offset4 += 4; + } + sl->equirectangular_radiance_gputexture = GPU_texture_create_2D( + ibuf->x, ibuf->y, GPU_R11F_G11F_B10F, sl->gpu_matcap_3components, error); + } + else { + sl->equirectangular_radiance_gputexture = GPU_texture_create_2D( + ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error); + GPUTexture *tex = sl->equirectangular_radiance_gputexture; + GPU_texture_bind(tex, 0); + GPU_texture_filter_mode(tex, true); + GPU_texture_wrap_mode(tex, true); + GPU_texture_unbind(tex); + } } sl->flag |= STUDIOLIGHT_EQUIRECTANGULAR_RADIANCE_GPUTEXTURE; } -static void studiolight_create_equierectangular_irradiance_gputexture(StudioLight *sl) +static void studiolight_create_equirectangular_irradiance_gputexture(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { char error[256]; BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED); ImBuf *ibuf = sl->equirectangular_irradiance_buffer; - sl->equirectangular_irradiance_gputexture = GPU_texture_create_2D(ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error); + sl->equirectangular_irradiance_gputexture = GPU_texture_create_2D( + ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error); GPUTexture *tex = sl->equirectangular_irradiance_gputexture; GPU_texture_bind(tex, 0); GPU_texture_filter_mode(tex, true); @@ -283,67 +331,191 @@ BLI_INLINE void studiolight_evaluate_radiance_buffer( } -static void studiolight_calculate_irradiance(StudioLight *sl, float color[3], const float normal[3]) +BLI_INLINE float studiolight_area_element(float x, float y) { - int hits = 0; - copy_v3_fl(color, 0.0f); + return atan2(x * y, sqrtf(x * x + y * y + 1)); +} - /* back */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], normal, color, &hits, 0, 2, 1, 0.5); - /* front */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], normal, color, &hits, 0, 2, 1, -0.5); +BLI_INLINE float studiolight_texel_solid_angle(float x, float y, float halfpix) +{ + float v1x = (x - halfpix) * 2.0f - 1.0f; + float v1y = (y - halfpix) * 2.0f - 1.0f; + float v2x = (x + halfpix) * 2.0f - 1.0f; + float v2y = (y + halfpix) * 2.0f - 1.0f; - /* left */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], normal, color, &hits, 1, 2, 0, 0.5); - /* right */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], normal, color, &hits, 1, 2, 0, -0.5); + return studiolight_area_element(v1x, v1y) - studiolight_area_element(v1x, v2y) - studiolight_area_element(v2x, v1y) + studiolight_area_element(v2x, v2y); +} - /* top */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], normal, color, &hits, 0, 1, 2, 0.5); - /* bottom */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], normal, color, &hits, 0, 1, 2, -0.5); +static void studiolight_calculate_cubemap_vector_weight(float normal[3], float *weight, int face, float x, float y) +{ + copy_v3_fl3(normal, x * 2.0f - 1.0f, y * 2.0f - 1.0f, 1.0f); + const float conversion_matrices[6][3][3] = { + { + {0.0f, 0.0f, 1.0f}, + {0.0f, -1.0f, 0.0f}, + {1.0f, 0.0f, 0.0f}, + }, + { + {0.0f, 0.0f, -1.0f}, + {0.0f, -1.0f, 0.0f}, + {-1.0f, 0.0f, 0.0f}, + }, + { + {1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, -1.0f}, + {0.0f, 1.0f, 0.0f}, + }, + { + {1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 1.0f}, + {0.0f, -1.0f, 0.0f}, + }, + { + {1.0f, 0.0f, 0.0f}, + {0.0f, -1.0f, 0.0f}, + {0.0f, 0.0f, -1.0f}, + }, + { + {-1.0f, 0.0f, 0.0f}, + {0.0f, -1.0f, 0.0f}, + {0.0f, 0.0f, 1.0f}, + } + }; - if (hits) { - mul_v3_fl(color, 3.0 / hits); - } - else { - copy_v3_fl3(color, 1.0, 0.0, 1.0); + mul_m3_v3(conversion_matrices[face], normal); + normalize_v3(normal); + const float halfpix = 1.0f / (2.0f * STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE); + *weight = studiolight_texel_solid_angle(x + halfpix, y + halfpix, halfpix); +} + +static void studiolight_calculate_spherical_harmonics_coefficient(StudioLight *sl, int sh_component) +{ + const float M_4PI = M_PI * 4.0f; + + float weight_accum = 0.0f; + float sh[3] = {0.0f, 0.0f, 0.0f}; + for (int face = 0; face < 6; face++) { + float *color; + color = sl->radiance_cubemap_buffers[face]->rect_float; + for (int y = 0; y < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; y++) { + float yf = y / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; + for (int x = 0; x < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; x++) { + float xf = x / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; + float weight, coef; + float cubevec[3]; + studiolight_calculate_cubemap_vector_weight(cubevec, &weight, face, xf, yf); + + switch (sh_component) { + case 0: + { + coef = 0.2822095f; + break; + } + + case 1: + { + coef = -0.488603f * cubevec[2] * 2.0f / 3.0f; + break; + } + case 2: + { + coef = 0.488603f * cubevec[1] * 2.0f / 3.0f; + break; + } + case 3: + { + coef = -0.488603f * cubevec[0] * 2.0f / 3.0f; + break; + } + + case 4: + { + coef = 1.092548f * cubevec[0] * cubevec[2] * 1.0f / 4.0f; + break; + } + case 5: + { + coef = -1.092548f * cubevec[2] * cubevec[1] * 1.0f / 4.0f; + break; + } + case 6: + { + coef = 0.315392f * (3.0f * cubevec[2] * cubevec[2] - 1.0f) * 1.0f / 4.0f; + break; + } + case 7: + { + coef = 1.092548f * cubevec[0] * cubevec[1] * 1.0f / 4.0f; + break; + } + case 8: + { + coef = 0.546274f * (cubevec[0] * cubevec[0] - cubevec[2] * cubevec[2]) * 1.0f / 4.0f; + break; + } + + default: + { + coef = 0.0f; + } + } + + madd_v3_v3fl(sh, color, coef * weight); + weight_accum += weight; + color += 4; + } + } } + + mul_v3_fl(sh, M_4PI / weight_accum); + copy_v3_v3(sl->spherical_harmonics_coefs[sh_component], sh); } static void studiolight_calculate_diffuse_light(StudioLight *sl) { /* init light to black */ - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_NEG], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_NEG], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_NEG], 0.0f); - if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { - const float normal_x_neg[3] = {-1.0f, 0.0f, 0.0f}; - const float normal_x_pos[3] = { 1.0f, 0.0f, 0.0f}; - const float normal_y_neg[3] = { 0.0f, 1.0f, 0.0f}; - const float normal_y_pos[3] = { 0.0f, -1.0f, 0.0f}; - const float normal_z_neg[3] = { 0.0f, 0.0f, -1.0f}; - const float normal_z_pos[3] = { 0.0f, 0.0f, 1.0f}; - BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_X_POS], normal_x_pos); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_X_NEG], normal_x_neg); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Y_POS], normal_y_pos); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Y_NEG], normal_y_neg); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Z_POS], normal_z_pos); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Z_NEG], normal_z_neg); + for (int comp = 0; comp < STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS; comp ++) { + studiolight_calculate_spherical_harmonics_coefficient(sl, comp); + } + if (sl->flag & STUDIOLIGHT_USER_DEFINED) { + FILE *fp = BLI_fopen(sl->path_sh_cache, "wb"); + if (fp) { + fwrite(sl->spherical_harmonics_coefs, sizeof(sl->spherical_harmonics_coefs), 1, fp); + fclose(fp); + } + } } - sl->flag |= STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED; + sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED; +} + +static float area_element(float x, float y ) +{ + return atan2f(x * y, sqrt(x * x + y * y + 1)); +} + +static float texel_coord_solid_angle(float a_U, float a_V, int a_Size) +{ + //scale up to [-1, 1] range (inclusive), offset by 0.5 to point to texel center. + float u = (2.0f * ((float)a_U + 0.5f) / (float)a_Size ) - 1.0f; + float v = (2.0f * ((float)a_V + 0.5f) / (float)a_Size ) - 1.0f; + + float resolution_inv = 1.0f / a_Size; + + // U and V are the -1..1 texture coordinate on the current face. + // Get projected area for this texel + float x0 = u - resolution_inv; + float y0 = v - resolution_inv; + float x1 = u + resolution_inv; + float y1 = v + resolution_inv; + return area_element(x0, y0) - area_element(x0, y1) - area_element(x1, y0) + area_element(x1, y1); } BLI_INLINE void studiolight_evaluate_specular_radiance_buffer( - ImBuf *radiance_buffer, const float specular, const float normal[3], float color[3], int *hits, + ImBuf *radiance_buffer, const float normal[3], float color[3], int xoffset, int yoffset, int zoffset, float zvalue) { if (radiance_buffer == NULL) { @@ -355,13 +527,14 @@ BLI_INLINE void studiolight_evaluate_specular_radiance_buffer( for (int y = 0; y < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; y ++) { for (int x = 0; x < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; x ++) { // calculate light direction; + float u = (x / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; + float v = (y / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; direction[zoffset] = zvalue; - direction[xoffset] = (x / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; - direction[yoffset] = (y / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; + direction[xoffset] = u; + direction[yoffset] = v; normalize_v3(direction); - angle = pow(fmax(0.0f, dot_v3v3(direction, normal)), specular); + angle = fmax(0.0f, dot_v3v3(direction, normal)) * texel_coord_solid_angle(x, y, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE); madd_v3_v3fl(color, radiance_color, angle); - (*hits) ++; radiance_color += 4; } } @@ -370,42 +543,73 @@ BLI_INLINE void studiolight_evaluate_specular_radiance_buffer( static void studiolight_calculate_specular_irradiance(StudioLight *sl, float color[3], const float normal[3]) { - const float specular = 4.0f; - int hits = 0; copy_v3_fl(color, 0.0f); /* back */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], specular, normal, color, &hits, 0, 2, 1, 0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], normal, color, 0, 2, 1, 0.5); /* front */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], specular, normal, color, &hits, 0, 2, 1, -0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], normal, color, 0, 2, 1, -0.5); /* left */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], specular, normal, color, &hits, 1, 2, 0, 0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], normal, color, 1, 2, 0, 0.5); /* right */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], specular, normal, color, &hits, 1, 2, 0, -0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], normal, color, 1, 2, 0, -0.5); /* top */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], specular, normal, color, &hits, 0, 1, 2, 0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], normal, color, 0, 1, 2, 0.5); /* bottom */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], specular, normal, color, &hits, 0, 1, 2, -0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], normal, color, 0, 1, 2, -0.5); - if (hits) { - mul_v3_fl(color, specular / hits); + mul_v3_fl(color, 1.0 / M_PI); +} + +static bool studiolight_load_irradiance_equirectangular_image(StudioLight *sl) +{ +#ifdef STUDIOLIGHT_LOAD_CACHED_FILES + if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { + ImBuf *ibuf = NULL; + ibuf = IMB_loadiffname(sl->path_irr_cache, 0, NULL); + if (ibuf) { + IMB_float_from_rect(ibuf); + sl->equirectangular_irradiance_buffer = ibuf; + sl->flag |= STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED; + return true; + } } - else { - copy_v3_fl3(color, 1.0, 0.0, 1.0); +#endif + return false; +} + +static bool studiolight_load_spherical_harmonics_coefficients(StudioLight *sl) +{ +#ifdef STUDIOLIGHT_LOAD_CACHED_FILES + if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { + FILE *fp = BLI_fopen(sl->path_sh_cache, "rb"); + if (fp) { + if (fread((void*)(sl->spherical_harmonics_coefs), sizeof(sl->spherical_harmonics_coefs), 1, fp)) + { + sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED; + fclose(fp); + return true; + } + fclose(fp); + } } +#endif + return false; } static void studiolight_calculate_irradiance_equirectangular_image(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { + /* check for cached irr file */ + BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED); float *colbuf = MEM_mallocN(STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_WIDTH * STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT * sizeof(float[4]), __func__); @@ -427,10 +631,10 @@ static void studiolight_calculate_irradiance_equirectangular_image(StudioLight * STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_WIDTH, STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT); MEM_freeN(colbuf); -#if 0 - IMB_saveiff(sl->equirectangular_irradiance_buffer, "/tmp/studiolight_specular_irradiance.png", IB_rectfloat); -#endif + if (sl->flag & STUDIOLIGHT_USER_DEFINED) { + IMB_saveiff(sl->equirectangular_irradiance_buffer, sl->path_irr_cache, IB_rectfloat); + } } sl->flag |= STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED; } @@ -481,11 +685,12 @@ static void studiolight_add_files_from_datafolder(const int folder_id, const cha if ((dir[i].type & S_IFREG)) { const char *filename = dir[i].relname; const char *path = dir[i].path; - if (BLI_testextensie_array(filename, imb_ext_image)) { - sl = studiolight_create(); - sl->flag = STUDIOLIGHT_EXTERNAL_FILE | flag; + if (BLI_path_extension_check_array(filename, imb_ext_image)) { + sl = studiolight_create(STUDIOLIGHT_EXTERNAL_FILE | flag); BLI_strncpy(sl->name, filename, FILE_MAXFILE); BLI_strncpy(sl->path, path, FILE_MAXFILE); + sl->path_irr_cache = BLI_string_joinN(path, ".irr"); + sl->path_sh_cache = BLI_string_joinN(path, ".sh2"); BLI_addtail(&studiolights, sl); } } @@ -493,7 +698,6 @@ static void studiolight_add_files_from_datafolder(const int folder_id, const cha BLI_filelist_free(dir, totfile); dir = NULL; } - } static int studiolight_flag_cmp_order(const StudioLight *sl) @@ -525,187 +729,149 @@ static int studiolight_cmp(const void *a, const void *b) } /* icons */ -static uint *studiolight_radiance_preview(StudioLight *sl, int icon_size) + +/* Takes normalized uvs as parameter (range from 0 to 1). + * inner_edge and outer_edge are distances (from the center) + * in uv space for the alpha mask falloff. */ +static uint alpha_circle_mask(float u, float v, float inner_edge, float outer_edge) +{ + /* Coords from center. */ + float co[2] = {u - 0.5f, v - 0.5f}; + float dist = len_v2(co); + float alpha = 1.0f + (inner_edge - dist) / (outer_edge - inner_edge); + uint mask = (uint)floorf(255.0f * min_ff(max_ff(alpha, 0.0f), 1.0f)); + return mask << 24; +} + +#define STUDIOLIGHT_DIAMETER 0.95f + +static void studiolight_radiance_preview(uint* icon_buffer, StudioLight *sl) { BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED); - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - int icon_center = icon_size / 2; - float sphere_radius = icon_center * 0.9; + float pixel_size = 1.0f / (float)STUDIOLIGHT_ICON_SIZE; int offset = 0; - for (int y = 0; y < icon_size; y++) { - float dy = y - icon_center; - for (int x = 0; x < icon_size; x++) { - float dx = x - icon_center; - /* calculate aliasing */ - float alias = 0; - const float alias_step = 0.333; - for (float ay = dy - 0.5; ay < dy + 0.5; ay += alias_step) { - for (float ax = dx - 0.5; ax < dx + 0.5; ax += alias_step) { - if (sqrt(ay * ay + ax * ax) < sphere_radius) { - alias += alias_step * alias_step; - } - } - } + for (int y = 0; y < STUDIOLIGHT_ICON_SIZE; y++) { + float dy = (y + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dy = dy / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + for (int x = 0; x < STUDIOLIGHT_ICON_SIZE; x++) { + float dx = (x + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dx = dx / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + uint pixelresult = 0x0; - uint alias_i = clamp_i(alias * 256, 0, 255); - if (alias_i != 0) { - /* calculate normal */ - uint alias_mask = alias_i << 24; - float incoming[3]; - copy_v3_fl3(incoming, 0.0, 1.0, 0.0); + uint alphamask = alpha_circle_mask(dx, dy, 0.5f - pixel_size, 0.5f); + if (alphamask != 0) { + float incoming[3] = {0.0f, 0.0f, -1.0f}; float normal[3]; - normal[0] = dx / sphere_radius; - normal[2] = dy / sphere_radius; - normal[1] = -sqrt(-(normal[0] * normal[0]) - (normal[2] * normal[2]) + 1); - normalize_v3(normal); + normal[0] = dx * 2.0f - 1.0f; + normal[1] = dy * 2.0f - 1.0f; + float dist = len_v2(normal); + normal[2] = sqrtf(1.0f - SQUARE(dist)); float direction[3]; reflect_v3_v3v3(direction, incoming, normal); + /* We want to see horizon not poles. */ + SWAP(float, direction[1], direction[2]); + direction[1] = -direction[1]; + float color[4]; studiolight_calculate_radiance(sl->equirectangular_radiance_buffer, color, direction); pixelresult = rgb_to_cpack( linearrgb_to_srgb(color[0]), linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alias_mask; + linearrgb_to_srgb(color[2])) | alphamask; } - rect[offset++] = pixelresult; + icon_buffer[offset++] = pixelresult; } } - return rect; } -static uint *studiolight_matcap_preview(StudioLight *sl, int icon_size) +static void studiolight_matcap_preview(uint* icon_buffer, StudioLight *sl, bool flipped) { BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED); - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - const uint alphamask = 0xff000000; float color[4]; float fx, fy; + float pixel_size = 1.0f / (float)STUDIOLIGHT_ICON_SIZE; int offset = 0; ImBuf *ibuf = sl->equirectangular_radiance_buffer; - for (int y = 0; y < icon_size; y++) { - for (int x = 0; x < icon_size; x++) { - fx = x * ibuf->x / icon_size; - fy = y * ibuf->y / icon_size; - nearest_interpolation_color(ibuf, NULL, color, fx, fy); - rect[offset++] = rgb_to_cpack(linearrgb_to_srgb(color[0]), - linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alphamask; + + for (int y = 0; y < STUDIOLIGHT_ICON_SIZE; y++) { + fy = (y + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + fy = fy / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + for (int x = 0; x < STUDIOLIGHT_ICON_SIZE; x++) { + fx = (x + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + fx = fx / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + if (flipped) { + fx = 1.0f - fx; + } + nearest_interpolation_color(ibuf, NULL, color, fx * ibuf->x, fy * ibuf->y); + + uint alphamask = alpha_circle_mask(fx, fy, 0.5f - pixel_size, 0.5f); + + icon_buffer[offset++] = rgb_to_cpack( + linearrgb_to_srgb(color[0]), + linearrgb_to_srgb(color[1]), + linearrgb_to_srgb(color[2])) | alphamask; } } - return rect; } -static uint *studiolight_irradiance_preview(StudioLight *sl, int icon_size) +static void studiolight_irradiance_preview(uint* icon_buffer, StudioLight *sl) { - if (/*!(sl->flag & STUDIOLIGHT_EXTERNAL_FILE)*/ 1) { + BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED); - BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED); + float pixel_size = 1.0f / (float)STUDIOLIGHT_ICON_SIZE; - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - int icon_center = icon_size / 2; - float sphere_radius = icon_center * 0.9; + int offset = 0; + for (int y = 0; y < STUDIOLIGHT_ICON_SIZE; y++) { + float dy = (y + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dy = dy / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + for (int x = 0; x < STUDIOLIGHT_ICON_SIZE; x++) { + float dx = (x + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dx = dx / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; - int offset = 0; - for (int y = 0; y < icon_size; y++) { - float dy = y - icon_center; - for (int x = 0; x < icon_size; x++) { - float dx = x - icon_center; - /* calculate aliasing */ - float alias = 0; - const float alias_step = 0.333; - for (float ay = dy - 0.5; ay < dy + 0.5; ay += alias_step) { - for (float ax = dx - 0.5; ax < dx + 0.5; ax += alias_step) { - if (sqrt(ay * ay + ax * ax) < sphere_radius) { - alias += alias_step * alias_step; - } - } - } - uint pixelresult = 0x0; - uint alias_i = clamp_i(alias * 256, 0, 255); - if (alias_i != 0) { - /* calculate normal */ - uint alias_mask = alias_i << 24; - float normal[3]; - normal[0] = dx / sphere_radius; - normal[1] = dy / sphere_radius; - normal[2] = sqrt(-(normal[0] * normal[0]) - (normal[1] * normal[1]) + 1); - normalize_v3(normal); - - float color[3]; - mul_v3_v3fl(color, sl->diffuse_light[STUDIOLIGHT_X_POS], clamp_f(normal[0], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_X_NEG], clamp_f(-normal[0], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_Z_POS], clamp_f(normal[1], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_Z_NEG], clamp_f(-normal[1], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_Y_POS], clamp_f(normal[2], 0.0, 1.0)); - - pixelresult = rgb_to_cpack( - linearrgb_to_srgb(color[0]), - linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alias_mask; - } - rect[offset++] = pixelresult; - } - } - return rect; - } - else { - BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED); + uint pixelresult = 0x0; + uint alphamask = alpha_circle_mask(dx, dy, 0.5f - pixel_size, 0.5f); + if (alphamask != 0) { + /* calculate normal */ + float normal[3]; + normal[0] = dx * 2.0f - 1.0f; + normal[1] = -(dy * 2.0f - 1.0f); + float dist = len_v2(normal); + normal[2] = -sqrtf(1.0f - SQUARE(dist)); + SWAP(float, normal[1], normal[2]); + + float color[3] = {0.0f, 0.0f, 0.0f}; + /* Spherical Harmonics L0 */ + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[0], 0.282095f); + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 0 + /* Spherical Harmonics L1 */ + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[1], -0.488603f * normal[2]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[2], 0.488603f * normal[1]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[3], -0.488603f * normal[0]); +#endif - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - int icon_center = icon_size / 2; - float sphere_radius = icon_center * 0.9; - - int offset = 0; - for (int y = 0; y < icon_size; y++) { - float dy = y - icon_center; - for (int x = 0; x < icon_size; x++) { - float dx = x - icon_center; - /* calculate aliasing */ - float alias = 0; - const float alias_step = 0.333; - for (float ay = dy - 0.5; ay < dy + 0.5; ay += alias_step) { - for (float ax = dx - 0.5; ax < dx + 0.5; ax += alias_step) { - if (sqrt(ay * ay + ax * ax) < sphere_radius) { - alias += alias_step * alias_step; - } - } - } - uint pixelresult = 0x0; - uint alias_i = clamp_i(alias * 256, 0, 255); - if (alias_i != 0) { - /* calculate normal */ - uint alias_mask = alias_i << 24; - float incoming[3]; - copy_v3_fl3(incoming, 0.0, 1.0, 0.0); - - float normal[3]; - normal[0] = dx / sphere_radius; - normal[2] = dy / sphere_radius; - normal[1] = -sqrt(-(normal[0] * normal[0]) - (normal[2] * normal[2]) + 1); - normalize_v3(normal); - - float direction[3]; - reflect_v3_v3v3(direction, incoming, normal); - - float color[4]; - studiolight_calculate_radiance(sl->equirectangular_irradiance_buffer, color, direction); - - pixelresult = rgb_to_cpack( - linearrgb_to_srgb(color[0]), - linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alias_mask; - } - rect[offset++] = pixelresult; +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 1 + /* Spherical Harmonics L1 */ + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[4], 1.092548f * normal[0] * normal[2]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[5], -1.092548f * normal[2] * normal[1]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[6], 0.315392f * (3.0f * normal[1] * normal[1] - 1.0f)); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[7], -1.092548 * normal[0] * normal[1]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[8], 0.546274 * (normal[0] * normal[0] - normal[2] * normal[2])); +#endif + pixelresult = rgb_to_cpack( + linearrgb_to_srgb(color[0]), + linearrgb_to_srgb(color[1]), + linearrgb_to_srgb(color[2])) | alphamask; } + icon_buffer[offset++] = pixelresult; } - return rect; } } @@ -717,15 +883,24 @@ void BKE_studiolight_init(void) /* order studio lights by name */ /* Also reserve icon space for it. */ /* Add default studio light */ - sl = studiolight_create(); - BLI_strncpy(sl->name, "INTERNAL_01", FILE_MAXFILE); - sl->flag = STUDIOLIGHT_INTERNAL | STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED | STUDIOLIGHT_ORIENTATION_CAMERA; - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_NEG], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_POS], 0.8f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_NEG], 0.05f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_POS], 0.2f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_NEG], 0.1f); + sl = studiolight_create(STUDIOLIGHT_INTERNAL | STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED | STUDIOLIGHT_ORIENTATION_CAMERA); + BLI_strncpy(sl->name, "Default", FILE_MAXFILE); + + + copy_v3_fl3(sl->spherical_harmonics_coefs[0], 1.03271556f, 1.07163882f, 1.11193657f); +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 0 + copy_v3_fl3(sl->spherical_harmonics_coefs[1], -0.00480952f, 0.05290511f, 0.16394117f); + copy_v3_fl3(sl->spherical_harmonics_coefs[2], -0.29686999f, -0.27378261f, -0.24797194f); + copy_v3_fl3(sl->spherical_harmonics_coefs[3], 0.47932500f, 0.48242140f, 0.47190312f); +#endif +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 1 + copy_v3_fl3(sl->spherical_harmonics_coefs[4], -0.00576984f, 0.00504886f, 0.01640534f); + copy_v3_fl3(sl->spherical_harmonics_coefs[5], 0.15500379f, 0.15415503f, 0.16244425f); + copy_v3_fl3(sl->spherical_harmonics_coefs[6], -0.02483751f, -0.02245096f, -0.00536885f); + copy_v3_fl3(sl->spherical_harmonics_coefs[7], 0.11155496f, 0.11005443f, 0.10839636f); + copy_v3_fl3(sl->spherical_harmonics_coefs[8], 0.01363425f, 0.01278363f, -0.00159006f); +#endif + BLI_addtail(&studiolights, sl); studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_CAMERA_FOLDER, STUDIOLIGHT_ORIENTATION_CAMERA); @@ -790,21 +965,34 @@ struct ListBase *BKE_studiolight_listbase(void) return &studiolights; } -uint *BKE_studiolight_preview(StudioLight *sl, int icon_size, int icon_id_type) +void BKE_studiolight_preview(uint* icon_buffer, StudioLight *sl, int icon_id_type) { - if (icon_id_type == STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE) { - if (sl->flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) { - return studiolight_matcap_preview(sl, icon_size); + switch (icon_id_type) { + case STUDIOLIGHT_ICON_ID_TYPE_RADIANCE: + default: + { + studiolight_radiance_preview(icon_buffer, sl); + break; } - else { - return studiolight_irradiance_preview(sl, icon_size); + case STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE: + { + studiolight_irradiance_preview(icon_buffer, sl); + break; + } + case STUDIOLIGHT_ICON_ID_TYPE_MATCAP: + { + studiolight_matcap_preview(icon_buffer, sl, false); + break; + } + case STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED: + { + studiolight_matcap_preview(icon_buffer, sl, true); + break; } - } - else { - return studiolight_radiance_preview(sl, icon_size); } } +/* Ensure state of Studiolights */ void BKE_studiolight_ensure_flag(StudioLight *sl, int flag) { if ((sl->flag & flag) == flag) { @@ -812,25 +1000,29 @@ void BKE_studiolight_ensure_flag(StudioLight *sl, int flag) } if ((flag & STUDIOLIGHT_EXTERNAL_IMAGE_LOADED)) { - studiolight_load_equierectangular_image(sl); + studiolight_load_equirectangular_image(sl); } if ((flag & STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED)) { studiolight_calculate_radiance_cubemap_buffers(sl); } - if ((flag & STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED)) { - studiolight_calculate_diffuse_light(sl); + if ((flag & STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED)) { + if (!studiolight_load_spherical_harmonics_coefficients(sl)) { + studiolight_calculate_diffuse_light(sl); + } } if ((flag & STUDIOLIGHT_EQUIRECTANGULAR_RADIANCE_GPUTEXTURE)) { - studiolight_create_equierectangular_radiance_gputexture(sl); + studiolight_create_equirectangular_radiance_gputexture(sl); } if ((flag & STUDIOLIGHT_LIGHT_DIRECTION_CALCULATED)) { studiolight_calculate_light_direction(sl); } if ((flag & STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_GPUTEXTURE)) { - studiolight_create_equierectangular_irradiance_gputexture(sl); + studiolight_create_equirectangular_irradiance_gputexture(sl); } if ((flag & STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED)) { - studiolight_calculate_irradiance_equirectangular_image(sl); + if (!studiolight_load_irradiance_equirectangular_image(sl)) { + studiolight_calculate_irradiance_equirectangular_image(sl); + } } } @@ -839,3 +1031,26 @@ void BKE_studiolight_refresh(void) BKE_studiolight_free(); BKE_studiolight_init(); } + +void BKE_studiolight_set_free_function(StudioLight *sl, StudioLightFreeFunction *free_function, void *data) +{ + sl->free_function = free_function; + sl->free_function_data = data; +} + +void BKE_studiolight_unset_icon_id(StudioLight *sl, int icon_id) +{ + BLI_assert(sl != NULL); + if (sl->icon_id_radiance == icon_id) { + sl->icon_id_radiance = 0; + } + if (sl->icon_id_irradiance == icon_id) { + sl->icon_id_irradiance = 0; + } + if (sl->icon_id_matcap == icon_id) { + sl->icon_id_matcap = 0; + } + if (sl->icon_id_matcap_flipped == icon_id) { + sl->icon_id_matcap_flipped = 0; + } +} diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index d735944c93d..e4f08703dfc 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -197,7 +197,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 @@ -315,7 +315,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, limit, false, true); if (!vmap) return 0; - + ccgSubSurf_initFullSync(ss); /* create vertices */ @@ -613,12 +613,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; } @@ -633,7 +633,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); @@ -647,7 +647,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; @@ -669,7 +669,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); } @@ -1100,7 +1100,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); @@ -1214,7 +1214,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; @@ -1223,14 +1223,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)) @@ -1254,11 +1254,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) @@ -1266,11 +1266,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]; @@ -1309,7 +1309,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); @@ -1626,7 +1626,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)) { @@ -1657,7 +1657,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)); @@ -1824,7 +1824,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); @@ -2117,7 +2117,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*/ @@ -2183,7 +2183,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; } @@ -2191,7 +2191,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; } @@ -2968,7 +2968,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); @@ -3061,9 +3061,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 b74143b5c07..043fc813b95 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 226ab33e45e..f876592c0a8 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -229,15 +229,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; @@ -270,18 +270,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); @@ -292,7 +292,7 @@ int txt_extended_ascii_as_utf8(char **str) MEM_freeN(*str); *str = newstr; } - + return added; } @@ -389,7 +389,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; @@ -424,7 +424,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; @@ -454,9 +454,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; @@ -605,7 +605,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; @@ -616,16 +616,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; } @@ -636,29 +636,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; @@ -796,7 +796,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); @@ -888,7 +888,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; } @@ -924,7 +924,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; } @@ -932,7 +932,7 @@ void txt_move_right(Text *text, const bool sel) (*charp) += BLI_str_utf8_size((*linep)->line + *charp); } } - + if (!sel) txt_pop_sel(text); } @@ -948,7 +948,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); } @@ -960,11 +960,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); } @@ -976,7 +976,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); @@ -1041,7 +1041,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; @@ -1050,7 +1050,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); } @@ -1062,7 +1062,7 @@ static void txt_curs_swap(Text *text) { TextLine *tmpl; int tmpc; - + tmpl = text->curl; text->curl = text->sell; text->sell = tmpl; @@ -1079,7 +1079,7 @@ static void txt_pop_first(Text *text) { txt_curs_swap(text); } - + txt_pop_sel(text); } @@ -1090,7 +1090,7 @@ static void txt_pop_last(Text *text) { txt_curs_swap(text); } - + txt_pop_sel(text); } @@ -1104,7 +1104,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) || @@ -1136,7 +1136,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) { @@ -1152,15 +1152,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; } @@ -1169,7 +1169,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; } @@ -1190,7 +1190,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; @@ -1213,7 +1213,7 @@ char *txt_to_buf(Text *text) linef = text->lines.first; charf = 0; - + linel = text->lines.last; charl = linel->len; @@ -1221,7 +1221,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; } @@ -1229,37 +1229,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; } @@ -1269,11 +1269,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) { @@ -1290,7 +1290,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); @@ -1311,10 +1311,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; @@ -1334,7 +1334,7 @@ char *txt_sel_to_buf(Text *text) else { linef = text->curl; linel = text->sell; - + charf = text->curc; charl = text->selc; } @@ -1343,39 +1343,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; } @@ -1393,11 +1393,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); } @@ -1407,7 +1407,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++; @@ -1492,16 +1492,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 "; } @@ -1559,7 +1559,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++; @@ -1600,14 +1600,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++; @@ -1624,7 +1624,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++; @@ -1634,17 +1634,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)++; @@ -1652,7 +1652,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)++; @@ -1736,7 +1736,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; @@ -1770,7 +1770,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); } @@ -1869,10 +1869,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'; @@ -1896,7 +1896,7 @@ static unsigned int txt_undo_read_unicode(const char *undo_buf, int *undo_pos, s unicode = 0; break; } - + return unicode; } @@ -1945,10 +1945,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)++; @@ -1972,7 +1972,7 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s unicode = 0; break; } - + return unicode; } @@ -1986,7 +1986,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) unsigned short curc, selc; unsigned short charp; char *buf; - + if (utxt->pos < 0) { return; } @@ -1994,21 +1994,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; @@ -2018,12 +2018,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--; @@ -2069,7 +2069,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); @@ -2078,7 +2078,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) txt_move_to(text, selln, selc, 1); utxt->pos--; - + break; } case UNDO_IBLOCK: @@ -2086,7 +2086,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++) { @@ -2096,29 +2096,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; } @@ -2131,7 +2131,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); } @@ -2147,7 +2147,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: @@ -2196,10 +2196,10 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) default: //XXX error("Undo buffer error - resetting"); utxt->pos = -1; - + break; } - + undoing = 0; } @@ -2212,15 +2212,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) { @@ -2229,12 +2229,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); @@ -2253,7 +2253,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); @@ -2270,7 +2270,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); @@ -2287,12 +2287,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; @@ -2312,7 +2312,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); @@ -2320,7 +2320,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) utxt->pos += 4; break; - + case UNDO_INDENT: case UNDO_COMMENT: case UNDO_UNCOMMENT: @@ -2389,15 +2389,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) @@ -2410,13 +2410,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); @@ -2424,7 +2424,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; @@ -2433,14 +2433,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); } @@ -2449,7 +2449,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); @@ -2462,21 +2462,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); } @@ -2484,16 +2484,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); } } @@ -2520,7 +2520,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; @@ -2530,7 +2530,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); } @@ -2544,9 +2544,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); @@ -2554,10 +2554,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); } @@ -2565,7 +2565,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, @@ -2579,7 +2579,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); } @@ -2616,7 +2616,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); @@ -2624,23 +2624,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); @@ -2675,10 +2675,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); @@ -2690,11 +2690,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); @@ -2749,7 +2749,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; @@ -2766,7 +2766,7 @@ static void txt_select_prefix(Text *text, const char *add) text->curl = text->curl->prev; num--; } - + /* caller must handle undo */ } @@ -2816,10 +2816,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); @@ -2830,7 +2830,7 @@ static void txt_select_unprefix( num++; } - + } if (unindented_first) @@ -2898,7 +2898,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; } @@ -2919,13 +2919,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) { @@ -2937,7 +2937,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); } @@ -2967,7 +2967,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 2bf2fa7807b..ad60e81fe19 100644 --- a/source/blender/blenkernel/intern/texture.c +++ b/source/blender/blenkernel/intern/texture.c @@ -76,9 +76,9 @@ TexMapping *BKE_texture_mapping_add(int type) { TexMapping *texmap = MEM_callocN(sizeof(TexMapping), "TexMapping"); - + BKE_texture_mapping_default(texmap, type); - + return texmap; } @@ -132,7 +132,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 */ @@ -173,9 +173,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; } @@ -211,7 +211,7 @@ void BKE_texture_free(Tex *tex) } MEM_SAFE_FREE(tex->coba); - + BKE_icon_id_delete((ID *)tex); BKE_previewimg_free(&tex->preview); } @@ -271,7 +271,7 @@ void BKE_texture_default(Tex *tex) tex->iuser.ok = 1; tex->iuser.frames = 100; tex->iuser.sfra = 1; - + tex->preview = NULL; } @@ -287,9 +287,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; } @@ -369,11 +369,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; } @@ -388,7 +388,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; @@ -474,19 +474,19 @@ 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); - + texn->preview = NULL; - + if (tex->nodetree) { texn->nodetree = ntreeLocalize(tex->nodetree); } - + return texn; } @@ -590,12 +590,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; } @@ -612,7 +612,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); } @@ -657,7 +657,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)) { diff --git a/source/blender/blenkernel/intern/tracking_solver.c b/source/blender/blenkernel/intern/tracking_solver.c index c21883c6eb8..a5d35449229 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 a05e79aae1f..173b459f442 100644 --- a/source/blender/blenkernel/intern/undo_system.c +++ b/source/blender/blenkernel/intern/undo_system.c @@ -235,6 +235,23 @@ void BKE_undosys_stack_clear(UndoStack *ustack) ustack->step_active = NULL; } +void BKE_undosys_stack_clear_active(UndoStack *ustack) +{ + /* Remove active and all following undos. */ + UndoStep *us = ustack->step_active; + + if (us) { + ustack->step_active = us->prev; + bool is_not_empty = ustack->step_active != NULL; + + while (ustack->steps.last != ustack->step_active) { + UndoStep *us_iter = ustack->steps.last; + undosys_step_free_and_unlink(ustack, us_iter); + undosys_stack_validate(ustack, is_not_empty); + } + } +} + static bool undosys_stack_push_main(UndoStack *ustack, const char *name, struct Main *bmain) { UNDO_NESTED_ASSERT(false); diff --git a/source/blender/blenkernel/intern/workspace.c b/source/blender/blenkernel/intern/workspace.c index b71dfaf5aea..99fb6b14a35 100644 --- a/source/blender/blenkernel/intern/workspace.c +++ b/source/blender/blenkernel/intern/workspace.c @@ -227,13 +227,14 @@ void BKE_workspace_instance_hook_free(const Main *bmain, WorkSpaceInstanceHook * * Add a new layout to \a workspace for \a screen. */ WorkSpaceLayout *BKE_workspace_layout_add( + Main *bmain, WorkSpace *workspace, bScreen *screen, const char *name) { WorkSpaceLayout *layout = MEM_callocN(sizeof(*layout), __func__); - BLI_assert(!workspaces_is_screen_used(G.main, screen)); + BLI_assert(!workspaces_is_screen_used(bmain, screen)); layout->screen = screen; workspace_layout_name_set(workspace, layout, name); BLI_addtail(&workspace->layouts, layout); diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c index 1b06e7ed851..69096ad7a08 100644 --- a/source/blender/blenkernel/intern/world.c +++ b/source/blender/blenkernel/intern/world.c @@ -70,7 +70,7 @@ void BKE_world_free(World *wrld) } GPU_material_free(&wrld->gpumaterial); - + BKE_icon_id_delete((struct ID *)wrld); BKE_previewimg_free(&wrld->preview); } @@ -85,7 +85,7 @@ void BKE_world_init(World *wrld) wrld->aodist = 10.0f; wrld->aoenergy = 1.0f; - + wrld->preview = NULL; wrld->miststa = 5.0f; wrld->mistdist = 25.0f; @@ -145,16 +145,16 @@ World *BKE_world_localize(World *wrld) * ... Once f*** nodes are fully converted to that too :( */ World *wrldn; - + wrldn = BKE_libblock_copy_nolib(&wrld->id, false); - + 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 33ac312425b..994592ec307 100644 --- a/source/blender/blenkernel/intern/writeavi.c +++ b/source/blender/blenkernel/intern/writeavi.c @@ -150,7 +150,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"); } @@ -189,7 +189,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); @@ -199,7 +199,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; } @@ -211,7 +211,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; @@ -222,7 +222,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]; @@ -234,7 +234,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 17c665f3bcd..394f4cc1122 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; @@ -511,7 +511,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; @@ -540,13 +540,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; @@ -563,7 +563,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; @@ -617,11 +617,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) { @@ -643,7 +643,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) { @@ -681,7 +681,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int PRINT("Using global header\n"); c->flags |= CODEC_FLAG_GLOBAL_HEADER; } - + /* xasp & yasp got float lately... */ st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255); @@ -879,7 +879,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"); @@ -967,7 +967,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) { @@ -975,7 +975,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); @@ -1061,14 +1061,14 @@ fail: 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); @@ -1294,11 +1294,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) { @@ -1360,7 +1360,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; } @@ -1379,17 +1379,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); @@ -1449,7 +1449,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_)); @@ -1466,7 +1466,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); @@ -1487,7 +1487,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/nla_private.h b/source/blender/blenkernel/nla_private.h index c441f00ceaa..87f4e37e86d 100644 --- a/source/blender/blenkernel/nla_private.h +++ b/source/blender/blenkernel/nla_private.h @@ -40,13 +40,13 @@ struct Depsgraph; /* 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; @@ -56,7 +56,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, @@ -67,11 +67,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_callbacks.h b/source/blender/blenlib/BLI_callbacks.h index adc7bf5af6b..c913510bda3 100644 --- a/source/blender/blenlib/BLI_callbacks.h +++ b/source/blender/blenlib/BLI_callbacks.h @@ -62,7 +62,7 @@ typedef struct bCallbackFuncStore { } bCallbackFuncStore; -void BLI_callback_exec(struct Main *main, struct ID *self, eCbEvent evt); +void BLI_callback_exec(struct Main *bmain, struct ID *self, eCbEvent evt); void BLI_callback_add(bCallbackFuncStore *funcstore, eCbEvent evt); void BLI_callback_global_init(void); diff --git a/source/blender/blenlib/BLI_dlrbTree.h b/source/blender/blenlib/BLI_dlrbTree.h index 05b67e358a4..6e47fd4ddb3 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: <DLRBT_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: <DLRBT_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_dynstr.h b/source/blender/blenlib/BLI_dynstr.h index b26accc7f78..796dd225404 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 41789201265..83b519fc750 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_heap.h b/source/blender/blenlib/BLI_heap.h index 19e162d777f..771b9dabe4d 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_kdtree.h b/source/blender/blenlib/BLI_kdtree.h index 18908f8c551..689c07e05db 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 7eec54e67e1..214915163c7 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 dd6d737f111..fad0b4e7552 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__ diff --git a/source/blender/blenlib/BLI_math_geom.h b/source/blender/blenlib/BLI_math_geom.h index f12ee2b3c69..630a508727c 100644 --- a/source/blender/blenlib/BLI_math_geom.h +++ b/source/blender/blenlib/BLI_math_geom.h @@ -422,7 +422,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); diff --git a/source/blender/blenlib/BLI_math_matrix.h b/source/blender/blenlib/BLI_math_matrix.h index a6f8f9a54e9..b38e26ecb2f 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 ***** diff --git a/source/blender/blenlib/BLI_mempool.h b/source/blender/blenlib/BLI_mempool.h index 45efb8d7ef1..dfa6fdd2625 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 b59e7f99d59..b4329bf81ac 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 69b23b2473f..612151b7ea2 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__ @@ -64,16 +64,6 @@ void BLI_rng_shuffle_array(struct RNG *rng, void *data, unsigned int elem /** Note that skipping is as slow as generating n numbers! */ void BLI_rng_skip(struct RNG *rng, int n) ATTR_NONNULL(1); -/** Seed for the random number generator, using noise.c hash[] */ -void BLI_srandom(unsigned int seed); - -/** Return a pseudo-random number N where 0<=N<(2^31) */ -int BLI_rand(void) ATTR_WARN_UNUSED_RESULT; - -/** Return a pseudo-random number N where 0.0f<=N<1.0f */ -float BLI_frand(void) ATTR_WARN_UNUSED_RESULT; -void BLI_frand_unit_v3(float v[3]); - /** Return a pseudo-random (hash) float from an integer value */ float BLI_hash_frand(unsigned int seed) ATTR_WARN_UNUSED_RESULT; diff --git a/source/blender/blenlib/BLI_smallhash.h b/source/blender/blenlib/BLI_smallhash.h index 495fc94a53c..d1bcf4e9dc6 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 80ee50621ca..ccafa1cf327 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_threads.h b/source/blender/blenlib/BLI_threads.h index 96bb739f683..87a1467e573 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); diff --git a/source/blender/blenlib/BLI_utildefines.h b/source/blender/blenlib/BLI_utildefines.h index 9c90b86832a..36281ee0fcc 100644 --- a/source/blender/blenlib/BLI_utildefines.h +++ b/source/blender/blenlib/BLI_utildefines.h @@ -552,13 +552,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_winstuff.h b/source/blender/blenlib/BLI_winstuff.h index 6fbbed01400..8cca19ea0bb 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__ diff --git a/source/blender/blenlib/CMakeLists.txt b/source/blender/blenlib/CMakeLists.txt index 31abf258d0f..61f53f938e2 100644 --- a/source/blender/blenlib/CMakeLists.txt +++ b/source/blender/blenlib/CMakeLists.txt @@ -129,6 +129,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 @@ -164,6 +165,7 @@ set(SRC 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 6e347339980..088b275738e 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 d31367c5e87..1f4c59ac2fb 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 bce6614beb5..d3fc8ae0ed5 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_kdopbvh.c b/source/blender/blenlib/intern/BLI_kdopbvh.c index c6daae97688..ddfb75fc2ce 100644 --- a/source/blender/blenlib/intern/BLI_kdopbvh.c +++ b/source/blender/blenlib/intern/BLI_kdopbvh.c @@ -470,10 +470,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]); @@ -494,7 +494,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); @@ -574,7 +574,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++) { @@ -645,7 +645,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) { @@ -662,7 +662,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) { @@ -679,7 +679,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); } @@ -1022,7 +1022,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) || @@ -1036,7 +1036,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; @@ -1122,18 +1122,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 */ @@ -1194,7 +1194,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])) { @@ -1335,7 +1335,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) && @@ -1347,7 +1347,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; @@ -1379,12 +1379,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); @@ -1417,7 +1417,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 @@ -1562,7 +1562,7 @@ static void bfs_find_nearest(BVHNearestData *data, BVHNode *node) push_heaps++; } } - + if (heap_size == 0) break; current = heap[0]; @@ -1659,7 +1659,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; } } @@ -1675,7 +1675,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]; @@ -1787,7 +1787,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 { @@ -1881,23 +1881,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 800e245d6bd..700000b7717 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; diff --git a/source/blender/blenlib/intern/BLI_linklist.c b/source/blender/blenlib/intern/BLI_linklist.c index 051792f7f7c..80d5cbc8cd0 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 31b4b7cd4a5..6ef77890e95 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 dea39631389..0b83423921f 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/callbacks.c b/source/blender/blenlib/intern/callbacks.c index 191be49263c..766e3f38f00 100644 --- a/source/blender/blenlib/intern/callbacks.c +++ b/source/blender/blenlib/intern/callbacks.c @@ -32,13 +32,13 @@ static ListBase callback_slots[BLI_CB_EVT_TOT] = {{NULL}}; -void BLI_callback_exec(struct Main *main, struct ID *self, eCbEvent evt) +void BLI_callback_exec(struct Main *bmain, struct ID *self, eCbEvent evt) { ListBase *lb = &callback_slots[evt]; bCallbackFuncStore *funcstore; for (funcstore = lb->first; funcstore; funcstore = funcstore->next) { - funcstore->func(main, self, funcstore->arg); + funcstore->func(bmain, self, funcstore->arg); } } diff --git a/source/blender/blenlib/intern/dynlib.c b/source/blender/blenlib/intern/dynlib.c index 51b91fb360f..36e849cda40 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); diff --git a/source/blender/blenlib/intern/fileops.c b/source/blender/blenlib/intern/fileops.c index ad53457f863..0b57a727452 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/freetypefont.c b/source/blender/blenlib/intern/freetypefont.c index e990f0b663c..c7604b3cd6d 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/gsqueue.c b/source/blender/blenlib/intern/gsqueue.c index 5c8c43ab92a..29b882d0e99 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/jitter_2d.c b/source/blender/blenlib/intern/jitter_2d.c index 2632e8bc234..f1ee85f47c2 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 5918b4d3cf9..568448327bd 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 f8af6c20ae5..b89647d5b9b 100644 --- a/source/blender/blenlib/intern/math_geom.c +++ b/source/blender/blenlib/intern/math_geom.c @@ -3953,11 +3953,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]); @@ -5246,7 +5246,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/noise.c b/source/blender/blenlib/intern/noise.c index 83012694ac0..075ae2f5357 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 a3651de73a2..6272f2109d2 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 700524965f0..9e56ce6b2cf 100644 --- a/source/blender/blenlib/intern/rand.c +++ b/source/blender/blenlib/intern/rand.c @@ -265,29 +265,6 @@ void BLI_rng_skip(RNG *rng, int n) /***/ -/* initialize with some non-zero seed */ -static RNG theBLI_rng = {611330372042337130}; - -void BLI_srandom(unsigned int seed) -{ - BLI_rng_srandom(&theBLI_rng, seed); -} - -int BLI_rand(void) -{ - return BLI_rng_get_int(&theBLI_rng); -} - -float BLI_frand(void) -{ - return BLI_rng_get_float(&theBLI_rng); -} - -void BLI_frand_unit_v3(float v[3]) -{ - BLI_rng_get_float_unit_v3(&theBLI_rng, v); -} - float BLI_hash_frand(unsigned int seed) { RNG rng; @@ -312,7 +289,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 +315,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 4406a45d4fc..f1564d132e3 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 1b3af142b33..c1696a912ba 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 197169ab381..de24fc4d1f5 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 dd79f3f5e5e..d1af0551062 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; diff --git a/source/blender/blenlib/intern/time.c b/source/blender/blenlib/intern/time.c index 3cf3221bd08..a2665f96b29 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 <windows.h> -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 <unistd.h> #include <sys/time.h> -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 093333769d6..37b7ca37ba5 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 d6834428376..bf0b28b5cc2 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 bde0734a740..4e2a6976ce4 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 8b5c64f4ecd..327812f78d5 100644 --- a/source/blender/blenloader/BLO_readfile.h +++ b/source/blender/blenloader/BLO_readfile.h @@ -164,7 +164,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/CMakeLists.txt b/source/blender/blenloader/CMakeLists.txt index f42336a2c7a..2c6f6f3edfb 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 @@ -82,10 +82,6 @@ if(WITH_INTERNATIONAL) add_definitions(-DWITH_INTERNATIONAL) endif() -if(WITH_CLAY_ENGINE) - add_definitions(-DWITH_CLAY_ENGINE) -endif() - if(WITH_CODEC_FFMPEG) add_definitions(-DWITH_FFMPEG) endif() diff --git a/source/blender/blenloader/intern/readblenentry.c b/source/blender/blenloader/intern/readblenentry.c index 8d90a11f5d9..4ccdbd9e8e1 100644 --- a/source/blender/blenloader/intern/readblenentry.c +++ b/source/blender/blenloader/intern/readblenentry.c @@ -68,10 +68,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. * @@ -104,7 +104,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; @@ -117,7 +117,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; @@ -127,7 +127,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))); } } @@ -225,7 +225,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); @@ -255,7 +255,7 @@ LinkNode *BLO_blendhandle_get_previews(BlendHandle *bh, int ofblocktype, int *to new_prv = NULL; prv = NULL; } - + } *tot_prev = tot; @@ -274,7 +274,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; @@ -289,11 +289,11 @@ LinkNode *BLO_blendhandle_get_linkable_groups(BlendHandle *bh) } } } - + BLI_gset_free(gathered, NULL); - + return names; -} +} /** * Close and free a blendhandle. The handle becomes invalid after this call. @@ -303,7 +303,7 @@ LinkNode *BLO_blendhandle_get_linkable_groups(BlendHandle *bh) void BLO_blendhandle_close(BlendHandle *bh) { FileData *fd = (FileData *) bh; - + blo_freefiledata(fd); } @@ -323,7 +323,7 @@ BlendFileData *BLO_read_from_file( { BlendFileData *bfd = NULL; FileData *fd; - + fd = blo_openblenderfile(filepath, reports); if (fd) { fd->reports = reports; @@ -350,7 +350,7 @@ BlendFileData *BLO_read_from_memory( { BlendFileData *bfd = NULL; FileData *fd; - + fd = blo_openblendermemory(mem, memsize, reports); if (fd) { fd->reports = reports; @@ -375,13 +375,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); @@ -389,26 +389,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); @@ -467,7 +467,7 @@ void BLO_blendfiledata_free(BlendFileData *bfd) if (bfd->main) { BKE_main_free(bfd->main); } - + if (bfd->user) { MEM_freeN(bfd->user); } diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c index 6aeb3e0e0cd..3de14260ed9 100644 --- a/source/blender/blenloader/intern/readfile.c +++ b/source/blender/blenloader/intern/readfile.c @@ -274,17 +274,17 @@ static void expand_scene_collection(FileData *fd, Main *mainvar, SceneCollection 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); } @@ -296,27 +296,27 @@ static const char *library_parent_filepath(Library *lib) return lib->parent ? lib->parent->filepath : "<direct>"; } -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); @@ -327,9 +327,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); @@ -399,19 +399,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]; @@ -421,7 +421,7 @@ static void *oldnewmap_lookup_and_inc(OldNewMap *onm, const void *addr, bool inc entry->nr++; return entry->newp; } - + return NULL; } @@ -460,7 +460,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; @@ -473,13 +473,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); @@ -495,7 +495,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--) { @@ -506,7 +506,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); @@ -542,10 +542,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__); @@ -560,7 +560,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--) { @@ -577,7 +577,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"); @@ -642,37 +642,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; } @@ -684,7 +684,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); @@ -696,7 +696,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); @@ -719,12 +719,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; } @@ -733,10 +733,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; @@ -748,7 +748,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 @@ -756,7 +756,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. @@ -767,12 +767,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); } @@ -790,12 +790,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)); } @@ -810,10 +810,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 !) */ @@ -822,9 +822,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); @@ -844,7 +844,7 @@ static BHeadN *get_bhead(FileData *fd) if (new_bhead) { BLI_addtail(&fd->listbase, new_bhead); } - + return(new_bhead); } @@ -852,7 +852,7 @@ BHead *blo_firstbhead(FileData *fd) { BHeadN *new_bhead; BHead *bhead = NULL; - + /* Rewind the file * Read in a new block if necessary */ @@ -860,11 +860,11 @@ BHead *blo_firstbhead(FileData *fd) if (new_bhead == NULL) { new_bhead = get_bhead(fd); } - + if (new_bhead) { bhead = &new_bhead->bhead; } - + return(bhead); } @@ -872,7 +872,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; } @@ -880,25 +880,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); } @@ -957,11 +957,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); @@ -973,12 +973,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; } @@ -1027,28 +1027,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); } @@ -1056,10 +1056,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); } @@ -1069,13 +1069,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; @@ -1084,48 +1084,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; @@ -1134,14 +1134,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) { @@ -1157,7 +1157,7 @@ static FileData *blo_decode_and_check(FileData *fd, ReportList *reports) blo_freefiledata(fd); fd = NULL; } - + return fd; } @@ -1168,7 +1168,7 @@ FileData *blo_openblenderfile(const char *filepath, ReportList *reports) gzFile gzfile; errno = 0; gzfile = BLI_gzopen(filepath, "rb"); - + if (gzfile == (gzFile)Z_NULL) { BKE_reportf(reports, RPT_WARNING, "Unable to open '%s': %s", filepath, errno ? strerror(errno) : TIP_("unknown error reading file")); @@ -1178,10 +1178,10 @@ FileData *blo_openblenderfile(const char *filepath, ReportList *reports) FileData *fd = filedata_new(); fd->gzfiledes = gzfile; fd->read = fd_read_gzip_from_file; - + /* needed for library_append and read_libraries */ BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase)); - + return blo_decode_and_check(fd, reports); } } @@ -1244,12 +1244,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; } @@ -1262,10 +1262,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)) { @@ -1275,7 +1275,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; return blo_decode_and_check(fd, reports); @@ -1291,10 +1291,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); } } @@ -1306,22 +1306,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); @@ -1329,7 +1329,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) @@ -1346,7 +1346,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); @@ -1368,7 +1368,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); } /** @@ -1543,7 +1543,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); } @@ -1561,9 +1561,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; } @@ -1584,13 +1584,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 ); @@ -1601,15 +1601,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); } @@ -1623,7 +1623,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; @@ -1635,9 +1635,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); @@ -1646,9 +1646,9 @@ void blo_make_image_pointer_map(FileData *fd, Main *oldmain) oldnewmap_insert(fd->imamap, ima->gputexture[a], ima->gputexture[a], 0); if (ima->rr) oldnewmap_insert(fd->imamap, ima->rr, ima->rr, 0); - for (a=0; a < IMA_MAX_RENDER_SLOT; a++) - if (ima->renders[a]) - oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0); + LISTBASE_FOREACH(RenderSlot *, slot, &ima->renderslots) + if (slot->render) + oldnewmap_insert(fd->imamap, slot->render, slot->render, 0); } for (; sce; sce = sce->id.next) { if (sce->nodetree && sce->nodetree->previews) { @@ -1669,26 +1669,25 @@ 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) { ima->tpageflag &= ~IMA_GLBIND_IS_DATA; for (i = 0; i < TEXTARGET_COUNT; i++) { - ima->bindcode[i] = 0; ima->gputexture[i] = NULL; } ima->rr = NULL; } - for (i = 0; i < IMA_MAX_RENDER_SLOT; i++) - ima->renders[i] = newimaadr(fd, ima->renders[i]); - + LISTBASE_FOREACH(RenderSlot *, slot, &ima->renderslots) + slot->render = newimaadr(fd, slot->render); + for (i = 0; i < TEXTARGET_COUNT; i++) ima->gputexture[i] = newimaadr(fd, ima->gputexture[i]); ima->rr = newimaadr(fd, ima->rr); @@ -1697,7 +1696,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); @@ -1719,17 +1718,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; @@ -1748,18 +1747,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; @@ -1773,12 +1772,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); } } @@ -1789,13 +1788,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); } @@ -1815,9 +1814,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; @@ -1828,15 +1827,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); @@ -1853,13 +1852,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; @@ -1868,13 +1867,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); } @@ -1885,7 +1884,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--) { @@ -1906,14 +1905,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; } } @@ -1921,12 +1920,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)); @@ -1947,9 +1946,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); @@ -1984,7 +1983,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) { @@ -2012,11 +2011,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); @@ -2027,11 +2026,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++; @@ -2052,21 +2051,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); } @@ -2075,15 +2074,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); } @@ -2111,9 +2110,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); @@ -2145,7 +2144,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); @@ -2228,7 +2227,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) { @@ -2240,7 +2239,7 @@ static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_p prv->icon_id = 0; prv->tag = 0; } - + return prv; } @@ -2309,10 +2308,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; @@ -2403,7 +2402,7 @@ static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf) if (pf) { pf->data = newpackedadr(fd, pf->data); } - + return pf; } @@ -2415,7 +2414,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; @@ -2434,7 +2433,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); @@ -2447,7 +2446,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); @@ -2461,9 +2460,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); } @@ -2483,7 +2482,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) { @@ -2498,33 +2497,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); } @@ -2535,20 +2534,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); } @@ -2558,7 +2557,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; @@ -2566,7 +2565,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); @@ -2580,38 +2579,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) { @@ -2626,7 +2625,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); @@ -2639,14 +2638,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) { @@ -2673,13 +2672,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); @@ -2689,17 +2688,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); @@ -2709,29 +2708,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); @@ -2742,11 +2741,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); } @@ -2758,11 +2757,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); } } } @@ -2772,12 +2771,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); @@ -2791,22 +2790,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); } @@ -2816,19 +2815,19 @@ 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); adt->driver_array = NULL; - + /* 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) @@ -2837,7 +2836,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 *************** */ @@ -2963,7 +2962,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); @@ -2979,17 +2978,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) { @@ -2999,7 +2998,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); } @@ -3029,10 +3028,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); @@ -3045,7 +3044,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); @@ -3069,19 +3068,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 @@ -3094,7 +3093,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 */ @@ -3108,12 +3107,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 @@ -3126,7 +3125,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; @@ -3137,21 +3136,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. @@ -3159,13 +3158,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; @@ -3176,13 +3175,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; @@ -3193,11 +3192,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; @@ -3208,19 +3207,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) { @@ -3234,7 +3233,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); @@ -3249,31 +3248,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); @@ -3281,14 +3280,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) { @@ -3319,18 +3318,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); @@ -3338,19 +3337,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) { @@ -3368,7 +3367,7 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree) /* XXX TODO */ ntree->previews = NULL; #endif - + /* type verification is in lib-link */ } @@ -3383,7 +3382,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 */ @@ -3399,7 +3398,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) */ @@ -3415,29 +3414,29 @@ static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist) con->flag &= ~CONSTRAINT_STATICOVERRIDE_LOCAL; } } - + /* 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; @@ -3479,10 +3478,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; @@ -3499,7 +3498,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); @@ -3513,7 +3512,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); @@ -3528,7 +3527,7 @@ static void lib_link_pose(FileData *fd, Main *bmain, Object *ob, bPose *pose) } BLI_ghash_free(bone_hash, NULL, NULL); - + if (rebuild) { DEG_id_tag_update_ex(bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); @@ -3564,15 +3563,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); } @@ -3580,17 +3579,17 @@ 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->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; } @@ -3603,11 +3602,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); - + for (CameraBGImage *bgpic = ca->bg_images.first; bgpic; bgpic = bgpic->next) { bgpic->ima = newlibadr_us(fd, ca->id.lib, bgpic->ima); bgpic->clip = newlibadr_us(fd, ca->id.lib, bgpic->clip); @@ -3639,14 +3638,14 @@ 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); - + 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; } } @@ -3656,7 +3655,7 @@ static void direct_link_lamp(FileData *fd, Lamp *la) { la->adt = newdataadr(fd, la->adt); direct_link_animdata(fd, la->adt); - + la->curfalloff = newdataadr(fd, la->curfalloff); if (la->curfalloff) direct_link_curvemapping(fd, la->curfalloff); @@ -3666,7 +3665,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); } @@ -3690,10 +3689,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; } } @@ -3703,14 +3702,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: @@ -3721,7 +3720,7 @@ static void switch_endian_keyblock(Key *key, KeyBlock *kb) poin += sizeof(float) * b; break; } - + cp += 2; } data += elemsize; @@ -3731,17 +3730,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); } @@ -3755,13 +3754,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; } } @@ -3771,12 +3770,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;*/ @@ -3792,14 +3791,14 @@ 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 - + 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; } } @@ -3809,13 +3808,13 @@ static void direct_link_world(FileData *fd, World *wrld) { wrld->adt = newdataadr(fd, wrld->adt); direct_link_animdata(fd, wrld->adt); - + 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); } @@ -3868,24 +3867,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); } @@ -3896,7 +3895,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; } } @@ -3916,21 +3915,22 @@ static void direct_link_image(FileData *fd, Image *ima) if (!ima->cache) { ima->tpageflag &= ~IMA_GLBIND_IS_DATA; for (int i = 0; i < TEXTARGET_COUNT; i++) { - ima->bindcode[i] = 0; ima->gputexture[i] = NULL; } ima->rr = NULL; } - + /* undo system, try to restore render buffers */ + link_list(fd, &(ima->renderslots)); if (fd->imamap) { - int a; - - for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) - ima->renders[a] = newimaadr(fd, ima->renders[a]); + LISTBASE_FOREACH(RenderSlot *, slot, &ima->renderslots) { + slot->render = newimaadr(fd, slot->render); + } } else { - memset(ima->renders, 0, sizeof(ima->renders)); + LISTBASE_FOREACH(RenderSlot *, slot, &ima->renderslots) { + slot->render = NULL; + } ima->last_render_slot = ima->render_slot; } @@ -3962,11 +3962,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); @@ -3974,10 +3974,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; } } @@ -3998,10 +3998,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); @@ -4016,7 +4016,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)); @@ -4035,14 +4035,14 @@ static void direct_link_curve(FileData *fd, Curve *cu) cu->editnurb = NULL; cu->editfont = NULL; cu->batch_cache = 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); } @@ -4058,15 +4058,15 @@ 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->nodetree) { lib_link_ntree(fd, &tex->id, tex->nodetree); tex->nodetree->id.lib = tex->id.lib; } - + tex->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -4084,9 +4084,9 @@ static void direct_link_texture(FileData *fd, Tex *tex) 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; } @@ -4100,14 +4100,14 @@ 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 - + 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; } } @@ -4117,15 +4117,15 @@ static void direct_link_material(FileData *fd, Material *ma) { ma->adt = newdataadr(fd, ma->adt); direct_link_animdata(fd, ma->adt); - + ma->texpaintslot = NULL; - + 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); } @@ -4173,7 +4173,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; @@ -4193,7 +4193,7 @@ static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointC cache->step = 1; } } - + *ocache = newdataadr(fd, *ocache); } else if (*ocache) { @@ -4204,7 +4204,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; } } @@ -4225,16 +4225,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); } @@ -4282,7 +4282,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; @@ -4315,7 +4315,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; } } @@ -4329,7 +4329,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); @@ -4360,7 +4360,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); @@ -4381,17 +4381,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 */ @@ -4406,7 +4406,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); } @@ -4417,21 +4417,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; a<psys->totpart; a++, pa++) pa->hair=newdataadr(fd, pa->hair); } - + if (psys->particles && psys->particles->keys) { for (a=0, pa=psys->particles; a<psys->totpart; a++, pa++) { pa->keys= NULL; pa->totkey= 0; } - + psys->flag &= ~PSYS_KEYED; } @@ -4448,14 +4448,14 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles) for (a=0, pa=psys->particles; a<psys->totpart; 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; @@ -4463,21 +4463,21 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles) BLI_listbase_clear(&psys->pathcachebufs); BLI_listbase_clear(&psys->childcachebufs); psys->pdd = 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_mesh = psys->hair_out_mesh = NULL; psys->clmd->solver_result = NULL; } @@ -4501,16 +4501,16 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles) 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++) { @@ -4533,12 +4533,12 @@ static void lib_link_mesh(FileData *fd, Main *main) if (me->totface && !me->totpoly) { /* temporarily switch main so that reading from * external CustomData works */ - Main *gmain = G.main; - G.main = main; - + Main *gmain = G_MAIN; + G_MAIN = main; + BKE_mesh_do_versions_convert_mfaces_to_mpolys(me); - - G.main = gmain; + + G_MAIN = gmain; } /* @@ -4565,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; @@ -4591,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 @@ -4604,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 */ @@ -4620,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) @@ -4633,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) @@ -4662,7 +4662,7 @@ static void direct_link_customdata(FileData *fd, CustomData *data, int count) i++; } } - + CustomData_update_typemap(data); } @@ -4670,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); @@ -4683,15 +4683,15 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh) mesh->mloopcol = newdataadr(fd, mesh->mloopcol); mesh->mloopuv = newdataadr(fd, mesh->mloopuv); 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); @@ -4711,19 +4711,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 @@ -4735,7 +4735,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); @@ -4750,11 +4750,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); } @@ -4769,10 +4769,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; } } @@ -4781,13 +4781,13 @@ 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->batch_cache = NULL; - + lt->adt = newdataadr(fd, lt->adt); direct_link_animdata(fd, lt->adt); } @@ -4828,7 +4828,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); @@ -4846,14 +4846,14 @@ static void lib_link_object(FileData *fd, Main *main) ob->dup_group = NULL; ob->transflag &= ~OB_DUPLICOLLECTION; } - + 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 @@ -4865,19 +4865,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 @@ -4893,9 +4893,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) { @@ -4906,21 +4906,21 @@ 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->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); @@ -4929,29 +4929,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); @@ -4971,7 +4971,7 @@ static void lib_link_object(FileData *fd, Main *main) } } } - + if (warn) { BKE_report(fd->reports, RPT_WARNING, "Warning in console"); } @@ -4996,22 +4996,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); @@ -5026,56 +5026,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; @@ -5084,13 +5084,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; @@ -5100,13 +5100,13 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) smd->domain->tex_flame = 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]) { @@ -5153,22 +5153,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); } @@ -5186,17 +5186,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; @@ -5208,11 +5208,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->mesh = NULL; surmd->bvhtree = NULL; surmd->x = NULL; @@ -5221,7 +5221,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); @@ -5234,7 +5234,7 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) } else if (md->type == eModifierType_ParticleSystem) { ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md; - + psmd->mesh_final = NULL; psmd->mesh_original = NULL; psmd->psys= newdataadr(fd, psmd->psys); @@ -5243,22 +5243,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); @@ -5275,14 +5275,14 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) } 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); @@ -5351,7 +5351,7 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) static void direct_link_object(FileData *fd, Object *ob) { PartEff *paf; - + /* XXX This should not be needed - but seems like it can happen in some cases, so for now play safe... */ ob->proxy_from = NULL; @@ -5367,31 +5367,31 @@ 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); link_list(fd, &ob->fmaps); // 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) { @@ -5402,7 +5402,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; @@ -5413,12 +5413,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; } @@ -5426,29 +5426,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; @@ -5462,21 +5462,21 @@ 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->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; @@ -5494,12 +5494,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. @@ -5511,15 +5511,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); @@ -5573,6 +5573,8 @@ static void direct_link_layer_collections(FileData *fd, ListBase *lb, bool maste lc->collection = newdataadr(fd, lc->collection); } + lc->runtime_flag = 0; + direct_link_layer_collections(fd, &lc->layer_collections, false); } } @@ -5595,6 +5597,7 @@ static void direct_link_view_layer(FileData *fd, ViewLayer *view_layer) BLI_listbase_clear(&view_layer->drawdata); view_layer->object_bases_array = NULL; view_layer->object_bases_hash = NULL; + view_layer->runtime_flag = 0; } static void lib_link_layer_collection(FileData *fd, Library *lib, LayerCollection *layer_collection, bool master) @@ -5614,9 +5617,6 @@ static void lib_link_layer_collection(FileData *fd, Library *lib, LayerCollectio static void lib_link_view_layer(FileData *fd, Library *lib, ViewLayer *view_layer) { - /* tag scene layer to update for collection tree evaluation */ - view_layer->flag |= VIEW_LAYER_ENGINE_DIRTY; - for (FreestyleModuleConfig *fmc = view_layer->freestyle_config.modules.first; fmc; fmc = fmc->next) { fmc->script = newlibadr(fd, lib, fmc->script); } @@ -5631,7 +5631,6 @@ static void lib_link_view_layer(FileData *fd, Library *lib, ViewLayer *view_laye /* we only bump the use count for the collection objects */ base->object = newlibadr(fd, lib, base->object); - base->flag |= BASE_DIRTY_ENGINE_SETTINGS; if (base->object == NULL) { /* Free in case linked object got lost. */ @@ -5756,7 +5755,7 @@ static void lib_link_collection(FileData *fd, Main *main) 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; @@ -5818,21 +5817,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); @@ -5854,14 +5853,14 @@ 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->particle.shape_object = newlibadr(fd, sce->id.lib, sce->toolsettings->particle.shape_object); - + for (Base *base_legacy_next, *base_legacy = sce->base.first; base_legacy; base_legacy = base_legacy_next) { base_legacy_next = base_legacy->next; - + base_legacy->object = newlibadr_us(fd, sce->id.lib, base_legacy->object); - + if (base_legacy->object == NULL) { blo_reportf_wrap(fd->reports, RPT_WARNING, TIP_("LIB: object lost from scene: '%s'"), sce->id.name + 2); @@ -5870,7 +5869,7 @@ static void lib_link_scene(FileData *fd, Main *main) MEM_freeN(base_legacy); } } - + Sequence *seq; SEQ_BEGIN (sce->ed, seq) { @@ -5917,11 +5916,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 collections */ if (sce->rigidbody_world) { RigidBodyWorld *rbw = sce->rigidbody_world; @@ -5932,13 +5931,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); for (FreestyleModuleConfig *fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) { @@ -6007,9 +6006,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); @@ -6069,34 +6068,34 @@ static void direct_link_scene(FileData *fd, Scene *sce) RigidBodyWorld *rbw; ViewLayer *view_layer; SceneRenderLayer *srl; - + sce->depsgraph_hash = NULL; 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; @@ -6104,7 +6103,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) { @@ -6121,7 +6120,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) { @@ -6131,29 +6130,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; @@ -6165,7 +6164,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); } @@ -6206,22 +6205,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); @@ -6230,24 +6229,24 @@ 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; } } } } - + sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata); if (sce->r.avicodecdata) { sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat); @@ -6257,7 +6256,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)); @@ -6270,7 +6269,7 @@ static void direct_link_scene(FileData *fd, Scene *sce) link_list(fd, &(srl->freestyleConfig.modules)); link_list(fd, &(srl->freestyleConfig.linesets)); } - + sce->nodetree = newdataadr(fd, sce->nodetree); if (sce->nodetree) { direct_link_id(fd, &sce->nodetree->id); @@ -6278,12 +6277,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; @@ -6355,7 +6354,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); @@ -6368,21 +6367,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; @@ -6433,6 +6432,10 @@ static void direct_link_region(FileData *fd, ARegion *ar, int spacetype) /* unkown space type, don't leak regiondata */ ar->regiondata = NULL; } + else if (ar->flag & RGN_FLAG_TEMP_REGIONDATA) { + /* Runtime data, don't use. */ + ar->regiondata = NULL; + } else { ar->regiondata = newdataadr(fd, ar->regiondata); if (ar->regiondata) { @@ -6450,7 +6453,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; @@ -6592,7 +6595,7 @@ static void direct_link_area(FileData *fd, ScrArea *area) 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 @@ -6603,12 +6606,12 @@ static void direct_link_area(FileData *fd, ScrArea *area) } 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; @@ -6616,14 +6619,14 @@ static void direct_link_area(FileData *fd, ScrArea *area) } 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; } 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 * @@ -6927,10 +6930,10 @@ static bool direct_link_area_map(FileData *fd, ScrAreaMap *area_map) 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) { WorkSpaceInstanceHook *hook = win->workspace_hook; @@ -6947,12 +6950,12 @@ 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->gesture); - + win->active = 0; win->cursor = 0; @@ -6968,13 +6971,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; @@ -6985,7 +6988,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; @@ -6997,7 +7000,7 @@ 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. */ @@ -7008,7 +7011,7 @@ static void lib_link_windowmanager(FileData *fd, Main *main) win->scene = newlibadr(fd, wm->id.lib, win->scene); /* deprecated, but needed for versioning (will be NULL'ed then) */ win->screen = newlibadr(fd, NULL, win->screen); - + for (ScrArea *area = win->global_areas.areabase.first; area; area = area->next) { lib_link_area(fd, &wm->id, area); } @@ -7021,7 +7024,7 @@ static void lib_link_windowmanager(FileData *fd, Main *main) /* ****************** 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) { @@ -7036,7 +7039,7 @@ 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 *area = sc->areabase.first; area; area = area->next) { lib_link_area(fd, &sc->id, area); } @@ -7206,7 +7209,7 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main if (sl->spacetype == SPACE_VIEW3D) { View3D *v3d = (View3D *)sl; ARegion *ar; - + v3d->camera = restore_pointer_by_name(id_map, (ID *)v3d->camera, USER_REAL); v3d->ob_centre = restore_pointer_by_name(id_map, (ID *)v3d->ob_centre, USER_REAL); @@ -7215,25 +7218,26 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main /* free render engines for now */ for (ar = sa->regionbase.first; ar; ar = ar->next) { - RegionView3D *rv3d= ar->regiondata; - - if (rv3d && rv3d->render_engine) { - RE_engine_free(rv3d->render_engine); - rv3d->render_engine = NULL; + if (ar->regiontype == RGN_TYPE_WINDOW) { + RegionView3D *rv3d = ar->regiondata; + if (rv3d && rv3d->render_engine) { + RE_engine_free(rv3d->render_engine); + rv3d->render_engine = NULL; + } } } } 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 */ @@ -7257,28 +7261,28 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main } 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); @@ -7287,7 +7291,7 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main 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... */ @@ -7296,7 +7300,7 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main } 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... */ @@ -7305,25 +7309,25 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main 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); @@ -7331,9 +7335,9 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main } 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; @@ -7358,14 +7362,14 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main 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 */ @@ -7373,19 +7377,19 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main } 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) { @@ -7397,10 +7401,10 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main } 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; } } @@ -7459,11 +7463,11 @@ void blo_lib_link_restore(Main *newmain, wmWindowManager *curwm, Scene *curscene 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; @@ -7472,7 +7476,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->gridsubdiv == 0) v3d->gridsubdiv = 10; @@ -7481,7 +7485,7 @@ void blo_do_versions_view3d_split_250(View3D *v3d, ListBase *regions) static bool direct_link_screen(FileData *fd, bScreen *sc) { bool wrong_id = false; - + sc->regionbase.first = sc->regionbase.last= NULL; sc->context = NULL; sc->active_region = NULL; @@ -7502,7 +7506,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) { @@ -7510,10 +7514,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); @@ -7533,17 +7537,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; } @@ -7614,7 +7618,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; @@ -7648,11 +7652,11 @@ static void direct_link_sound(FileData *fd, bSound *sound) if (fd->soundmap) { sound->waveform = newsoundadr(fd, sound->waveform); - } + } else { sound->waveform = NULL; } - + if (sound->spinlock) { sound->spinlock = MEM_mallocN(sizeof(SpinLock), "sound_spinlock"); BLI_spin_init(sound->spinlock); @@ -7671,7 +7675,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; @@ -7689,9 +7693,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); } @@ -7751,7 +7755,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); @@ -7785,9 +7789,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); @@ -8203,13 +8207,13 @@ static const char *dataname(short id_code) case ID_WS: return "Data from WS"; } 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 @@ -8222,14 +8226,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; } @@ -8318,14 +8322,14 @@ 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->orig_id = NULL; 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). */ @@ -8336,10 +8340,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); @@ -8457,14 +8461,14 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short direct_link_workspace(fd, (WorkSpace *)id, main); break; } - + oldnewmap_free_unused(fd->datamap); oldnewmap_clear(fd->datamap); - + if (wrong_id) { BKE_libblock_free(main, id); } - + return (bhead); } @@ -8473,41 +8477,41 @@ 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->minversionfile = fg->minversion; 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; bfd->cur_view_layer = fg->cur_view_layer; MEM_freeN(fg); - + fd->globalf = bfd->globalf; fd->fileflags = bfd->fileflags; - + return blo_nextbhead(fd, bhead); } @@ -8529,12 +8533,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); @@ -8555,7 +8559,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; @@ -8571,7 +8575,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); @@ -8596,7 +8600,7 @@ static void do_versions_after_linking(Main *main) static void lib_link_all(FileData *fd, Main *main) { oldnewmap_sort(fd); - + lib_link_id(fd, main); /* No load UI for undo memfiles */ @@ -8657,22 +8661,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); @@ -8682,20 +8686,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); } @@ -8707,13 +8711,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; } @@ -8722,14 +8726,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)); @@ -8779,7 +8783,7 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath) 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. */ @@ -8804,17 +8808,17 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath) } } } - + /* 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. */ @@ -8840,9 +8844,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; @@ -8858,7 +8862,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; @@ -8869,20 +8873,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); } @@ -8906,19 +8910,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) @@ -8980,32 +8984,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; } @@ -9016,10 +9020,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 @@ -9029,11 +9033,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); } } @@ -9115,14 +9119,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; @@ -9134,15 +9138,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); @@ -9150,7 +9154,7 @@ static void expand_fcurves(FileData *fd, Main *mainvar, ListBase *list) DRIVER_TARGETS_LOOPER_END } } - + /* F-Curve Modifiers */ expand_fmodifiers(fd, mainvar, &fcu->modifiers); } @@ -9159,14 +9163,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); @@ -9181,7 +9185,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) { @@ -9193,17 +9197,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); } @@ -9212,32 +9216,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); @@ -9297,7 +9301,7 @@ static void expand_collection(FileData *fd, Main *mainvar, Collection *collectio 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); } @@ -9306,13 +9310,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); @@ -9336,10 +9340,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); } @@ -9355,10 +9359,10 @@ static void expand_brush(FileData *fd, Main *mainvar, Brush *brush) static void expand_material(FileData *fd, Main *mainvar, Material *ma) { 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); } @@ -9366,10 +9370,10 @@ static void expand_material(FileData *fd, Main *mainvar, Material *ma) static void expand_lamp(FileData *fd, Main *mainvar, Lamp *la) { 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); } @@ -9378,7 +9382,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); } @@ -9387,10 +9391,10 @@ static void expand_lattice(FileData *fd, Main *mainvar, Lattice *lt) static void expand_world(FileData *fd, Main *mainvar, World *wrld) { 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); } @@ -9399,11 +9403,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); } @@ -9411,11 +9415,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); @@ -9425,7 +9429,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); } @@ -9433,14 +9437,14 @@ static void expand_curve(FileData *fd, Main *mainvar, Curve *cu) static void expand_mesh(FileData *fd, Main *mainvar, Mesh *me) { int a; - + 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); } @@ -9461,13 +9465,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) @@ -9478,10 +9482,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); @@ -9512,10 +9516,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); } @@ -9525,56 +9529,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); @@ -9622,23 +9626,23 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce) SceneRenderLayer *srl; FreestyleModuleConfig *module; FreestyleLineSet *lineset; - + for (Base *base_legacy = sce->base.first; base_legacy; base_legacy = base_legacy->next) { expand_doit(fd, mainvar, base_legacy->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); for (module = srl->freestyleConfig.modules.first; module; module = module->next) { @@ -9671,10 +9675,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); @@ -9687,7 +9691,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); @@ -9715,7 +9719,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); } @@ -9852,10 +9856,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; @@ -9951,10 +9955,10 @@ void BLO_expand_main(void *fdhandle, Main *mainvar) default: break; } - + do_it = true; id->tag &= ~LIB_TAG_NEED_EXPAND; - + } id = id->next; } @@ -9964,17 +9968,17 @@ void BLO_expand_main(void *fdhandle, Main *mainvar) /* ***************************** */ - + static bool object_in_any_scene(Main *bmain, Object *ob) { Scene *sce; - + for (sce = bmain->scene.first; sce; sce = sce->id.next) { if (BKE_scene_object_find(sce, ob)) { return true; } } - + return false; } @@ -10002,13 +10006,15 @@ static void add_loose_objects_to_scene( if ((ob->id.tag & LIB_TAG_INDIRECT) && (ob->id.tag & LIB_TAG_PRE_EXISTING) == 0) { bool do_it = false; - if (ob->id.us == 0) { - do_it = true; - } - else if (!is_link && (ob->id.lib == lib) && (object_in_any_scene(bmain, ob) == 0)) { - /* When appending, make sure any indirectly loaded objects get a base, else they cant be accessed at all - * (see T27437). */ - do_it = true; + if (!is_link) { + if (ob->id.us == 0) { + do_it = true; + } + else if ((ob->id.lib == lib) && (object_in_any_scene(bmain, ob) == 0)) { + /* When appending, make sure any indirectly loaded objects get a base, else they cant be accessed at all + * (see T27437). */ + do_it = true; + } } if (do_it) { @@ -10142,10 +10148,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; } @@ -10182,7 +10188,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; @@ -10313,30 +10319,30 @@ static Main *library_link_begin(Main *mainvar, FileData **fd, const char *filepa Main *mainl; (*fd)->mainlist = MEM_callocN(sizeof(ListBase), "FileData.mainlist"); - + /* clear for collection instantiating tag */ BKE_main_id_tag_listbase(&(mainvar->collection), 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; } /** * Initialize the BlendHandle for linking library data. * - * \param mainvar The current main database, e.g. G.main or CTX_data_main(C). + * \param mainvar The current main database, e.g. G_MAIN or CTX_data_main(C). * \param bh A blender file handle as returned by \a BLO_blendhandle_from_file or \a BLO_blendhandle_from_memory. * \param filepath Used for relative linking, copied to the \a lib->name. * \return the library Main, to be passed to \a BLO_library_append_named_part as \a mainl. @@ -10479,11 +10485,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; @@ -10501,13 +10507,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) { @@ -10515,22 +10521,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)); } @@ -10551,12 +10557,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) { @@ -10566,7 +10572,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, @@ -10575,15 +10581,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 @@ -10598,7 +10604,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); @@ -10645,7 +10651,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) } BLO_expand_main(fd, mainptr); } - + mainptr = mainptr->next; } } @@ -10659,7 +10665,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) { @@ -10674,13 +10680,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 = BKE_main_new(); for (mainptr = mainl->next; mainptr; mainptr = mainptr->next) { @@ -10696,10 +10702,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; } @@ -10716,17 +10722,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 7618c023882..65938c88192 100644 --- a/source/blender/blenloader/intern/readfile.h +++ b/source/blender/blenloader/intern/readfile.h @@ -66,23 +66,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; @@ -92,13 +92,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. */ diff --git a/source/blender/blenloader/intern/runtime.c b/source/blender/blenloader/intern/runtime.c index ec496e1c866..ec0e8ba4738 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,11 @@ 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 e1ae267ea11..614a3be559b 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 d51289bee43..973591c49da 100644 --- a/source/blender/blenloader/intern/versioning_250.c +++ b/source/blender/blenloader/intern/versioning_250.c @@ -582,7 +582,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; @@ -592,14 +592,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; } @@ -615,10 +615,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"); @@ -1934,13 +1934,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) @@ -1950,17 +1950,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! */ @@ -1971,17 +1971,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! */ @@ -1992,12 +1992,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)! @@ -2203,19 +2203,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 2cded68f7ec..c405e385e9f 100644 --- a/source/blender/blenloader/intern/versioning_260.c +++ b/source/blender/blenloader/intern/versioning_260.c @@ -2438,10 +2438,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 ba714405cc0..7a106611e64 100644 --- a/source/blender/blenloader/intern/versioning_270.c +++ b/source/blender/blenloader/intern/versioning_270.c @@ -171,7 +171,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 */ @@ -180,13 +180,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; } } @@ -197,7 +197,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); } } @@ -289,7 +289,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 */ @@ -297,7 +297,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; @@ -313,7 +313,7 @@ static void do_version_bbone_easing_fcurve_fix(ID *UNUSED(id), FCurve *fcu, void 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) { @@ -326,13 +326,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) */ @@ -656,7 +656,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) { @@ -1040,63 +1040,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; } @@ -1105,17 +1105,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 */ @@ -1124,7 +1124,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) enabled = true; } } - + if (enabled) gpd->flag |= GP_DATA_SHOW_ONIONSKINS; else @@ -1239,7 +1239,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); @@ -1261,7 +1261,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) @@ -1381,19 +1381,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) { @@ -1402,7 +1402,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; @@ -1410,7 +1410,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; } @@ -1665,7 +1665,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) } } - { + if (!MAIN_VERSION_ATLEAST(bmain, 279, 4)) { /* Fix for invalid state of screen due to bug in older versions. */ for (bScreen *sc = bmain->screen.first; sc; sc = sc->id.next) { for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) { @@ -1755,7 +1755,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_280.c b/source/blender/blenloader/intern/versioning_280.c index eb165efb4f9..190b9d86d59 100644 --- a/source/blender/blenloader/intern/versioning_280.c +++ b/source/blender/blenloader/intern/versioning_280.c @@ -60,6 +60,7 @@ #include "BKE_customdata.h" #include "BKE_freestyle.h" #include "BKE_idprop.h" +#include "BKE_image.h" #include "BKE_layer.h" #include "BKE_main.h" #include "BKE_mesh.h" @@ -113,7 +114,7 @@ static void do_version_workspaces_create_from_screens(Main *bmain) else { workspace = BKE_workspace_add(bmain, screen->id.name + 2); } - BKE_workspace_layout_add(workspace, screen, screen->id.name + 2); + BKE_workspace_layout_add(bmain, workspace, screen, screen->id.name + 2); BKE_workspace_view_layer_set(workspace, layer, scene); } } @@ -354,13 +355,6 @@ static void do_version_scene_collection_to_collection(Main *bmain, Scene *scene) #endif -enum { - DO_VERSION_COLLECTION_VISIBLE = 0, - DO_VERSION_COLLECTION_HIDE = 1, - DO_VERSION_COLLECTION_HIDE_RENDER = 2, - DO_VERSION_COLLECTION_HIDE_ALL = 3, -}; - static void do_version_layers_to_collections(Main *bmain, Scene *scene) { /* Since we don't have access to FileData we check the (always valid) first @@ -375,99 +369,26 @@ static void do_version_layers_to_collections(Main *bmain, Scene *scene) /* Create collections from layers. */ Collection *collection_master = BKE_collection_master(scene); - - struct DoVersionSceneCollections { - Collection *collections[20]; - int created; - const char *suffix; - int flag; - } collections[] = - { - { - .collections = {NULL}, - .created = 0, - .suffix = "", - .flag = 0, - }, - { - .collections = {NULL}, - .created = 0, - .suffix = " - Hide Viewport", - .flag = COLLECTION_RESTRICT_VIEW, - }, - { - .collections = {NULL}, - .created = 0, - .suffix = " - Hide Render", - .flag = COLLECTION_RESTRICT_RENDER, - }, - { - .collections = {NULL}, - .created = 0, - .suffix = " - Hide Render All", - .flag = COLLECTION_RESTRICT_VIEW | COLLECTION_RESTRICT_RENDER, - } - }; + Collection *collections[20] = {NULL}; for (int layer = 0; layer < 20; layer++) { for (Base *base = scene->base.first; base; base = base->next) { if (base->lay & (1 << layer)) { - int collection_index = -1; - if ((base->object->restrictflag & OB_RESTRICT_VIEW) && - (base->object->restrictflag & OB_RESTRICT_RENDER)) - { - collection_index = DO_VERSION_COLLECTION_HIDE_ALL; - } - else if (base->object->restrictflag & OB_RESTRICT_VIEW) { - collection_index = DO_VERSION_COLLECTION_HIDE; - } - else if (base->object->restrictflag & OB_RESTRICT_RENDER) { - collection_index = DO_VERSION_COLLECTION_HIDE_RENDER; - } - else { - collection_index = DO_VERSION_COLLECTION_VISIBLE; - } - /* Create collections when needed only. */ - if ((collections[collection_index].created & (1 << layer)) == 0) { + if (collections[layer] == NULL) { char name[MAX_NAME]; - if ((collections[DO_VERSION_COLLECTION_VISIBLE].created & (1 << layer)) == 0) { - BLI_snprintf(name, - sizeof(collection_master->id.name), - "Collection %d%s", - layer + 1, - collections[DO_VERSION_COLLECTION_VISIBLE].suffix); - - Collection *collection = BKE_collection_add(bmain, collection_master, name); - collection->id.lib = scene->id.lib; - collection->flag |= collections[DO_VERSION_COLLECTION_VISIBLE].flag; - collections[DO_VERSION_COLLECTION_VISIBLE].collections[layer] = collection; - collections[DO_VERSION_COLLECTION_VISIBLE].created |= (1 << layer); - - if (!(scene->lay & (1 << layer))) { - collection->flag |= COLLECTION_RESTRICT_VIEW | COLLECTION_RESTRICT_RENDER; - } - } + BLI_snprintf(name, + sizeof(collection_master->id.name), + "Collection %d", + layer + 1); - if (collection_index != DO_VERSION_COLLECTION_VISIBLE) { - Collection *collection_parent; - collection_parent = collections[DO_VERSION_COLLECTION_VISIBLE].collections[layer]; - BLI_snprintf(name, - sizeof(collection_master->id.name), - "Collection %d%s", - layer + 1, - collections[collection_index].suffix); - - Collection *collection = BKE_collection_add(bmain, collection_parent, name); - collection->id.lib = scene->id.lib; - collection->flag |= collections[collection_index].flag; - collections[collection_index].collections[layer] = collection; - collections[collection_index].created |= (1 << layer); - - if (!(scene->lay & (1 << layer))) { - collection->flag |= COLLECTION_RESTRICT_VIEW | COLLECTION_RESTRICT_RENDER; - } + Collection *collection = BKE_collection_add(bmain, collection_master, name); + collection->id.lib = scene->id.lib; + collections[layer] = collection; + + if (!(scene->lay & (1 << layer))) { + collection->flag |= COLLECTION_RESTRICT_VIEW | COLLECTION_RESTRICT_RENDER; } } @@ -475,7 +396,7 @@ static void do_version_layers_to_collections(Main *bmain, Scene *scene) * but since no view layers exists yet at this point it's fast. */ BKE_collection_object_add( bmain, - collections[collection_index].collections[layer], base->object); + collections[layer], base->object); } if (base->flag & SELECT) { @@ -487,46 +408,6 @@ static void do_version_layers_to_collections(Main *bmain, Scene *scene) } } - /* Re-order the nested hidden collections. */ - CollectionChild *child_parent = collection_master->children.first; - Collection *collection_parent = (child_parent) ? child_parent->collection : NULL; - - for (int layer = 0; layer < 20; layer++) { - if (collections[DO_VERSION_COLLECTION_VISIBLE].created & (1 << layer)) { - CollectionChild *hide_child = BLI_findptr( - &collection_parent->children, - collections[DO_VERSION_COLLECTION_HIDE].collections[layer], - offsetof(CollectionChild, collection)); - - if ((collections[DO_VERSION_COLLECTION_HIDE].created & (1 << layer)) && - (hide_child != collection_parent->children.first)) - { - BLI_listbase_swaplinks( - &collection_parent->children, - hide_child, - collection_parent->children.first); - } - - CollectionChild *hide_all_child = BLI_findptr( - &collection_parent->children, - collections[DO_VERSION_COLLECTION_HIDE_ALL].collections[layer], - offsetof(CollectionChild, collection)); - - if ((collections[DO_VERSION_COLLECTION_HIDE_ALL].created & (1 << layer)) && - (hide_all_child != collection_parent->children.last)) - { - BLI_listbase_swaplinks( - &collection_parent->children, - hide_all_child, - collection_parent->children.last); - } - - child_parent = child_parent->next; - collection_parent = (child_parent) ? child_parent->collection : NULL; - } - } - BLI_assert(collection_parent == NULL); - /* Handle legacy render layers. */ bool have_override = false; @@ -576,8 +457,8 @@ static void do_version_layers_to_collections(Main *bmain, Scene *scene) /* Set exclusion and overrides. */ for (int layer = 0; layer < 20; layer++) { - if (collections[DO_VERSION_COLLECTION_VISIBLE].created & (1 << layer)) { - Collection *collection = collections[DO_VERSION_COLLECTION_VISIBLE].collections[layer]; + Collection *collection = collections[layer]; + if (collection) { LayerCollection *lc = BKE_layer_collection_first_from_scene_collection(view_layer, collection); if (srl->lay_exclude & (1 << layer)) { @@ -611,14 +492,6 @@ static void do_version_layers_to_collections(Main *bmain, Scene *scene) false); } } - - LayerCollection *nlc = lc->layer_collections.first; - for (int j = 1; j < 4; j++) { - if (collections[j].created & (1 << layer)) { - nlc = nlc->next; - } - } - BLI_assert(nlc == NULL); } } @@ -1444,15 +1317,8 @@ void blo_do_versions_280(FileData *fd, Library *UNUSED(lib), Main *bmain) if (!MAIN_VERSION_ATLEAST(bmain, 280, 15)) { for (Scene *scene = bmain->scene.first; scene; scene = scene->id.next) { - scene->display.matcap_icon = 1; - scene->display.matcap_type = CLAY_MATCAP_NONE; - scene->display.matcap_hue = 0.5f; - scene->display.matcap_saturation = 0.5f; - scene->display.matcap_value = 0.5f; scene->display.matcap_ssao_distance = 0.2f; scene->display.matcap_ssao_attenuation = 1.0f; - scene->display.matcap_ssao_factor_cavity = 1.0f; - scene->display.matcap_ssao_factor_edge = 1.0f; scene->display.matcap_ssao_samples = 16; } @@ -1499,7 +1365,8 @@ void blo_do_versions_280(FileData *fd, Library *UNUSED(lib), Main *bmain) } } - { + + if (!MAIN_VERSION_ATLEAST(bmain, 280, 18)) { if (!DNA_struct_elem_find(fd->filesdna, "Material", "float", "roughness")) { for (Material *mat = bmain->mat.first; mat; mat = mat->id.next) { if (mat->use_nodes) { @@ -1594,4 +1461,18 @@ void blo_do_versions_280(FileData *fd, Library *UNUSED(lib), Main *bmain) } } } + + if (!MAIN_VERSION_ATLEAST(bmain, 280, 19)) { + if (!DNA_struct_elem_find(fd->filesdna, "Image", "ListBase", "renderslot")) { + for (Image *ima = bmain->image.first; ima; ima = ima->id.next) { + if (ima->type == IMA_TYPE_R_RESULT) { + for (int i = 0; i < 8; i++) { + RenderSlot *slot = MEM_callocN(sizeof(RenderSlot), "Image Render Slot Init"); + BLI_snprintf(slot->name, sizeof(slot->name), "Slot %d", i + 1); + BLI_addtail(&ima->renderslots, slot); + } + } + } + } + } } diff --git a/source/blender/blenloader/intern/versioning_defaults.c b/source/blender/blenloader/intern/versioning_defaults.c index cbd6988655d..210dc07d7f2 100644 --- a/source/blender/blenloader/intern/versioning_defaults.c +++ b/source/blender/blenloader/intern/versioning_defaults.c @@ -141,6 +141,8 @@ void BLO_update_defaults_startup_blend(Main *bmain) if (scene->toolsettings) { ToolSettings *ts = scene->toolsettings; + ts->object_flag |= SCE_OBJECT_MODE_LOCK; + ts->uvcalc_flag |= UVCALC_TRANSFORM_CORRECT; if (ts->sculpt) { @@ -149,7 +151,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; @@ -163,17 +165,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; @@ -183,28 +185,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; @@ -219,7 +221,7 @@ void BLO_update_defaults_startup_blend(Main *bmain) } scene->r.ffcodecdata.audio_mixrate = 48000; - + /* set av sync by default */ scene->audio.flag |= AUDIO_SYNC; scene->flag &= ~SCE_FRAME_DROP; @@ -402,4 +404,3 @@ void BLO_update_defaults_startup_blend(Main *bmain) } } } - diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c index 6abcf6cfa02..9c55c949fcf 100644 --- a/source/blender/blenloader/intern/writefile.c +++ b/source/blender/blenloader/intern/writefile.c @@ -2260,6 +2260,8 @@ static void write_image(WriteData *wd, Image *ima) writestruct(wd, DATA, Stereo3dFormat, 1, ima->stereo3d_format); ima->packedfile = NULL; + + writelist(wd, DATA, RenderSlot, &ima->renderslots); } } @@ -2687,6 +2689,10 @@ static void write_region(WriteData *wd, ARegion *ar, int spacetype) writestruct(wd, DATA, ARegion, 1, ar); if (ar->regiondata) { + if (ar->flag & RGN_FLAG_TEMP_REGIONDATA) { + return; + } + switch (spacetype) { case SPACE_VIEW3D: if (ar->regiontype == RGN_TYPE_WINDOW) { @@ -4091,7 +4097,7 @@ bool BLO_write_file( if (G.relbase_valid) { /* blend may not have been saved before. Tn this case * we should not have any relative paths, but if there - * is somehow, an invalid or empty G.main->name it will + * is somehow, an invalid or empty G_MAIN->name it will * print an error, don't try make the absolute in this case. */ BKE_bpath_absolute_convert(mainvar, BKE_main_blendfile_path_from_global(), NULL); } @@ -4099,7 +4105,7 @@ bool BLO_write_file( } if (write_flags & G_FILE_RELATIVE_REMAP) { - /* note, making relative to something OTHER then G.main->name */ + /* note, making relative to something OTHER then G_MAIN->name */ BKE_bpath_relative_convert(mainvar, filepath, NULL); } diff --git a/source/blender/bmesh/intern/bmesh_core.c b/source/blender/bmesh/intern/bmesh_core.c index c6836187eee..97f1bad08b7 100644 --- a/source/blender/bmesh/intern/bmesh_core.c +++ b/source/blender/bmesh/intern/bmesh_core.c @@ -2508,19 +2508,17 @@ void BM_vert_separate_hflag( } } -void BM_vert_separate_wire_hflag( +void BM_vert_separate_tested_edges( BMesh *UNUSED(bm), BMVert *v_dst, BMVert *v_src, - const char hflag) + bool (*testfn)(BMEdge *, void *arg), void *arg) { LinkNode *edges_hflag = NULL; BMEdge *e_iter, *e_first; e_iter = e_first = v_src->e; do { - if (BM_elem_flag_test(e_iter, hflag)) { - if (BM_edge_is_wire(e_iter)) { - BLI_linklist_prepend_alloca(&edges_hflag, e_iter); - } + if (testfn(e_iter, arg)) { + BLI_linklist_prepend_alloca(&edges_hflag, e_iter); } } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v_src)) != e_first); diff --git a/source/blender/bmesh/intern/bmesh_core.h b/source/blender/bmesh/intern/bmesh_core.h index fb6b66809f3..93bb12fe742 100644 --- a/source/blender/bmesh/intern/bmesh_core.h +++ b/source/blender/bmesh/intern/bmesh_core.h @@ -81,9 +81,9 @@ void BM_vert_separate( void BM_vert_separate_hflag( BMesh *bm, BMVert *v, const char hflag, const bool copy_select, BMVert ***r_vout, int *r_vout_len); -void BM_vert_separate_wire_hflag( +void BM_vert_separate_tested_edges( BMesh *bm, BMVert *v_dst, BMVert *v_src, - const char hflag); + bool (*testfn)(BMEdge *, void *arg), void *arg); /** * BMesh Kernel: For modifying structure. diff --git a/source/blender/bmesh/intern/bmesh_mesh.c b/source/blender/bmesh/intern/bmesh_mesh.c index 4d0f259b4e3..96707335081 100644 --- a/source/blender/bmesh/intern/bmesh_mesh.c +++ b/source/blender/bmesh/intern/bmesh_mesh.c @@ -1108,43 +1108,43 @@ void BM_lnorspace_invalidate(BMesh *bm, const bool do_invalidate_all) * - all smooth fans of all immediate loop-neighbors vertices; * This can be simplified as 'all loops of selected vertices and their immediate neighbors' * need to be tagged for update. -*/ -BM_ITER_MESH(v, &viter, bm, BM_VERTS_OF_MESH) { - if (BM_elem_flag_test(v, BM_ELEM_SELECT)) { - BM_ITER_ELEM(l, &liter, v, BM_LOOPS_OF_VERT) { - BM_ELEM_API_FLAG_ENABLE(l, BM_LNORSPACE_UPDATE); - - /* Note that we only handle unselected neighbor vertices here, main loop will take care of - * selected ones. */ - if (!BM_elem_flag_test(l->prev->v, BM_ELEM_SELECT) && - !BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->prev->v))) - { - BMLoop *l_prev; - BMIter liter_prev; - BM_ITER_ELEM(l_prev, &liter_prev, l->prev->v, BM_LOOPS_OF_VERT) { - BM_ELEM_API_FLAG_ENABLE(l_prev, BM_LNORSPACE_UPDATE); + */ + BM_ITER_MESH(v, &viter, bm, BM_VERTS_OF_MESH) { + if (BM_elem_flag_test(v, BM_ELEM_SELECT)) { + BM_ITER_ELEM(l, &liter, v, BM_LOOPS_OF_VERT) { + BM_ELEM_API_FLAG_ENABLE(l, BM_LNORSPACE_UPDATE); + + /* Note that we only handle unselected neighbor vertices here, main loop will take care of + * selected ones. */ + if (!BM_elem_flag_test(l->prev->v, BM_ELEM_SELECT) && + !BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->prev->v))) + { + BMLoop *l_prev; + BMIter liter_prev; + BM_ITER_ELEM(l_prev, &liter_prev, l->prev->v, BM_LOOPS_OF_VERT) { + BM_ELEM_API_FLAG_ENABLE(l_prev, BM_LNORSPACE_UPDATE); + } + BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_prev->v)); } - BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_prev->v)); - } - if (!BM_elem_flag_test(l->next->v, BM_ELEM_SELECT) && - !BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->next->v))) - { - BMLoop *l_next; - BMIter liter_next; - BM_ITER_ELEM(l_next, &liter_next, l->next->v, BM_LOOPS_OF_VERT) { - BM_ELEM_API_FLAG_ENABLE(l_next, BM_LNORSPACE_UPDATE); + if (!BM_elem_flag_test(l->next->v, BM_ELEM_SELECT) && + !BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->next->v))) + { + BMLoop *l_next; + BMIter liter_next; + BM_ITER_ELEM(l_next, &liter_next, l->next->v, BM_LOOPS_OF_VERT) { + BM_ELEM_API_FLAG_ENABLE(l_next, BM_LNORSPACE_UPDATE); + } + BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_next->v)); } - BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_next->v)); } - } - BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(v)); + BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(v)); + } } -} -MEM_freeN(done_verts); -bm->spacearr_dirty |= BM_SPACEARR_DIRTY; + MEM_freeN(done_verts); + bm->spacearr_dirty |= BM_SPACEARR_DIRTY; } void BM_lnorspace_rebuild(BMesh *bm, bool preserve_clnor) @@ -1471,59 +1471,6 @@ int BM_total_loop_select(BMesh *bm) return r_sel; } -static void UNUSED_FUNCTION(bm_mdisps_space_set)( - Object *ob, BMesh *bm, int from, int to) -{ - /* switch multires data out of tangent space */ - if (CustomData_has_layer(&bm->ldata, CD_MDISPS)) { - BMEditMesh *em = BKE_editmesh_create(bm, false); - DerivedMesh *dm = CDDM_from_editbmesh(em, true, false); - MDisps *mdisps; - BMFace *f; - BMIter iter; - // int i = 0; // UNUSED - - multires_set_space(dm, ob, from, to); - - mdisps = CustomData_get_layer(&dm->loopData, CD_MDISPS); - - BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) { - BMLoop *l; - BMIter liter; - BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) { - MDisps *lmd = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_MDISPS); - - if (!lmd->disps) { - printf("%s: warning - 'lmd->disps' == NULL\n", __func__); - } - - if (lmd->disps && lmd->totdisp == mdisps->totdisp) { - memcpy(lmd->disps, mdisps->disps, sizeof(float) * 3 * lmd->totdisp); - } - else if (mdisps->disps) { - if (lmd->disps) - MEM_freeN(lmd->disps); - - lmd->disps = MEM_dupallocN(mdisps->disps); - lmd->totdisp = mdisps->totdisp; - lmd->level = mdisps->level; - } - - mdisps++; - // i += 1; - } - } - - dm->needsFree = 1; - dm->release(dm); - - /* setting this to NULL prevents BKE_editmesh_free from freeing it */ - em->bm = NULL; - BKE_editmesh_free(em); - MEM_freeN(em); - } -} - /** * \brief BMesh Begin Edit * diff --git a/source/blender/bmesh/intern/bmesh_mesh_conv.c b/source/blender/bmesh/intern/bmesh_mesh_conv.c index 5ba3f149689..00bb0110e74 100644 --- a/source/blender/bmesh/intern/bmesh_mesh_conv.c +++ b/source/blender/bmesh/intern/bmesh_mesh_conv.c @@ -548,8 +548,12 @@ BLI_INLINE void bmesh_quick_edgedraw_flag(MEdge *med, BMEdge *e) } } +/** + * + * \param bmain May be NULL in case \a calc_object_remap parameter option is set. + */ void BM_mesh_bm_to_me( - BMesh *bm, Mesh *me, + Main *bmain, BMesh *bm, Mesh *me, const struct BMeshToMeshParams *params) { MLoop *mloop; @@ -710,11 +714,12 @@ void BM_mesh_bm_to_me( /* patch hook indices and vertex parents */ if (params->calc_object_remap && (ototvert > 0)) { + BLI_assert(bmain != NULL); Object *ob; ModifierData *md; BMVert **vertMap = NULL; - for (ob = G.main->object.first; ob; ob = ob->id.next) { + for (ob = bmain->object.first; ob; ob = ob->id.next) { if ((ob->parent) && (ob->parent->data == me) && ELEM(ob->partype, PARVERT1, PARVERT3)) { if (vertMap == NULL) { diff --git a/source/blender/bmesh/intern/bmesh_mesh_conv.h b/source/blender/bmesh/intern/bmesh_mesh_conv.h index 6e9d62349ea..008960e7f6e 100644 --- a/source/blender/bmesh/intern/bmesh_mesh_conv.h +++ b/source/blender/bmesh/intern/bmesh_mesh_conv.h @@ -32,6 +32,7 @@ * \ingroup bmesh */ +struct Main; struct Mesh; void BM_mesh_cd_validate(BMesh *bm); @@ -60,8 +61,8 @@ struct BMeshToMeshParams { int64_t cd_mask_extra; }; void BM_mesh_bm_to_me( - BMesh *bm, struct Mesh *me, + struct Main *bmain, BMesh *bm, struct Mesh *me, const struct BMeshToMeshParams *params) -ATTR_NONNULL(1, 2, 3); +ATTR_NONNULL(2, 3, 4); #endif /* __BMESH_MESH_CONV_H__ */ diff --git a/source/blender/bmesh/intern/bmesh_polygon_edgenet.c b/source/blender/bmesh/intern/bmesh_polygon_edgenet.c index 85dfd3f58e2..4703dbf3bcd 100644 --- a/source/blender/bmesh/intern/bmesh_polygon_edgenet.c +++ b/source/blender/bmesh/intern/bmesh_polygon_edgenet.c @@ -1051,6 +1051,16 @@ static int bm_face_split_edgenet_find_connection( #ifdef USE_PARTIAL_CONNECT /** + * Used to identify edges that get split off when making island from partial connection. + * fptr should be a BMFace*, but is a void* for general interface to BM_vert_separate_tested_edges + */ +static bool test_tagged_and_notface(BMEdge *e, void *fptr) +{ + BMFace *f = (BMFace *)fptr; + return BM_elem_flag_test(e, BM_ELEM_INTERNAL_TAG) && !BM_edge_in_face(e, f); +} + +/** * Split vertices which are part of a partial connection * (only a single vertex connecting an island). * @@ -1058,7 +1068,7 @@ static int bm_face_split_edgenet_find_connection( * This function leaves all the flags set as well. * */ -static BMVert *bm_face_split_edgenet_partial_connect(BMesh *bm, BMVert *v_delimit) +static BMVert *bm_face_split_edgenet_partial_connect(BMesh *bm, BMVert *v_delimit, BMFace *f) { /* -------------------------------------------------------------------- */ /* Initial check that we may be a delimiting vert (keep this fast) */ @@ -1084,7 +1094,7 @@ static BMVert *bm_face_split_edgenet_partial_connect(BMesh *bm, BMVert *v_delimi BLI_assert(BM_elem_flag_test(BM_edge_other_vert(e_iter, v_delimit), VERT_NOT_IN_STACK)); BLI_linklist_prepend_alloca(&e_delimit_list, e_iter); e_delimit_list_len++; - if (e_iter->l != NULL) { + if (e_iter->l != NULL && BM_edge_in_face(e_iter, f)) { e_face_init = e_iter; } } @@ -1133,7 +1143,7 @@ static BMVert *bm_face_split_edgenet_partial_connect(BMesh *bm, BMVert *v_delimi bool is_delimit = false; FOREACH_VERT_EDGE(v_delimit, e_iter, { BMVert *v_step = BM_edge_other_vert(e_iter, v_delimit); - if (BM_elem_flag_test(v_step, VERT_NOT_IN_STACK) && BM_edge_is_wire(e_iter)) { + if (BM_elem_flag_test(v_step, VERT_NOT_IN_STACK) && !BM_edge_in_face(e_iter, f)) { is_delimit = true; /* if one vertex is valid - we have a mix */ } else { @@ -1148,7 +1158,7 @@ static BMVert *bm_face_split_edgenet_partial_connect(BMesh *bm, BMVert *v_delimi BMVert *v_split = NULL; if (is_delimit) { v_split = BM_vert_create(bm, v_delimit->co, NULL, 0); - BM_vert_separate_wire_hflag(bm, v_split, v_delimit, EDGE_NOT_IN_STACK); + BM_vert_separate_tested_edges(bm, v_split, v_delimit, test_tagged_and_notface, f); BM_elem_flag_enable(v_split, VERT_NOT_IN_STACK); BLI_assert(v_delimit->e != NULL); @@ -1224,6 +1234,7 @@ bool BM_face_split_edgenet_connect_islands( const uint edge_arr_len = (uint)edge_net_init_len + (uint)f->len; BMEdge **edge_arr = BLI_array_alloca(edge_arr, edge_arr_len); bool ok = false; + uint edge_net_new_len = (uint)edge_net_init_len; memcpy(edge_arr, edge_net_init, sizeof(*edge_arr) * (size_t)edge_net_init_len); @@ -1272,7 +1283,7 @@ bool BM_face_split_edgenet_connect_islands( BMVert *v_other; /* note, remapping will _never_ map a vertex to an already mapped vertex */ - while (UNLIKELY((v_other = bm_face_split_edgenet_partial_connect(bm, v_delimit)))) { + while (UNLIKELY((v_other = bm_face_split_edgenet_partial_connect(bm, v_delimit, f)))) { struct TempVertPair *tvp = BLI_memarena_alloc(mem_arena, sizeof(*tvp)); tvp->next = temp_vert_pairs.list; tvp->v_orig = v_delimit; @@ -1509,7 +1520,7 @@ bool BM_face_split_edgenet_connect_islands( /* Create connections between groups */ /* may be an over-alloc, but not by much */ - uint edge_net_new_len = (uint)edge_net_init_len + ((group_arr_len - 1) * 2); + edge_net_new_len = (uint)edge_net_init_len + ((group_arr_len - 1) * 2); BMEdge **edge_net_new = BLI_memarena_alloc(mem_arena, sizeof(*edge_net_new) * edge_net_new_len); memcpy(edge_net_new, edge_net_init, sizeof(*edge_net_new) * (size_t)edge_net_init_len); diff --git a/source/blender/bmesh/operators/bmo_mesh_conv.c b/source/blender/bmesh/operators/bmo_mesh_conv.c index 7311ed5ce64..cc1f45baf0c 100644 --- a/source/blender/bmesh/operators/bmo_mesh_conv.c +++ b/source/blender/bmesh/operators/bmo_mesh_conv.c @@ -38,6 +38,7 @@ #include "bmesh.h" #include "intern/bmesh_operators_private.h" +#include "BKE_global.h" void bmo_mesh_to_bmesh_exec(BMesh *bm, BMOperator *op) { @@ -72,7 +73,7 @@ void bmo_bmesh_to_mesh_exec(BMesh *bm, BMOperator *op) /* Object *ob = BMO_slot_ptr_get(op, "object"); */ BM_mesh_bm_to_me( - bm, me, + G.main, bm, me, (&(struct BMeshToMeshParams){ .calc_object_remap = true, })); diff --git a/source/blender/bmesh/tools/bmesh_intersect.c b/source/blender/bmesh/tools/bmesh_intersect.c index cc8511c65f1..a35bb81a1c2 100644 --- a/source/blender/bmesh/tools/bmesh_intersect.c +++ b/source/blender/bmesh/tools/bmesh_intersect.c @@ -237,7 +237,7 @@ static void face_edges_add( #ifdef USE_NET static void face_edges_split( BMesh *bm, BMFace *f, struct LinkBase *e_ls_base, - bool use_island_connect, + bool use_island_connect, bool use_partial_connect, MemArena *mem_arena_edgenet) { uint i; @@ -262,7 +262,7 @@ static void face_edges_split( if (BM_face_split_edgenet_connect_islands( bm, f, edge_arr, edge_arr_len, - false, + use_partial_connect, mem_arena_edgenet, &edge_arr_holes, &edge_arr_holes_len)) { @@ -980,7 +980,7 @@ bool BM_mesh_intersect( struct BMLoop *(*looptris)[3], const int looptris_tot, int (*test_fn)(BMFace *f, void *user_data), void *user_data, const bool use_self, const bool use_separate, const bool use_dissolve, const bool use_island_connect, - const bool use_edge_tag, const int boolean_mode, + const bool use_partial_connect, const bool use_edge_tag, const int boolean_mode, const float eps) { struct ISectState s; @@ -1223,7 +1223,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) && @@ -1491,7 +1491,7 @@ bool BM_mesh_intersect( BLI_assert(BM_elem_index_get(f) == f_index); - face_edges_split(bm, f, e_ls_base, use_island_connect, mem_arena_edgenet); + face_edges_split(bm, f, e_ls_base, use_island_connect, use_partial_connect, mem_arena_edgenet); BLI_memarena_clear(mem_arena_edgenet); } diff --git a/source/blender/bmesh/tools/bmesh_intersect.h b/source/blender/bmesh/tools/bmesh_intersect.h index 51926a01710..82910a5df80 100644 --- a/source/blender/bmesh/tools/bmesh_intersect.h +++ b/source/blender/bmesh/tools/bmesh_intersect.h @@ -30,7 +30,7 @@ bool BM_mesh_intersect( struct BMLoop *(*looptris)[3], const int looptris_tot, int (*test_fn)(BMFace *f, void *user_data), void *user_data, const bool use_self, const bool use_separate, const bool use_dissolve, const bool use_island_connect, - const bool use_edge_tag, const int boolean_mode, + const bool use_partial_connect, const bool use_edge_tag, const int boolean_mode, const float eps); enum { diff --git a/source/blender/collada/AnimationExporter.cpp b/source/blender/collada/AnimationExporter.cpp index 95298986f5a..ab53e282476 100644 --- a/source/blender/collada/AnimationExporter.cpp +++ b/source/blender/collada/AnimationExporter.cpp @@ -34,9 +34,10 @@ void forEachObjectInExportSet(Scene *sce, Functor &f, LinkNode *export_set) } } -bool AnimationExporter::exportAnimations(Scene *sce) +bool AnimationExporter::exportAnimations(Main *bmain, Scene *sce) { bool has_animations = hasAnimations(sce); + m_bmain = bmain; if (has_animations) { this->scene = sce; @@ -214,7 +215,7 @@ void AnimationExporter::export_sampled_matrix_animation(Object *ob, std::vector< for (std::vector<float>::iterator ctime = ctimes.begin(); ctime != ctimes.end(); ++ctime) { float fmat[4][4]; - bc_update_scene(depsgraph, scene, *ctime); + bc_update_scene(m_bmain, depsgraph, scene, *ctime); BKE_object_matrix_local_get(ob, fmat); if (this->export_settings->limit_precision) bc_sanitize_mat(fmat, 6); @@ -246,7 +247,7 @@ void AnimationExporter::export_sampled_transrotloc_animation(Object *ob, std::ve float fsize[3]; float feul[3]; - bc_update_scene(depsgraph, scene, *ctime); + bc_update_scene(m_bmain, depsgraph, scene, *ctime); BKE_object_matrix_local_get(ob, fmat); mat4_decompose(floc, fquat, fsize, fmat); quat_to_eul(feul, fquat); @@ -1315,7 +1316,7 @@ std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Obj float frame = *it; float ctime = BKE_scene_frame_get_from_ctime(scene, frame); - bc_update_scene(depsgraph, scene, ctime); + bc_update_scene(m_bmain, depsgraph, scene, ctime); if (is_bone_animation) { if (pchan->flag & POSE_CHAIN) { diff --git a/source/blender/collada/AnimationExporter.h b/source/blender/collada/AnimationExporter.h index a50bcaf0ef4..67468458f81 100644 --- a/source/blender/collada/AnimationExporter.h +++ b/source/blender/collada/AnimationExporter.h @@ -84,6 +84,7 @@ struct Depsgraph; class AnimationExporter: COLLADASW::LibraryAnimations { private: + Main *m_bmain; Scene *scene; Depsgraph *depsgraph; COLLADASW::StreamWriter *sw; @@ -98,7 +99,8 @@ public: this->sw = sw; } - bool exportAnimations(Scene *sce); + bool exportAnimations(Main *bmain, Scene *sce); + // called for each exported object void operator() (Object *ob); diff --git a/source/blender/collada/ArmatureImporter.cpp b/source/blender/collada/ArmatureImporter.cpp index 19f174d4840..2f5c3237bf6 100644 --- a/source/blender/collada/ArmatureImporter.cpp +++ b/source/blender/collada/ArmatureImporter.cpp @@ -55,8 +55,10 @@ static const char *bc_get_joint_name(T *node) } -ArmatureImporter::ArmatureImporter(UnitConverter *conv, MeshImporterBase *mesh, Scene *sce, ViewLayer *view_layer, const ImportSettings *import_settings) : +ArmatureImporter::ArmatureImporter( + UnitConverter *conv, MeshImporterBase *mesh, Main *bmain, Scene *sce, ViewLayer *view_layer, const ImportSettings *import_settings) : TransformReader(conv), + m_bmain(bmain), scene(sce), view_layer(view_layer), unit_converter(conv), @@ -411,7 +413,7 @@ Object *ArmatureImporter::get_empty_for_leaves() { if (empty) return empty; - empty = bc_add_object(scene, view_layer, OB_EMPTY, NULL); + empty = bc_add_object(m_bmain, scene, view_layer, OB_EMPTY, NULL); empty->empty_drawtype = OB_EMPTY_SPHERE; return empty; @@ -586,7 +588,7 @@ Object *ArmatureImporter::create_armature_bones(Main *bmain, SkinInfo& skin) ob_arm = skin.set_armature(shared); } else { - ob_arm = skin.create_armature(scene, view_layer); //once for every armature + ob_arm = skin.create_armature(m_bmain, scene, view_layer); //once for every armature } // enter armature edit mode @@ -856,8 +858,9 @@ bool ArmatureImporter::write_controller(const COLLADAFW::Controller *controller) return true; } -void ArmatureImporter::make_shape_keys() +void ArmatureImporter::make_shape_keys(bContext *C) { + Main *bmain = CTX_data_main(C); std::vector<COLLADAFW::MorphController *>::iterator mc; float weight; @@ -873,7 +876,7 @@ void ArmatureImporter::make_shape_keys() Mesh *source_me = (Mesh *)source_ob->data; //insert key to source mesh - Key *key = source_me->key = BKE_key_add((ID *)source_me); + Key *key = source_me->key = BKE_key_add(bmain, (ID *)source_me); key->type = KEY_RELATIVE; KeyBlock *kb; diff --git a/source/blender/collada/ArmatureImporter.h b/source/blender/collada/ArmatureImporter.h index b13e40bf855..419861554f4 100644 --- a/source/blender/collada/ArmatureImporter.h +++ b/source/blender/collada/ArmatureImporter.h @@ -62,6 +62,7 @@ extern "C" { class ArmatureImporter : private TransformReader { private: + Main *m_bmain; Scene *scene; ViewLayer *view_layer; UnitConverter *unit_converter; @@ -138,7 +139,8 @@ private: TagsMap uid_tags_map; public: - ArmatureImporter(UnitConverter *conv, MeshImporterBase *mesh, Scene *sce, ViewLayer *view_layer, const ImportSettings *import_settings); + ArmatureImporter( + UnitConverter *conv, MeshImporterBase *mesh, Main *bmain, Scene *sce, ViewLayer *view_layer, const ImportSettings *import_settings); ~ArmatureImporter(); void add_root_joint(COLLADAFW::Node *node, Object *parent); @@ -146,7 +148,7 @@ public: // here we add bones to armatures, having armatures previously created in write_controller void make_armatures(bContext *C, std::vector<Object *> &objects_to_scale); - void make_shape_keys(); + void make_shape_keys(bContext *C); #if 0 // link with meshes, create vertex groups, assign weights diff --git a/source/blender/collada/ControllerExporter.cpp b/source/blender/collada/ControllerExporter.cpp index 122094e33a6..6cb1e58db6e 100644 --- a/source/blender/collada/ControllerExporter.cpp +++ b/source/blender/collada/ControllerExporter.cpp @@ -104,9 +104,10 @@ bool ControllerExporter::add_instance_controller(Object *ob) return true; } -void ControllerExporter::export_controllers(struct Depsgraph *depsgraph, Scene *sce) +void ControllerExporter::export_controllers(Main *bmain, Depsgraph *depsgraph, Scene *sce) { this->depsgraph = depsgraph; + m_bmain = bmain; scene = sce; openLibrary(); @@ -198,7 +199,10 @@ void ControllerExporter::export_skin_controller(Object *ob, Object *ob_arm) bool use_instantiation = this->export_settings->use_object_instantiation; Mesh *me; - me = bc_get_mesh_copy(depsgraph, scene, + me = bc_get_mesh_copy( + m_bmain, + depsgraph, + scene, ob, this->export_settings->export_mesh_type, this->export_settings->apply_modifiers, @@ -289,7 +293,7 @@ void ControllerExporter::export_skin_controller(Object *ob, Object *ob_arm) add_joints_element(&ob->defbase, joints_source_id, inv_bind_mat_source_id); add_vertex_weights_element(weights_source_id, joints_source_id, vcounts, joints); - BKE_libblock_free_us(G.main, me); + BKE_libblock_free_us(m_bmain, me); closeSkin(); closeController(); @@ -300,7 +304,10 @@ void ControllerExporter::export_morph_controller(Object *ob, Key *key) bool use_instantiation = this->export_settings->use_object_instantiation; Mesh *me; - me = bc_get_mesh_copy(depsgraph, scene, + me = bc_get_mesh_copy( + m_bmain, + depsgraph, + scene, ob, this->export_settings->export_mesh_type, this->export_settings->apply_modifiers, @@ -325,7 +332,7 @@ void ControllerExporter::export_morph_controller(Object *ob, Key *key) COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, morph_weights_id))); targets.add(); - BKE_libblock_free_us(G.main, me); + BKE_libblock_free_us(m_bmain, me); //support for animations diff --git a/source/blender/collada/ControllerExporter.h b/source/blender/collada/ControllerExporter.h index e13d7c7ebea..2b6853901be 100644 --- a/source/blender/collada/ControllerExporter.h +++ b/source/blender/collada/ControllerExporter.h @@ -66,12 +66,13 @@ public: bool add_instance_controller(Object *ob); - void export_controllers(struct Depsgraph *depsgraph, Scene *sce); + void export_controllers(Main *bmain, Depsgraph *depsgraph, Scene *sce); void operator()(Object *ob); private: - struct Depsgraph *depsgraph; + Depsgraph *depsgraph; + Main *m_bmain; Scene *scene; UnitConverter converter; const ExportSettings *export_settings; diff --git a/source/blender/collada/DocumentExporter.cpp b/source/blender/collada/DocumentExporter.cpp index 9e78c164dad..541f84f96f5 100644 --- a/source/blender/collada/DocumentExporter.cpp +++ b/source/blender/collada/DocumentExporter.cpp @@ -168,7 +168,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 = @@ -182,6 +182,7 @@ static COLLADABU::NativeString make_temp_filepath(const char *name, const char * int DocumentExporter::exportCurrentScene(bContext *C, Scene *sce) { + Main *bmain = CTX_data_main(C); PointerRNA sceneptr, unit_settings; PropertyRNA *system; /* unused , *scale; */ @@ -286,7 +287,7 @@ int DocumentExporter::exportCurrentScene(bContext *C, Scene *sce) // <library_geometries> if (bc_has_object_type(export_set, OB_MESH)) { GeometryExporter ge(writer, this->export_settings); - ge.exportGeom(depsgraph, sce); + ge.exportGeom(bmain, depsgraph, sce); } // <library_controllers> @@ -294,7 +295,7 @@ int DocumentExporter::exportCurrentScene(bContext *C, Scene *sce) ControllerExporter controller_exporter(writer, this->export_settings); if (bc_has_object_type(export_set, OB_ARMATURE) || this->export_settings->include_shapekeys) { - controller_exporter.export_controllers(depsgraph, sce); + controller_exporter.export_controllers(bmain, depsgraph, sce); } // <library_visual_scenes> @@ -304,7 +305,7 @@ int DocumentExporter::exportCurrentScene(bContext *C, Scene *sce) if (this->export_settings->include_animations) { // <library_animations> AnimationExporter ae(depsgraph, writer, this->export_settings); - ae.exportAnimations(sce); + ae.exportAnimations(bmain, sce); } se.exportScene(C, depsgraph, sce); diff --git a/source/blender/collada/DocumentImporter.cpp b/source/blender/collada/DocumentImporter.cpp index aab5a4ecfa9..c6ba3b8f4ac 100644 --- a/source/blender/collada/DocumentImporter.cpp +++ b/source/blender/collada/DocumentImporter.cpp @@ -108,8 +108,8 @@ DocumentImporter::DocumentImporter(bContext *C, const ImportSettings *import_set mImportStage(General), mContext(C), view_layer(CTX_data_view_layer(mContext)), - armature_importer(&unit_converter, &mesh_importer, CTX_data_scene(C), view_layer, import_settings), - mesh_importer(&unit_converter, &armature_importer, CTX_data_scene(C), view_layer), + armature_importer(&unit_converter, &mesh_importer, CTX_data_main(C), CTX_data_scene(C), view_layer, import_settings), + mesh_importer(&unit_converter, &armature_importer, CTX_data_main(C), CTX_data_scene(C), view_layer), anim_importer(&unit_converter, &armature_importer, CTX_data_scene(C)) { } @@ -244,7 +244,7 @@ void DocumentImporter::finish() armature_importer.set_tags_map(this->uid_tags_map); armature_importer.make_armatures(mContext, *objects_to_scale); - armature_importer.make_shape_keys(); + armature_importer.make_shape_keys(mContext); DEG_relations_tag_update(bmain); #if 0 @@ -266,7 +266,7 @@ void DocumentImporter::finish() std::vector<Object *>::iterator it; for (it = libnode_ob.begin(); it != libnode_ob.end(); it++) { Object *ob = *it; - BKE_scene_collections_object_remove(G.main, sce, ob, true); + BKE_scene_collections_object_remove(bmain, sce, ob, true); } libnode_ob.clear(); @@ -379,11 +379,12 @@ Object *DocumentImporter::create_camera_object(COLLADAFW::InstanceCamera *camera return NULL; } - Object *ob = bc_add_object(sce, view_layer, OB_CAMERA, NULL); + Main *bmain = CTX_data_main(mContext); + Object *ob = bc_add_object(bmain, sce, view_layer, OB_CAMERA, NULL); Camera *cam = uid_camera_map[cam_uid]; Camera *old_cam = (Camera *)ob->data; ob->data = cam; - BKE_libblock_free_us(G.main, old_cam); + BKE_libblock_free_us(bmain, old_cam); return ob; } @@ -395,11 +396,12 @@ Object *DocumentImporter::create_lamp_object(COLLADAFW::InstanceLight *lamp, Sce return NULL; } - Object *ob = bc_add_object(sce, view_layer, OB_LAMP, NULL); + Main *bmain = CTX_data_main(mContext); + Object *ob = bc_add_object(bmain, sce, view_layer, OB_LAMP, NULL); Lamp *la = uid_lamp_map[lamp_uid]; Lamp *old_lamp = (Lamp *)ob->data; ob->data = la; - BKE_libblock_free_us(G.main, old_lamp); + BKE_libblock_free_us(bmain, old_lamp); return ob; } @@ -407,9 +409,10 @@ Object *DocumentImporter::create_instance_node(Object *source_ob, COLLADAFW::Nod { fprintf(stderr, "create <instance_node> under node id=%s from node id=%s\n", instance_node ? instance_node->getOriginalId().c_str() : NULL, source_node ? source_node->getOriginalId().c_str() : NULL); - Object *obn = BKE_object_copy(G.main, source_ob); + Main *bmain = CTX_data_main(mContext); + Object *obn = BKE_object_copy(bmain, source_ob); DEG_id_tag_update(&obn->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); - BKE_collection_object_add_from(G.main, sce, source_ob, obn); + BKE_collection_object_add_from(bmain, sce, source_ob, obn); if (instance_node) { anim_importer.read_node_transform(instance_node, obn); @@ -490,6 +493,7 @@ void DocumentImporter::report_unknown_reference(const COLLADAFW::Node &node, con std::vector<Object *> *DocumentImporter::write_node(COLLADAFW::Node *node, COLLADAFW::Node *parent_node, Scene *sce, Object *par, bool is_library_node) { + Main *bmain = CTX_data_main(mContext); Object *ob = NULL; bool is_joint = node->getType() == COLLADAFW::Node::JOINT; bool read_transform = true; @@ -511,7 +515,7 @@ std::vector<Object *> *DocumentImporter::write_node(COLLADAFW::Node *node, COLLA if (parent_node == NULL && !is_library_node) { // A Joint on root level is a skeleton without root node. // Here we add the armature "on the fly": - par = bc_add_object(sce, view_layer, OB_ARMATURE, std::string("Armature").c_str()); + par = bc_add_object(bmain, sce, view_layer, OB_ARMATURE, std::string("Armature").c_str()); objects_done->push_back(par); root_objects->push_back(par); object_map.insert(std::pair<COLLADAFW::UniqueId, Object *>(node->getUniqueId(), par)); @@ -624,10 +628,10 @@ std::vector<Object *> *DocumentImporter::write_node(COLLADAFW::Node *node, COLLA if ( (geom_done + camera_done + lamp_done + controller_done + inst_done) < 1) { //Check if Object is armature, by checking if immediate child is a JOINT node. if (is_armature(node)) { - ob = bc_add_object(sce, view_layer, OB_ARMATURE, name.c_str()); + ob = bc_add_object(bmain, sce, view_layer, OB_ARMATURE, name.c_str()); } else { - ob = bc_add_object(sce, view_layer, OB_EMPTY, NULL); + ob = bc_add_object(bmain, sce, view_layer, OB_EMPTY, NULL); } objects_done->push_back(ob); if (parent_node == NULL) { @@ -644,7 +648,7 @@ std::vector<Object *> *DocumentImporter::write_node(COLLADAFW::Node *node, COLLA for (std::vector<Object *>::iterator it = objects_done->begin(); it != objects_done->end(); ++it) { ob = *it; std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId(); - BKE_libblock_rename(G.main, &ob->id, (char *)nodename.c_str()); + BKE_libblock_rename(bmain, &ob->id, (char *)nodename.c_str()); object_map.insert(std::pair<COLLADAFW::UniqueId, Object *>(node->getUniqueId(), ob)); node_map[node->getUniqueId()] = node; @@ -754,8 +758,9 @@ bool DocumentImporter::writeMaterial(const COLLADAFW::Material *cmat) if (mImportStage != General) return true; + Main *bmain = CTX_data_main(mContext); const std::string& str_mat_id = cmat->getName().size() ? cmat->getName() : cmat->getOriginalId(); - Material *ma = BKE_material_add(G.main, (char *)str_mat_id.c_str()); + Material *ma = BKE_material_add(bmain, (char *)str_mat_id.c_str()); this->uid_effect_map[cmat->getInstantiatedEffect()] = ma; this->uid_material_map[cmat->getUniqueId()] = ma; @@ -940,14 +945,15 @@ bool DocumentImporter::writeCamera(const COLLADAFW::Camera *camera) if (mImportStage != General) return true; + Main *bmain = CTX_data_main(mContext); Camera *cam = NULL; std::string cam_id, cam_name; ExtraTags *et=getExtraTags(camera->getUniqueId()); cam_id = camera->getOriginalId(); cam_name = camera->getName(); - if (cam_name.size()) cam = (Camera *)BKE_camera_add(G.main, (char *)cam_name.c_str()); - else cam = (Camera *)BKE_camera_add(G.main, (char *)cam_id.c_str()); + if (cam_name.size()) cam = (Camera *)BKE_camera_add(bmain, (char *)cam_name.c_str()); + else cam = (Camera *)BKE_camera_add(bmain, (char *)cam_id.c_str()); if (!cam) { fprintf(stderr, "Cannot create camera.\n"); @@ -1102,6 +1108,7 @@ bool DocumentImporter::writeLight(const COLLADAFW::Light *light) if (mImportStage != General) return true; + Main *bmain = CTX_data_main(mContext); Lamp *lamp = NULL; std::string la_id, la_name; @@ -1114,8 +1121,8 @@ bool DocumentImporter::writeLight(const COLLADAFW::Light *light) la_id = light->getOriginalId(); la_name = light->getName(); - if (la_name.size()) lamp = (Lamp *)BKE_lamp_add(G.main, (char *)la_name.c_str()); - else lamp = (Lamp *)BKE_lamp_add(G.main, (char *)la_id.c_str()); + if (la_name.size()) lamp = (Lamp *)BKE_lamp_add(bmain, (char *)la_name.c_str()); + else lamp = (Lamp *)BKE_lamp_add(bmain, (char *)la_id.c_str()); if (!lamp) { fprintf(stderr, "Cannot create lamp.\n"); diff --git a/source/blender/collada/GeometryExporter.cpp b/source/blender/collada/GeometryExporter.cpp index 65e844cbe50..f59be97b545 100644 --- a/source/blender/collada/GeometryExporter.cpp +++ b/source/blender/collada/GeometryExporter.cpp @@ -57,11 +57,12 @@ GeometryExporter::GeometryExporter(COLLADASW::StreamWriter *sw, const ExportSett { } -void GeometryExporter::exportGeom(struct Depsgraph *depsgraph, Scene *sce) +void GeometryExporter::exportGeom(Main *bmain, struct Depsgraph *depsgraph, Scene *sce) { openLibrary(); mDepsgraph = depsgraph; + m_bmain = bmain; mScene = sce; GeometryFunctor gf; gf.forEachMeshObjectInExportSet<GeometryExporter>(sce, *this, this->export_settings->export_set); @@ -77,7 +78,10 @@ void GeometryExporter::operator()(Object *ob) #endif bool use_instantiation = this->export_settings->use_object_instantiation; - Mesh *me = bc_get_mesh_copy(mDepsgraph, mScene, + Mesh *me = bc_get_mesh_copy( + m_bmain, + mDepsgraph, + mScene, ob, this->export_settings->export_mesh_type, this->export_settings->apply_modifiers, @@ -166,7 +170,7 @@ void GeometryExporter::operator()(Object *ob) } } - BKE_libblock_free_us(G.main, me); + BKE_libblock_free_us(m_bmain, me); } diff --git a/source/blender/collada/GeometryExporter.h b/source/blender/collada/GeometryExporter.h index b0cd650adcd..5d74124b07a 100644 --- a/source/blender/collada/GeometryExporter.h +++ b/source/blender/collada/GeometryExporter.h @@ -75,12 +75,13 @@ class GeometryExporter : COLLADASW::LibraryGeometries Normal n; struct Depsgraph *mDepsgraph; + Main *m_bmain; Scene *mScene; public: GeometryExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings); - void exportGeom(struct Depsgraph *depsgraph, Scene *sce); + void exportGeom(Main *bmain, Depsgraph *depsgraph, Scene *sce); void operator()(Object *ob); diff --git a/source/blender/collada/MeshImporter.cpp b/source/blender/collada/MeshImporter.cpp index e95f8ed0888..4a8fca6d3cd 100644 --- a/source/blender/collada/MeshImporter.cpp +++ b/source/blender/collada/MeshImporter.cpp @@ -207,8 +207,9 @@ void VCOLDataWrapper::get_vcol(int v_index, MLoopCol *mloopcol) } -MeshImporter::MeshImporter(UnitConverter *unitconv, ArmatureImporter *arm, Scene *sce, ViewLayer *view_layer): +MeshImporter::MeshImporter(UnitConverter *unitconv, ArmatureImporter *arm, Main *bmain, Scene *sce, ViewLayer *view_layer): unitconverter(unitconv), + m_bmain(bmain), scene(sce), view_layer(view_layer), armature_importer(arm) { @@ -1035,7 +1036,7 @@ void MeshImporter::assign_material_to_geom( // Attention! This temporaly assigns material to object on purpose! // See note above. ob->actcol=0; - assign_material(G.main, ob, ma, mat_index + 1, BKE_MAT_ASSIGN_OBJECT); + assign_material(m_bmain, ob, ma, mat_index + 1, BKE_MAT_ASSIGN_OBJECT); MaterialIdPrimitiveArrayMap& mat_prim_map = geom_uid_mat_mapping_map[*geom_uid]; COLLADAFW::MaterialId mat_id = cmaterial.getMaterialId(); @@ -1090,7 +1091,7 @@ Object *MeshImporter::create_mesh_object(COLLADAFW::Node *node, COLLADAFW::Insta const char *name = (id.length()) ? id.c_str() : NULL; // add object - Object *ob = bc_add_object(scene, view_layer, OB_MESH, name); + Object *ob = bc_add_object(m_bmain, scene, view_layer, OB_MESH, name); bc_set_mark(ob); // used later for material assignement optimization @@ -1102,11 +1103,11 @@ Object *MeshImporter::create_mesh_object(COLLADAFW::Node *node, COLLADAFW::Insta Mesh *old_mesh = (Mesh *)ob->data; Mesh *new_mesh = uid_mesh_map[*geom_uid]; - BKE_mesh_assign_object(G.main, ob, new_mesh); + BKE_mesh_assign_object(m_bmain, ob, new_mesh); BKE_mesh_calc_normals(new_mesh); id_us_plus(&old_mesh->id); /* Because BKE_mesh_assign_object would have already decreased it... */ - BKE_libblock_free_us(G.main, old_mesh); + BKE_libblock_free_us(m_bmain, old_mesh); COLLADAFW::MaterialBindingArray& mat_array = geom->getMaterialBindings(); @@ -1145,7 +1146,7 @@ bool MeshImporter::write_geometry(const COLLADAFW::Geometry *geom) } const std::string& str_geom_id = mesh->getName().size() ? mesh->getName() : mesh->getOriginalId(); - Mesh *me = BKE_mesh_add(G.main, (char *)str_geom_id.c_str()); + Mesh *me = BKE_mesh_add(m_bmain, (char *)str_geom_id.c_str()); id_us_min(&me->id); // is already 1 here, but will be set later in BKE_mesh_assign_object // store the Mesh pointer to link it later with an Object diff --git a/source/blender/collada/MeshImporter.h b/source/blender/collada/MeshImporter.h index c98126916d7..4583242808b 100644 --- a/source/blender/collada/MeshImporter.h +++ b/source/blender/collada/MeshImporter.h @@ -90,6 +90,7 @@ private: UnitConverter *unitconverter; + Main *m_bmain; Scene *scene; ViewLayer *view_layer; @@ -160,7 +161,7 @@ private: public: - MeshImporter(UnitConverter *unitconv, ArmatureImporter *arm, Scene *sce, ViewLayer *view_layer); + MeshImporter(UnitConverter *unitconv, ArmatureImporter *arm, Main *bmain, Scene *sce, ViewLayer *view_layer); virtual Object *get_object_by_geom_uid(const COLLADAFW::UniqueId& geom_uid); diff --git a/source/blender/collada/SkinInfo.cpp b/source/blender/collada/SkinInfo.cpp index 7ec3f04aabf..b07c6518050 100644 --- a/source/blender/collada/SkinInfo.cpp +++ b/source/blender/collada/SkinInfo.cpp @@ -159,9 +159,9 @@ void SkinInfo::set_controller(const COLLADAFW::SkinController *co) } // called from write_controller -Object *SkinInfo::create_armature(Scene *scene, ViewLayer *view_layer) +Object *SkinInfo::create_armature(Main *bmain, Scene *scene, ViewLayer *view_layer) { - ob_arm = bc_add_object(scene, view_layer, OB_ARMATURE, NULL); + ob_arm = bc_add_object(bmain, scene, view_layer, OB_ARMATURE, NULL); return ob_arm; } diff --git a/source/blender/collada/SkinInfo.h b/source/blender/collada/SkinInfo.h index fdfee0a943a..39808c546b1 100644 --- a/source/blender/collada/SkinInfo.h +++ b/source/blender/collada/SkinInfo.h @@ -99,7 +99,7 @@ public: void set_controller(const COLLADAFW::SkinController* co); // called from write_controller - Object *create_armature(Scene *scene, ViewLayer *view_layer); + Object *create_armature(Main *bmain, Scene *scene, ViewLayer *view_layer); Object* set_armature(Object *ob_arm); diff --git a/source/blender/collada/collada_utils.cpp b/source/blender/collada/collada_utils.cpp index 945dda68745..4ded9bd2d86 100644 --- a/source/blender/collada/collada_utils.cpp +++ b/source/blender/collada/collada_utils.cpp @@ -142,29 +142,22 @@ Scene *bc_get_scene(bContext *C) return CTX_data_scene(C); } -Main *bc_get_main() -{ - return G.main; -} - - -void bc_update_scene(Depsgraph *depsgraph, Scene *scene, float ctime) +void bc_update_scene(Main *bmain, Depsgraph *depsgraph, Scene *scene, float ctime) { BKE_scene_frame_set(scene, ctime); - Main *bmain = bc_get_main(); BKE_scene_graph_update_for_newframe(depsgraph, bmain); } -Object *bc_add_object(Scene *scene, ViewLayer *view_layer, int type, const char *name) +Object *bc_add_object(Main *bmain, Scene *scene, ViewLayer *view_layer, int type, const char *name) { - Object *ob = BKE_object_add_only_object(G.main, type, name); + Object *ob = BKE_object_add_only_object(bmain, type, name); - ob->data = BKE_object_obdata_add_from_type(G.main, type, name); + ob->data = BKE_object_obdata_add_from_type(bmain, type, name); ob->lay = scene->lay; DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); LayerCollection *layer_collection = BKE_layer_collection_get_active(view_layer); - BKE_collection_object_add(G.main, layer_collection->collection, ob); + BKE_collection_object_add(bmain, layer_collection->collection, ob); Base *base = BKE_view_layer_base_find(view_layer, ob); BKE_view_layer_base_select(view_layer, base); @@ -172,7 +165,8 @@ Object *bc_add_object(Scene *scene, ViewLayer *view_layer, int type, const char return ob; } -Mesh *bc_get_mesh_copy(struct Depsgraph *depsgraph, Scene *scene, Object *ob, BC_export_mesh_type export_mesh_type, bool apply_modifiers, bool triangulate) +Mesh *bc_get_mesh_copy( + Main *bmain, Depsgraph *depsgraph, Scene *scene, Object *ob, BC_export_mesh_type export_mesh_type, bool apply_modifiers, bool triangulate) { Mesh *tmpmesh; CustomDataMask mask = CD_MASK_MESH; @@ -196,7 +190,7 @@ Mesh *bc_get_mesh_copy(struct Depsgraph *depsgraph, Scene *scene, Object *ob, BC dm = mesh_create_derived((Mesh *)ob->data, NULL); } - tmpmesh = BKE_mesh_add(G.main, "ColladaMesh"); // name is not important here + tmpmesh = BKE_mesh_add(bmain, "ColladaMesh"); // name is not important here DM_to_mesh(dm, tmpmesh, ob, CD_MASK_MESH, true); tmpmesh->flag = mesh->flag; @@ -449,7 +443,8 @@ void bc_triangulate_mesh(Mesh *me) BM_mesh_triangulate(bm, quad_method, use_beauty, tag_only, NULL, NULL, NULL); BMeshToMeshParams bm_to_me_params = {0}; - BM_mesh_bm_to_me(bm, me, &bm_to_me_params); + bm_to_me_params.calc_object_remap = false; + BM_mesh_bm_to_me(NULL, bm, me, &bm_to_me_params); BM_mesh_free(bm); } diff --git a/source/blender/collada/collada_utils.h b/source/blender/collada/collada_utils.h index 20c569834d8..de9167efb07 100644 --- a/source/blender/collada/collada_utils.h +++ b/source/blender/collada/collada_utils.h @@ -65,15 +65,15 @@ struct Depsgraph; typedef std::map<COLLADAFW::TextureMapId, std::vector<MTex *> > TexIndexTextureArrayMap; extern Scene *bc_get_scene(bContext *C); -extern Main *bc_get_main(); extern Depsgraph *bc_get_depsgraph(); -extern void bc_update_scene(Depsgraph *depsgraph, Scene *scene, float ctime); +extern void bc_update_scene(Main *bmain, Depsgraph *depsgraph, Scene *scene, float ctime); extern float bc_get_float_value(const COLLADAFW::FloatOrDoubleArray& array, unsigned int index); extern int bc_test_parent_loop(Object *par, Object *ob); extern int bc_set_parent(Object *ob, Object *par, bContext *C, bool is_parent_space = true); -extern Object *bc_add_object(Scene *scene, ViewLayer *view_layer, int type, const char *name); -extern Mesh *bc_get_mesh_copy(struct Depsgraph *depsgraph, Scene *scene, Object *ob, BC_export_mesh_type export_mesh_type, bool apply_modifiers, bool triangulate); +extern Object *bc_add_object(Main *bmain, Scene *scene, ViewLayer *view_layer, int type, const char *name); +extern Mesh *bc_get_mesh_copy( + Main *bmain, Depsgraph *depsgraph, Scene *scene, Object *ob, BC_export_mesh_type export_mesh_type, bool apply_modifiers, bool triangulate); extern Object *bc_get_assigned_armature(Object *ob); extern Object *bc_get_highest_selected_ancestor_or_self(LinkNode *export_set, Object *ob); diff --git a/source/blender/compositor/intern/COM_ChunkOrder.h b/source/blender/compositor/intern/COM_ChunkOrder.h index 0310933e5c5..4728b771e3c 100644 --- a/source/blender/compositor/intern/COM_ChunkOrder.h +++ b/source/blender/compositor/intern/COM_ChunkOrder.h @@ -34,7 +34,7 @@ public: 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_CompositorContext.h b/source/blender/compositor/intern/COM_CompositorContext.h index d58e8502414..1c702503915 100644 --- a/source/blender/compositor/intern/COM_CompositorContext.h +++ b/source/blender/compositor/intern/COM_CompositorContext.h @@ -126,7 +126,7 @@ public: * @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 @@ public: 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 3d49443c146..58e0da04e5e 100644 --- a/source/blender/compositor/intern/COM_Converter.cpp +++ b/source/blender/compositor/intern/COM_Converter.cpp @@ -414,7 +414,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 +433,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 7ed5616d899..b57220351e8 100644 --- a/source/blender/compositor/intern/COM_Converter.h +++ b/source/blender/compositor/intern/COM_Converter.h @@ -50,14 +50,14 @@ public: * @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 @@ public: * @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 b95b7500cca..6179bd26275 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,12 +266,12 @@ 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) { @@ -279,13 +279,13 @@ bool DebugInfo::graphviz_system(const ExecutionSystem *system, char *str, int ma 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<NodeOperation *, std::vector<std::string> > 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 +302,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<std::string> &read_groups = op_groups[read]; std::vector<std::string> &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 +344,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 +367,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<std::string> &from_groups = op_groups[from_op]; std::vector<std::string> &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 +385,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 +399,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 4b4894d36cf..f5db93e8825 100644 --- a/source/blender/compositor/intern/COM_Debug.h +++ b/source/blender/compositor/intern/COM_Debug.h @@ -39,27 +39,27 @@ public: EG_RUNNING, EG_FINISHED } GroupState; - + typedef std::map<const Node *, std::string> NodeNameMap; typedef std::map<const NodeOperation *, std::string> OpNameMap; typedef std::map<const ExecutionGroup *, GroupState> 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 @@ protected: 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.h b/source/blender/compositor/intern/COM_Device.h index 62653357fdf..4ab6e1e2f96 100644 --- a/source/blender/compositor/intern/COM_Device.h +++ b/source/blender/compositor/intern/COM_Device.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 8a8193bcb62..5a651f07868 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 0f84dccb711..20ffbeaa357 100644 --- a/source/blender/compositor/intern/COM_ExecutionGroup.h +++ b/source/blender/compositor/intern/COM_ExecutionGroup.h @@ -65,89 +65,89 @@ typedef enum ChunkExecutionState { class ExecutionGroup { public: typedef std::vector<NodeOperation*> 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 @@ private: * - 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 @@ private: * @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 @@ private: * @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 @@ private: * @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 @@ private: public: // constructors ExecutionGroup(); - + // methods /** * @brief add an operation to this ExecutionGroup @@ -261,7 +261,7 @@ public: * @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 @@ public: * @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 @@ public: * @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 @@ public: * @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 @@ public: * @param memoryProxies result */ void determineDependingMemoryProxies(vector<MemoryProxy *> *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 8e8539e3016..07f7979629c 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<NodeOperation *>::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 2c67a5f7b7f..acde4a9b772 100644 --- a/source/blender/compositor/intern/COM_ExecutionSystem.h +++ b/source/blender/compositor/intern/COM_ExecutionSystem.h @@ -114,7 +114,7 @@ class ExecutionSystem { public: typedef std::vector<NodeOperation*> Operations; typedef std::vector<ExecutionGroup*> Groups; - + private: /** * @brief the context used during execution @@ -136,7 +136,7 @@ private: //methods * find all execution group with output nodes */ void findOutputExecutionGroup(vector<ExecutionGroup *> *result, CompositorPriority priority) const; - + /** * find all execution group with output nodes */ diff --git a/source/blender/compositor/intern/COM_MemoryBuffer.h b/source/blender/compositor/intern/COM_MemoryBuffer.h index 27baca0ab6f..be948b3e99b 100644 --- a/source/blender/compositor/intern/COM_MemoryBuffer.h +++ b/source/blender/compositor/intern/COM_MemoryBuffer.h @@ -64,29 +64,29 @@ private: * @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 @@ public: * @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 @@ public: * @brief destructor */ ~MemoryBuffer(); - + /** * @brief read the ChunkNumber of this MemoryBuffer */ @@ -134,7 +134,7 @@ public: * @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 @@ public: { 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 @@ public: x = (x >= 0.0f ? (x % w) : (x % w) + w); break; } - + switch (extend_y) { case COM_MB_CLIP: break; @@ -174,7 +174,7 @@ public: 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 @@ public: 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 @@ public: } 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 @@ public: * 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.h b/source/blender/compositor/intern/COM_MemoryProxy.h index 755d513c72f..b732db37db2 100644 --- a/source/blender/compositor/intern/COM_MemoryProxy.h +++ b/source/blender/compositor/intern/COM_MemoryProxy.h @@ -42,17 +42,17 @@ private: * @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 @@ private: 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 a374403fef7..67b64baa26e 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 1c28292fb2e..1b78e7fec6d 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<NodeInput *> Inputs; typedef std::vector<NodeOutput *> 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 @@ protected: * @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 @@ public: * @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 @@ public: * 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 @@ public: * @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 @@ public: * 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 @@ protected: */ 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 @@ protected: */ 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 df8a7e6353c..1b62466f81f 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 fb7529ae2a7..825c26bb7af 100644 --- a/source/blender/compositor/intern/COM_NodeConverter.h +++ b/source/blender/compositor/intern/COM_NodeConverter.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 @@ public: * 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; diff --git a/source/blender/compositor/intern/COM_NodeGraph.cpp b/source/blender/compositor/intern/COM_NodeGraph.cpp index 5196108818b..d78450074ed 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 fe8740fee97..7c6322d2a42 100644 --- a/source/blender/compositor/intern/COM_NodeGraph.h +++ b/source/blender/compositor/intern/COM_NodeGraph.h @@ -48,66 +48,66 @@ public: 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<Node *> Nodes; typedef Nodes::iterator NodeIterator; typedef std::vector<Link> 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<NodeIterator, NodeIterator> NodeRange; typedef std::vector<NodeInput *> 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 diff --git a/source/blender/compositor/intern/COM_NodeOperation.cpp b/source/blender/compositor/intern/COM_NodeOperation.cpp index 496a27b379c..1063386aa58 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 1f3c72a820e..5ee3cc22b53 100644 --- a/source/blender/compositor/intern/COM_NodeOperation.h +++ b/source/blender/compositor/intern/COM_NodeOperation.h @@ -81,11 +81,11 @@ class NodeOperation : public SocketReader { public: typedef std::vector<NodeOperationInput*> Inputs; typedef std::vector<NodeOperationOutput*> 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 @@ private: * @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 @@ private: * @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 @@ public: 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 @@ public: this->m_isResolutionSet = true; } } - + void getConnectedInputSockets(Inputs *sockets); @@ -288,14 +288,14 @@ public: * @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 @@ protected: void initMutex(); void lockMutex(); void unlockMutex(); - + /** * @brief set whether this operation is complex * @@ -345,35 +345,35 @@ protected: 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 @@ public: 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 fc1584e3dbb..f282037823a 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 2bb5b94c57f..0eafd27b46a 100644 --- a/source/blender/compositor/intern/COM_NodeOperationBuilder.h +++ b/source/blender/compositor/intern/COM_NodeOperationBuilder.h @@ -52,48 +52,48 @@ public: 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<NodeOperation *> Operations; typedef std::vector<Link> Links; typedef std::vector<ExecutionGroup *> Groups; - + typedef std::map<NodeOperationInput *, NodeInput *> InputSocketMap; typedef std::map<NodeOutput *, NodeOperationOutput *> OutputSocketMap; - + typedef std::vector<NodeOperationInput *> OpInputs; typedef std::map<NodeInput *, OpInputs> 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 @@ public: 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 @@ protected: 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; diff --git a/source/blender/compositor/intern/COM_OpenCLDevice.cpp b/source/blender/compositor/intern/COM_OpenCLDevice.cpp index 54044f747fb..881c7b8f49a 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 78d3c66cb5c..fa358f65ddf 100644 --- a/source/blender/compositor/intern/COM_OpenCLDevice.h +++ b/source/blender/compositor/intern/COM_OpenCLDevice.h @@ -42,17 +42,17 @@ private: * @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 @@ public: * @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 @@ public: * @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 27d4d0951e8..9ab67a40055 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 82d0b04e064..e0dc06ef733 100644 --- a/source/blender/compositor/intern/COM_SingleThreadedOperation.h +++ b/source/blender/compositor/intern/COM_SingleThreadedOperation.h @@ -27,7 +27,7 @@ class SingleThreadedOperation : public NodeOperation { private: MemoryBuffer *m_cachedInstance; - + protected: inline bool isCached() { return this->m_cachedInstance != NULL; @@ -35,17 +35,17 @@ protected: 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 @@ public: void *initializeTileData(rcti *rect); virtual MemoryBuffer *createMemoryBuffer(rcti *rect) = 0; - + int isSingleThreaded() { return true; } }; #endif diff --git a/source/blender/compositor/intern/COM_WorkScheduler.cpp b/source/blender/compositor/intern/COM_WorkScheduler.cpp index ce45b9fdbe9..4136983e13c 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 7f07978a9c7..14b02e70913 100644 --- a/source/blender/compositor/intern/COM_WorkScheduler.h +++ b/source/blender/compositor/intern/COM_WorkScheduler.h @@ -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. diff --git a/source/blender/compositor/intern/COM_compositor.cpp b/source/blender/compositor/intern/COM_compositor.cpp index 467286084f9..4599832b433 100644 --- a/source/blender/compositor/intern/COM_compositor.cpp +++ b/source/blender/compositor/intern/COM_compositor.cpp @@ -94,7 +94,7 @@ void COM_execute(RenderData *rd, Scene *scene, bNodeTree *editingtree, int rende 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 0c35f079a8b..3481fd1addd 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_BilateralBlurNode.cpp b/source/blender/compositor/nodes/COM_BilateralBlurNode.cpp index fe6b447b23b..dba1a009417 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_BlurNode.cpp b/source/blender/compositor/nodes/COM_BlurNode.cpp index 66ccbaa4de8..ed1c15d15a2 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_BokehBlurNode.cpp b/source/blender/compositor/nodes/COM_BokehBlurNode.cpp index b71f2f5fa07..b36e8cc4c53 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_BokehImageNode.cpp b/source/blender/compositor/nodes/COM_BokehImageNode.cpp index 7f25a19ee37..7a388f80def 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_BoxMaskNode.cpp b/source/blender/compositor/nodes/COM_BoxMaskNode.cpp index b3cffb90459..f798c95b1b1 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_BrightnessNode.cpp b/source/blender/compositor/nodes/COM_BrightnessNode.cpp index fc7294eb6b1..b2422a230cd 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_ChromaMatteNode.cpp b/source/blender/compositor/nodes/COM_ChromaMatteNode.cpp index 2c985cd5bd1..d725ad135a5 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_ColorBalanceNode.cpp b/source/blender/compositor/nodes/COM_ColorBalanceNode.cpp index 98d2e048807..28966beb4f4 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_ColorCorrectionNode.cpp b/source/blender/compositor/nodes/COM_ColorCorrectionNode.cpp index c4eefe038a5..72943f6b53f 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_ColorCurveNode.cpp b/source/blender/compositor/nodes/COM_ColorCurveNode.cpp index 41052ef536d..fb8587adabb 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_ColorMatteNode.cpp b/source/blender/compositor/nodes/COM_ColorMatteNode.cpp index f7c20894087..477fdddff8a 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_ColorNode.cpp b/source/blender/compositor/nodes/COM_ColorNode.cpp index 2c37a927e46..c9254b30e8e 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_ColorRampNode.cpp b/source/blender/compositor/nodes/COM_ColorRampNode.cpp index 175267a3a4f..3e5128fa0fa 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_ColorSpillNode.cpp b/source/blender/compositor/nodes/COM_ColorSpillNode.cpp index f33f2858397..bef518bb186 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_ColorToBWNode.cpp b/source/blender/compositor/nodes/COM_ColorToBWNode.cpp index 2ce4dd5d3a8..1b26354117a 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_CombineColorNode.cpp b/source/blender/compositor/nodes/COM_CombineColorNode.cpp index b7b84b9986c..ad410038c65 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 4cb626ea384..d5439e0056c 100644 --- a/source/blender/compositor/nodes/COM_CombineColorNode.h +++ b/source/blender/compositor/nodes/COM_CombineColorNode.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 @@ public: CombineRGBANode(bNode *editorNode) : CombineColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -49,7 +49,7 @@ public: CombineHSVANode(bNode *editorNode) : CombineColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -58,7 +58,7 @@ public: CombineYCCANode(bNode *editorNode) : CombineColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -67,7 +67,7 @@ public: 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 b2a1df7ee9e..002f28f3135 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_ConvertAlphaNode.cpp b/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp index fbf5dbb6253..75f72669e1e 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_CornerPinNode.cpp b/source/blender/compositor/nodes/COM_CornerPinNode.cpp index 5e4e463595a..b03a3e64f83 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_CropNode.cpp b/source/blender/compositor/nodes/COM_CropNode.cpp index 12eb5268be4..4f80b868f3a 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_DefocusNode.cpp b/source/blender/compositor/nodes/COM_DefocusNode.cpp index 5df246db1d2..19bb42327f5 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_DespeckleNode.cpp b/source/blender/compositor/nodes/COM_DespeckleNode.cpp index a21885bf42d..d211050389e 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_DifferenceMatteNode.cpp b/source/blender/compositor/nodes/COM_DifferenceMatteNode.cpp index f19cfd443a8..3867a543063 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_DilateErodeNode.cpp b/source/blender/compositor/nodes/COM_DilateErodeNode.cpp index 6e78fcb38f1..102dba3b957 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_DirectionalBlurNode.cpp b/source/blender/compositor/nodes/COM_DirectionalBlurNode.cpp index 9a4ced2bf96..9f846c67b1d 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_DistanceMatteNode.cpp b/source/blender/compositor/nodes/COM_DistanceMatteNode.cpp index 52c764f2223..fc05e0564bc 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_DoubleEdgeMaskNode.cpp b/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.cpp index 913d97a6395..1a10b912b23 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_EllipseMaskNode.cpp b/source/blender/compositor/nodes/COM_EllipseMaskNode.cpp index c0c99a2efe8..60dc377518b 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_FilterNode.cpp b/source/blender/compositor/nodes/COM_FilterNode.cpp index 627f2a30f6e..ad25894929e 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 4cbae9bab66..2d1b60b784e 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_GammaNode.cpp b/source/blender/compositor/nodes/COM_GammaNode.cpp index 383231ff326..fdee02b2d02 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_GlareNode.cpp b/source/blender/compositor/nodes/COM_GlareNode.cpp index b52ef9ebb33..2e012b097b3 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_HueSaturationValueCorrectNode.cpp b/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.cpp index 0c572c1ddc7..3542bc7f36e 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_HueSaturationValueNode.cpp b/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp index b31fe7ac030..7da8c5b3d3d 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_IDMaskNode.cpp b/source/blender/compositor/nodes/COM_IDMaskNode.cpp index 47137352226..ab5931ea566 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_ImageNode.cpp b/source/blender/compositor/nodes/COM_ImageNode.cpp index 337169ba748..36e71aa1203 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) { diff --git a/source/blender/compositor/nodes/COM_InpaintNode.cpp b/source/blender/compositor/nodes/COM_InpaintNode.cpp index 17cc2fa653e..41cc65e2fee 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_InvertNode.cpp b/source/blender/compositor/nodes/COM_InvertNode.cpp index ebdb2cdb7c5..c83db3fe78f 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_KeyingNode.cpp b/source/blender/compositor/nodes/COM_KeyingNode.cpp index ddfba07d9f7..261bdb93adb 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 70b3b696e37..df9668883e8 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 b6cc2acb9a6..2bad80839e1 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_LuminanceMatteNode.cpp b/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp index de6ad3df030..12f3b1bc410 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 81ee4f0d7a9..6590cf04306 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 c593805c940..dc477ad9da0 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_MapValueNode.cpp b/source/blender/compositor/nodes/COM_MapValueNode.cpp index 9a4c4880b62..6276548c7a7 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 e9bed136a37..d16300ebff4 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(); @@ -90,12 +90,12 @@ void MathNode::convertToOperations(NodeConverter &converter, const CompositorCon operation = new MathArcTan2Operation(); 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_MixNode.cpp b/source/blender/compositor/nodes/COM_MixNode.cpp index e807365d9db..e0af0106513 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_MovieClipNode.cpp b/source/blender/compositor/nodes/COM_MovieClipNode.cpp index 269d7f2cafe..18e6f811fff 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 c4277354b43..e3009e068ab 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_NormalNode.cpp b/source/blender/compositor/nodes/COM_NormalNode.cpp index bde5a126325..64231d116fa 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_OutputFileNode.cpp b/source/blender/compositor/nodes/COM_OutputFileNode.cpp index 46e7f7fe790..5a7e5e2c623 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_PixelateNode.cpp b/source/blender/compositor/nodes/COM_PixelateNode.cpp index fe806dbf307..2b7ab0ea4e8 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_PlaneTrackDeformNode.cpp b/source/blender/compositor/nodes/COM_PlaneTrackDeformNode.cpp index 379b9f193e8..d8e4655b84e 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 77638d66987..fe85d5db255 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_ScaleNode.cpp b/source/blender/compositor/nodes/COM_ScaleNode.cpp index ef4128a78b4..dc512684ce6 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_SeparateColorNode.cpp b/source/blender/compositor/nodes/COM_SeparateColorNode.cpp index 68fdaf01f5c..b3f9ab46f35 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 d378a311e73..0e47a98a1aa 100644 --- a/source/blender/compositor/nodes/COM_SeparateColorNode.h +++ b/source/blender/compositor/nodes/COM_SeparateColorNode.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 @@ public: SeparateRGBANode(bNode *editorNode) : SeparateColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -49,7 +49,7 @@ public: SeparateHSVANode(bNode *editorNode) : SeparateColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -58,7 +58,7 @@ public: SeparateYCCANode(bNode *editorNode) : SeparateColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -67,7 +67,7 @@ public: 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 4c55a4bdc0a..b5d5bf9d9d9 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_SocketProxyNode.cpp b/source/blender/compositor/nodes/COM_SocketProxyNode.cpp index c76b057577c..230c27dd9a0 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 410cbf94842..faa458492cb 100644 --- a/source/blender/compositor/nodes/COM_SocketProxyNode.h +++ b/source/blender/compositor/nodes/COM_SocketProxyNode.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_Stabilize2dNode.cpp b/source/blender/compositor/nodes/COM_Stabilize2dNode.cpp index a575cf65b99..38b8a466369 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_SwitchNode.cpp b/source/blender/compositor/nodes/COM_SwitchNode.cpp index e0c12e4dbea..7e1eaabc886 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_TextureNode.cpp b/source/blender/compositor/nodes/COM_TextureNode.cpp index 411dea2925f..47b32f6e04d 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 8450b521267..883ff72229d 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_TonemapNode.cpp b/source/blender/compositor/nodes/COM_TonemapNode.cpp index 1ecc42a0a27..a01be6acb7b 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_TrackPositionNode.cpp b/source/blender/compositor/nodes/COM_TrackPositionNode.cpp index 490f72b4aa1..cddb3557498 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 5b772d1ce56..288f394a10f 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 0e658e09931..ac09b38951b 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)); diff --git a/source/blender/compositor/nodes/COM_ValueNode.cpp b/source/blender/compositor/nodes/COM_ValueNode.cpp index f2eef188861..b7484eb4ed6 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_VectorBlurNode.cpp b/source/blender/compositor/nodes/COM_VectorBlurNode.cpp index 5cfd83360c7..5a6b49c9bd1 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_VectorCurveNode.cpp b/source/blender/compositor/nodes/COM_VectorCurveNode.cpp index db7e1597bf3..dc4b2f66a0a 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_ViewLevelsNode.cpp b/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp index b7e4c9e8a1d..134ab5628ec 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_ZCombineNode.cpp b/source/blender/compositor/nodes/COM_ZCombineNode.cpp index c77bd031824..a5d42bb0333 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/operations/COM_AlphaOverKeyOperation.cpp b/source/blender/compositor/operations/COM_AlphaOverKeyOperation.cpp index 928525f2594..e6ae9b5fc8b 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 8e4a0c93202..144c60f2966 100644 --- a/source/blender/compositor/operations/COM_AlphaOverKeyOperation.h +++ b/source/blender/compositor/operations/COM_AlphaOverKeyOperation.h @@ -35,7 +35,7 @@ public: * 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 990ec5f5370..748b5c63409 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); } diff --git a/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h b/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h index 8c97b065792..a76bf12481d 100644 --- a/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h +++ b/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h @@ -37,12 +37,12 @@ public: * 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 1f397e8a126..b6a1ab57b14 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,7 +46,7 @@ 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]; diff --git a/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h b/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h index 1dad453ca4e..8551dba7b7c 100644 --- a/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h +++ b/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h @@ -35,7 +35,7 @@ public: * 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 13632a81084..a6f74eb214c 100644 --- a/source/blender/compositor/operations/COM_AntiAliasOperation.h +++ b/source/blender/compositor/operations/COM_AntiAliasOperation.h @@ -38,19 +38,19 @@ protected: 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 4a6da3092a2..506c2181ee9 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 b013e357b9c..70f291d5e1c 100644 --- a/source/blender/compositor/operations/COM_BilateralBlurOperation.h +++ b/source/blender/compositor/operations/COM_BilateralBlurOperation.h @@ -39,19 +39,19 @@ public: * 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 9fd7c017715..1a57b170c9a 100644 --- a/source/blender/compositor/operations/COM_BlurBaseOperation.h +++ b/source/blender/compositor/operations/COM_BlurBaseOperation.h @@ -62,12 +62,12 @@ public: * 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 c413f45cbaa..2476ab3b591 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<cl_mem> *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp, list<cl_kernel> * /*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 3bfaae6617e..f1540835eaf 100644 --- a/source/blender/compositor/operations/COM_BokehBlurOperation.h +++ b/source/blender/compositor/operations/COM_BokehBlurOperation.h @@ -46,21 +46,21 @@ public: * 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<cl_mem> *clMemToCleanUp, diff --git a/source/blender/compositor/operations/COM_BokehImageOperation.h b/source/blender/compositor/operations/COM_BokehImageOperation.h index a2dd3b6ddb7..6f2001566ea 100644 --- a/source/blender/compositor/operations/COM_BokehImageOperation.h +++ b/source/blender/compositor/operations/COM_BokehImageOperation.h @@ -61,27 +61,27 @@ private: * @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 @@ private: * @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 @@ public: * @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 @@ public: * @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 e19e5bf031c..d4fe976cf26 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 c8b2ba14467..292e3a9391f 100644 --- a/source/blender/compositor/operations/COM_BoxMaskOperation.h +++ b/source/blender/compositor/operations/COM_BoxMaskOperation.h @@ -32,31 +32,31 @@ private: */ 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.h b/source/blender/compositor/operations/COM_BrightnessOperation.h index 0b7656c5364..8bda13ea418 100644 --- a/source/blender/compositor/operations/COM_BrightnessOperation.h +++ b/source/blender/compositor/operations/COM_BrightnessOperation.h @@ -38,17 +38,17 @@ private: 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 0fa8b5fa5d2..be6d2b40d7e 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 4fa89290c82..d7d927791b2 100644 --- a/source/blender/compositor/operations/COM_CalculateMeanOperation.h +++ b/source/blender/compositor/operations/COM_CalculateMeanOperation.h @@ -35,34 +35,34 @@ protected: * @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 ff4857b7b0f..28012cdfabf 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_ChangeHSVOperation.cpp b/source/blender/compositor/operations/COM_ChangeHSVOperation.cpp index a02c1b03006..f90e9b70053 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; diff --git a/source/blender/compositor/operations/COM_ChangeHSVOperation.h b/source/blender/compositor/operations/COM_ChangeHSVOperation.h index e6f45c5ad36..9685a298607 100644 --- a/source/blender/compositor/operations/COM_ChangeHSVOperation.h +++ b/source/blender/compositor/operations/COM_ChangeHSVOperation.h @@ -41,10 +41,10 @@ public: * 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 3faffc1e3ff..688cbe91cf7 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,7 +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_ColorBalanceASCCDLOperation.cpp b/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.cpp index 23390bd337d..806772417a4 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 cc6bd894748..44981a2c957 100644 --- a/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.h +++ b/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.h @@ -35,7 +35,7 @@ protected: */ SocketReader *m_inputValueOperation; SocketReader *m_inputColorOperation; - + float m_offset[3]; float m_power[3]; float m_slope[3]; @@ -45,22 +45,22 @@ public: * 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 e13fd26aed2..e264c065f47 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 86d7abc92bc..97fc8b6f870 100644 --- a/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.h +++ b/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.h @@ -36,7 +36,7 @@ protected: */ SocketReader *m_inputValueOperation; SocketReader *m_inputColorOperation; - + float m_gain[3]; float m_lift[3]; float m_gamma_inv[3]; @@ -46,22 +46,22 @@ public: * 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 05edaf51a25..5e08dadd635 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; } diff --git a/source/blender/compositor/operations/COM_ColorCorrectionOperation.h b/source/blender/compositor/operations/COM_ColorCorrectionOperation.h index c386a2f3e6e..7c7ccf2db9b 100644 --- a/source/blender/compositor/operations/COM_ColorCorrectionOperation.h +++ b/source/blender/compositor/operations/COM_ColorCorrectionOperation.h @@ -33,29 +33,29 @@ private: 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 5967147b3d1..4cecc53ad01 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 3b10786fb2c..17c94feed5f 100644 --- a/source/blender/compositor/operations/COM_ColorCurveOperation.h +++ b/source/blender/compositor/operations/COM_ColorCurveOperation.h @@ -37,17 +37,17 @@ private: 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 @@ private: 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_ColorRampOperation.h b/source/blender/compositor/operations/COM_ColorRampOperation.h index 55f711165d6..2d1919bb4b5 100644 --- a/source/blender/compositor/operations/COM_ColorRampOperation.h +++ b/source/blender/compositor/operations/COM_ColorRampOperation.h @@ -34,22 +34,22 @@ private: 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 0769e5d0b01..2f30ed83043 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 3b94c293ec9..5971db9fa76 100644 --- a/source/blender/compositor/operations/COM_ColorSpillOperation.h +++ b/source/blender/compositor/operations/COM_ColorSpillOperation.h @@ -55,7 +55,7 @@ public: 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_ConvertColorProfileOperation.h b/source/blender/compositor/operations/COM_ConvertColorProfileOperation.h index ceba2a85da0..47f9f20f393 100644 --- a/source/blender/compositor/operations/COM_ConvertColorProfileOperation.h +++ b/source/blender/compositor/operations/COM_ConvertColorProfileOperation.h @@ -35,17 +35,17 @@ private: * 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 @@ public: * 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 9057c3c92ec..111bfeadf35 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 697ac455702..65db1cf45d9 100644 --- a/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.h +++ b/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.h @@ -43,34 +43,34 @@ private: 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 5dee63ea739..9c23cc9bda7 100644 --- a/source/blender/compositor/operations/COM_ConvertOperation.h +++ b/source/blender/compositor/operations/COM_ConvertOperation.h @@ -29,10 +29,10 @@ class ConvertBaseOperation : public NodeOperation { protected: SocketReader *m_inputOperation; - + public: ConvertBaseOperation(); - + void initExecution(); void deinitExecution(); }; @@ -41,7 +41,7 @@ public: class ConvertValueToColorOperation : public ConvertBaseOperation { public: ConvertValueToColorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -49,7 +49,7 @@ public: class ConvertColorToValueOperation : public ConvertBaseOperation { public: ConvertColorToValueOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -57,7 +57,7 @@ public: class ConvertColorToBWOperation : public ConvertBaseOperation { public: ConvertColorToBWOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -65,7 +65,7 @@ public: class ConvertColorToVectorOperation : public ConvertBaseOperation { public: ConvertColorToVectorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -73,7 +73,7 @@ public: class ConvertValueToVectorOperation : public ConvertBaseOperation { public: ConvertValueToVectorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -81,7 +81,7 @@ public: class ConvertVectorToColorOperation : public ConvertBaseOperation { public: ConvertVectorToColorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -89,7 +89,7 @@ public: class ConvertVectorToValueOperation : public ConvertBaseOperation { public: ConvertVectorToValueOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -114,9 +114,9 @@ private: 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 @@ public: class ConvertRGBToYUVOperation : public ConvertBaseOperation { public: ConvertRGBToYUVOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -133,7 +133,7 @@ public: class ConvertYUVToRGBOperation : public ConvertBaseOperation { public: ConvertYUVToRGBOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -141,7 +141,7 @@ public: class ConvertRGBToHSVOperation : public ConvertBaseOperation { public: ConvertRGBToHSVOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -149,7 +149,7 @@ public: class ConvertHSVToRGBOperation : public ConvertBaseOperation { public: ConvertHSVToRGBOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -177,10 +177,10 @@ private: 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 @@ private: 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 56815459ee7..9eb2d1bfcc5 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_ConvolutionFilterOperation.cpp b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp index 41cc504af05..b14fdc811d4 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 75fba0ee1e4..99e6fc52ddc 100644 --- a/source/blender/compositor/operations/COM_ConvolutionFilterOperation.h +++ b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.h @@ -40,7 +40,7 @@ public: 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 162811ac31d..af68fa09f1a 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 7c5b995fb17..f73b4c602f6 100644 --- a/source/blender/compositor/operations/COM_CropOperation.h +++ b/source/blender/compositor/operations/COM_CropOperation.h @@ -34,7 +34,7 @@ protected: int m_xmin; int m_ymax; int m_ymin; - + void updateArea(); public: CropBaseOperation(); diff --git a/source/blender/compositor/operations/COM_CurveBaseOperation.h b/source/blender/compositor/operations/COM_CurveBaseOperation.h index 169022de5f5..191cf7f5307 100644 --- a/source/blender/compositor/operations/COM_CurveBaseOperation.h +++ b/source/blender/compositor/operations/COM_CurveBaseOperation.h @@ -34,13 +34,13 @@ protected: public: CurveBaseOperation(); ~CurveBaseOperation(); - + /** * Initialize the execution */ void initExecution(); void deinitExecution(); - + void setCurveMapping(CurveMapping *mapping); }; #endif diff --git a/source/blender/compositor/operations/COM_DifferenceMatteOperation.h b/source/blender/compositor/operations/COM_DifferenceMatteOperation.h index ddf6bf6f893..3766f85444d 100644 --- a/source/blender/compositor/operations/COM_DifferenceMatteOperation.h +++ b/source/blender/compositor/operations/COM_DifferenceMatteOperation.h @@ -39,15 +39,15 @@ public: * 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 2ea438d070d..17f3dfeac62 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 c929fcf7fec..92c453d9d85 100644 --- a/source/blender/compositor/operations/COM_DilateErodeOperation.h +++ b/source/blender/compositor/operations/COM_DilateErodeOperation.h @@ -31,11 +31,11 @@ private: * 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 @@ private: 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 @@ protected: 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<cl_mem> *clMemToCleanUp, list<cl_kernel> *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<cl_mem> *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp, list<cl_kernel> *clKernelsToCleanUp); }; @@ -125,38 +125,38 @@ protected: * 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 2e0be8d8410..e3dec838589 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<cl_mem> *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp, list<cl_kernel> * /*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 a6194a0ca73..eaabf49bf74 100644 --- a/source/blender/compositor/operations/COM_DirectionalBlurOperation.h +++ b/source/blender/compositor/operations/COM_DirectionalBlurOperation.h @@ -41,25 +41,25 @@ public: * 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<cl_mem> *clMemToCleanUp, list<cl_kernel> *clKernelsToCleanUp); - + }; #endif diff --git a/source/blender/compositor/operations/COM_DisplaceOperation.cpp b/source/blender/compositor/operations/COM_DisplaceOperation.cpp index 9b3377e887a..0d959996be1 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]); diff --git a/source/blender/compositor/operations/COM_DisplaceOperation.h b/source/blender/compositor/operations/COM_DisplaceOperation.h index cec7937d9d6..680f2606692 100644 --- a/source/blender/compositor/operations/COM_DisplaceOperation.h +++ b/source/blender/compositor/operations/COM_DisplaceOperation.h @@ -49,14 +49,14 @@ public: * 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 40b4fdec28e..0d7cd129a2f 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); diff --git a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h index 6e52dfe86e9..b3da61722ec 100644 --- a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h +++ b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h @@ -49,12 +49,12 @@ public: * 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 b9e6864b340..adc977d014d 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 a815caa5ef5..22bc10b7bc3 100644 --- a/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.h +++ b/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.h @@ -41,15 +41,15 @@ public: * 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_DotproductOperation.h b/source/blender/compositor/operations/COM_DotproductOperation.h index 218409cbf5b..0fbefd716eb 100644 --- a/source/blender/compositor/operations/COM_DotproductOperation.h +++ b/source/blender/compositor/operations/COM_DotproductOperation.h @@ -32,7 +32,7 @@ private: 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 8d2a0f3b427..ffa2f812ed7 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); diff --git a/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h b/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h index a12c44b02a1..4574454dd02 100644 --- a/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h +++ b/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h @@ -43,12 +43,12 @@ public: * 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 @@ public: 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 482473cbe1f..fac0e028c6d 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) { diff --git a/source/blender/compositor/operations/COM_EllipseMaskOperation.h b/source/blender/compositor/operations/COM_EllipseMaskOperation.h index 419b2c2d63b..9de9fb3e11c 100644 --- a/source/blender/compositor/operations/COM_EllipseMaskOperation.h +++ b/source/blender/compositor/operations/COM_EllipseMaskOperation.h @@ -32,34 +32,34 @@ private: */ 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 a223ac31e3d..11843da3634 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; diff --git a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h index 1cfaee3f537..2b02cf322ef 100644 --- a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h +++ b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h @@ -35,7 +35,7 @@ public: 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 @@ public: 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(); diff --git a/source/blender/compositor/operations/COM_FlipOperation.cpp b/source/blender/compositor/operations/COM_FlipOperation.cpp index 80e67a7297b..c75201903eb 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 3a7bf77f29b..e577259fea4 100644 --- a/source/blender/compositor/operations/COM_FlipOperation.h +++ b/source/blender/compositor/operations/COM_FlipOperation.h @@ -34,7 +34,7 @@ public: 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 b3f0cedce22..aabfe09fbf2 100644 --- a/source/blender/compositor/operations/COM_GammaCorrectOperation.h +++ b/source/blender/compositor/operations/COM_GammaCorrectOperation.h @@ -34,17 +34,17 @@ private: 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 @@ private: 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 79b70b5170e..0cc0cbefd46 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 9243ece6b30..ce221965eb5 100644 --- a/source/blender/compositor/operations/COM_GammaOperation.h +++ b/source/blender/compositor/operations/COM_GammaOperation.h @@ -35,17 +35,17 @@ private: 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 0fab888b9d9..c560257b859 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 fc5b3384749..651e8d9e658 100644 --- a/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.h @@ -41,7 +41,7 @@ public: * @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 @@ public: * @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 b4e535cbf20..b90320afdeb 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 4f2f2ec3fe4..dc9e5607ae6 100644 --- a/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.h @@ -36,12 +36,12 @@ private: 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 @@ public: * 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 c268cff557a..483ddb53344 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; } diff --git a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h index e483ffd4f2d..9089838add5 100644 --- a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h @@ -40,19 +40,19 @@ public: * 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 @@ public: * 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 ef438e1d364..3eafc7a1bfe 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 46a5c4e3c03..4ad57bda742 100644 --- a/source/blender/compositor/operations/COM_GaussianXBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianXBlurOperation.h @@ -55,7 +55,7 @@ public: * @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 6f8f96a6344..45089598af5 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 ca3172bd505..da1adbd0ea7 100644 --- a/source/blender/compositor/operations/COM_GaussianYBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianYBlurOperation.h @@ -35,7 +35,7 @@ private: void updateGauss(); public: GaussianYBlurOperation(); - + /** * the inner loop of this program */ @@ -55,7 +55,7 @@ public: * 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_GlareThresholdOperation.cpp b/source/blender/compositor/operations/COM_GlareThresholdOperation.cpp index f54e75a6b35..62ebe601d8d 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 7760a19251b..647cf74cdcf 100644 --- a/source/blender/compositor/operations/COM_GlareThresholdOperation.h +++ b/source/blender/compositor/operations/COM_GlareThresholdOperation.h @@ -57,7 +57,7 @@ public: 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 06d785f2c51..97bfc836ae2 100644 --- a/source/blender/compositor/operations/COM_HueSaturationValueCorrectOperation.h +++ b/source/blender/compositor/operations/COM_HueSaturationValueCorrectOperation.h @@ -33,17 +33,17 @@ private: 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_ImageOperation.h b/source/blender/compositor/operations/COM_ImageOperation.h index 1f9a9a45af1..8ab93c2ba64 100644 --- a/source/blender/compositor/operations/COM_ImageOperation.h +++ b/source/blender/compositor/operations/COM_ImageOperation.h @@ -57,11 +57,11 @@ protected: * 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 11896b1d78c..da31638ff07 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,12 +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 9ddcac93c5c..fe8e2dd2a19 100644 --- a/source/blender/compositor/operations/COM_InpaintOperation.h +++ b/source/blender/compositor/operations/COM_InpaintOperation.h @@ -30,9 +30,9 @@ protected: * Cached reference to the inputProgram */ SocketReader *m_inputImageProgram; - + int m_iterations; - + float *m_cached_buffer; bool m_cached_buffer_ready; @@ -41,25 +41,25 @@ protected: 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 833b91ac1e3..53f181cf008 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 diff --git a/source/blender/compositor/operations/COM_InvertOperation.h b/source/blender/compositor/operations/COM_InvertOperation.h index 977feeb87af..4528895c282 100644 --- a/source/blender/compositor/operations/COM_InvertOperation.h +++ b/source/blender/compositor/operations/COM_InvertOperation.h @@ -32,28 +32,28 @@ private: */ 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_LuminanceMatteOperation.cpp b/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp index 1401ab56fbd..e07da3bd17f 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; diff --git a/source/blender/compositor/operations/COM_LuminanceMatteOperation.h b/source/blender/compositor/operations/COM_LuminanceMatteOperation.h index 93051f52228..951c054d241 100644 --- a/source/blender/compositor/operations/COM_LuminanceMatteOperation.h +++ b/source/blender/compositor/operations/COM_LuminanceMatteOperation.h @@ -37,15 +37,15 @@ public: * 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 6124a53d5b9..f5d3b146196 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 48ecad9d226..405faf3fb2c 100644 --- a/source/blender/compositor/operations/COM_MapRangeOperation.h +++ b/source/blender/compositor/operations/COM_MapRangeOperation.h @@ -46,26 +46,26 @@ public: * 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 0112f4bbf21..54d63b6a12c 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. diff --git a/source/blender/compositor/operations/COM_MapUVOperation.h b/source/blender/compositor/operations/COM_MapUVOperation.h index 796ee952607..1bb26bf14f0 100644 --- a/source/blender/compositor/operations/COM_MapUVOperation.h +++ b/source/blender/compositor/operations/COM_MapUVOperation.h @@ -33,7 +33,7 @@ private: SocketReader *m_inputColorProgram; float m_alpha; - + public: MapUVOperation(); @@ -53,7 +53,7 @@ public: * 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 59d4d836b1b..afe3961dbf1 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 ba19e76f4db..97528efca19 100644 --- a/source/blender/compositor/operations/COM_MapValueOperation.h +++ b/source/blender/compositor/operations/COM_MapValueOperation.h @@ -41,26 +41,26 @@ public: * 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_MathBaseOperation.cpp b/source/blender/compositor/operations/COM_MathBaseOperation.cpp index bb6e1f9da8d..0a515da1877 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,4 @@ 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 +} diff --git a/source/blender/compositor/operations/COM_MathBaseOperation.h b/source/blender/compositor/operations/COM_MathBaseOperation.h index 862783fff5d..c636117451f 100644 --- a/source/blender/compositor/operations/COM_MathBaseOperation.h +++ b/source/blender/compositor/operations/COM_MathBaseOperation.h @@ -51,12 +51,12 @@ public: * 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 */ diff --git a/source/blender/compositor/operations/COM_MixOperation.cpp b/source/blender/compositor/operations/COM_MixOperation.cpp index 314e16895f3..0acbe63e20e 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 f375a47f087..fa13a486657 100644 --- a/source/blender/compositor/operations/COM_MixOperation.h +++ b/source/blender/compositor/operations/COM_MixOperation.h @@ -50,23 +50,23 @@ protected: 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 @@ public: 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_MovieClipOperation.h b/source/blender/compositor/operations/COM_MovieClipOperation.h index 93452752234..28e6c0d0c3a 100644 --- a/source/blender/compositor/operations/COM_MovieClipOperation.h +++ b/source/blender/compositor/operations/COM_MovieClipOperation.h @@ -41,7 +41,7 @@ protected: int m_movieClipwidth; int m_framenumber; bool m_cacheFrame; - + /** * Determine the output resolution. The resolution is retrieved from the Renderer */ @@ -49,7 +49,7 @@ protected: public: MovieClipBaseOperation(); - + void initExecution(); void deinitExecution(); void setMovieClip(MovieClip *image) { this->m_movieClip = image; } diff --git a/source/blender/compositor/operations/COM_NormalizeOperation.cpp b/source/blender/compositor/operations/COM_NormalizeOperation.cpp index 6106a805f87..3527c874bcf 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_OutputFileOperation.cpp b/source/blender/compositor/operations/COM_OutputFileOperation.cpp index 39877e35605..db2598ad6dc 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,14 +299,14 @@ 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 60862de48cb..32c9b5ab5b8 100644 --- a/source/blender/compositor/operations/COM_OutputFileOperation.h +++ b/source/blender/compositor/operations/COM_OutputFileOperation.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 @@ protected: 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 @@ public: /* 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<OutputOpenExrLayer> 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_PlaneCornerPinOperation.cpp b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp index d6affa6eee9..4e4e803c757 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 ed70d9c80a3..a9bd18299eb 100644 --- a/source/blender/compositor/operations/COM_PlaneCornerPinOperation.h +++ b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.h @@ -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 @@ public: 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_PreviewOperation.cpp b/source/blender/compositor/operations/COM_PreviewOperation.cpp index d4075844f0e..90e1bba3cd9 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 ca1d6f54cdc..907a6c8997f 100644 --- a/source/blender/compositor/operations/COM_PreviewOperation.h +++ b/source/blender/compositor/operations/COM_PreviewOperation.h @@ -44,16 +44,16 @@ protected: 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 020bdde8c93..e135abe5f20 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 9eb90b6006b..12efff14839 100644 --- a/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.h +++ b/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.h @@ -31,30 +31,30 @@ private: * 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_ReadBufferOperation.cpp b/source/blender/compositor/operations/COM_ReadBufferOperation.cpp index f256d3a6aa1..6e7a32ba5a9 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 898b568bb91..c42de32b9e9 100644 --- a/source/blender/compositor/operations/COM_ReadBufferOperation.h +++ b/source/blender/compositor/operations/COM_ReadBufferOperation.h @@ -38,7 +38,7 @@ public: 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 ca135a650bd..e1a77158175 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) { ViewLayer *view_layer = (ViewLayer *)BLI_findlink(&scene->view_layers, getLayerId()); if (view_layer) { @@ -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) { ViewLayer *view_layer = (ViewLayer *)BLI_findlink(&sce->view_layers, getLayerId()); if (view_layer) { @@ -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_RotateOperation.cpp b/source/blender/compositor/operations/COM_RotateOperation.cpp index 2d0d5aaf8d3..4186a0e1fc8 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 7b99b6faa97..d332f7208b5 100644 --- a/source/blender/compositor/operations/COM_RotateOperation.h +++ b/source/blender/compositor/operations/COM_RotateOperation.h @@ -42,7 +42,7 @@ public: void initExecution(); void deinitExecution(); void setDoDegree2RadConversion(bool abool) { this->m_doDegree2RadConversion = abool; } - + void ensureDegree(); }; diff --git a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp index 651c336452e..f7b8d285cc2 100644 --- a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp +++ b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp @@ -26,6 +26,7 @@ extern "C" { # include "BLI_math.h" # include "BLI_utildefines.h" # include "BLI_rand.h" +# include "PIL_time.h" } ScreenLensDistortionOperation::ScreenLensDistortionOperation() : NodeOperation() @@ -59,10 +60,14 @@ void ScreenLensDistortionOperation::initExecution() { this->m_inputProgram = this->getInputSocketReader(0); this->initMutex(); - + + uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); + rng_seed ^= (uint)GET_INT_FROM_POINTER(m_inputProgram); + this->m_rng = BLI_rng_new(rng_seed); + 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 +85,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 +96,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 +128,7 @@ bool ScreenLensDistortionOperation::get_delta(float r_sq, float k4, const float } else return false; - + } void ScreenLensDistortionOperation::accumulate(MemoryBuffer *buffer, @@ -133,7 +138,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; @@ -142,13 +147,13 @@ void ScreenLensDistortionOperation::accumulate(MemoryBuffer *buffer, float dk4 = m_dk4[a]; for (float z = 0; z < ds; ++z) { - float tz = (z + (m_jitter ? BLI_frand() : 0.5f)) * sd; + float tz = (z + (m_jitter ? BLI_rng_get_float(m_rng) : 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 +180,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; } @@ -192,6 +197,7 @@ void ScreenLensDistortionOperation::deinitExecution() { this->deinitMutex(); this->m_inputProgram = NULL; + BLI_rng_free(this->m_rng); } void ScreenLensDistortionOperation::determineUV(float result[6], float x, float y) const @@ -200,7 +206,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 +222,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 +232,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 +240,7 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti * /*in */ #if 1 rcti imageInput; - + operation = getInputOperation(0); imageInput.xmax = operation->getWidth(); imageInput.xmin = 0; @@ -248,9 +254,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 +290,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 648a7a6e551..e1e276d0dc4 100644 --- a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.h +++ b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.h @@ -31,10 +31,11 @@ private: * Cached reference to the inputProgram */ SocketReader *m_inputProgram; - + struct RNG *m_rng; + bool m_fit; bool m_jitter; - + float m_dispersion; float m_distortion; bool m_dispersion_const; @@ -47,31 +48,31 @@ private: 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 91933484027..e6c04a4b68c 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 12e3debf3d3..c4e12a367a5 100644 --- a/source/blender/compositor/operations/COM_SetAlphaOperation.h +++ b/source/blender/compositor/operations/COM_SetAlphaOperation.h @@ -39,12 +39,12 @@ public: * 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_SetSamplerOperation.h b/source/blender/compositor/operations/COM_SetSamplerOperation.h index 903bcef95f0..6d97b20769d 100644 --- a/source/blender/compositor/operations/COM_SetSamplerOperation.h +++ b/source/blender/compositor/operations/COM_SetSamplerOperation.h @@ -38,9 +38,9 @@ public: * 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 10de8825d38..a0867a3bc9c 100644 --- a/source/blender/compositor/operations/COM_SetValueOperation.h +++ b/source/blender/compositor/operations/COM_SetValueOperation.h @@ -38,17 +38,17 @@ public: * 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 b01f2f7a6b5..79b55bb7d91 100644 --- a/source/blender/compositor/operations/COM_SetVectorOperation.h +++ b/source/blender/compositor/operations/COM_SetVectorOperation.h @@ -41,7 +41,7 @@ public: * 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 @@ public: 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 86c8b23b115..55cf6d376b7 100644 --- a/source/blender/compositor/operations/COM_SocketProxyOperation.h +++ b/source/blender/compositor/operations/COM_SocketProxyOperation.h @@ -28,13 +28,13 @@ 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_SunBeamsOperation.cpp b/source/blender/compositor/operations/COM_SunBeamsOperation.cpp index 81b967bf530..964ba36d08c 100644 --- a/source/blender/compositor/operations/COM_SunBeamsOperation.cpp +++ b/source/blender/compositor/operations/COM_SunBeamsOperation.cpp @@ -61,7 +61,7 @@ template <int fxu, int fxv, int fyu, int fyv> 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 diff --git a/source/blender/compositor/operations/COM_TextureOperation.h b/source/blender/compositor/operations/COM_TextureOperation.h index a2fb7c7501f..26d50ca1753 100644 --- a/source/blender/compositor/operations/COM_TextureOperation.h +++ b/source/blender/compositor/operations/COM_TextureOperation.h @@ -54,7 +54,7 @@ protected: * 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 51ffaac8503..6fcf72c9d14 100644 --- a/source/blender/compositor/operations/COM_TonemapOperation.h +++ b/source/blender/compositor/operations/COM_TonemapOperation.h @@ -47,12 +47,12 @@ protected: * @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 @@ protected: 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_TranslateOperation.h b/source/blender/compositor/operations/COM_TranslateOperation.h index e30ba7ff2d7..f3708ef3c7c 100644 --- a/source/blender/compositor/operations/COM_TranslateOperation.h +++ b/source/blender/compositor/operations/COM_TranslateOperation.h @@ -45,7 +45,7 @@ public: 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 e8dbff9b2d7..a252af053cc 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<cl_mem> *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list<cl_mem> *clMemToCleanUp, list<cl_kernel> * /*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 110bb6b4952..57ffde6d398 100644 --- a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.h +++ b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.h @@ -46,23 +46,23 @@ public: * 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 @@ private: 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 05c2c3183c1..30ca2f644bb 100644 --- a/source/blender/compositor/operations/COM_VectorBlurOperation.h +++ b/source/blender/compositor/operations/COM_VectorBlurOperation.h @@ -34,27 +34,27 @@ private: 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 @@ public: 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 444f848cb0a..518e4713c99 100644 --- a/source/blender/compositor/operations/COM_VectorCurveOperation.h +++ b/source/blender/compositor/operations/COM_VectorCurveOperation.h @@ -33,17 +33,17 @@ private: 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 0eff52f4d9a..51fd5d4dc76 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 e5eed3e8024..0e4bff2c4e8 100644 --- a/source/blender/compositor/operations/COM_ViewerOperation.h +++ b/source/blender/compositor/operations/COM_ViewerOperation.h @@ -45,7 +45,7 @@ private: 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_WriteBufferOperation.cpp b/source/blender/compositor/operations/COM_WriteBufferOperation.cpp index 85602e6741c..5a34673b2bd 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<cl_mem> *clMemToCleanUp = new list<cl_mem>(); 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 afcdc70889b..73314c947f5 100644 --- a/source/blender/compositor/operations/COM_WriteBufferOperation.h +++ b/source/blender/compositor/operations/COM_WriteBufferOperation.h @@ -41,7 +41,7 @@ public: 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 a89a2c7bd62..c9d26adfc46 100644 --- a/source/blender/compositor/operations/COM_ZCombineOperation.h +++ b/source/blender/compositor/operations/COM_ZCombineOperation.h @@ -40,10 +40,10 @@ public: * Default constructor */ ZCombineOperation(); - + void initExecution(); void deinitExecution(); - + /** * the inner loop of this program */ diff --git a/source/blender/depsgraph/intern/builder/deg_builder.cc b/source/blender/depsgraph/intern/builder/deg_builder.cc index f1f3da85968..1b2dcd8fcf8 100644 --- a/source/blender/depsgraph/intern/builder/deg_builder.cc +++ b/source/blender/depsgraph/intern/builder/deg_builder.cc @@ -30,9 +30,14 @@ #include "intern/builder/deg_builder.h" +#include "DNA_anim_types.h" #include "DNA_object_types.h" #include "DNA_ID.h" +extern "C" { +#include "BKE_animsys.h" +} + #include "intern/depsgraph.h" #include "intern/depsgraph_types.h" #include "intern/eval/deg_eval_copy_on_write.h" @@ -53,12 +58,17 @@ void deg_graph_build_finalize(Main *bmain, Depsgraph *graph) foreach (IDDepsNode *id_node, graph->id_nodes) { ID *id = id_node->id_orig; id_node->finalize_build(graph); + int flag = DEG_TAG_TRANSFORM | DEG_TAG_GEOMETRY; if ((id->recalc & ID_RECALC_ALL)) { - DEG_id_tag_update_ex(bmain, id_node->id_orig, 0); + AnimData *adt = BKE_animdata_from_id(id); + if (adt != NULL && (adt->recalc & ADT_RECALC_ANIM) != 0) { + flag |= DEG_TAG_TIME; + } } if (!deg_copy_on_write_is_expanded(id_node->id_cow)) { - DEG_id_tag_update_ex(bmain, id_node->id_orig, DEG_TAG_COPY_ON_WRITE); + flag |= DEG_TAG_COPY_ON_WRITE; } + DEG_id_tag_update_ex(bmain, id_node->id_orig, flag); } } diff --git a/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc b/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc index d67f702ba85..9b0c3354c47 100644 --- a/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc +++ b/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc @@ -458,6 +458,14 @@ void DepsgraphNodeBuilder::build_collection( add_id_node(&collection->id); /* Build collection objects. */ LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) { + if (allow_restrict_flags) { + const int restrict_flag = (graph_->mode == DAG_EVAL_VIEWPORT) + ? OB_RESTRICT_VIEW + : OB_RESTRICT_RENDER; + if (cob->ob->restrictflag & restrict_flag) { + continue; + } + } build_object(-1, cob->ob, DEG_ID_LINKED_INDIRECTLY); } /* Build child collections. */ @@ -552,7 +560,7 @@ void DepsgraphNodeBuilder::build_object_flags( const bool is_from_set = (linked_state == DEG_ID_LINKED_VIA_SET); /* TODO(sergey): Is this really best component to be used? */ add_operation_node(&object->id, - DEG_NODE_TYPE_LAYER_COLLECTIONS, + DEG_NODE_TYPE_OBJECT_FROM_LAYER, function_bind(BKE_object_eval_flush_base_flags, _1, scene_cow, @@ -897,11 +905,11 @@ void DepsgraphNodeBuilder::build_rigidbody(Scene *scene) /* objects - simulation participants */ if (rbw->group) { - const ListBase group_objects = BKE_collection_object_cache_get(rbw->group); - LISTBASE_FOREACH (Base *, base, &group_objects) { - Object *object = base->object; + build_collection(DEG_COLLECTION_OWNER_OBJECT, rbw->group); - if (!object || (object->type != OB_MESH)) + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) + { + if (object->type != OB_MESH) continue; /* 2) create operation for flushing results */ @@ -915,6 +923,7 @@ void DepsgraphNodeBuilder::build_rigidbody(Scene *scene) get_cow_datablock(object)), DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY); } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } } diff --git a/source/blender/depsgraph/intern/builder/deg_builder_relations.cc b/source/blender/depsgraph/intern/builder/deg_builder_relations.cc index eb1ee0c1535..d0b699d34e4 100644 --- a/source/blender/depsgraph/intern/builder/deg_builder_relations.cc +++ b/source/blender/depsgraph/intern/builder/deg_builder_relations.cc @@ -334,51 +334,49 @@ void DepsgraphRelationBuilder::add_forcefield_relations( const char *name) { ListBase *effectors = pdInitEffectors(NULL, scene, object, psys, eff, false); - if (effectors != NULL) { - LISTBASE_FOREACH (EffectorCache *, eff, effectors) { + if (effectors == NULL) { + return; + } + LISTBASE_FOREACH (EffectorCache *, eff, effectors) { + if (eff->ob != object) { + ComponentKey eff_key(&eff->ob->id, DEG_NODE_TYPE_TRANSFORM); + add_relation(eff_key, key, name); + } + if (eff->psys != NULL) { if (eff->ob != object) { - ComponentKey eff_key(&eff->ob->id, DEG_NODE_TYPE_TRANSFORM); + ComponentKey eff_key(&eff->ob->id, DEG_NODE_TYPE_EVAL_PARTICLES); add_relation(eff_key, key, name); + /* TODO: remove this when/if EVAL_PARTICLES is sufficient + * for up to date particles. + */ + ComponentKey mod_key(&eff->ob->id, DEG_NODE_TYPE_GEOMETRY); + add_relation(mod_key, key, name); } - if (eff->psys != NULL) { - if (eff->ob != object) { - ComponentKey eff_key(&eff->ob->id, DEG_NODE_TYPE_EVAL_PARTICLES); - add_relation(eff_key, key, name); - - /* TODO: remove this when/if EVAL_PARTICLES is sufficient - * for up to date particles. - */ - ComponentKey mod_key(&eff->ob->id, DEG_NODE_TYPE_GEOMETRY); - add_relation(mod_key, key, name); - } - else if (eff->psys != psys) { - OperationKey eff_key(&eff->ob->id, - DEG_NODE_TYPE_EVAL_PARTICLES, - DEG_OPCODE_PARTICLE_SYSTEM_EVAL, - eff->psys->name); - add_relation(eff_key, key, name); - } - } - if (eff->pd->forcefield == PFIELD_SMOKEFLOW && eff->pd->f_source) { - ComponentKey trf_key(&eff->pd->f_source->id, - DEG_NODE_TYPE_TRANSFORM); - add_relation(trf_key, key, "Smoke Force Domain"); - - ComponentKey eff_key(&eff->pd->f_source->id, - DEG_NODE_TYPE_GEOMETRY); - add_relation(eff_key, key, "Smoke Force Domain"); - } - if (add_absorption && (eff->pd->flag & PFIELD_VISIBILITY)) { - add_collision_relations(key, - scene, - object, - NULL, - true, - "Force Absorption"); + else if (eff->psys != psys) { + OperationKey eff_key(&eff->ob->id, + DEG_NODE_TYPE_EVAL_PARTICLES, + DEG_OPCODE_PARTICLE_SYSTEM_EVAL, + eff->psys->name); + add_relation(eff_key, key, name); } } + if (eff->pd->forcefield == PFIELD_SMOKEFLOW && eff->pd->f_source) { + ComponentKey trf_key(&eff->pd->f_source->id, + DEG_NODE_TYPE_TRANSFORM); + add_relation(trf_key, key, "Smoke Force Domain"); + ComponentKey eff_key(&eff->pd->f_source->id, + DEG_NODE_TYPE_GEOMETRY); + add_relation(eff_key, key, "Smoke Force Domain"); + } + if (add_absorption && (eff->pd->flag & PFIELD_VISIBILITY)) { + add_collision_relations(key, + scene, + object, + NULL, + true, + "Force Absorption"); + } } - pdEndEffectors(&effectors); } @@ -471,6 +469,14 @@ void DepsgraphRelationBuilder::build_collection( DEG_OPCODE_TRANSFORM_LOCAL); if (!group_done) { LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) { + if (allow_restrict_flags) { + const int restrict_flag = (graph_->mode == DAG_EVAL_VIEWPORT) + ? OB_RESTRICT_VIEW + : OB_RESTRICT_RENDER; + if (cob->ob->restrictflag & restrict_flag) { + continue; + } + } build_object(NULL, cob->ob); } LISTBASE_FOREACH (CollectionChild *, child, &collection->children) { @@ -478,16 +484,12 @@ void DepsgraphRelationBuilder::build_collection( } } if (object != NULL) { - const ListBase group_objects = BKE_collection_object_cache_get(collection); - const int base_flag = (graph_->mode == DAG_EVAL_VIEWPORT) ? - BASE_VISIBLE_VIEWPORT : BASE_VISIBLE_RENDER; - LISTBASE_FOREACH (Base *, base, &group_objects) { - if ((base->flag & base_flag) == 0) { - continue; - } - ComponentKey dupli_transform_key(&base->object->id, DEG_NODE_TYPE_TRANSFORM); + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(collection, ob, graph_->mode) + { + ComponentKey dupli_transform_key(&ob->id, DEG_NODE_TYPE_TRANSFORM); add_relation(dupli_transform_key, object_local_transform_key, "Dupligroup"); } + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } } @@ -610,7 +612,7 @@ void DepsgraphRelationBuilder::build_object_flags(Base *base, Object *object) DEG_NODE_TYPE_LAYER_COLLECTIONS, DEG_OPCODE_VIEW_LAYER_EVAL); OperationKey object_flags_key(&object->id, - DEG_NODE_TYPE_LAYER_COLLECTIONS, + DEG_NODE_TYPE_OBJECT_FROM_LAYER, DEG_OPCODE_OBJECT_BASE_FLAGS); add_relation(view_layer_done_key, object_flags_key, "Base flags flush"); } @@ -1430,10 +1432,11 @@ void DepsgraphRelationBuilder::build_rigidbody(Scene *scene) /* objects - simulation participants */ if (rbw->group) { - const ListBase group_objects = BKE_collection_object_cache_get(rbw->group); - LISTBASE_FOREACH (Base *, base, &group_objects) { - Object *object = base->object; - if (object == NULL || object->type != OB_MESH) { + build_collection(DEG_COLLECTION_OWNER_OBJECT, NULL, rbw->group); + + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) + { + if (object->type != OB_MESH) { continue; } @@ -1452,6 +1455,13 @@ void DepsgraphRelationBuilder::build_rigidbody(Scene *scene) add_relation(sim_key, rbo_key, "Rigidbody Sim Eval -> RBO Sync"); + /* Geometry must be known to create the rigid body. RBO_MESH_BASE uses the non-evaluated + * mesh, so then the evaluation is unnecessary. */ + if (object->rigidbody_object->mesh_source != RBO_MESH_BASE) { + ComponentKey geom_key(&object->id, DEG_NODE_TYPE_GEOMETRY); + add_relation(geom_key, init_key, "Object Geom Eval -> Rigidbody Rebuild"); + } + /* if constraints exist, those depend on the result of the rigidbody sim * - This allows constraints to modify the result of the sim (i.e. clamping) * while still allowing the sim to depend on some changes to the objects. @@ -1481,14 +1491,14 @@ void DepsgraphRelationBuilder::build_rigidbody(Scene *scene) /* Needed to get correct base values. */ add_relation(trans_op, sim_key, "Base Ob Transform -> Rigidbody Sim Eval"); } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } /* constraints */ if (rbw->constraints) { - const ListBase constraint_objects = BKE_collection_object_cache_get(rbw->constraints); - LISTBASE_FOREACH (Base *, base, &constraint_objects) { - Object *object = base->object; - if (object == NULL || !object->rigidbody_constraint) { + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, object) + { + if (!object->rigidbody_constraint) { continue; } @@ -1508,6 +1518,7 @@ void DepsgraphRelationBuilder::build_rigidbody(Scene *scene) /* - ensure that sim depends on this constraint's transform */ add_relation(trans_key, sim_key, "RigidBodyConstraint Transform -> RB Simulation"); } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } } diff --git a/source/blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc b/source/blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc index d64ab79d918..df6e72f490f 100644 --- a/source/blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc +++ b/source/blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc @@ -271,6 +271,26 @@ static void deg_debug_graphviz_relation_style(const DebugContext &ctx, deg_debug_fprintf(ctx, "%s", style); } +static void deg_debug_graphviz_relation_arrowhead(const DebugContext &ctx, + const DepsRelation *rel) +{ + const char *shape_default = "normal"; + const char *shape_no_cow = "box"; + const char *shape = shape_default; + if (rel->from->get_class() == DEG_NODE_CLASS_OPERATION && + rel->to->get_class() == DEG_NODE_CLASS_OPERATION) + { + OperationDepsNode *op_from = (OperationDepsNode *)rel->from; + OperationDepsNode *op_to = (OperationDepsNode *)rel->to; + if (op_from->owner->type == DEG_NODE_TYPE_COPY_ON_WRITE && + !op_to->owner->need_tag_cow_before_update()) + { + shape = shape_no_cow; + } + } + deg_debug_fprintf(ctx, "%s", shape); +} + static void deg_debug_graphviz_node_style(const DebugContext &ctx, const DepsNode *node) { const char *base_style = "filled"; /* default style */ @@ -386,6 +406,7 @@ static void deg_debug_graphviz_node(const DebugContext &ctx, case DEG_NODE_TYPE_LAYER_COLLECTIONS: case DEG_NODE_TYPE_EVAL_PARTICLES: case DEG_NODE_TYPE_COPY_ON_WRITE: + case DEG_NODE_TYPE_OBJECT_FROM_LAYER: case DEG_NODE_TYPE_BATCH_CACHE: { ComponentDepsNode *comp_node = (ComponentDepsNode *)node; @@ -484,6 +505,8 @@ static void deg_debug_graphviz_node_relations(const DebugContext &ctx, deg_debug_graphviz_relation_color(ctx, rel); deg_debug_fprintf(ctx, ",style="); deg_debug_graphviz_relation_style(ctx, rel); + deg_debug_fprintf(ctx, ",arrowhead="); + deg_debug_graphviz_relation_arrowhead(ctx, rel); deg_debug_fprintf(ctx, ",penwidth=\"%f\"", penwidth); /* NOTE: edge from node to own cluster is not possible and gives graphviz * warning, avoid this here by just linking directly to the invisible diff --git a/source/blender/depsgraph/intern/depsgraph.cc b/source/blender/depsgraph/intern/depsgraph.cc index 26a23cff372..16427d3eb59 100644 --- a/source/blender/depsgraph/intern/depsgraph.cc +++ b/source/blender/depsgraph/intern/depsgraph.cc @@ -327,27 +327,33 @@ IDDepsNode *Depsgraph::add_id_node(ID *id, ID *id_cow_hint) return id_node; } -void Depsgraph::clear_id_nodes() +void Depsgraph::clear_id_nodes_conditional(const std::function <bool (ID_Type id_type)>& filter) { - /* Free memory used by ID nodes. */ - { - /* Stupid workaround to ensure we free IDs in a proper order. */ - foreach (IDDepsNode *id_node, id_nodes) { - if (id_node->id_cow == NULL) { - /* This means builder "stole" ownership of the copy-on-written - * datablock for her own dirty needs. - */ - continue; - } - if (!deg_copy_on_write_is_expanded(id_node->id_cow)) { - continue; - } - const ID_Type id_type = GS(id_node->id_cow->name); - if (id_type != ID_PA) { - id_node->destroy(); - } + foreach (IDDepsNode *id_node, id_nodes) { + if (id_node->id_cow == NULL) { + /* This means builder "stole" ownership of the copy-on-written + * datablock for her own dirty needs. + */ + continue; + } + if (!deg_copy_on_write_is_expanded(id_node->id_cow)) { + continue; + } + const ID_Type id_type = GS(id_node->id_cow->name); + if (filter(id_type)) { + id_node->destroy(); } } +} + +void Depsgraph::clear_id_nodes() +{ + /* Free memory used by ID nodes. */ + + /* Stupid workaround to ensure we free IDs in a proper order. */ + clear_id_nodes_conditional([](ID_Type id_type) { return id_type == ID_SCE; }); + clear_id_nodes_conditional([](ID_Type id_type) { return id_type != ID_PA; }); + foreach (IDDepsNode *id_node, id_nodes) { OBJECT_GUARDED_DELETE(id_node, IDDepsNode); } diff --git a/source/blender/depsgraph/intern/depsgraph.h b/source/blender/depsgraph/intern/depsgraph.h index 3c1233cd5bb..a69be39c50b 100644 --- a/source/blender/depsgraph/intern/depsgraph.h +++ b/source/blender/depsgraph/intern/depsgraph.h @@ -38,6 +38,8 @@ #include <stdlib.h> +#include "DNA_ID.h" /* for ID_Type */ + #include "BKE_library.h" /* for MAX_LIBARRAY */ #include "BLI_threads.h" /* for SpinLock */ @@ -128,6 +130,7 @@ struct Depsgraph { IDDepsNode *find_id_node(const ID *id) const; IDDepsNode *add_id_node(ID *id, ID *id_cow_hint = NULL); void clear_id_nodes(); + void clear_id_nodes_conditional(const std::function <bool (ID_Type id_type)>& filter); /* Add new relationship between two nodes. */ DepsRelation *add_new_relation(OperationDepsNode *from, diff --git a/source/blender/depsgraph/intern/depsgraph_query_iter.cc b/source/blender/depsgraph/intern/depsgraph_query_iter.cc index 5dca0e83124..1dd6f8b6a0b 100644 --- a/source/blender/depsgraph/intern/depsgraph_query_iter.cc +++ b/source/blender/depsgraph/intern/depsgraph_query_iter.cc @@ -60,9 +60,30 @@ extern "C" { # include "intern/eval/deg_eval_copy_on_write.h" #endif +// If defined, all working data will be set to an invalid state, helping +// to catch issues when areas accessing data which is considered to be no +// longer available. +#undef INVALIDATE_WORK_DATA + +#ifndef NDEBUG +# define INVALIDATE_WORK_DATA +#endif + /* ************************ DEG ITERATORS ********************* */ -static void verify_id_proeprties_freed(DEGObjectIterData *data) +namespace { + +void deg_invalidate_iterator_work_data(DEGObjectIterData *data) +{ +#ifdef INVALIDATE_WORK_DATA + BLI_assert(data != NULL); + memset(&data->temp_dupli_object, 0xff, sizeof(data->temp_dupli_object)); +#else + (void) data; +#endif +} + +void verify_id_proeprties_freed(DEGObjectIterData *data) { if (data->dupli_object_current == NULL) { // We didn't enter duplication yet, so we can't have any dangling @@ -86,7 +107,7 @@ static void verify_id_proeprties_freed(DEGObjectIterData *data) temp_dupli_object->id.properties = NULL; } -static bool deg_objects_dupli_iterator_next(BLI_Iterator *iter) +bool deg_objects_dupli_iterator_next(BLI_Iterator *iter) { DEGObjectIterData *data = (DEGObjectIterData *)iter->data; while (data->dupli_object_next != NULL) { @@ -137,7 +158,7 @@ static bool deg_objects_dupli_iterator_next(BLI_Iterator *iter) return false; } -static void DEG_iterator_objects_step(BLI_Iterator *iter, DEG::IDDepsNode *id_node) +void deg_iterator_objects_step(BLI_Iterator *iter, DEG::IDDepsNode *id_node) { /* Set it early in case we need to exit and we are running from within a loop. */ iter->skip = true; @@ -191,6 +212,8 @@ static void DEG_iterator_objects_step(BLI_Iterator *iter, DEG::IDDepsNode *id_no iter->skip = false; } +} // namespace + void DEG_iterator_objects_begin(BLI_Iterator *iter, DEGObjectIterData *data) { Depsgraph *depsgraph = data->graph; @@ -215,9 +238,10 @@ void DEG_iterator_objects_begin(BLI_Iterator *iter, DEGObjectIterData *data) data->visibility_check = (eval_mode == DAG_EVAL_RENDER) ? OB_VISIBILITY_CHECK_FOR_RENDER : OB_VISIBILITY_CHECK_FOR_VIEWPORT; + deg_invalidate_iterator_work_data(data); DEG::IDDepsNode *id_node = deg_graph->id_nodes[data->id_node_index]; - DEG_iterator_objects_step(iter, id_node); + deg_iterator_objects_step(iter, id_node); if (iter->skip) { DEG_iterator_objects_next(iter); @@ -242,6 +266,7 @@ void DEG_iterator_objects_next(BLI_Iterator *iter) data->dupli_list = NULL; data->dupli_object_next = NULL; data->dupli_object_current = NULL; + deg_invalidate_iterator_work_data(data); } } @@ -252,24 +277,19 @@ void DEG_iterator_objects_next(BLI_Iterator *iter) } DEG::IDDepsNode *id_node = deg_graph->id_nodes[data->id_node_index]; - DEG_iterator_objects_step(iter, id_node); + deg_iterator_objects_step(iter, id_node); } while (iter->skip); } void DEG_iterator_objects_end(BLI_Iterator *iter) { -#ifndef NDEBUG DEGObjectIterData *data = (DEGObjectIterData *)iter->data; - - if (data) { + if (data != NULL) { /* Force crash in case the iterator data is referenced and accessed down * the line. (T51718) */ - memset(&data->temp_dupli_object, 0xff, sizeof(data->temp_dupli_object)); + deg_invalidate_iterator_work_data(data); } -#else - (void) iter; -#endif } /* ************************ DEG ID ITERATOR ********************* */ diff --git a/source/blender/depsgraph/intern/depsgraph_tag.cc b/source/blender/depsgraph/intern/depsgraph_tag.cc index 8ff11ca5fd2..9128571155f 100644 --- a/source/blender/depsgraph/intern/depsgraph_tag.cc +++ b/source/blender/depsgraph/intern/depsgraph_tag.cc @@ -142,7 +142,7 @@ void depsgraph_select_tag_to_component_opcode( *operation_code = DEG_OPCODE_VIEW_LAYER_EVAL; } else if (id_type == ID_OB) { - *component_type = DEG_NODE_TYPE_LAYER_COLLECTIONS; + *component_type = DEG_NODE_TYPE_OBJECT_FROM_LAYER; *operation_code = DEG_OPCODE_OBJECT_BASE_FLAGS; } else { @@ -162,7 +162,7 @@ void depsgraph_base_flags_tag_to_component_opcode( *operation_code = DEG_OPCODE_VIEW_LAYER_EVAL; } else if (id_type == ID_OB) { - *component_type = DEG_NODE_TYPE_LAYER_COLLECTIONS; + *component_type = DEG_NODE_TYPE_OBJECT_FROM_LAYER; *operation_code = DEG_OPCODE_OBJECT_BASE_FLAGS; } } @@ -284,7 +284,7 @@ void depsgraph_tag_component(Depsgraph *graph, } } /* If component depends on copy-on-write, tag it as well. */ - if (component_node->depends_on_cow()) { + if (component_node->need_tag_cow_before_update()) { ComponentDepsNode *cow_comp = id_node->find_component(DEG_NODE_TYPE_COPY_ON_WRITE); cow_comp->tag_update(graph); @@ -449,17 +449,7 @@ void deg_graph_node_tag_zero(Main *bmain, Depsgraph *graph, IDDepsNode *id_node) GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, id_node->components) { if (comp_node->type == DEG_NODE_TYPE_ANIMATION) { - AnimData *adt = BKE_animdata_from_id(id); - /* NOTE: Animation data might be null if relations are tagged - * for update. - */ - if (adt == NULL || (adt->recalc & ADT_RECALC_ANIM) == 0) { - /* If there is no animation, or animation is not tagged for - * update yet, we don't force animation channel to be evaluated. - */ - continue; - } - id->recalc |= ID_RECALC_ANIMATION; + continue; } comp_node->tag_update(graph); } diff --git a/source/blender/depsgraph/intern/depsgraph_type_defines.cc b/source/blender/depsgraph/intern/depsgraph_type_defines.cc index 79d29f72b8d..9b1733bae8e 100644 --- a/source/blender/depsgraph/intern/depsgraph_type_defines.cc +++ b/source/blender/depsgraph/intern/depsgraph_type_defines.cc @@ -92,6 +92,7 @@ const char *nodeTypeAsString(eDepsNode_Type type) STRINGIFY_TYPE(SEQUENCER); STRINGIFY_TYPE(LAYER_COLLECTIONS); STRINGIFY_TYPE(COPY_ON_WRITE); + STRINGIFY_TYPE(OBJECT_FROM_LAYER); /* **** Evaluation-Related Outer Types (with Subdata) **** */ STRINGIFY_TYPE(EVAL_POSE); STRINGIFY_TYPE(BONE); diff --git a/source/blender/depsgraph/intern/depsgraph_types.h b/source/blender/depsgraph/intern/depsgraph_types.h index cec279a04bb..c6eb0d57bac 100644 --- a/source/blender/depsgraph/intern/depsgraph_types.h +++ b/source/blender/depsgraph/intern/depsgraph_types.h @@ -134,6 +134,10 @@ typedef enum eDepsNode_Type { * execution. */ DEG_NODE_TYPE_COPY_ON_WRITE, + /* Used by all operations which are updating object when something is + * changed in view layer. + */ + DEG_NODE_TYPE_OBJECT_FROM_LAYER, /* **** Evaluation-Related Outer Types (with Subdata) **** */ diff --git a/source/blender/depsgraph/intern/eval/deg_eval_flush.cc b/source/blender/depsgraph/intern/eval/deg_eval_flush.cc index 3330c802aa9..e9f11f8e089 100644 --- a/source/blender/depsgraph/intern/eval/deg_eval_flush.cc +++ b/source/blender/depsgraph/intern/eval/deg_eval_flush.cc @@ -34,9 +34,13 @@ // TODO(sergey): Use some sort of wrapper. #include <deque> +#include <cmath> + +#include "BKE_object.h" #include "BLI_utildefines.h" #include "BLI_listbase.h" +#include "BLI_math_vector.h" #include "BLI_task.h" #include "BLI_ghash.h" @@ -55,6 +59,17 @@ extern "C" { #include "intern/eval/deg_eval_copy_on_write.h" #include "util/deg_util_foreach.h" +// Invalidate datablock data when update is flushed on it. +// +// The idea of this is to help catching cases when area is accessing data which +// is not yet evaluated, which could happen due to missing relations. The issue +// is that usually that data will be kept from previous frame, and it looks to +// be plausible. +// +// This ensures that data does not look plausible, making it much easier to +// catch usage of invalid state. +#undef INVALIDATE_ON_FLUSH + namespace DEG { enum { @@ -255,6 +270,72 @@ void flush_editors_id_update(Main *bmain, } } +#ifdef INVALIDATE_ON_FLUSH +void invalidate_tagged_evaluated_transform(ID *id) +{ + const ID_Type id_type = GS(id->name); + switch (id_type) { + case ID_OB: + { + Object *object = (Object *)id; + copy_vn_fl((float *)object->obmat, 16, NAN); + break; + } + default: + break; + } +} + +void invalidate_tagged_evaluated_geometry(ID *id) +{ + const ID_Type id_type = GS(id->name); + switch (id_type) { + case ID_OB: + { + Object *object = (Object *)id; + BKE_object_free_derived_caches(object); + break; + } + default: + break; + } +} +#endif + +void invalidate_tagged_evaluated_data(Depsgraph *graph) +{ +#ifdef INVALIDATE_ON_FLUSH + foreach (IDDepsNode *id_node, graph->id_nodes) { + if (id_node->done != ID_STATE_MODIFIED) { + continue; + } + ID *id_cow = id_node->id_cow; + if (!deg_copy_on_write_is_expanded(id_cow)) { + continue; + } + GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, id_node->components) + { + if (comp_node->done != COMPONENT_STATE_DONE) { + continue; + } + switch (comp_node->type) { + case DEG_TAG_TRANSFORM: + invalidate_tagged_evaluated_transform(id_cow); + break; + case DEG_TAG_GEOMETRY: + invalidate_tagged_evaluated_geometry(id_cow); + break; + default: + break; + } + } + GHASH_FOREACH_END(); + } +#else + (void) graph; +#endif +} + } // namespace /* Flush updates from tagged nodes outwards until all affected nodes @@ -300,6 +381,10 @@ void deg_graph_flush_updates(Main *bmain, Depsgraph *graph) } /* Inform editors about all changes. */ flush_editors_id_update(bmain, graph, &update_ctx); + /* Reset evaluation result tagged which is tagged for update to some state + * which is obvious to catch. + */ + invalidate_tagged_evaluated_data(graph); } static void graph_clear_operation_func( diff --git a/source/blender/depsgraph/intern/nodes/deg_node_component.cc b/source/blender/depsgraph/intern/nodes/deg_node_component.cc index 699ee1a3cad..9600eadb126 100644 --- a/source/blender/depsgraph/intern/nodes/deg_node_component.cc +++ b/source/blender/depsgraph/intern/nodes/deg_node_component.cc @@ -392,6 +392,7 @@ DEG_COMPONENT_NODE_DEFINE(Sequencer, SEQUENCER, ID_RECALC); DEG_COMPONENT_NODE_DEFINE(Shading, SHADING, ID_RECALC_DRAW); DEG_COMPONENT_NODE_DEFINE(ShadingParameters, SHADING_PARAMETERS, ID_RECALC_DRAW); DEG_COMPONENT_NODE_DEFINE(Transform, TRANSFORM, ID_RECALC_TRANSFORM); +DEG_COMPONENT_NODE_DEFINE(ObjectFromLayer, OBJECT_FROM_LAYER, ID_RECALC); /* Node Types Register =================================== */ @@ -412,6 +413,7 @@ void deg_register_component_depsnodes() deg_register_node_typeinfo(&DNTI_SHADING); deg_register_node_typeinfo(&DNTI_SHADING_PARAMETERS); deg_register_node_typeinfo(&DNTI_TRANSFORM); + deg_register_node_typeinfo(&DNTI_OBJECT_FROM_LAYER); } } // namespace DEG diff --git a/source/blender/depsgraph/intern/nodes/deg_node_component.h b/source/blender/depsgraph/intern/nodes/deg_node_component.h index 5b6461f950e..5e79dc1c685 100644 --- a/source/blender/depsgraph/intern/nodes/deg_node_component.h +++ b/source/blender/depsgraph/intern/nodes/deg_node_component.h @@ -144,8 +144,12 @@ struct ComponentDepsNode : public DepsNode { OperationDepsNode *entry_operation; OperationDepsNode *exit_operation; - // XXX: a poll() callback to check if component's first node can be started? virtual bool depends_on_cow() { return true; } + + /* Denotes whether COW component is to be tagged when this component + * is tagged for update. + */ + virtual bool need_tag_cow_before_update() { return true; } }; /* ---------------------------------------- */ @@ -168,8 +172,14 @@ struct ComponentDepsNode : public DepsNode { DEG_COMPONENT_NODE_DECLARE; \ } +#define DEG_COMPONENT_NODE_DECLARE_NO_COW_TAG_ON_UPDATE(name) \ + struct name ## ComponentDepsNode : public ComponentDepsNode { \ + DEG_COMPONENT_NODE_DECLARE; \ + virtual bool need_tag_cow_before_update() { return false; } \ + } + DEG_COMPONENT_NODE_DECLARE_GENERIC(Animation); -DEG_COMPONENT_NODE_DECLARE_GENERIC(BatchCache); +DEG_COMPONENT_NODE_DECLARE_NO_COW_TAG_ON_UPDATE(BatchCache); DEG_COMPONENT_NODE_DECLARE_GENERIC(Cache); DEG_COMPONENT_NODE_DECLARE_GENERIC(CopyOnWrite); DEG_COMPONENT_NODE_DECLARE_GENERIC(Geometry); @@ -182,6 +192,7 @@ DEG_COMPONENT_NODE_DECLARE_GENERIC(Sequencer); DEG_COMPONENT_NODE_DECLARE_GENERIC(Shading); DEG_COMPONENT_NODE_DECLARE_GENERIC(ShadingParameters); DEG_COMPONENT_NODE_DECLARE_GENERIC(Transform); +DEG_COMPONENT_NODE_DECLARE_NO_COW_TAG_ON_UPDATE(ObjectFromLayer); /* Bone Component */ struct BoneComponentDepsNode : public ComponentDepsNode { diff --git a/source/blender/depsgraph/intern/nodes/deg_node_id.cc b/source/blender/depsgraph/intern/nodes/deg_node_id.cc index 956c23978ab..3a164a50692 100644 --- a/source/blender/depsgraph/intern/nodes/deg_node_id.cc +++ b/source/blender/depsgraph/intern/nodes/deg_node_id.cc @@ -156,6 +156,7 @@ void IDDepsNode::destroy() if (id_cow != id_orig && id_cow != NULL) { deg_free_copy_on_write_datablock(id_cow); MEM_freeN(id_cow); + id_cow = NULL; DEG_COW_PRINT("Destroy CoW for %s: id_orig=%p id_cow=%p\n", id_orig->name, id_orig, id_cow); } diff --git a/source/blender/draw/CMakeLists.txt b/source/blender/draw/CMakeLists.txt index 7d869982f29..2f268663186 100644 --- a/source/blender/draw/CMakeLists.txt +++ b/source/blender/draw/CMakeLists.txt @@ -91,7 +91,6 @@ set(SRC modes/pose_mode.c modes/sculpt_mode.c engines/basic/basic_engine.c - engines/clay/clay_engine.c engines/eevee/eevee_bloom.c engines/eevee/eevee_data.c engines/eevee/eevee_depth_of_field.c @@ -134,27 +133,12 @@ set(SRC modes/draw_mode_engines.h modes/edit_mesh_mode_intern.h engines/basic/basic_engine.h - engines/clay/clay_engine.h engines/eevee/eevee_engine.h engines/eevee/eevee_lut.h engines/eevee/eevee_private.h engines/external/external_engine.h ) -if(WITH_CLAY_ENGINE) - add_definitions(-DWITH_CLAY_ENGINE) -endif() - -data_to_c_simple(engines/clay/shaders/clay_frag.glsl SRC) -data_to_c_simple(engines/clay/shaders/clay_fxaa.glsl SRC) -data_to_c_simple(engines/clay/shaders/clay_copy.glsl SRC) -data_to_c_simple(engines/clay/shaders/clay_prepass_frag.glsl SRC) -data_to_c_simple(engines/clay/shaders/clay_vert.glsl SRC) -data_to_c_simple(engines/clay/shaders/clay_particle_vert.glsl SRC) -data_to_c_simple(engines/clay/shaders/clay_particle_strand_frag.glsl SRC) -data_to_c_simple(engines/clay/shaders/ssao_alchemy.glsl SRC) -data_to_c_simple(engines/clay/shaders/ssao_groundtruth.glsl SRC) - data_to_c_simple(engines/eevee/shaders/ambient_occlusion_lib.glsl SRC) data_to_c_simple(engines/eevee/shaders/default_frag.glsl SRC) data_to_c_simple(engines/eevee/shaders/default_world_frag.glsl SRC) @@ -224,6 +208,7 @@ data_to_c_simple(engines/workbench/shaders/workbench_checkerboard_depth_frag.gls data_to_c_simple(engines/workbench/shaders/workbench_common_lib.glsl SRC) data_to_c_simple(engines/workbench/shaders/workbench_data_lib.glsl SRC) data_to_c_simple(engines/workbench/shaders/workbench_deferred_composite_frag.glsl SRC) +data_to_c_simple(engines/workbench/shaders/workbench_effect_fxaa_frag.glsl SRC) data_to_c_simple(engines/workbench/shaders/workbench_forward_composite_frag.glsl SRC) data_to_c_simple(engines/workbench/shaders/workbench_forward_depth_frag.glsl SRC) data_to_c_simple(engines/workbench/shaders/workbench_forward_transparent_accum_frag.glsl SRC) @@ -259,6 +244,7 @@ data_to_c_simple(modes/shaders/armature_shape_outline_vert.glsl SRC) data_to_c_simple(modes/shaders/armature_shape_outline_geom.glsl SRC) data_to_c_simple(modes/shaders/armature_stick_vert.glsl SRC) data_to_c_simple(modes/shaders/armature_stick_frag.glsl SRC) +data_to_c_simple(modes/shaders/edit_mesh_overlay_common_lib.glsl SRC) data_to_c_simple(modes/shaders/edit_mesh_overlay_frag.glsl SRC) data_to_c_simple(modes/shaders/edit_mesh_overlay_vert.glsl SRC) data_to_c_simple(modes/shaders/edit_mesh_overlay_geom_tri.glsl SRC) diff --git a/source/blender/draw/DRW_engine.h b/source/blender/draw/DRW_engine.h index 524a94e5886..d126dcb71aa 100644 --- a/source/blender/draw/DRW_engine.h +++ b/source/blender/draw/DRW_engine.h @@ -94,6 +94,8 @@ void DRW_notify_view_update(const DRWUpdateContext *update_ctx); typedef enum eDRWSelectStage { DRW_SELECT_PASS_PRE = 1, DRW_SELECT_PASS_POST, } eDRWSelectStage; typedef bool (*DRW_SelectPassFn)( eDRWSelectStage stage, void *user_data); +typedef bool (*DRW_ObjectFilterFn)( + struct Object *ob, void *user_data); void DRW_draw_view(const struct bContext *C); @@ -118,7 +120,8 @@ void DRW_draw_select_loop( struct Depsgraph *depsgraph, struct ARegion *ar, struct View3D *v3d, bool use_obedit_skip, bool use_nearest, const struct rcti *rect, - DRW_SelectPassFn select_pass_fn, void *select_pass_user_data); + DRW_SelectPassFn select_pass_fn, void *select_pass_user_data, + DRW_ObjectFilterFn object_filter_fn, void *object_filter_user_data); void DRW_draw_depth_loop( struct Depsgraph *depsgraph, struct ARegion *ar, struct View3D *v3d); diff --git a/source/blender/draw/engines/clay/clay_engine.c b/source/blender/draw/engines/clay/clay_engine.c deleted file mode 100644 index 5d3717097b1..00000000000 --- a/source/blender/draw/engines/clay/clay_engine.c +++ /dev/null @@ -1,985 +0,0 @@ -/* - * Copyright 2016, 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(s): Blender Institute - * - */ - -#include "BLI_utildefines.h" -#include "BLI_string_utils.h" -#include "BLI_rand.h" - -#include "DNA_particle_types.h" -#include "DNA_view3d_types.h" - -#include "BKE_icons.h" -#include "BKE_idprop.h" -#include "BKE_main.h" -#include "BKE_particle.h" - -#include "GPU_shader.h" - -#include "IMB_imbuf.h" -#include "IMB_imbuf_types.h" - -#include "UI_resources.h" -#include "UI_interface_icons.h" - -#include "DRW_render.h" - -#include "DEG_depsgraph_query.h" - -#include "clay_engine.h" - -#ifdef WITH_CLAY_ENGINE -#include "../eevee/eevee_lut.h" /* TODO find somewhere to share blue noise Table */ - -/* Shaders */ - -#define CLAY_ENGINE "BLENDER_CLAY" - -#define MAX_CLAY_MAT 512 /* 512 = 9 bit material id */ - -#define SHADER_DEFINES_NO_AO \ - "#define MAX_MATERIAL " STRINGIFY(MAX_CLAY_MAT) "\n" \ - "#define USE_ROTATION\n" \ - "#define USE_HSV\n" - -#define SHADER_DEFINES \ - SHADER_DEFINES_NO_AO \ - "#define USE_AO\n" - -extern char datatoc_clay_frag_glsl[]; -extern char datatoc_clay_prepass_frag_glsl[]; -extern char datatoc_clay_copy_glsl[]; -extern char datatoc_clay_vert_glsl[]; -extern char datatoc_clay_fxaa_glsl[]; -extern char datatoc_clay_particle_vert_glsl[]; -extern char datatoc_clay_particle_strand_frag_glsl[]; -extern char datatoc_ssao_alchemy_glsl[]; -extern char datatoc_common_fxaa_lib_glsl[]; - -/* *********** LISTS *********** */ - -/** - * UBOs data needs to be 16 byte aligned (size of vec4) - * - * Reminder: float, int, bool are 4 bytes - * - * \note struct is expected to be initialized with all pad-bits zero'd - * so we can use 'memcmp' to check for duplicates. Possibly hash data later. - */ -typedef struct CLAY_UBO_Material { - float ssao_params_var[4]; - /* - 16 -*/ - float matcap_hsv[3]; - float matcap_id; /* even float encoding have enough precision */ - /* - 16 -*/ - float matcap_rot[2]; - float pad[2]; /* ensure 16 bytes alignement */ -} CLAY_UBO_Material; /* 48 bytes */ -BLI_STATIC_ASSERT_ALIGN(CLAY_UBO_Material, 16) - -typedef struct CLAY_HAIR_UBO_Material { - float hair_randomness; - float matcap_id; - float matcap_rot[2]; - float matcap_hsv[3]; - float pad; -} CLAY_HAIR_UBO_Material; /* 32 bytes */ -BLI_STATIC_ASSERT_ALIGN(CLAY_HAIR_UBO_Material, 16) - -typedef struct CLAY_UBO_Storage { - CLAY_UBO_Material materials[MAX_CLAY_MAT]; -} CLAY_UBO_Storage; - -typedef struct CLAY_HAIR_UBO_Storage { - CLAY_HAIR_UBO_Material materials[MAX_CLAY_MAT]; -} CLAY_HAIR_UBO_Storage; - -/* GPUViewport.storage - * Is freed everytime the viewport engine changes */ -typedef struct CLAY_Storage { - /* Materials Parameter UBO */ - CLAY_UBO_Storage mat_storage; - CLAY_HAIR_UBO_Storage hair_mat_storage; - int ubo_current_id; - int hair_ubo_current_id; - DRWShadingGroup *shgrps[MAX_CLAY_MAT]; - DRWShadingGroup *shgrps_flat[MAX_CLAY_MAT]; - DRWShadingGroup *shgrps_pre[MAX_CLAY_MAT]; - DRWShadingGroup *shgrps_pre_flat[MAX_CLAY_MAT]; - DRWShadingGroup *hair_shgrps[MAX_CLAY_MAT]; -} CLAY_Storage; - -typedef struct CLAY_StorageList { - struct CLAY_Storage *storage; - struct CLAY_PrivateData *g_data; -} CLAY_StorageList; - -typedef struct CLAY_FramebufferList { - struct GPUFrameBuffer *antialias_fb; - struct GPUFrameBuffer *prepass_fb; -} CLAY_FramebufferList; - -typedef struct CLAY_PassList { - struct DRWPass *clay_ps; - struct DRWPass *clay_cull_ps; - struct DRWPass *clay_flat_ps; - struct DRWPass *clay_flat_cull_ps; - struct DRWPass *clay_pre_ps; - struct DRWPass *clay_pre_cull_ps; - struct DRWPass *clay_flat_pre_ps; - struct DRWPass *clay_flat_pre_cull_ps; - struct DRWPass *clay_deferred_ps; - struct DRWPass *fxaa_ps; - struct DRWPass *copy_ps; - struct DRWPass *hair_pass; -} CLAY_PassList; - - -typedef struct CLAY_Data { - void *engine_type; - CLAY_FramebufferList *fbl; - DRWViewportEmptyList *txl; - CLAY_PassList *psl; - CLAY_StorageList *stl; -} CLAY_Data; - -typedef struct CLAY_ViewLayerData { - struct GPUTexture *jitter_tx; - struct GPUUniformBuffer *mat_ubo; - struct GPUUniformBuffer *matcaps_ubo; - struct GPUUniformBuffer *hair_mat_ubo; - struct GPUUniformBuffer *sampling_ubo; - int cached_sample_num; -} CLAY_ViewLayerData; - -/* *********** STATIC *********** */ - -static struct { - /* Shading Pass */ - struct GPUShader *clay_sh; - struct GPUShader *clay_flat_sh; - struct GPUShader *clay_prepass_flat_sh; - struct GPUShader *clay_prepass_sh; - struct GPUShader *clay_deferred_shading_sh; - struct GPUShader *fxaa_sh; - struct GPUShader *copy_sh; - struct GPUShader *hair_sh; - /* Matcap textures */ - struct GPUTexture *matcap_array; - float matcap_colors[24][4]; - /* Just a serie of int from 0 to MAX_CLAY_MAT-1 */ - int ubo_mat_idxs[MAX_CLAY_MAT]; - /* To avoid useless texture and ubo binds. */ - bool first_shgrp; -} e_data = {NULL}; /* Engine data */ - -typedef struct CLAY_PrivateData { - DRWShadingGroup *depth_shgrp; - DRWShadingGroup *depth_shgrp_select; - DRWShadingGroup *depth_shgrp_active; - DRWShadingGroup *depth_shgrp_cull; - DRWShadingGroup *depth_shgrp_cull_select; - DRWShadingGroup *depth_shgrp_cull_active; - /* Deferred shading */ - struct GPUTexture *depth_tx; /* ref only, not alloced */ - struct GPUTexture *normal_tx; /* ref only, not alloced */ - struct GPUTexture *id_tx; /* ref only, not alloced */ - struct GPUTexture *color_copy; /* ref only, not alloced */ - bool enable_deferred_path; - /* Ssao */ - float winmat[4][4]; - float viewvecs[3][4]; - float ssao_params[4]; -} CLAY_PrivateData; /* Transient data */ - -/* Functions */ - -static void clay_view_layer_data_free(void *storage) -{ - CLAY_ViewLayerData *sldata = (CLAY_ViewLayerData *)storage; - - DRW_UBO_FREE_SAFE(sldata->mat_ubo); - DRW_UBO_FREE_SAFE(sldata->matcaps_ubo); - DRW_UBO_FREE_SAFE(sldata->hair_mat_ubo); - DRW_UBO_FREE_SAFE(sldata->sampling_ubo); - DRW_TEXTURE_FREE_SAFE(sldata->jitter_tx); -} - -static CLAY_ViewLayerData *CLAY_view_layer_data_get(void) -{ - CLAY_ViewLayerData **sldata = (CLAY_ViewLayerData **)DRW_view_layer_engine_data_ensure( - &draw_engine_clay_type, &clay_view_layer_data_free); - - if (*sldata == NULL) { - *sldata = MEM_callocN(sizeof(**sldata), "CLAY_ViewLayerData"); - } - - return *sldata; -} - -static void add_icon_to_rect(PreviewImage *prv, float *final_rect, int layer) -{ - int image_size = prv->w[0] * prv->h[0]; - float *new_rect = &final_rect[image_size * 4 * layer]; - - IMB_buffer_float_from_byte(new_rect, (unsigned char *)prv->rect[0], IB_PROFILE_SRGB, IB_PROFILE_SRGB, - false, prv->w[0], prv->h[0], prv->w[0], prv->w[0]); - - /* Find overall color */ - for (int y = 0; y < 4; ++y) { - for (int x = 0; x < 4; ++x) { - e_data.matcap_colors[layer][0] += new_rect[y * 512 * 128 * 4 + x * 128 * 4 + 0]; - e_data.matcap_colors[layer][1] += new_rect[y * 512 * 128 * 4 + x * 128 * 4 + 1]; - e_data.matcap_colors[layer][2] += new_rect[y * 512 * 128 * 4 + x * 128 * 4 + 2]; - } - } - - e_data.matcap_colors[layer][0] /= 16.0f * 2.0f; /* the * 2 is to darken for shadows */ - e_data.matcap_colors[layer][1] /= 16.0f * 2.0f; - e_data.matcap_colors[layer][2] /= 16.0f * 2.0f; -} - -static struct GPUTexture *load_matcaps(PreviewImage *prv[24], int nbr) -{ - struct GPUTexture *tex; - int w = prv[0]->w[0]; - int h = prv[0]->h[0]; - float *final_rect = MEM_callocN(sizeof(float) * 4 * w * h * nbr, "Clay Matcap array rect"); - - for (int i = 0; i < nbr; ++i) { - add_icon_to_rect(prv[i], final_rect, i); - BKE_previewimg_free(&prv[i]); - } - - tex = DRW_texture_create_2D_array(w, h, nbr, GPU_RGBA8, DRW_TEX_FILTER, final_rect); - MEM_freeN(final_rect); - - return tex; -} - -static int matcap_to_index(int matcap) -{ - return matcap - 1; -} - -/* Using Hammersley distribution */ -static float *create_disk_samples(int num_samples) -{ - /* vec4 to ensure memory alignment. */ - float (*texels)[4] = MEM_mallocN(sizeof(float[4]) * num_samples, "concentric_tex"); - const float num_samples_inv = 1.0f / num_samples; - - for (int i = 0; i < num_samples; i++) { - float r = (i + 0.5f) * num_samples_inv; - double dphi; - BLI_hammersley_1D(i, &dphi); - - float phi = (float)dphi * 2.0f * M_PI; - texels[i][0] = cosf(phi); - texels[i][1] = sinf(phi); - /* This deliberatly distribute more samples - * at the center of the disk (and thus the shadow). */ - texels[i][2] = r; - } - - return (float *)texels; -} - -static struct GPUTexture *create_jitter_texture(int num_samples) -{ - float jitter[64 * 64][3]; - const float num_samples_inv = 1.0f / num_samples; - - for (int i = 0; i < 64 * 64; i++) { - float phi = blue_noise[i][0] * 2.0f * M_PI; - /* This rotate the sample per pixels */ - jitter[i][0] = cosf(phi); - jitter[i][1] = sinf(phi); - /* This offset the sample along it's direction axis (reduce banding) */ - float bn = blue_noise[i][1] - 0.5f; - CLAMP(bn, -0.499f, 0.499f); /* fix fireflies */ - jitter[i][2] = bn * num_samples_inv; - } - - UNUSED_VARS(bsdf_split_sum_ggx, btdf_split_sum_ggx, ltc_mag_ggx, ltc_mat_ggx, ltc_disk_integral); - - return DRW_texture_create_2D(64, 64, GPU_RGB16F, DRW_TEX_FILTER | DRW_TEX_WRAP, &jitter[0][0]); -} - -static void clay_engine_init(void *vedata) -{ - CLAY_StorageList *stl = ((CLAY_Data *)vedata)->stl; - CLAY_FramebufferList *fbl = ((CLAY_Data *)vedata)->fbl; - CLAY_ViewLayerData *sldata = CLAY_view_layer_data_get(); - DefaultTextureList *dtxl = DRW_viewport_texture_list_get(); - - /* Create Texture Array */ - if (!e_data.matcap_array) { - PreviewImage *prv[24]; /* For now use all of the 24 internal matcaps */ - const int num_matcap = ARRAY_SIZE(prv); - - /* TODO only load used matcaps */ - for (int i = 0; i < num_matcap; ++i) { - prv[i] = UI_icon_to_preview((int)ICON_MATCAP_01 + i); - } - - e_data.matcap_array = load_matcaps(prv, num_matcap); - } - - /* Shading pass */ - if (!e_data.clay_sh) { - char *matcap_with_ao = BLI_string_joinN( - datatoc_clay_frag_glsl, - datatoc_ssao_alchemy_glsl); - - e_data.clay_sh = DRW_shader_create( - datatoc_clay_vert_glsl, NULL, datatoc_clay_frag_glsl, - SHADER_DEFINES_NO_AO); - e_data.clay_flat_sh = DRW_shader_create( - datatoc_clay_vert_glsl, NULL, datatoc_clay_frag_glsl, - SHADER_DEFINES_NO_AO - "#define USE_FLAT_NORMAL\n"); - - e_data.clay_prepass_sh = DRW_shader_create( - datatoc_clay_vert_glsl, NULL, datatoc_clay_prepass_frag_glsl, - SHADER_DEFINES); - e_data.clay_prepass_flat_sh = DRW_shader_create( - datatoc_clay_vert_glsl, NULL, datatoc_clay_prepass_frag_glsl, - SHADER_DEFINES - "#define USE_FLAT_NORMAL\n"); - - e_data.clay_deferred_shading_sh = DRW_shader_create_fullscreen( - matcap_with_ao, - SHADER_DEFINES - "#define DEFERRED_SHADING\n"); - - MEM_freeN(matcap_with_ao); - - char *fxaa_str = BLI_string_joinN( - datatoc_common_fxaa_lib_glsl, - datatoc_clay_fxaa_glsl); - - e_data.fxaa_sh = DRW_shader_create_fullscreen(fxaa_str, NULL); - - MEM_freeN(fxaa_str); - - e_data.copy_sh = DRW_shader_create_fullscreen(datatoc_clay_copy_glsl, NULL); - } - - if (!stl->storage) { - stl->storage = MEM_callocN(sizeof(CLAY_Storage), "CLAY_Storage"); - } - - if (!stl->g_data) { - stl->g_data = MEM_mallocN(sizeof(*stl->g_data), "CLAY_PrivateStorage"); - } - - CLAY_PrivateData *g_data = stl->g_data; - - if (!sldata->mat_ubo) { - sldata->mat_ubo = DRW_uniformbuffer_create(sizeof(CLAY_UBO_Storage), NULL); - } - - if (!sldata->hair_mat_ubo) { - sldata->hair_mat_ubo = DRW_uniformbuffer_create(sizeof(CLAY_HAIR_UBO_Storage), NULL); - } - - if (!sldata->matcaps_ubo) { - sldata->matcaps_ubo = DRW_uniformbuffer_create(sizeof(e_data.matcap_colors), e_data.matcap_colors); - } - - if (e_data.ubo_mat_idxs[1] == 0) { - /* Just int to have pointers to them */ - for (int i = 0; i < MAX_CLAY_MAT; ++i) { - e_data.ubo_mat_idxs[i] = i; - } - } - - /* FBO setup */ - { - const float *viewport_size = DRW_viewport_size_get(); - const int size[2] = {(int)viewport_size[0], (int)viewport_size[1]}; - - g_data->normal_tx = DRW_texture_pool_query_2D(size[0], size[1], GPU_RG8, &draw_engine_clay_type); - g_data->id_tx = DRW_texture_pool_query_2D(size[0], size[1], GPU_R16UI, &draw_engine_clay_type); - - GPU_framebuffer_ensure_config(&fbl->prepass_fb, { - GPU_ATTACHMENT_TEXTURE(dtxl->depth), - GPU_ATTACHMENT_TEXTURE(g_data->normal_tx), - GPU_ATTACHMENT_TEXTURE(g_data->id_tx) - }); - - /* For FXAA */ - /* TODO(fclem): OPTI: we could merge normal_tx and id_tx into a GPU_RGBA8 - * and reuse it for the fxaa target. */ - g_data->color_copy = DRW_texture_pool_query_2D(size[0], size[1], GPU_RGBA8, &draw_engine_clay_type); - - GPU_framebuffer_ensure_config(&fbl->antialias_fb, { - GPU_ATTACHMENT_NONE, - GPU_ATTACHMENT_TEXTURE(g_data->color_copy) - }); - } - - /* SSAO setup */ - { - const DRWContextState *draw_ctx = DRW_context_state_get(); - Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph); - const int ssao_samples = scene_eval->display.matcap_ssao_samples; - - float invproj[4][4]; - float dfdyfacs[2]; - const bool is_persp = DRW_viewport_is_persp_get(); - /* view vectors for the corners of the view frustum. - * Can be used to recreate the world space position easily */ - float viewvecs[3][4] = { - {-1.0f, -1.0f, -1.0f, 1.0f}, - {1.0f, -1.0f, -1.0f, 1.0f}, - {-1.0f, 1.0f, -1.0f, 1.0f} - }; - int i; - const float *size = DRW_viewport_size_get(); - - DRW_state_dfdy_factors_get(dfdyfacs); - - g_data->ssao_params[0] = ssao_samples; - g_data->ssao_params[1] = size[0] / 64.0; - g_data->ssao_params[2] = size[1] / 64.0; - g_data->ssao_params[3] = dfdyfacs[1]; /* dfdy sign for offscreen */ - - /* invert the view matrix */ - DRW_viewport_matrix_get(g_data->winmat, DRW_MAT_WIN); - invert_m4_m4(invproj, g_data->winmat); - - /* convert the view vectors to view space */ - for (i = 0; i < 3; i++) { - mul_m4_v4(invproj, viewvecs[i]); - /* normalized trick see: - * http://www.derschmale.com/2014/01/26/reconstructing-positions-from-the-depth-buffer */ - mul_v3_fl(viewvecs[i], 1.0f / viewvecs[i][3]); - if (is_persp) - mul_v3_fl(viewvecs[i], 1.0f / viewvecs[i][2]); - viewvecs[i][3] = 1.0; - - copy_v4_v4(g_data->viewvecs[i], viewvecs[i]); - } - - /* we need to store the differences */ - g_data->viewvecs[1][0] -= g_data->viewvecs[0][0]; - g_data->viewvecs[1][1] = g_data->viewvecs[2][1] - g_data->viewvecs[0][1]; - - /* calculate a depth offset as well */ - if (!is_persp) { - float vec_far[] = {-1.0f, -1.0f, 1.0f, 1.0f}; - mul_m4_v4(invproj, vec_far); - mul_v3_fl(vec_far, 1.0f / vec_far[3]); - g_data->viewvecs[1][2] = vec_far[2] - g_data->viewvecs[0][2]; - } - - /* AO Samples Tex */ - if (sldata->sampling_ubo && (sldata->cached_sample_num != ssao_samples)) { - DRW_UBO_FREE_SAFE(sldata->sampling_ubo); - DRW_TEXTURE_FREE_SAFE(sldata->jitter_tx); - } - - if (sldata->sampling_ubo == NULL) { - float *samples = create_disk_samples(ssao_samples); - sldata->jitter_tx = create_jitter_texture(ssao_samples); - sldata->sampling_ubo = DRW_uniformbuffer_create(sizeof(float[4]) * ssao_samples, samples); - sldata->cached_sample_num = ssao_samples; - MEM_freeN(samples); - } - } -} - -static DRWShadingGroup *CLAY_shgroup_create(DRWPass *pass, GPUShader *sh, int id) -{ - CLAY_ViewLayerData *sldata = CLAY_view_layer_data_get(); - DRWShadingGroup *grp = DRW_shgroup_create(sh, pass); - DRW_shgroup_uniform_int(grp, "mat_id", &e_data.ubo_mat_idxs[id], 1); - if (e_data.first_shgrp) { - DRW_shgroup_uniform_texture_persistent(grp, "matcaps", e_data.matcap_array); - DRW_shgroup_uniform_block_persistent(grp, "material_block", sldata->mat_ubo); - DRW_shgroup_uniform_block_persistent(grp, "matcaps_block", sldata->matcaps_ubo); - } - return grp; -} - -static DRWShadingGroup *CLAY_shgroup_deferred_prepass_create(DRWPass *pass, GPUShader *sh, int id) -{ - DRWShadingGroup *grp = DRW_shgroup_create(sh, pass); - DRW_shgroup_uniform_int(grp, "mat_id", &e_data.ubo_mat_idxs[id], 1); - - return grp; -} - -static DRWShadingGroup *CLAY_shgroup_deferred_shading_create(DRWPass *pass, CLAY_PrivateData *g_data) -{ - CLAY_ViewLayerData *sldata = CLAY_view_layer_data_get(); - DRWShadingGroup *grp = DRW_shgroup_create(e_data.clay_deferred_shading_sh, pass); - DRW_shgroup_uniform_texture_ref(grp, "depthtex", &g_data->depth_tx); - DRW_shgroup_uniform_texture_ref(grp, "normaltex", &g_data->normal_tx); - DRW_shgroup_uniform_texture_ref(grp, "idtex", &g_data->id_tx); - DRW_shgroup_uniform_texture(grp, "matcaps", e_data.matcap_array); - DRW_shgroup_uniform_texture(grp, "ssao_jitter", sldata->jitter_tx); - DRW_shgroup_uniform_block(grp, "samples_block", sldata->sampling_ubo); - DRW_shgroup_uniform_block(grp, "material_block", sldata->mat_ubo); - DRW_shgroup_uniform_block(grp, "matcaps_block", sldata->matcaps_ubo); - /* TODO put in ubo */ - DRW_shgroup_uniform_mat4(grp, "WinMatrix", g_data->winmat); - DRW_shgroup_uniform_vec2(grp, "invscreenres", DRW_viewport_invert_size_get(), 1); - DRW_shgroup_uniform_vec4(grp, "viewvecs[0]", (float *)g_data->viewvecs, 3); - DRW_shgroup_uniform_vec4(grp, "ssao_params", g_data->ssao_params, 1); - return grp; -} - -static DRWShadingGroup *CLAY_hair_shgroup_create(DRWPass *pass, int id) -{ - CLAY_ViewLayerData *sldata = CLAY_view_layer_data_get(); - - if (!e_data.hair_sh) { - e_data.hair_sh = DRW_shader_create( - datatoc_clay_particle_vert_glsl, NULL, datatoc_clay_particle_strand_frag_glsl, - "#define MAX_MATERIAL " STRINGIFY(MAX_CLAY_MAT) "\n" ); - } - - DRWShadingGroup *grp = DRW_shgroup_create(e_data.hair_sh, pass); - DRW_shgroup_uniform_texture(grp, "matcaps", e_data.matcap_array); - DRW_shgroup_uniform_block(grp, "material_block", sldata->mat_ubo); - DRW_shgroup_uniform_int(grp, "mat_id", &e_data.ubo_mat_idxs[id], 1); - - return grp; -} - -static int search_mat_to_ubo(CLAY_Storage *storage, const CLAY_UBO_Material *mat_ubo_test) -{ - /* For now just use a linear search and test all parameters */ - /* TODO make a hash table */ - for (int i = 0; i < storage->ubo_current_id; ++i) { - CLAY_UBO_Material *ubo = &storage->mat_storage.materials[i]; - if (memcmp(ubo, mat_ubo_test, sizeof(*mat_ubo_test)) == 0) { - return i; - } - } - - return -1; -} - -static int search_hair_mat_to_ubo(CLAY_Storage *storage, const CLAY_HAIR_UBO_Material *hair_mat_ubo_test) -{ - /* For now just use a linear search and test all parameters */ - /* TODO make a hash table */ - for (int i = 0; i < storage->hair_ubo_current_id; ++i) { - CLAY_HAIR_UBO_Material *ubo = &storage->hair_mat_storage.materials[i]; - if (memcmp(ubo, hair_mat_ubo_test, sizeof(*hair_mat_ubo_test)) == 0) { - return i; - } - } - - return -1; -} - -static int push_mat_to_ubo(CLAY_Storage *storage, const CLAY_UBO_Material *mat_ubo_test) -{ - int id = storage->ubo_current_id++; - id = min_ii(MAX_CLAY_MAT, id); - storage->mat_storage.materials[id] = *mat_ubo_test; - return id; -} - -static int push_hair_mat_to_ubo(CLAY_Storage *storage, const CLAY_HAIR_UBO_Material *hair_mat_ubo_test) -{ - int id = storage->hair_ubo_current_id++; - id = min_ii(MAX_CLAY_MAT, id); - storage->hair_mat_storage.materials[id] = *hair_mat_ubo_test; - return id; -} - -static int mat_in_ubo(CLAY_Storage *storage, const CLAY_UBO_Material *mat_ubo_test) -{ - /* Search material in UBO */ - int id = search_mat_to_ubo(storage, mat_ubo_test); - - /* if not found create it */ - if (id == -1) { - id = push_mat_to_ubo(storage, mat_ubo_test); - } - - return id; -} - -static int hair_mat_in_ubo(CLAY_Storage *storage, const CLAY_HAIR_UBO_Material *hair_mat_ubo_test) -{ - /* Search material in UBO */ - int id = search_hair_mat_to_ubo(storage, hair_mat_ubo_test); - - /* if not found create it */ - if (id == -1) { - id = push_hair_mat_to_ubo(storage, hair_mat_ubo_test); - } - - return id; -} - -static void ubo_mat_from_object(CLAY_Storage *storage, Object *UNUSED(ob), bool *r_needs_ao, int *r_id) -{ - const DRWContextState *draw_ctx = DRW_context_state_get(); - const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph); - - const int matcap_icon = scene_eval->display.matcap_icon; - const float matcap_rot = scene_eval->display.matcap_rotation; - const float matcap_hue = scene_eval->display.matcap_hue; - const float matcap_sat = scene_eval->display.matcap_saturation; - const float matcap_val = scene_eval->display.matcap_value; - const float ssao_distance = scene_eval->display.matcap_ssao_distance; - const float ssao_factor_cavity = scene_eval->display.matcap_ssao_factor_cavity; - const float ssao_factor_edge = scene_eval->display.matcap_ssao_factor_edge; - const float ssao_attenuation = scene_eval->display.matcap_ssao_attenuation; - - CLAY_UBO_Material r_ubo = {{0.0f}}; - - if (((ssao_factor_cavity > 0.0) || (ssao_factor_edge > 0.0)) && - (ssao_distance > 0.0)) - { - *r_needs_ao = true; - - r_ubo.ssao_params_var[0] = ssao_distance; - r_ubo.ssao_params_var[1] = ssao_factor_cavity; - r_ubo.ssao_params_var[2] = ssao_factor_edge; - r_ubo.ssao_params_var[3] = ssao_attenuation; - } - else { - *r_needs_ao = false; - } - - r_ubo.matcap_rot[0] = cosf(matcap_rot * 3.14159f * 2.0f); - r_ubo.matcap_rot[1] = sinf(matcap_rot * 3.14159f * 2.0f); - - r_ubo.matcap_hsv[0] = matcap_hue + 0.5f; - r_ubo.matcap_hsv[1] = matcap_sat * 2.0f; - r_ubo.matcap_hsv[2] = matcap_val * 2.0f; - - r_ubo.matcap_id = matcap_to_index(matcap_icon); - - *r_id = mat_in_ubo(storage, &r_ubo); -} - -static void hair_ubo_mat_from_object(Object *UNUSED(ob), CLAY_HAIR_UBO_Material *r_ubo) -{ - const DRWContextState *draw_ctx = DRW_context_state_get(); - const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph); - - const int matcap_icon = scene_eval->display.matcap_icon; - const float matcap_rot = scene_eval->display.matcap_rotation; - const float matcap_hue = scene_eval->display.matcap_hue; - const float matcap_sat = scene_eval->display.matcap_saturation; - const float matcap_val = scene_eval->display.matcap_value; - const float hair_randomness = scene_eval->display.matcap_hair_brightness_randomness; - - memset(r_ubo, 0x0, sizeof(*r_ubo)); - - r_ubo->matcap_rot[0] = cosf(matcap_rot * 3.14159f * 2.0f); - r_ubo->matcap_rot[1] = sinf(matcap_rot * 3.14159f * 2.0f); - r_ubo->matcap_hsv[0] = matcap_hue + 0.5f; - r_ubo->matcap_hsv[1] = matcap_sat * 2.0f; - r_ubo->matcap_hsv[2] = matcap_val * 2.0f; - r_ubo->hair_randomness = hair_randomness; - r_ubo->matcap_id = matcap_to_index(matcap_icon); -} - -static DRWShadingGroup *CLAY_object_shgrp_get(CLAY_Data *vedata, Object *ob, bool use_flat, bool cull) -{ - bool prepass; int id; - CLAY_PassList *psl = vedata->psl; - CLAY_Storage *storage = vedata->stl->storage; - DRWShadingGroup **shgrps; - DRWPass *pass; GPUShader *sh; - - ubo_mat_from_object(storage, ob, &prepass, &id); - - if (prepass) { - if (use_flat) { - shgrps = storage->shgrps_pre_flat; - pass = (cull) ? psl->clay_flat_pre_cull_ps : psl->clay_flat_pre_ps; - sh = e_data.clay_prepass_flat_sh; - } - else { - shgrps = storage->shgrps_pre; - pass = (cull) ? psl->clay_pre_cull_ps : psl->clay_pre_ps; - sh = e_data.clay_prepass_sh; - } - - if (shgrps[id] == NULL) { - shgrps[id] = CLAY_shgroup_deferred_prepass_create(pass, sh, id); - } - - vedata->stl->g_data->enable_deferred_path = true; - } - else { - if (use_flat) { - shgrps = storage->shgrps_flat; - pass = (cull) ? psl->clay_flat_cull_ps : psl->clay_flat_ps; - sh = e_data.clay_flat_sh; - } - else { - shgrps = storage->shgrps; - pass = (cull) ? psl->clay_cull_ps : psl->clay_ps; - sh = e_data.clay_sh; - } - - if (shgrps[id] == NULL) { - shgrps[id] = CLAY_shgroup_create(pass, sh, id); - e_data.first_shgrp = false; - } - } - - return shgrps[id]; -} - -static DRWShadingGroup *CLAY_hair_shgrp_get( - CLAY_Data *UNUSED(vedata), Object *ob, CLAY_StorageList *stl, CLAY_PassList *psl) -{ - DRWShadingGroup **hair_shgrps = stl->storage->hair_shgrps; - - CLAY_HAIR_UBO_Material hair_mat_ubo_test; - hair_ubo_mat_from_object(ob, &hair_mat_ubo_test); - - int hair_id = hair_mat_in_ubo(stl->storage, &hair_mat_ubo_test); - - if (hair_shgrps[hair_id] == NULL) { - hair_shgrps[hair_id] = CLAY_hair_shgroup_create(psl->hair_pass, hair_id); - } - - return hair_shgrps[hair_id]; -} - -static void clay_cache_init(void *vedata) -{ - DefaultTextureList *dtxl = DRW_viewport_texture_list_get(); - CLAY_PassList *psl = ((CLAY_Data *)vedata)->psl; - CLAY_StorageList *stl = ((CLAY_Data *)vedata)->stl; - - /* Disable AO unless a material needs it. */ - stl->g_data->enable_deferred_path = false; - - /* Reset UBO datas, shgrp pointers and material id counters. */ - memset(stl->storage, 0, sizeof(*stl->storage)); - e_data.first_shgrp = true; - - /* Solid Passes */ - { - DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL; - psl->clay_ps = DRW_pass_create("Clay", state); - psl->clay_cull_ps = DRW_pass_create("Clay Culled", state | DRW_STATE_CULL_BACK); - psl->clay_flat_ps = DRW_pass_create("Clay Flat", state); - psl->clay_flat_cull_ps = DRW_pass_create("Clay Flat Culled", state | DRW_STATE_CULL_BACK); - - DRWState prepass_state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL; - DRWState prepass_cull_state = prepass_state | DRW_STATE_CULL_BACK; - psl->clay_pre_ps = DRW_pass_create("Clay Deferred Pre", prepass_state); - psl->clay_pre_cull_ps = DRW_pass_create("Clay Deferred Pre Culled", prepass_cull_state); - psl->clay_flat_pre_ps = DRW_pass_create("Clay Deferred Flat Pre", prepass_state); - psl->clay_flat_pre_cull_ps = DRW_pass_create("Clay Deferred Flat Pre Culled", prepass_cull_state); - - psl->clay_deferred_ps = DRW_pass_create("Clay Deferred Shading", DRW_STATE_WRITE_COLOR); - DRWShadingGroup *grp = CLAY_shgroup_deferred_shading_create(psl->clay_deferred_ps, stl->g_data); - DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL); - } - - /* Hair Pass */ - { - psl->hair_pass = DRW_pass_create( - "Hair Pass", - DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_WIRE); - } - - { - psl->fxaa_ps = DRW_pass_create("Fxaa", DRW_STATE_WRITE_COLOR); - DRWShadingGroup *grp = DRW_shgroup_create(e_data.fxaa_sh, psl->fxaa_ps); - DRW_shgroup_uniform_texture_ref(grp, "colortex", &dtxl->color); - DRW_shgroup_uniform_vec2(grp, "invscreenres", DRW_viewport_invert_size_get(), 1); - DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL); - - psl->copy_ps = DRW_pass_create("Copy", DRW_STATE_WRITE_COLOR); - grp = DRW_shgroup_create(e_data.copy_sh, psl->copy_ps); - DRW_shgroup_uniform_texture_ref(grp, "colortex", &stl->g_data->color_copy); - DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL); - } -} - -static void clay_cache_populate_particles(void *vedata, Object *ob) -{ - CLAY_PassList *psl = ((CLAY_Data *)vedata)->psl; - CLAY_StorageList *stl = ((CLAY_Data *)vedata)->stl; - const DRWContextState *draw_ctx = DRW_context_state_get(); - - if (ob == draw_ctx->object_edit) { - return; - } - - for (ParticleSystem *psys = ob->particlesystem.first; psys; psys = psys->next) { - if (!psys_check_enabled(ob, psys, false)) { - continue; - } - if (!DRW_check_psys_visible_within_active_context(ob, psys)) { - continue; - } - ParticleSettings *part = psys->part; - const int draw_as = (part->draw_as == PART_DRAW_REND) ? part->ren_as : part->draw_as; - if (draw_as == PART_DRAW_PATH) { - struct Gwn_Batch *geom = DRW_cache_particles_get_hair(ob, psys, NULL); - DRWShadingGroup *hair_shgrp = CLAY_hair_shgrp_get(vedata, ob, stl, psl); - DRW_shgroup_call_add(hair_shgrp, geom, NULL); - } - } -} - -static void clay_cache_populate(void *vedata, Object *ob) -{ - DRWShadingGroup *clay_shgrp; - - if (!DRW_object_is_renderable(ob)) - return; - - const DRWContextState *draw_ctx = DRW_context_state_get(); - const bool is_active = (ob == draw_ctx->obact); - if (is_active) { - if (DRW_object_is_mode_shade(ob) == true) { - return; - } - } - - /* Handle particles first in case the emitter itself shouldn't be rendered. */ - if (ob->type == OB_MESH) { - clay_cache_populate_particles(vedata, ob); - } - - if (DRW_check_object_visible_within_active_context(ob) == false) { - return; - } - - struct Gwn_Batch *geom = DRW_cache_object_surface_get(ob); - if (geom) { - const bool do_cull = (draw_ctx->v3d && (draw_ctx->v3d->flag2 & V3D_BACKFACE_CULLING)); - const bool is_sculpt_mode = is_active && (draw_ctx->object_mode & OB_MODE_SCULPT) != 0; - const bool use_flat = is_sculpt_mode && DRW_object_is_flat_normal(ob); - - clay_shgrp = CLAY_object_shgrp_get(vedata, ob, use_flat, do_cull); - - if (is_sculpt_mode) { - DRW_shgroup_call_sculpt_add(clay_shgrp, ob, ob->obmat); - } - else { - DRW_shgroup_call_object_add(clay_shgrp, geom, ob); - } - } -} - -static void clay_cache_finish(void *vedata) -{ - CLAY_ViewLayerData *sldata = CLAY_view_layer_data_get(); - CLAY_StorageList *stl = ((CLAY_Data *)vedata)->stl; - - DRW_uniformbuffer_update(sldata->mat_ubo, &stl->storage->mat_storage); - DRW_uniformbuffer_update(sldata->hair_mat_ubo, &stl->storage->hair_mat_storage); -} - -static void clay_draw_scene(void *vedata) -{ - CLAY_StorageList *stl = ((CLAY_Data *)vedata)->stl; - CLAY_PassList *psl = ((CLAY_Data *)vedata)->psl; - CLAY_FramebufferList *fbl = ((CLAY_Data *)vedata)->fbl; - DefaultFramebufferList *dfbl = DRW_viewport_framebuffer_list_get(); - DefaultTextureList *dtxl = DRW_viewport_texture_list_get(); - stl->g_data->depth_tx = dtxl->depth; - - /* Passes are ordered to have less _potential_ overdraw */ - DRW_draw_pass(psl->clay_cull_ps); - DRW_draw_pass(psl->clay_flat_cull_ps); - DRW_draw_pass(psl->clay_ps); - DRW_draw_pass(psl->clay_flat_ps); - DRW_draw_pass(psl->hair_pass); - - if (stl->g_data->enable_deferred_path) { - GPU_framebuffer_bind(fbl->prepass_fb); - /* We need to clear the id texture unfortunately. */ - const float clear_col[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - GPU_framebuffer_clear_color(fbl->prepass_fb, clear_col); - - DRW_draw_pass(psl->clay_pre_cull_ps); - DRW_draw_pass(psl->clay_flat_pre_cull_ps); - DRW_draw_pass(psl->clay_pre_ps); - DRW_draw_pass(psl->clay_flat_pre_ps); - - GPU_framebuffer_bind(dfbl->color_only_fb); - DRW_draw_pass(psl->clay_deferred_ps); - } - - if (true) { /* Always on for now. We might want a parameter for this. */ - GPU_framebuffer_bind(fbl->antialias_fb); - DRW_draw_pass(psl->fxaa_ps); - - GPU_framebuffer_bind(dfbl->color_only_fb); - DRW_draw_pass(psl->copy_ps); - } -} - -static void clay_engine_free(void) -{ - DRW_SHADER_FREE_SAFE(e_data.clay_sh); - DRW_SHADER_FREE_SAFE(e_data.clay_flat_sh); - DRW_SHADER_FREE_SAFE(e_data.clay_prepass_flat_sh); - DRW_SHADER_FREE_SAFE(e_data.clay_prepass_sh); - DRW_SHADER_FREE_SAFE(e_data.clay_deferred_shading_sh); - DRW_SHADER_FREE_SAFE(e_data.fxaa_sh); - DRW_SHADER_FREE_SAFE(e_data.copy_sh); - DRW_SHADER_FREE_SAFE(e_data.hair_sh); - DRW_TEXTURE_FREE_SAFE(e_data.matcap_array); -} - -static const DrawEngineDataSize clay_data_size = DRW_VIEWPORT_DATA_SIZE(CLAY_Data); - -DrawEngineType draw_engine_clay_type = { - NULL, NULL, - N_("Clay"), - &clay_data_size, - &clay_engine_init, - &clay_engine_free, - &clay_cache_init, - &clay_cache_populate, - &clay_cache_finish, - NULL, - &clay_draw_scene, - NULL, - NULL, - NULL, -}; - -RenderEngineType DRW_engine_viewport_clay_type = { - NULL, NULL, - CLAY_ENGINE, N_("Clay"), RE_INTERNAL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, - &draw_engine_clay_type, - {NULL, NULL, NULL} -}; - - -#undef CLAY_ENGINE - -#endif /* WITH_CLAY_ENGINE */ diff --git a/source/blender/draw/engines/clay/clay_engine.h b/source/blender/draw/engines/clay/clay_engine.h deleted file mode 100644 index b7c9d00c9ae..00000000000 --- a/source/blender/draw/engines/clay/clay_engine.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2016, 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(s): Blender Institute - * - */ - -/** \file clay_engine.h - * \ingroup draw_engine - */ - -#ifndef __CLAY_ENGINE_H__ -#define __CLAY_ENGINE_H__ - -extern DrawEngineType draw_engine_clay_type; -extern RenderEngineType DRW_engine_viewport_clay_type; - -struct IDProperty; - -struct IDProperty *CLAY_render_settings_create(void); - -#endif /* __CLAY_ENGINE_H__ */ diff --git a/source/blender/draw/engines/clay/shaders/clay_copy.glsl b/source/blender/draw/engines/clay/shaders/clay_copy.glsl deleted file mode 100644 index ec462978e67..00000000000 --- a/source/blender/draw/engines/clay/shaders/clay_copy.glsl +++ /dev/null @@ -1,10 +0,0 @@ - -in vec4 uvcoordsvar; -out vec4 fragColor; - -uniform sampler2D colortex; - -void main() -{ - fragColor = texture(colortex, uvcoordsvar.st); -} diff --git a/source/blender/draw/engines/clay/shaders/clay_frag.glsl b/source/blender/draw/engines/clay/shaders/clay_frag.glsl deleted file mode 100644 index 1939e4b735d..00000000000 --- a/source/blender/draw/engines/clay/shaders/clay_frag.glsl +++ /dev/null @@ -1,252 +0,0 @@ -uniform vec2 invscreenres; -uniform mat4 WinMatrix; - -/* Matcap */ -uniform sampler2DArray matcaps; - -/* Screen Space Occlusion */ -/* store the view space vectors for the corners of the view frustum here. - * It helps to quickly reconstruct view space vectors by using uv coordinates, - * see http://www.derschmale.com/2014/01/26/reconstructing-positions-from-the-depth-buffer */ -uniform vec4 viewvecs[3]; -uniform vec4 ssao_params; - -uniform sampler2D ssao_jitter; - -/* Material Parameters packed in an UBO */ -struct Material { - vec4 ssao_params_var; - vec4 matcap_hsv_id; - vec4 matcap_rot; /* vec4 to ensure 16 bytes alignement (don't trust compiler) */ -}; - -layout(std140) uniform samples_block { - vec4 ssao_samples[500]; -}; - -layout(std140) uniform matcaps_block { - vec4 matcaps_color[24]; -}; - -layout(std140) uniform material_block { - Material matcaps_param[MAX_MATERIAL]; -}; - -#ifdef DEFERRED_SHADING -uniform sampler2D depthtex; -uniform sampler2D normaltex; -uniform isampler2D idtex; -int mat_id; /* global */ -#else -uniform int mat_id; -#endif - -/* Aliases */ -#define ssao_samples_num ssao_params.x -#define jitter_tilling ssao_params.yz -#define dfdy_sign ssao_params.w - -#define matcap_hsv matcaps_param[mat_id].matcap_hsv_id.xyz -#define matcap_index matcaps_param[mat_id].matcap_hsv_id.w -#define matcap_rotation matcaps_param[mat_id].matcap_rot.xy - -#ifndef DEFERRED_SHADING -# ifdef USE_FLAT_NORMAL -flat in vec3 normal; -# else -in vec3 normal; -# endif -#endif - -out vec4 fragColor; - -/* TODO Move this to SSAO modules */ -/* simple depth reconstruction, see http://www.derschmale.com/2014/01/26/reconstructing-positions-from-the-depth-buffer - * we change the factors from the article to fit the OpennGL model. */ -vec3 get_view_space_from_depth(in vec2 uvcoords, in float depth) -{ - if (WinMatrix[3][3] == 0.0) { - /* Perspective */ - float d = 2.0 * depth - 1.0; - - float zview = -WinMatrix[3][2] / (d + WinMatrix[2][2]); - - return zview * (viewvecs[0].xyz + vec3(uvcoords, 0.0) * viewvecs[1].xyz); - } - else { - /* Orthographic */ - vec3 offset = vec3(uvcoords, depth); - - return viewvecs[0].xyz + offset * viewvecs[1].xyz; - } -} - -#ifdef USE_HSV -void rgb_to_hsv(vec3 rgb, out vec3 outcol) -{ - float cmax, cmin, h, s, v, cdelta; - vec3 c; - - cmax = max(rgb[0], max(rgb[1], rgb[2])); - cmin = min(rgb[0], min(rgb[1], rgb[2])); - cdelta = cmax - cmin; - - v = cmax; - if (cmax != 0.0) - s = cdelta / cmax; - else { - s = 0.0; - h = 0.0; - } - - if (s == 0.0) { - h = 0.0; - } - else { - c = (vec3(cmax, cmax, cmax) - rgb.xyz) / cdelta; - - if (rgb.x == cmax) h = c[2] - c[1]; - else if (rgb.y == cmax) h = 2.0 + c[0] - c[2]; - else h = 4.0 + c[1] - c[0]; - - h /= 6.0; - - if (h < 0.0) - h += 1.0; - } - - outcol = vec3(h, s, v); -} - -void hsv_to_rgb(vec3 hsv, out vec3 outcol) -{ - float i, f, p, q, t, h, s, v; - vec3 rgb; - - h = hsv[0]; - s = hsv[1]; - v = hsv[2]; - - if (s == 0.0) { - rgb = vec3(v, v, v); - } - else { - if (h == 1.0) - h = 0.0; - - h *= 6.0; - i = floor(h); - f = h - i; - rgb = vec3(f, f, f); - p = v * (1.0 - s); - q = v * (1.0 - (s * f)); - t = v * (1.0 - (s * (1.0 - f))); - - if (i == 0.0) rgb = vec3(v, t, p); - else if (i == 1.0) rgb = vec3(q, v, p); - else if (i == 2.0) rgb = vec3(p, v, t); - else if (i == 3.0) rgb = vec3(p, q, v); - else if (i == 4.0) rgb = vec3(t, p, v); - else rgb = vec3(v, p, q); - } - - outcol = rgb; -} - -void hue_sat(float hue, float sat, float value, inout vec3 col) -{ - vec3 hsv; - - rgb_to_hsv(col, hsv); - - hsv.x += hue; - hsv.x -= floor(hsv.x); - hsv.y *= sat; - hsv.y = clamp(hsv.y, 0.0, 1.0); - hsv.z *= value; - hsv.z = clamp(hsv.z, 0.0, 1.0); - - hsv_to_rgb(hsv, col); -} -#endif - -#ifdef USE_AO -/* Prototype */ -void ssao_factors( - in float depth, in vec3 normal, in vec3 position, in vec2 screenco, - out float cavities, out float edges); -#endif - -/* From http://aras-p.info/texts/CompactNormalStorage.html - * Using Method #4: Spheremap Transform */ -vec3 normal_decode(vec2 enc) -{ - vec2 fenc = enc * 4.0 - 2.0; - float f = dot(fenc, fenc); - float g = sqrt(1.0 - f / 4.0); - vec3 n; - n.xy = fenc*g; - n.z = 1 - f / 2; - return n; -} - -vec3 shade(vec3 N, vec3 position, float depth, vec2 screenco) -{ -#ifdef USE_ROTATION - /* Rotate texture coordinates */ - vec2 rotY = vec2(-matcap_rotation.y, matcap_rotation.x); - vec2 texco = abs(vec2(dot(N.xy, matcap_rotation), dot(N.xy, rotY)) * .49 + 0.5); -#else - vec2 texco = abs(N.xy * .49 + 0.5); -#endif - vec3 col = texture(matcaps, vec3(texco, matcap_index)).rgb; - -#ifdef USE_AO - float cavity = 0.0, edges = 0.0; - ssao_factors(depth, N, position, screenco, cavity, edges); - - col *= mix(vec3(1.0), matcaps_color[int(matcap_index)].rgb, cavity); -#endif - -#ifdef USE_HSV - hue_sat(matcap_hsv.x, matcap_hsv.y, matcap_hsv.z, col); -#endif - -#ifdef USE_AO - /* Apply highlights after hue shift */ - col *= edges + 1.0; -#endif - - return col; -} - -void main() -{ - vec2 screenco = vec2(gl_FragCoord.xy) * invscreenres; - -#ifdef DEFERRED_SHADING - ivec2 texel = ivec2(gl_FragCoord.xy); - mat_id = texelFetch(idtex, texel, 0).r; - - /* early out (manual stencil test) */ - if (mat_id == 0) - discard; - - float depth = texelFetch(depthtex, texel, 0).r; - vec3 N = normal_decode(texelFetch(normaltex, texel, 0).rg); - /* see the prepass for explanations. */ - if (mat_id < 0) { - N = -N; - } - mat_id = abs(mat_id) - 1; -#else - float depth = gl_FragCoord.z; - vec3 N = normal; -#endif - - vec3 position = get_view_space_from_depth(screenco, depth); - - vec3 col = shade(N, position, depth, screenco); - - fragColor = vec4(col, 1.0); -} diff --git a/source/blender/draw/engines/clay/shaders/clay_fxaa.glsl b/source/blender/draw/engines/clay/shaders/clay_fxaa.glsl deleted file mode 100644 index 924e51421aa..00000000000 --- a/source/blender/draw/engines/clay/shaders/clay_fxaa.glsl +++ /dev/null @@ -1,18 +0,0 @@ - -in vec4 uvcoordsvar; -out vec4 fragColor; - -uniform vec2 invscreenres; -uniform sampler2D colortex; - -void main() -{ - fragColor = vec4(FxaaPixelShader( - uvcoordsvar.st, - colortex, - invscreenres, - 1.0, - 0.166, - 0.0833 - ).rgb, 1.0); -} diff --git a/source/blender/draw/engines/clay/shaders/clay_particle_strand_frag.glsl b/source/blender/draw/engines/clay/shaders/clay_particle_strand_frag.glsl deleted file mode 100644 index 980a1e4690d..00000000000 --- a/source/blender/draw/engines/clay/shaders/clay_particle_strand_frag.glsl +++ /dev/null @@ -1,144 +0,0 @@ - -/* Material Parameters packed in an UBO */ -struct Material { - vec4 one; - vec4 two; -}; - -layout(std140) uniform material_block { - Material shader_param[MAX_MATERIAL]; -}; - -uniform mat4 ProjectionMatrix; -uniform sampler2DArray matcaps; -uniform int mat_id; - -#define randomness shader_param[mat_id].one.x -#define matcap_index shader_param[mat_id].one.y -#define matcap_rotation shader_param[mat_id].one.zw -#define matcap_hsv shader_param[mat_id].two.xyz - -in vec3 tangent; -in vec3 viewPosition; -flat in float colRand; -out vec4 fragColor; - -vec3 rotate(vec3 norm, vec3 ortho, float ang) -{ - return norm * cos(ang) + ortho * sin(ang); -} - -void rgb_to_hsv(vec3 rgb, out vec3 outcol) -{ - float cmax, cmin, h, s, v, cdelta; - vec3 c; - - cmax = max(rgb[0], max(rgb[1], rgb[2])); - cmin = min(rgb[0], min(rgb[1], rgb[2])); - cdelta = cmax - cmin; - - v = cmax; - if (cmax != 0.0) - s = cdelta / cmax; - else { - s = 0.0; - h = 0.0; - } - - if (s == 0.0) { - h = 0.0; - } - else { - c = (vec3(cmax, cmax, cmax) - rgb.xyz) / cdelta; - - if (rgb.x == cmax) h = c[2] - c[1]; - else if (rgb.y == cmax) h = 2.0 + c[0] - c[2]; - else h = 4.0 + c[1] - c[0]; - - h /= 6.0; - - if (h < 0.0) - h += 1.0; - } - - outcol = vec3(h, s, v); -} - -void hsv_to_rgb(vec3 hsv, out vec3 outcol) -{ - float i, f, p, q, t, h, s, v; - vec3 rgb; - - h = hsv[0]; - s = hsv[1]; - v = hsv[2]; - - if (s == 0.0) { - rgb = vec3(v, v, v); - } - else { - if (h == 1.0) - h = 0.0; - - h *= 6.0; - i = floor(h); - f = h - i; - rgb = vec3(f, f, f); - p = v * (1.0 - s); - q = v * (1.0 - (s * f)); - t = v * (1.0 - (s * (1.0 - f))); - - if (i == 0.0) rgb = vec3(v, t, p); - else if (i == 1.0) rgb = vec3(q, v, p); - else if (i == 2.0) rgb = vec3(p, v, t); - else if (i == 3.0) rgb = vec3(p, q, v); - else if (i == 4.0) rgb = vec3(t, p, v); - else rgb = vec3(v, p, q); - } - - outcol = rgb; -} - -void hue_sat(float hue, float sat, float value, inout vec3 col) -{ - vec3 hsv; - - rgb_to_hsv(col, hsv); - - hsv.x += hue; - hsv.x -= floor(hsv.x); - hsv.y *= sat; - hsv.y = clamp(hsv.y, 0.0, 1.0); - hsv.z *= value; - hsv.z = clamp(hsv.z, 0.0, 1.0); - - hsv_to_rgb(hsv, col); -} - -void main() -{ - vec3 viewvec = (ProjectionMatrix[3][3] == 0.0) ? normalize(viewPosition) : vec3(0.0, 0.0, -1.0); - vec3 ortho = normalize(cross(viewvec, tangent)); - vec3 norm = normalize(cross(ortho, tangent)); - - vec3 col = vec3(0); - - vec2 rotY = vec2(-matcap_rotation.y, matcap_rotation.x); - - for (int i = 0; i < 9; i++) { - vec3 rotNorm = rotate(norm, ortho, -0.5 + (i * 0.125)); - vec3 ray = reflect(viewvec, rotNorm); - vec2 texco = abs(vec2(dot(ray.xy, matcap_rotation), dot(ray.xy, rotY)) * .49 + 0.5); - - col += texture(matcaps, vec3(texco, matcap_index)).rgb / 9.0; - } - - hue_sat(matcap_hsv.x, matcap_hsv.y, matcap_hsv.z, col); - - float maxChan = max(max(col.r, col.g), col.b); - - col += (colRand * maxChan * randomness * 1.5) - (maxChan * randomness * 0.75); - - fragColor.rgb = col; - fragColor.a = 1.0; -} diff --git a/source/blender/draw/engines/clay/shaders/clay_particle_vert.glsl b/source/blender/draw/engines/clay/shaders/clay_particle_vert.glsl deleted file mode 100644 index d4c35d14182..00000000000 --- a/source/blender/draw/engines/clay/shaders/clay_particle_vert.glsl +++ /dev/null @@ -1,34 +0,0 @@ - -uniform mat4 ModelViewProjectionMatrix; -uniform mat3 NormalMatrix; -uniform mat4 ModelViewMatrix; - -in vec3 pos; -in vec3 nor; -in int ind; -out vec3 tangent; -out vec3 viewPosition; -flat out float colRand; - -float rand(int s) -{ - int seed = s * 1023423; - - seed = (seed ^ 61) ^ (seed >> 16); - seed *= 9; - seed = seed ^ (seed >> 4); - seed *= 0x27d4eb2d; - seed = seed ^ (seed >> 15); - - float value = float(seed); - value *= 1.0 / 42596.0; - return fract(value); -} - -void main() -{ - gl_Position = ModelViewProjectionMatrix * vec4(pos, 1.0); - tangent = normalize(NormalMatrix * nor); - viewPosition = (ModelViewMatrix * vec4(pos, 1.0)).xyz; - colRand = rand(ind); -} diff --git a/source/blender/draw/engines/clay/shaders/clay_prepass_frag.glsl b/source/blender/draw/engines/clay/shaders/clay_prepass_frag.glsl deleted file mode 100644 index f30322bc9fe..00000000000 --- a/source/blender/draw/engines/clay/shaders/clay_prepass_frag.glsl +++ /dev/null @@ -1,44 +0,0 @@ -uniform int mat_id; - -#ifdef USE_FLAT_NORMAL -flat in vec3 normal; -#else -in vec3 normal; -#endif - -layout(location = 0) out vec2 outNormals; -layout(location = 1) out int outIndex; - -/* From http://aras-p.info/texts/CompactNormalStorage.html - * Using Method #4: Spheremap Transform */ -vec2 normal_encode(vec3 n) -{ - float p = sqrt(n.z * 8.0 + 8.0); - return n.xy / p + 0.5; -} - -/* 4x4 bayer matrix prepared for 8bit UNORM precision error. */ -#define P(x) (((x + 0.5) * (1.0 / 16.0) - 0.5) * (1.0 / 255.0)) -const vec4 dither_mat[4] = vec4[4]( - vec4( P(0.0), P(8.0), P(2.0), P(10.0)), - vec4(P(12.0), P(4.0), P(14.0), P(6.0)), - vec4( P(3.0), P(11.0), P(1.0), P(9.0)), - vec4(P(15.0), P(7.0), P(13.0), P(5.0)) -); - -void main() { - outIndex = (mat_id + 1); /* 0 is clear color */ - /** - * To fix the normal buffer precision issue for backfaces, - * we invert normals and use the sign of the index buffer - * to tag them, and re-invert in deferred pass. - **/ - vec3 N = (gl_FrontFacing) ? normal : -normal; - outIndex = (gl_FrontFacing) ? outIndex : -outIndex; - - outNormals = normal_encode(N); - - /* Dither the output to fight low quality. */ - ivec2 tx = ivec2(gl_FragCoord.xy) % 4; - outNormals += dither_mat[tx.x][tx.y]; -} diff --git a/source/blender/draw/engines/clay/shaders/clay_vert.glsl b/source/blender/draw/engines/clay/shaders/clay_vert.glsl deleted file mode 100644 index 8f8866b3839..00000000000 --- a/source/blender/draw/engines/clay/shaders/clay_vert.glsl +++ /dev/null @@ -1,17 +0,0 @@ -uniform mat4 ModelViewProjectionMatrix; -uniform mat3 NormalMatrix; - -in vec3 pos; -in vec3 nor; - -#ifdef USE_FLAT_NORMAL -flat out vec3 normal; -#else -out vec3 normal; -#endif - -void main() -{ - normal = normalize(NormalMatrix * nor); - gl_Position = ModelViewProjectionMatrix * vec4(pos, 1.0); -} diff --git a/source/blender/draw/engines/clay/shaders/ssao_alchemy.glsl b/source/blender/draw/engines/clay/shaders/ssao_alchemy.glsl deleted file mode 100644 index 94e2d6f3c7b..00000000000 --- a/source/blender/draw/engines/clay/shaders/ssao_alchemy.glsl +++ /dev/null @@ -1,82 +0,0 @@ -#define ssao_distance matcaps_param[mat_id].ssao_params_var.x -#define ssao_factor_cavity matcaps_param[mat_id].ssao_params_var.y -#define ssao_factor_edge matcaps_param[mat_id].ssao_params_var.z -#define ssao_attenuation matcaps_param[mat_id].ssao_params_var.w - -/* from The Alchemy screen-space ambient obscurance algorithm - * http://graphics.cs.williams.edu/papers/AlchemyHPG11/VV11AlchemyAO.pdf */ - -void ssao_factors( - in float depth, in vec3 normal, in vec3 position, in vec2 screenco, - out float cavities, out float edges) -{ - cavities = edges = 0.0; - /* early out if there is no need for SSAO */ - if (ssao_factor_cavity == 0.0 && ssao_factor_edge == 0.0) - return; - - /* take the normalized ray direction here */ - vec3 noise = texture(ssao_jitter, screenco.xy * jitter_tilling).rgb; - - /* find the offset in screen space by multiplying a point - * in camera space at the depth of the point by the projection matrix. */ - vec2 offset; - float homcoord = WinMatrix[2][3] * position.z + WinMatrix[3][3]; - offset.x = WinMatrix[0][0] * ssao_distance / homcoord; - offset.y = WinMatrix[1][1] * ssao_distance / homcoord; - /* convert from -1.0...1.0 range to 0.0..1.0 for easy use with texture coordinates */ - offset *= 0.5; - - int num_samples = int(ssao_samples_num); - - /* Note. Putting noise usage here to put some ALU after texture fetch. */ - vec2 rotX = noise.rg; - vec2 rotY = vec2(-rotX.y, rotX.x); - - for (int x = 0; x < num_samples && x < 500; x++) { - /* ssao_samples[x].xy is sample direction (normalized). - * ssao_samples[x].z is sample distance from disk center. */ - - /* Rotate with random direction to get jittered result. */ - vec2 dir_jittered = vec2(dot(ssao_samples[x].xy, rotX), dot(ssao_samples[x].xy, rotY)); - dir_jittered.xy *= ssao_samples[x].z + noise.b; - - vec2 uvcoords = screenco.xy + dir_jittered * offset; - - if (uvcoords.x > 1.0 || uvcoords.x < 0.0 || uvcoords.y > 1.0 || uvcoords.y < 0.0) - continue; - - float depth_new = texture(depthtex, uvcoords).r; - - /* Handle Background case */ - bool is_background = (depth_new == 1.0); - - /* This trick provide good edge effect even if no neighboor is found. */ - vec3 pos_new = get_view_space_from_depth(uvcoords, (is_background) ? depth : depth_new); - - if (is_background) - pos_new.z -= ssao_distance; - - vec3 dir = pos_new - position; - float len = length(dir); - float f_cavities = dot(dir, normal); - float f_edge = -f_cavities; - float f_bias = 0.05 * len + 0.0001; - - float attenuation = 1.0 / (len * (1.0 + len * len * ssao_attenuation)); - - /* use minor bias here to avoid self shadowing */ - if (f_cavities > -f_bias) - cavities += f_cavities * attenuation; - - if (f_edge > f_bias) - edges += f_edge * attenuation; - } - - cavities /= ssao_samples_num; - edges /= ssao_samples_num; - - /* don't let cavity wash out the surface appearance */ - cavities = clamp(cavities * ssao_factor_cavity, 0.0, 1.0); - edges = edges * ssao_factor_edge; -} diff --git a/source/blender/draw/engines/clay/shaders/ssao_groundtruth.glsl b/source/blender/draw/engines/clay/shaders/ssao_groundtruth.glsl deleted file mode 100644 index 9c203a4246c..00000000000 --- a/source/blender/draw/engines/clay/shaders/ssao_groundtruth.glsl +++ /dev/null @@ -1,122 +0,0 @@ -#define ssao_distance matcaps_param[mat_id].ssao_params_var.x -#define ssao_factor_cavity matcaps_param[mat_id].ssao_params_var.y -#define ssao_factor_edge matcaps_param[mat_id].ssao_params_var.z -#define ssao_attenuation matcaps_param[mat_id].ssao_params_var.w - -/* Based on Practical Realtime Strategies for Accurate Indirect Occlusion - * http://blog.selfshadow.com/publications/s2016-shading-course/activision/s2016_pbs_activision_occlusion.pdf - * http://blog.selfshadow.com/publications/s2016-shading-course/activision/s2016_pbs_activision_occlusion.pptx */ - -#define COSINE_WEIGHTING - -float integrate_arc(in float h1, in float h2, in float gamma, in float n_proj_len) -{ - float a = 0.0; -#ifdef COSINE_WEIGHTING - float cos_gamma = cos(gamma); - float sin_gamma_2 = 2.0 * sin(gamma); - a += -cos(2.0 * h1 - gamma) + cos_gamma + h1 * sin_gamma_2; - a += -cos(2.0 * h2 - gamma) + cos_gamma + h2 * sin_gamma_2; - a *= 0.25; /* 1/4 */ - a *= n_proj_len; -#else - /* Uniform weighting (slide 59) */ - a += 1 - cos(h1); - a += 1 - cos(h2); -#endif - return a; -} - -float get_max_horizon(in vec2 co, in vec3 x, in vec3 omega_o, in float h) -{ - if (co.x > 1.0 || co.x < 0.0 || co.y > 1.0 || co.y < 0.0) - return h; - - float depth = texture(depthtex, co).r; - - /* Background case */ - if (depth == 1.0) - return h; - - vec3 s = get_view_space_from_depth(co, depth); /* s View coordinate */ - vec3 omega_s = s - x; - float len = length(omega_s); - - if (len < ssao_distance) { - omega_s /= len; - h = max(h, dot(omega_s, omega_o)); - } - return h; -} - -void ssao_factors( - in float depth, in vec3 normal, in vec3 position, in vec2 screenco, - out float cavities, out float edges) -{ - /* Renaming */ - vec3 omega_o = -normalize(position); /* viewvec */ - vec2 x_ = screenco; /* x^ Screen coordinate */ - vec3 x = position; /* x view space coordinate */ - -#ifdef SPATIAL_DENOISE - float noise_dir = (1.0 / 16.0) * float(((int(gl_FragCoord.x + gl_FragCoord.y) & 0x3) << 2) + (int(gl_FragCoord.x) & 0x3)); - float noise_offset = (1.0 / 4.0) * float(int(gl_FragCoord.y - gl_FragCoord.x) & 0x3); -#else - float noise_dir = (1.0 / 16.0) * float(((int(gl_FragCoord.x + gl_FragCoord.y) & 0x3) << 2) + (int(gl_FragCoord.x) & 0x3)); - float noise_offset = (0.5 / 16.0) + (1.0 / 16.0) * float(((int(gl_FragCoord.x - gl_FragCoord.y) & 0x3) << 2) + (int(gl_FragCoord.x) & 0x3)); -#endif - - const float phi_step = 16.0; - const float theta_step = 16.0; - const float m_pi = 3.14159265358979323846; - vec2 pixel_ratio = vec2(screenres.y / screenres.x, 1.0); - vec2 pixel_size = vec2(1.0) / screenres.xy; - float min_stride = length(pixel_size); - float homcco = WinMatrix[2][3] * position.z + WinMatrix[3][3]; - float n = max(min_stride * theta_step, ssao_distance / homcco); /* Search distance */ - - /* Integral over PI */ - float A = 0.0; - for (float i = 0.0; i < phi_step; i++) { - float phi = m_pi * ((noise_dir + i) / phi_step); - - vec2 t_phi = vec2(cos(phi), sin(phi)); /* Screen space direction */ - - /* Search maximum horizon angles Theta1 and Theta2 */ - float theta1 = -1.0, theta2 = -1.0; /* init at cos(pi) */ - for (float j = 0.0; j < theta_step; j++) { - vec2 s_ = t_phi * pixel_ratio * n * ((j + noise_offset)/ theta_step); /* s^ Screen coordinate */ - vec2 co; - - co = x_ + s_; - theta1 = get_max_horizon(co, x, omega_o, theta1); - - co = x_ - s_; - theta2 = get_max_horizon(co, x, omega_o, theta2); - } - - /* (Slide 54) */ - theta1 = -acos(theta1); - theta2 = acos(theta2); - - /* Projecting Normal to Plane P defined by t_phi and omega_o */ - vec3 h = normalize(cross(vec3(t_phi, 0.0), omega_o)); /* Normal vector to Integration plane */ - vec3 t = cross(h, omega_o); /* Normal vector to plane */ - vec3 n_proj = normal - h * dot(normal, h); - float n_proj_len = length(n_proj); - vec3 n_proj_norm = normalize(n_proj); - - /* Clamping thetas (slide 58) */ - float gamma = sign(dot(n_proj_norm, t)) * acos(dot(normal, omega_o)); /* Angle between view vec and normal */ - theta1 = gamma + max(theta1 - gamma, -m_pi * 0.5); - theta2 = gamma + min(theta2 - gamma, m_pi * 0.5); - - /* Solving inner integral */ - A += integrate_arc(theta1, theta2, gamma, n_proj_len); - } - - A /= phi_step; - - cavities = 1.0 - A; - edges = 0.0; -} diff --git a/source/blender/draw/engines/eevee/eevee_lookdev.c b/source/blender/draw/engines/eevee/eevee_lookdev.c index 5c626b42ddd..806fb65b8e8 100644 --- a/source/blender/draw/engines/eevee/eevee_lookdev.c +++ b/source/blender/draw/engines/eevee/eevee_lookdev.c @@ -149,12 +149,12 @@ void EEVEE_lookdev_draw_background(EEVEE_Data *vedata) GPUFrameBuffer *fb = effects->final_fb; GPU_framebuffer_bind(fb); - GPU_framebuffer_viewport_set(fb, rect.xmax - viewport_inset_x, 0, viewport_inset_x, viewport_inset_y); + GPU_framebuffer_viewport_set(fb, rect.xmax - viewport_inset_x, rect.ymin, viewport_inset_x, viewport_inset_y); DRW_draw_pass(psl->lookdev_pass); fb = dfbl->depth_only_fb; GPU_framebuffer_bind(fb); - GPU_framebuffer_viewport_set(fb, rect.xmax - viewport_inset_x, 0, viewport_inset_x, viewport_inset_y); + GPU_framebuffer_viewport_set(fb, rect.xmax - viewport_inset_x, rect.ymin, viewport_inset_x, viewport_inset_y); DRW_draw_pass(psl->lookdev_pass); DRW_viewport_matrix_override_unset_all(); diff --git a/source/blender/draw/engines/eevee/eevee_render.c b/source/blender/draw/engines/eevee/eevee_render.c index 5d31488d75f..d24551976f9 100644 --- a/source/blender/draw/engines/eevee/eevee_render.c +++ b/source/blender/draw/engines/eevee/eevee_render.c @@ -423,6 +423,8 @@ void EEVEE_render_draw(EEVEE_Data *vedata, RenderEngine *engine, RenderLayer *rl DRW_render_instance_buffer_finish(); /* Need to be called after DRW_render_instance_buffer_finish() */ + /* Also we weed to have a correct fbo bound for DRW_hair_update */ + GPU_framebuffer_bind(fbl->main_fb); DRW_hair_update(); if ((view_layer->passflag & (SCE_PASS_SUBSURFACE_COLOR | diff --git a/source/blender/draw/engines/eevee/shaders/bsdf_common_lib.glsl b/source/blender/draw/engines/eevee/shaders/bsdf_common_lib.glsl index a1890433b0f..8b232bf14a4 100644 --- a/source/blender/draw/engines/eevee/shaders/bsdf_common_lib.glsl +++ b/source/blender/draw/engines/eevee/shaders/bsdf_common_lib.glsl @@ -666,6 +666,13 @@ Closure closure_add(Closure cl1, Closure cl2) return cl; } +Closure closure_emission(vec3 rgb) +{ + Closure cl = CLOSURE_DEFAULT; + cl.emission = rgb; + return cl; +} + #else /* VOLUMETRICS */ struct Closure { @@ -767,6 +774,13 @@ Closure closure_add(Closure cl1, Closure cl2) return cl; } +Closure closure_emission(vec3 rgb) +{ + Closure cl = CLOSURE_DEFAULT; + cl.radiance = rgb; + return cl; +} + # if defined(MESH_SHADER) && !defined(USE_ALPHA_HASH) && !defined(USE_ALPHA_CLIP) && !defined(SHADOW_SHADER) && !defined(USE_MULTIPLY) layout(location = 0) out vec4 fragColor; layout(location = 1) out vec4 ssrNormals; diff --git a/source/blender/draw/engines/eevee/shaders/lit_surface_frag.glsl b/source/blender/draw/engines/eevee/shaders/lit_surface_frag.glsl index ac1dd071a29..644b449c03e 100644 --- a/source/blender/draw/engines/eevee/shaders/lit_surface_frag.glsl +++ b/source/blender/draw/engines/eevee/shaders/lit_surface_frag.glsl @@ -374,7 +374,7 @@ void CLOSURE_NAME( accumulate_light(trans, 1.0, refr_accum); } #endif -#endif /* Specular probes */ +#endif /* Specular probes */ /* ---------------------------- */ @@ -479,4 +479,4 @@ void CLOSURE_NAME( #ifdef CLOSURE_SUBSURFACE #undef CLOSURE_SUBSURFACE -#endif
\ No newline at end of file +#endif diff --git a/source/blender/draw/engines/workbench/shaders/workbench_data_lib.glsl b/source/blender/draw/engines/workbench/shaders/workbench_data_lib.glsl index f67d2ff6745..2d913c63b00 100644 --- a/source/blender/draw/engines/workbench/shaders/workbench_data_lib.glsl +++ b/source/blender/draw/engines/workbench/shaders/workbench_data_lib.glsl @@ -4,12 +4,7 @@ struct LightData { }; struct WorldData { - vec4 diffuse_light_x_pos; - vec4 diffuse_light_x_neg; - vec4 diffuse_light_y_pos; - vec4 diffuse_light_y_neg; - vec4 diffuse_light_z_pos; - vec4 diffuse_light_z_neg; + vec3 spherical_harmonics_coefs[STUDIOLIGHT_SPHERICAL_HARMONICS_MAX_COMPONENTS]; vec4 background_color_low; vec4 background_color_high; vec4 object_outline_color; @@ -17,7 +12,8 @@ struct WorldData { LightData lights[3]; int num_lights; int matcap_orientation; - int pad[2]; + float background_alpha; + int pad[1]; }; struct MaterialData { diff --git a/source/blender/draw/engines/workbench/shaders/workbench_deferred_composite_frag.glsl b/source/blender/draw/engines/workbench/shaders/workbench_deferred_composite_frag.glsl index 461fb2fb130..c72df6b677d 100644 --- a/source/blender/draw/engines/workbench/shaders/workbench_deferred_composite_frag.glsl +++ b/source/blender/draw/engines/workbench/shaders/workbench_deferred_composite_frag.glsl @@ -32,7 +32,7 @@ void main() #ifndef V3D_SHADING_OBJECT_OUTLINE if (object_id == NO_OBJECT_ID) { - fragColor = vec4(background_color(world_data, uv_viewport.y), 0.0); + fragColor = vec4(background_color(world_data, uv_viewport.y), world_data.background_alpha); return; } #else /* !V3D_SHADING_OBJECT_OUTLINE */ @@ -41,10 +41,10 @@ void main() if (object_id == NO_OBJECT_ID) { vec3 background = background_color(world_data, uv_viewport.y); if (object_outline == 0.0) { - fragColor = vec4(background, 0.0); + fragColor = vec4(background, world_data.background_alpha); } else { - fragColor = vec4(mix(world_data.object_outline_color.rgb, background, object_outline), 1.0-object_outline); + fragColor = vec4(mix(world_data.object_outline_color.rgb, background, object_outline), clamp(world_data.background_alpha, 1.0, object_outline)); } return; } @@ -106,7 +106,7 @@ void main() #endif #ifdef V3D_SHADING_SHADOW - float light_factor = -dot(normal_viewport, world_data.light_direction_vs.xyz); + float light_factor = -dot(normal_viewport, world_data.lights[0].light_direction_vs.xyz); /* The step function might be ok for meshes but it's * clearly not the case for hairs. Do smoothstep in this case. */ float shadow_mix = (diffuse_color.a == 1.0 || diffuse_color.a == 0.0) diff --git a/source/blender/draw/engines/workbench/shaders/workbench_effect_fxaa_frag.glsl b/source/blender/draw/engines/workbench/shaders/workbench_effect_fxaa_frag.glsl new file mode 100644 index 00000000000..4ffd20c2839 --- /dev/null +++ b/source/blender/draw/engines/workbench/shaders/workbench_effect_fxaa_frag.glsl @@ -0,0 +1,19 @@ + +in vec4 uvcoordsvar; + +out vec4 FragColor; + +uniform sampler2D colorBuffer; +uniform vec2 invertedViewportSize; + +void main() +{ + FragColor = FxaaPixelShader( + uvcoordsvar.st, + colorBuffer, + invertedViewportSize, + 1.0, + 0.166, + 0.0833 + ); +} diff --git a/source/blender/draw/engines/workbench/shaders/workbench_world_light_lib.glsl b/source/blender/draw/engines/workbench/shaders/workbench_world_light_lib.glsl index 9d256e5350a..b13c4f1b43b 100644 --- a/source/blender/draw/engines/workbench/shaders/workbench_world_light_lib.glsl +++ b/source/blender/draw/engines/workbench/shaders/workbench_world_light_lib.glsl @@ -1,24 +1,36 @@ #define BLINN +vec3 spherical_harmonics(vec3 N, vec3 spherical_harmonics_coefs[STUDIOLIGHT_SPHERICAL_HARMONICS_MAX_COMPONENTS]) +{ + vec3 sh = vec3(0.0); + + sh += 0.282095 * spherical_harmonics_coefs[0]; + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 0 + sh += -0.488603 * N.z * spherical_harmonics_coefs[1]; + sh += 0.488603 * N.y * spherical_harmonics_coefs[2]; + sh += -0.488603 * N.x * spherical_harmonics_coefs[3]; +#endif + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 1 + sh += 1.092548 * N.x * N.z * spherical_harmonics_coefs[4]; + sh += -1.092548 * N.z * N.y * spherical_harmonics_coefs[5]; + sh += 0.315392 * (3.0 * N.y * N.y - 1.0) * spherical_harmonics_coefs[6]; + sh += -1.092548 * N.x * N.y * spherical_harmonics_coefs[7]; + sh += 0.546274 * (N.x * N.x - N.z * N.z) * spherical_harmonics_coefs[8]; +#endif + + return sh; +} + vec3 get_world_diffuse_light(WorldData world_data, vec3 N) { - vec4 result = world_data.diffuse_light_x_pos * clamp(N.x, 0.0, 1.0); - result = mix(result, world_data.diffuse_light_x_neg, clamp(-N.x, 0.0, 1.0)); - result = mix(result, world_data.diffuse_light_y_pos, clamp(-N.y, 0.0, 1.0)); - result = mix(result, world_data.diffuse_light_y_neg, clamp(N.y, 0.0, 1.0)); - result = mix(result, world_data.diffuse_light_z_pos, clamp(N.z, 0.0, 1.0)); - return mix(result, world_data.diffuse_light_z_neg, clamp(-N.z, 0.0, 1.0)).xyz; + return (spherical_harmonics(vec3(N.x, N.y, -N.z), world_data.spherical_harmonics_coefs)); } vec3 get_camera_diffuse_light(WorldData world_data, vec3 N) { - vec4 result = world_data.diffuse_light_x_pos * clamp(N.x, 0.0, 1.0); - result = mix(result, world_data.diffuse_light_x_neg, clamp(-N.x, 0.0, 1.0)); - result = mix(result, world_data.diffuse_light_z_pos, clamp( N.y, 0.0, 1.0)); - result = mix(result, world_data.diffuse_light_z_neg, clamp(-N.y, 0.0, 1.0)); - result = mix(result, world_data.diffuse_light_y_pos, clamp( N.z, 0.0, 1.0)); - result = mix(result, world_data.diffuse_light_y_neg, clamp(-N.z, 0.0, 1.0)); - return result.rgb; + return (spherical_harmonics(vec3(N.x, -N.z, -N.y), world_data.spherical_harmonics_coefs)); } /* N And I are in View Space. */ diff --git a/source/blender/draw/engines/workbench/workbench_data.c b/source/blender/draw/engines/workbench/workbench_data.c index df0a2bf4684..efadf969830 100644 --- a/source/blender/draw/engines/workbench/workbench_data.c +++ b/source/blender/draw/engines/workbench/workbench_data.c @@ -10,6 +10,7 @@ void workbench_private_data_init(WORKBENCH_PrivateData *wpd) const DRWContextState *draw_ctx = DRW_context_state_get(); const Scene *scene = draw_ctx->scene; wpd->material_hash = BLI_ghash_ptr_new(__func__); + wpd->user_preferences = &U; View3D *v3d = draw_ctx->v3d; if (v3d) { @@ -36,6 +37,7 @@ void workbench_private_data_init(WORKBENCH_PrivateData *wpd) WORKBENCH_UBO_World *wd = &wpd->world_data; wd->matcap_orientation = (wpd->shading.flag & V3D_SHADING_MATCAP_FLIP_X) > 0; + wd->background_alpha = 1.0f; if ((v3d->flag3 & V3D_SHOW_WORLD) && (scene->world != NULL)) @@ -116,7 +118,6 @@ void workbench_private_data_init(WORKBENCH_PrivateData *wpd) wpd->viewvecs[1][2] = vec_far[2] - wpd->viewvecs[0][2]; } } - } void workbench_private_data_get_light_direction(WORKBENCH_PrivateData *wpd, float light_direction[3]) @@ -152,22 +153,9 @@ void workbench_private_data_get_light_direction(WORKBENCH_PrivateData *wpd, floa wd->num_lights = light_index; } -#if 0 - if (STUDIOLIGHT_ORIENTATION_WORLD_ENABLED(wpd)) { - BKE_studiolight_ensure_flag(wpd->studio_light, STUDIOLIGHT_LIGHT_DIRECTION_CALCULATED); - float rot_matrix[3][3]; - axis_angle_to_mat3_single(rot_matrix, 'Z', wpd->shading.studiolight_rot_z); - mul_v3_m3v3(e_data.display.light_direction, rot_matrix, wpd->studio_light->light_direction); - } - else { -#else - { -#endif - copy_v3_v3(light_direction, scene->display.light_direction); - negate_v3(light_direction); - } - - DRW_uniformbuffer_update(wpd->world_ubo, &wpd->world_data); + copy_v3_v3(light_direction, scene->display.light_direction); + negate_v3(light_direction); + DRW_uniformbuffer_update(wpd->world_ubo, wd); } static void workbench_private_material_free(void *data) diff --git a/source/blender/draw/engines/workbench/workbench_deferred.c b/source/blender/draw/engines/workbench/workbench_deferred.c index 37978882abe..9b1a17a372a 100644 --- a/source/blender/draw/engines/workbench/workbench_deferred.c +++ b/source/blender/draw/engines/workbench/workbench_deferred.c @@ -49,7 +49,7 @@ /* *********** STATIC *********** */ -// #define DEBUG_SHADOW_VOLUME +/* #define DEBUG_SHADOW_VOLUME */ #ifdef DEBUG_SHADOW_VOLUME # include "draw_debug.h" @@ -65,6 +65,7 @@ static struct { struct GPUShader *shadow_pass_manifold_sh; struct GPUShader *shadow_caps_sh; struct GPUShader *shadow_caps_manifold_sh; + struct GPUShader *effect_fxaa_sh; struct GPUTexture *object_id_tx; /* ref only, not alloced */ struct GPUTexture *color_buffer_tx; /* ref only, not alloced */ @@ -72,9 +73,9 @@ static struct { struct GPUTexture *specular_buffer_tx; /* ref only, not alloced */ struct GPUTexture *normal_buffer_tx; /* ref only, not alloced */ struct GPUTexture *composite_buffer_tx; /* ref only, not alloced */ + struct GPUTexture *effect_buffer_tx; /* ref only, not alloced */ SceneDisplay display; /* world light direction for shadows */ - float light_direction_vs[3]; int next_object_id; float normal_world_matrix[3][3]; @@ -84,6 +85,8 @@ static struct { } e_data = {{NULL}}; /* Shaders */ +extern char datatoc_common_fxaa_lib_glsl[]; +extern char datatoc_common_fullscreen_vert_glsl[]; extern char datatoc_common_hair_lib_glsl[]; extern char datatoc_workbench_prepass_vert_glsl[]; @@ -100,6 +103,7 @@ extern char datatoc_workbench_background_lib_glsl[]; extern char datatoc_workbench_cavity_lib_glsl[]; extern char datatoc_workbench_common_lib_glsl[]; extern char datatoc_workbench_data_lib_glsl[]; +extern char datatoc_workbench_effect_fxaa_frag_glsl[]; extern char datatoc_workbench_object_outline_lib_glsl[]; extern char datatoc_workbench_world_light_lib_glsl[]; @@ -317,6 +321,12 @@ void workbench_deferred_engine_init(WORKBENCH_Data *vedata) char *cavity_frag = workbench_build_cavity_frag(); e_data.cavity_sh = DRW_shader_create_fullscreen(cavity_frag, NULL); MEM_freeN(cavity_frag); + + e_data.effect_fxaa_sh = DRW_shader_create_with_lib( + datatoc_common_fullscreen_vert_glsl, NULL, + datatoc_workbench_effect_fxaa_frag_glsl, + datatoc_common_fxaa_lib_glsl, + NULL); } if (!stl->g_data) { @@ -336,6 +346,8 @@ void workbench_deferred_engine_init(WORKBENCH_Data *vedata) e_data.specular_buffer_tx = DRW_texture_pool_query_2D(size[0], size[1], GPU_RGBA8, &draw_engine_workbench_solid); e_data.composite_buffer_tx = DRW_texture_pool_query_2D( size[0], size[1], GPU_RGBA16F, &draw_engine_workbench_solid); + e_data.effect_buffer_tx = DRW_texture_pool_query_2D( + size[0], size[1], GPU_RGBA16F, &draw_engine_workbench_solid); if (NORMAL_ENCODING_ENABLED()) { e_data.normal_buffer_tx = DRW_texture_pool_query_2D( @@ -361,6 +373,10 @@ void workbench_deferred_engine_init(WORKBENCH_Data *vedata) GPU_ATTACHMENT_TEXTURE(dtxl->depth), GPU_ATTACHMENT_TEXTURE(e_data.composite_buffer_tx), }); + GPU_framebuffer_ensure_config(&fbl->effect_fb, { + GPU_ATTACHMENT_NONE, + GPU_ATTACHMENT_TEXTURE(e_data.effect_buffer_tx), + }); } { @@ -406,6 +422,14 @@ void workbench_deferred_engine_init(WORKBENCH_Data *vedata) DRW_shgroup_uniform_block(grp, "samples_block", e_data.sampling_ubo); DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL); } + + { + psl->effect_fxaa_pass = DRW_pass_create("Effect FXAA", DRW_STATE_WRITE_COLOR); + DRWShadingGroup *grp = DRW_shgroup_create(e_data.effect_fxaa_sh, psl->effect_fxaa_pass); + DRW_shgroup_uniform_texture_ref(grp, "colorBuffer", &e_data.effect_buffer_tx); + DRW_shgroup_uniform_vec2(grp, "invertedViewportSize", DRW_viewport_invert_size_get(), 1); + DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL); + } } void workbench_deferred_engine_free() @@ -425,6 +449,7 @@ void workbench_deferred_engine_free() DRW_SHADER_FREE_SAFE(e_data.shadow_caps_sh); DRW_SHADER_FREE_SAFE(e_data.shadow_caps_manifold_sh); + DRW_SHADER_FREE_SAFE(e_data.effect_fxaa_sh); } static void workbench_composite_uniforms(WORKBENCH_PrivateData *wpd, DRWShadingGroup *grp) @@ -446,7 +471,7 @@ static void workbench_composite_uniforms(WORKBENCH_PrivateData *wpd, DRWShadingG if (STUDIOLIGHT_ORIENTATION_VIEWNORMAL_ENABLED(wpd)) { BKE_studiolight_ensure_flag(wpd->studio_light, STUDIOLIGHT_EQUIRECTANGULAR_RADIANCE_GPUTEXTURE); - DRW_shgroup_uniform_texture(grp, "matcapImage", wpd->studio_light->equirectangular_radiance_gputexture); DRW_shgroup_uniform_texture(grp, "matcapImage", wpd->studio_light->equirectangular_radiance_gputexture); + DRW_shgroup_uniform_texture(grp, "matcapImage", wpd->studio_light->equirectangular_radiance_gputexture); } workbench_material_set_normal_world_matrix(grp, wpd, e_data.normal_world_matrix); @@ -459,8 +484,6 @@ void workbench_deferred_cache_init(WORKBENCH_Data *vedata) WORKBENCH_PrivateData *wpd = stl->g_data; DRWShadingGroup *grp; const DRWContextState *draw_ctx = DRW_context_state_get(); - static float light_multiplier = 1.0f; - Scene *scene = draw_ctx->scene; @@ -468,9 +491,9 @@ void workbench_deferred_cache_init(WORKBENCH_Data *vedata) /* Deferred Mix Pass */ { workbench_private_data_get_light_direction(wpd, e_data.display.light_direction); + studiolight_update_light(wpd, e_data.display.light_direction); e_data.display.shadow_shift = scene->display.shadow_shift; - copy_v3_v3(e_data.light_direction_vs, wpd->world_data.lights[0].light_direction_vs); if (SHADOW_ENABLED(wpd)) { psl->composite_pass = DRW_pass_create( @@ -478,7 +501,7 @@ void workbench_deferred_cache_init(WORKBENCH_Data *vedata) grp = DRW_shgroup_create(wpd->composite_sh, psl->composite_pass); workbench_composite_uniforms(wpd, grp); DRW_shgroup_stencil_mask(grp, 0x00); - DRW_shgroup_uniform_float(grp, "lightMultiplier", &light_multiplier, 1); + DRW_shgroup_uniform_float_copy(grp, "lightMultiplier", 1.0f); DRW_shgroup_uniform_float(grp, "shadowMultiplier", &wpd->shadow_multiplier, 1); DRW_shgroup_uniform_float(grp, "shadowShift", &scene->display.shadow_shift, 1); DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL); @@ -522,7 +545,6 @@ void workbench_deferred_cache_init(WORKBENCH_Data *vedata) DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL); #endif - studiolight_update_light(wpd, e_data.display.light_direction); } else { psl->composite_pass = DRW_pass_create( @@ -568,7 +590,7 @@ static WORKBENCH_MaterialData *get_or_create_material_data( case OB_TEXTURE: { - GPUTexture *tex = GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, false, false); + GPUTexture *tex = GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, 0.0); DRW_shgroup_uniform_texture(material->shgrp, "image", tex); break; } @@ -631,7 +653,7 @@ static void workbench_cache_populate_particles(WORKBENCH_Data *vedata, Object *o DRW_shgroup_uniform_int(shgrp, "object_id", &material->object_id, 1); DRW_shgroup_uniform_block(shgrp, "material_block", material->material_ubo); if (image) { - GPUTexture *tex = GPU_texture_from_blender(image, NULL, GL_TEXTURE_2D, false, false, false); + GPUTexture *tex = GPU_texture_from_blender(image, NULL, GL_TEXTURE_2D, false, 0.0f); DRW_shgroup_uniform_texture(shgrp, "image", tex); } } @@ -690,7 +712,7 @@ void workbench_deferred_solid_cache_populate(WORKBENCH_Data *vedata, Object *ob) /* Fallback from not drawn OB_TEXTURE mode or just OB_SOLID mode */ if (!is_drawn) { - if ((wpd->shading.color_type != V3D_SHADING_MATERIAL_COLOR) || is_sculpt_mode) { + if ((wpd->shading.color_type != V3D_SHADING_MATERIAL_COLOR)) { /* No material split needed */ struct Gwn_Batch *geom = DRW_cache_object_surface_get(ob); if (geom) { @@ -720,7 +742,12 @@ void workbench_deferred_solid_cache_populate(WORKBENCH_Data *vedata, Object *ob) Material *mat = give_current_material(ob, i + 1); material = get_or_create_material_data(vedata, ob, mat, NULL, OB_SOLID); - DRW_shgroup_call_object_add(material->shgrp, mat_geom[i], ob); + if (is_sculpt_mode) { + DRW_shgroup_call_sculpt_add(material->shgrp, ob, ob->obmat); + } + else { + DRW_shgroup_call_object_add(material->shgrp, mat_geom[i], ob); + } } } } @@ -862,8 +889,21 @@ void workbench_deferred_draw_scene(WORKBENCH_Data *vedata) DRW_draw_pass(psl->composite_pass); } - GPU_framebuffer_bind(dfbl->color_only_fb); - DRW_transform_to_display(e_data.composite_buffer_tx); + if (FXAA_ENABLED(wpd)) { + GPU_framebuffer_bind(fbl->effect_fb); + DRW_transform_to_display(e_data.composite_buffer_tx); + + /* TODO: when rendering the fxaa pass should be done in display space + Currently we do not support rendering in the workbench + */ + GPU_framebuffer_bind(dfbl->color_only_fb); + DRW_draw_pass(psl->effect_fxaa_pass); + } + else { + GPU_framebuffer_bind(dfbl->color_only_fb); + DRW_transform_to_display(e_data.composite_buffer_tx); + } + workbench_private_data_free(wpd); } diff --git a/source/blender/draw/engines/workbench/workbench_forward.c b/source/blender/draw/engines/workbench/workbench_forward.c index 1a387c8087c..db07f9bb6f5 100644 --- a/source/blender/draw/engines/workbench/workbench_forward.c +++ b/source/blender/draw/engines/workbench/workbench_forward.c @@ -193,7 +193,7 @@ static WORKBENCH_MaterialData *get_or_create_material_data( case OB_TEXTURE: { - GPUTexture *tex = GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, false, false); + GPUTexture *tex = GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, 0.0f); DRW_shgroup_uniform_texture(grp, "image", tex); break; } @@ -306,7 +306,7 @@ void workbench_forward_engine_init(WORKBENCH_Data *vedata) e_data.transparent_revealage_tx = DRW_texture_pool_query_2D( size[0], size[1], GPU_R16F, &draw_engine_workbench_transparent); e_data.composite_buffer_tx = DRW_texture_pool_query_2D( - size[0], size[1], GPU_RGBA16F, &draw_engine_workbench_transparent); + size[0], size[1], GPU_R11F_G11F_B10F, &draw_engine_workbench_transparent); GPU_framebuffer_ensure_config(&fbl->object_outline_fb, { GPU_ATTACHMENT_TEXTURE(dtxl->depth), @@ -427,7 +427,7 @@ static void workbench_forward_cache_populate_particles(WORKBENCH_Data *vedata, O float hair_alpha = wpd->shading.xray_alpha * 0.33f; DRW_shgroup_uniform_float_copy(shgrp, "alpha", hair_alpha); if (image) { - GPUTexture *tex = GPU_texture_from_blender(image, NULL, GL_TEXTURE_2D, false, false, false); + GPUTexture *tex = GPU_texture_from_blender(image, NULL, GL_TEXTURE_2D, false, 0.0f); DRW_shgroup_uniform_texture(shgrp, "image", tex); } if (STUDIOLIGHT_ORIENTATION_VIEWNORMAL_ENABLED(wpd)) { @@ -476,7 +476,7 @@ void workbench_forward_cache_populate(WORKBENCH_Data *vedata, Object *ob) struct Gwn_Batch **geom_array = me->totcol ? DRW_cache_mesh_surface_texpaint_get(ob) : NULL; if (materials_len > 0 && geom_array) { for (int i = 0; i < materials_len; i++) { - if(geom_array[i] == NULL) { + if (geom_array[i] == NULL) { continue; } @@ -499,7 +499,7 @@ void workbench_forward_cache_populate(WORKBENCH_Data *vedata, Object *ob) /* Fallback from not drawn OB_TEXTURE mode or just OB_SOLID mode */ if (!is_drawn) { - if ((wpd->shading.color_type != V3D_SHADING_MATERIAL_COLOR) || is_sculpt_mode) { + if ((wpd->shading.color_type != V3D_SHADING_MATERIAL_COLOR)) { /* No material split needed */ struct Gwn_Batch *geom = DRW_cache_object_surface_get(ob); if (geom) { @@ -524,14 +524,20 @@ void workbench_forward_cache_populate(WORKBENCH_Data *vedata, Object *ob) ob, gpumat_array, materials_len, NULL, NULL, NULL); if (mat_geom) { for (int i = 0; i < materials_len; ++i) { - if(mat_geom[i] == NULL) { + if (mat_geom[i] == NULL) { continue; } Material *mat = give_current_material(ob, i + 1); material = get_or_create_material_data(vedata, ob, mat, NULL, OB_SOLID); - DRW_shgroup_call_object_add(material->shgrp_object_outline, mat_geom[i], ob); - DRW_shgroup_call_object_add(material->shgrp, mat_geom[i], ob); + if (is_sculpt_mode) { + DRW_shgroup_call_sculpt_add(material->shgrp_object_outline, ob, ob->obmat); + DRW_shgroup_call_sculpt_add(material->shgrp, ob, ob->obmat); + } + else { + DRW_shgroup_call_object_add(material->shgrp_object_outline, mat_geom[i], ob); + DRW_shgroup_call_object_add(material->shgrp, mat_geom[i], ob); + } } } } diff --git a/source/blender/draw/engines/workbench/workbench_materials.c b/source/blender/draw/engines/workbench/workbench_materials.c index 231d9a9582a..c0857cf74aa 100644 --- a/source/blender/draw/engines/workbench/workbench_materials.c +++ b/source/blender/draw/engines/workbench/workbench_materials.c @@ -95,6 +95,17 @@ char *workbench_material_build_defines(WORKBENCH_PrivateData *wpd, int drawtype, BLI_dynstr_appendf(ds, "#define HAIR_SHADER\n"); } +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 0 + BLI_dynstr_appendf(ds, "#define STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL 0\n"); +#endif +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 1 + BLI_dynstr_appendf(ds, "#define STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL 1\n"); +#endif +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 2 + BLI_dynstr_appendf(ds, "#define STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL 2\n"); +#endif + BLI_dynstr_appendf(ds, "#define STUDIOLIGHT_SPHERICAL_HARMONICS_MAX_COMPONENTS 9\n"); + str = BLI_dynstr_get_cstring(ds); BLI_dynstr_free(ds); return str; diff --git a/source/blender/draw/engines/workbench/workbench_private.h b/source/blender/draw/engines/workbench/workbench_private.h index b17cc93d148..68d50a85c35 100644 --- a/source/blender/draw/engines/workbench/workbench_private.h +++ b/source/blender/draw/engines/workbench/workbench_private.h @@ -32,6 +32,7 @@ #include "DNA_image_types.h" #include "DNA_view3d_types.h" #include "DNA_world_types.h" +#include "DNA_userdef_types.h" #include "DRW_render.h" @@ -50,6 +51,7 @@ #define STUDIOLIGHT_ORIENTATION_VIEWNORMAL_ENABLED(wpd) (MATCAP_ENABLED(wpd) && (wpd->studio_light->flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL)) #define CAVITY_ENABLED(wpd) (wpd->shading.flag & V3D_SHADING_CAVITY) #define SHADOW_ENABLED(wpd) (wpd->shading.flag & V3D_SHADING_SHADOW) +#define FXAA_ENABLED(wpd) (wpd->user_preferences->gpu_viewport_antialias & USER_AA_FXAA && (!DRW_state_is_opengl_render())) #define SPECULAR_HIGHLIGHT_ENABLED(wpd) ((wpd->shading.flag & V3D_SHADING_SPECULAR_HIGHLIGHT) && (!STUDIOLIGHT_ORIENTATION_VIEWNORMAL_ENABLED(wpd))) #define OBJECT_ID_PASS_ENABLED(wpd) (wpd->shading.flag & V3D_SHADING_OBJECT_OUTLINE) #define NORMAL_VIEWPORT_COMP_PASS_ENABLED(wpd) (MATCAP_ENABLED(wpd) || STUDIOLIGHT_ENABLED(wpd) || SHADOW_ENABLED(wpd) || SPECULAR_HIGHLIGHT_ENABLED(wpd)) @@ -61,6 +63,7 @@ typedef struct WORKBENCH_FramebufferList { struct GPUFrameBuffer *prepass_fb; struct GPUFrameBuffer *cavity_fb; struct GPUFrameBuffer *composite_fb; + struct GPUFrameBuffer *effect_fb; /* Forward render buffers */ struct GPUFrameBuffer *object_outline_fb; @@ -85,6 +88,7 @@ typedef struct WORKBENCH_PassList { struct DRWPass *shadow_depth_fail_caps_mani_pass; struct DRWPass *composite_pass; struct DRWPass *composite_shadow_pass; + struct DRWPass *effect_fxaa_pass; /* forward rendering */ struct DRWPass *transparent_accum_pass; @@ -108,12 +112,7 @@ typedef struct WORKBENCH_UBO_Light { } WORKBENCH_UBO_Light; typedef struct WORKBENCH_UBO_World { - float diffuse_light_x_pos[4]; - float diffuse_light_x_neg[4]; - float diffuse_light_y_pos[4]; - float diffuse_light_y_neg[4]; - float diffuse_light_z_pos[4]; - float diffuse_light_z_neg[4]; + float spherical_harmonics_coefs[STUDIOLIGHT_SPHERICAL_HARMONICS_MAX_COMPONENTS][4]; float background_color_low[4]; float background_color_high[4]; float object_outline_color[4]; @@ -121,7 +120,8 @@ typedef struct WORKBENCH_UBO_World { WORKBENCH_UBO_Light lights[3]; int num_lights; int matcap_orientation; - int pad[2]; + float background_alpha; + int pad[1]; } WORKBENCH_UBO_World; BLI_STATIC_ASSERT_ALIGN(WORKBENCH_UBO_World, 16) @@ -146,6 +146,7 @@ typedef struct WORKBENCH_PrivateData { struct GPUShader *transparent_accum_texture_hair_sh; View3DShading shading; StudioLight *studio_light; + UserDef *user_preferences; int drawtype; struct GPUUniformBuffer *world_ubo; struct DRWShadingGroup *shadow_shgrp; diff --git a/source/blender/draw/engines/workbench/workbench_studiolight.c b/source/blender/draw/engines/workbench/workbench_studiolight.c index 6451d1f57c8..f9e5df91388 100644 --- a/source/blender/draw/engines/workbench/workbench_studiolight.c +++ b/source/blender/draw/engines/workbench/workbench_studiolight.c @@ -34,14 +34,15 @@ void studiolight_update_world(StudioLight *sl, WORKBENCH_UBO_World *wd) { - BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED); - - copy_v3_v3(wd->diffuse_light_x_pos, sl->diffuse_light[STUDIOLIGHT_X_POS]); - copy_v3_v3(wd->diffuse_light_x_neg, sl->diffuse_light[STUDIOLIGHT_X_NEG]); - copy_v3_v3(wd->diffuse_light_y_pos, sl->diffuse_light[STUDIOLIGHT_Y_POS]); - copy_v3_v3(wd->diffuse_light_y_neg, sl->diffuse_light[STUDIOLIGHT_Y_NEG]); - copy_v3_v3(wd->diffuse_light_z_pos, sl->diffuse_light[STUDIOLIGHT_Z_POS]); - copy_v3_v3(wd->diffuse_light_z_neg, sl->diffuse_light[STUDIOLIGHT_Z_NEG]); + int i; + BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED); + + for (i = 0; i < STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS; i++) { + copy_v3_v3(wd->spherical_harmonics_coefs[i], sl->spherical_harmonics_coefs[i]); + } + for (; i < STUDIOLIGHT_SPHERICAL_HARMONICS_MAX_COMPONENTS; i++) { + copy_v3_fl(wd->spherical_harmonics_coefs[i], 0.0); + } } static void compute_parallel_lines_nor_and_dist(const float v1[2], const float v2[2], const float v3[2], float r_line[2]) @@ -125,6 +126,7 @@ static BoundBox *studiolight_object_shadow_bbox_get(WORKBENCH_PrivateData *wpd, for (int i = 0; i < 8; ++i) { mul_m4_v3(wpd->shadow_mat, oed->shadow_bbox.vec[i]); } + oed->shadow_bbox_dirty = false; } return &oed->shadow_bbox; diff --git a/source/blender/draw/intern/draw_cache_impl_particles.c b/source/blender/draw/intern/draw_cache_impl_particles.c index 380cb089628..d1e05b525ef 100644 --- a/source/blender/draw/intern/draw_cache_impl_particles.c +++ b/source/blender/draw/intern/draw_cache_impl_particles.c @@ -45,6 +45,7 @@ #include "DNA_customdata_types.h" #include "BKE_mesh.h" +#include "BKE_modifier.h" #include "BKE_particle.h" #include "BKE_pointcache.h" @@ -1309,17 +1310,42 @@ static void drw_particle_update_ptcache( } } +typedef struct ParticleDrawSource { + Object *object; + ParticleSystem *psys; + ModifierData *md; + PTCacheEdit *edit; +} ParticleDrawSource; + +static void drw_particle_get_hair_source( + Object *object, + ParticleSystem *psys, + ModifierData *md, + PTCacheEdit *edit, + ParticleDrawSource *r_draw_source) +{ + r_draw_source->object = object; + r_draw_source->psys = psys; + r_draw_source->md = md; + r_draw_source->edit = edit; + if ((object->mode & OB_MODE_PARTICLE_EDIT) != 0) { + r_draw_source->object = DEG_get_original_object(object); + r_draw_source->psys = psys_orig_get(psys); + } +} + Gwn_Batch *DRW_particles_batch_cache_get_hair( Object *object, ParticleSystem *psys, ModifierData *md) { ParticleBatchCache *cache = particle_batch_cache_get(psys); - if (cache->hair.hairs == NULL) { drw_particle_update_ptcache(object, psys); - ensure_seg_pt_count(NULL, psys, &cache->hair); - particle_batch_cache_ensure_pos_and_seg(NULL, psys, md, &cache->hair); + ParticleDrawSource source; + drw_particle_get_hair_source(object, psys, md, NULL, &source); + ensure_seg_pt_count(source.edit, source.psys, &cache->hair); + particle_batch_cache_ensure_pos_and_seg(source.edit, source.psys, source.md, &cache->hair); cache->hair.hairs = GWN_batch_create( GWN_PRIM_LINE_STRIP, cache->hair.pos, @@ -1515,7 +1541,7 @@ Gwn_Batch *DRW_particles_batch_cache_get_edit_tip_points( /* Ensure all textures and buffers needed for GPU accelerated drawing. */ bool particles_ensure_procedural_data( - Object *UNUSED(object), + Object *object, ParticleSystem *psys, ModifierData *md, ParticleHairCache **r_hair_cache, @@ -1524,22 +1550,27 @@ bool particles_ensure_procedural_data( { bool need_ft_update = false; - ParticleSettings *part = psys->part; - ParticleBatchCache *cache = particle_batch_cache_get(psys); + drw_particle_update_ptcache(object, psys); + + ParticleDrawSource source; + drw_particle_get_hair_source(object, psys, md, NULL, &source); + + ParticleSettings *part = source.psys->part; + ParticleBatchCache *cache = particle_batch_cache_get(source.psys); *r_hair_cache = &cache->hair; (*r_hair_cache)->final[subdiv].strands_res = 1 << (part->draw_step + subdiv); /* Refreshed on combing and simulation. */ if ((*r_hair_cache)->proc_point_buf == NULL) { - ensure_seg_pt_count(NULL, psys, &cache->hair); - particle_batch_cache_ensure_procedural_pos(NULL, psys, &cache->hair); + ensure_seg_pt_count(source.edit, source.psys, &cache->hair); + particle_batch_cache_ensure_procedural_pos(source.edit, source.psys, &cache->hair); need_ft_update = true; } /* Refreshed if active layer or custom data changes. */ if ((*r_hair_cache)->strand_tex == NULL) { - particle_batch_cache_ensure_procedural_strand_data(NULL, psys, md, &cache->hair); + particle_batch_cache_ensure_procedural_strand_data(source.edit, source.psys, source.md, &cache->hair); } /* Refreshed only on subdiv count change. */ @@ -1548,7 +1579,7 @@ bool particles_ensure_procedural_data( need_ft_update = true; } if ((*r_hair_cache)->final[subdiv].proc_hairs[thickness_res - 1] == NULL) { - particle_batch_cache_ensure_procedural_indices(NULL, psys, &cache->hair, thickness_res, subdiv); + particle_batch_cache_ensure_procedural_indices(source.edit, source.psys, &cache->hair, thickness_res, subdiv); } diff --git a/source/blender/draw/intern/draw_common.c b/source/blender/draw/intern/draw_common.c index fb8833f40c3..d40378dec2d 100644 --- a/source/blender/draw/intern/draw_common.c +++ b/source/blender/draw/intern/draw_common.c @@ -64,6 +64,7 @@ void DRW_globals_update(void) UI_GetThemeColor4fv(TH_VERTEX_SELECT, ts.colorVertexSelect); UI_GetThemeColor4fv(TH_EDITMESH_ACTIVE, ts.colorEditMeshActive); UI_GetThemeColor4fv(TH_EDGE_SELECT, ts.colorEdgeSelect); + UI_GetThemeColor4fv(TH_EDGE_SEAM, ts.colorEdgeSeam); UI_GetThemeColor4fv(TH_EDGE_SHARP, ts.colorEdgeSharp); UI_GetThemeColor4fv(TH_EDGE_CREASE, ts.colorEdgeCrease); @@ -118,8 +119,8 @@ void DRW_globals_update(void) ts.sizeLampCircleShadow = ts.sizeLampCircle + U.pixelsize * 3.0f; /* M_SQRT2 to be at least the same size of the old square */ - ts.sizeVertex = ceilf(UI_GetThemeValuef(TH_VERTEX_SIZE) * (float)M_SQRT2 / 2.0f); - ts.sizeFaceDot = ceilf(UI_GetThemeValuef(TH_FACEDOT_SIZE) * (float)M_SQRT2); + ts.sizeVertex = max_ff(1.0f, UI_GetThemeValuef(TH_VERTEX_SIZE) * (float)M_SQRT2 / 2.0f); + ts.sizeFaceDot = UI_GetThemeValuef(TH_FACEDOT_SIZE); ts.sizeEdge = 1.0f / 2.0f; /* TODO Theme */ ts.sizeEdgeFix = 0.5f + 2.0f * (2.0f * (MAX2(ts.sizeVertex, ts.sizeEdge)) * (float)M_SQRT1_2); diff --git a/source/blender/draw/intern/draw_manager.c b/source/blender/draw/intern/draw_manager.c index 054d070bea1..fcdc4a3a016 100644 --- a/source/blender/draw/intern/draw_manager.c +++ b/source/blender/draw/intern/draw_manager.c @@ -76,7 +76,6 @@ #include "draw_cache_impl.h" #include "draw_mode_engines.h" -#include "engines/clay/clay_engine.h" #include "engines/eevee/eevee_engine.h" #include "engines/basic/basic_engine.h" #include "engines/workbench/workbench_engine.h" @@ -1312,13 +1311,14 @@ void DRW_draw_render_loop_ex( } DRW_stats_begin(); - DRW_hair_update(); GPU_framebuffer_bind(DST.default_framebuffer); /* Start Drawing */ DRW_state_reset(); + DRW_hair_update(); + drw_engines_draw_background(); /* WIP, single image drawn over the camera view (replace) */ @@ -1360,15 +1360,21 @@ void DRW_draw_render_loop_ex( if (DST.draw_ctx.evil_C) { /* needed so manipulator isn't obscured */ - glDisable(GL_DEPTH_TEST); - DRW_draw_manipulator_3d(); + if (((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) && + ((v3d->twflag & V3D_MANIPULATOR_DRAW) != 0)) + { + glDisable(GL_DEPTH_TEST); + DRW_draw_manipulator_3d(); + } DRW_draw_region_info(); - /* Draw 2D after region info so we can draw on top of the camera passepartout overlay. - * 'DRW_draw_region_info' sets the projection in pixel-space. */ - DRW_draw_manipulator_2d(); - glEnable(GL_DEPTH_TEST); + if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) { + /* Draw 2D after region info so we can draw on top of the camera passepartout overlay. + * 'DRW_draw_region_info' sets the projection in pixel-space. */ + DRW_draw_manipulator_2d(); + glEnable(GL_DEPTH_TEST); + } } DRW_stats_reset(); @@ -1548,6 +1554,11 @@ void DRW_render_to_image(RenderEngine *engine, struct Depsgraph *depsgraph) GPU_viewport_free(DST.viewport); GPU_framebuffer_restore(); +#ifdef DEBUG + /* Avoid accidental reuse. */ + drw_state_ensure_not_reused(&DST); +#endif + /* Changing Context */ if (re_gl_context != NULL) { DRW_shape_cache_reset(); /* XXX fix that too. */ @@ -1560,11 +1571,6 @@ void DRW_render_to_image(RenderEngine *engine, struct Depsgraph *depsgraph) else { DRW_opengl_context_disable(); } - -#ifdef DEBUG - /* Avoid accidental reuse. */ - drw_state_ensure_not_reused(&DST); -#endif } void DRW_render_object_iter( @@ -1628,7 +1634,8 @@ void DRW_draw_select_loop( struct Depsgraph *depsgraph, ARegion *ar, View3D *v3d, bool UNUSED(use_obedit_skip), bool UNUSED(use_nearest), const rcti *rect, - DRW_SelectPassFn select_pass_fn, void *select_pass_user_data) + DRW_SelectPassFn select_pass_fn, void *select_pass_user_data, + DRW_ObjectFilterFn object_filter_fn, void *object_filter_user_data) { Scene *scene = DEG_get_evaluated_scene(depsgraph); RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype); @@ -1715,6 +1722,7 @@ void DRW_draw_select_loop( #endif } else { + bool filter_exclude = false; DEG_OBJECT_ITER_BEGIN( depsgraph, ob, DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY | @@ -1722,6 +1730,19 @@ void DRW_draw_select_loop( DEG_ITER_OBJECT_FLAG_DUPLI) { if ((ob->base_flag & BASE_SELECTABLED) != 0) { + + if (object_filter_fn != NULL) { + if (ob->base_flag & BASE_FROMDUPLI) { + /* pass (use previous filter_exclude value) */ + } + else { + filter_exclude = (object_filter_fn(ob, object_filter_user_data) == false); + } + if (filter_exclude) { + continue; + } + } + /* This relies on dupli instances being after their instancing object. */ if ((ob->base_flag & BASE_FROMDUPLI) == 0) { Object *ob_orig = DEG_get_original_object(ob); @@ -1738,8 +1759,6 @@ void DRW_draw_select_loop( DRW_render_instance_buffer_finish(); } - DRW_hair_update(); - /* Setup framebuffer */ draw_select_framebuffer_setup(rect); GPU_framebuffer_bind(g_select_buffer.framebuffer); @@ -1749,6 +1768,8 @@ void DRW_draw_select_loop( DRW_state_reset(); DRW_draw_callbacks_pre_scene(); + DRW_hair_update(); + DRW_state_lock( DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_ALWAYS | @@ -1898,10 +1919,11 @@ void DRW_draw_depth_loop( DRW_render_instance_buffer_finish(); } - DRW_hair_update(); - /* Start Drawing */ DRW_state_reset(); + + DRW_hair_update(); + DRW_draw_callbacks_pre_scene(); drw_engines_draw_scene(); DRW_draw_callbacks_post_scene(); @@ -2068,9 +2090,6 @@ void DRW_engine_register(DrawEngineType *draw_engine_type) void DRW_engines_register(void) { -#ifdef WITH_CLAY_ENGINE - RE_engines_register(&DRW_engine_viewport_clay_type); -#endif RE_engines_register(&DRW_engine_viewport_eevee_type); RE_engines_register(&DRW_engine_viewport_workbench_type); @@ -2165,10 +2184,6 @@ void DRW_engines_free(void) MEM_SAFE_FREE(DST.RST.bound_ubo_slots); DRW_opengl_context_disable(); - -#ifdef WITH_CLAY_ENGINE - BLI_remlink(&R_engines, &DRW_engine_viewport_clay_type); -#endif } /** \} */ diff --git a/source/blender/draw/intern/draw_manager_data.c b/source/blender/draw/intern/draw_manager_data.c index b49af47223f..db4e16d362a 100644 --- a/source/blender/draw/intern/draw_manager_data.c +++ b/source/blender/draw/intern/draw_manager_data.c @@ -768,7 +768,7 @@ static DRWShadingGroup *drw_shgroup_material_inputs(DRWShadingGroup *grp, struct if (input->ima) { double time = 0.0; /* TODO make time variable */ GPUTexture *tex = GPU_texture_from_blender( - input->ima, input->iuser, input->textarget, input->image_isdata, time, 1); + input->ima, input->iuser, input->textarget, input->image_isdata, time); if (input->bindtex) { DRW_shgroup_uniform_texture(grp, input->shadername, tex); diff --git a/source/blender/draw/intern/draw_manager_shader.c b/source/blender/draw/intern/draw_manager_shader.c index edc65afd465..435c6c77e59 100644 --- a/source/blender/draw/intern/draw_manager_shader.c +++ b/source/blender/draw/intern/draw_manager_shader.c @@ -211,7 +211,7 @@ void DRW_deferred_shader_remove(GPUMaterial *mat) { Scene *scene = GPU_material_scene(mat); - for (wmWindowManager *wm = G.main->wm.first; wm; wm = wm->id.next) { + for (wmWindowManager *wm = G_MAIN->wm.first; wm; wm = wm->id.next) { if (WM_jobs_test(wm, scene, WM_JOB_TYPE_SHADER_COMPILATION) == false) { /* No job running, do not create a new one by calling WM_jobs_get. */ continue; diff --git a/source/blender/draw/intern/draw_view.c b/source/blender/draw/intern/draw_view.c index 4bf2e65ce6f..a666ec5395f 100644 --- a/source/blender/draw/intern/draw_view.c +++ b/source/blender/draw/intern/draw_view.c @@ -627,7 +627,7 @@ static bool is_cursor_visible(const DRWContextState *draw_ctx, Scene *scene, Vie { Object *ob = OBACT(view_layer); View3D *v3d = draw_ctx->v3d; - if ((v3d->flag2 & V3D_RENDER_OVERRIDE) > 0 || (v3d->overlay.flag & V3D_OVERLAY_HIDE_CURSOR)) { + if ((v3d->flag2 & V3D_RENDER_OVERRIDE) || (v3d->overlay.flag & V3D_OVERLAY_HIDE_CURSOR)) { return false; } @@ -732,6 +732,9 @@ void DRW_draw_cursor(void) GWN_batch_program_set(cursor_batch, GPU_shader_get_program(shader), GPU_shader_get_interface(shader)); GWN_batch_draw(cursor_batch); + + glDisable(GL_BLEND); + glDisable(GL_LINE_SMOOTH); } } } diff --git a/source/blender/draw/modes/edit_mesh_mode.c b/source/blender/draw/modes/edit_mesh_mode.c index b50fb554a51..700132e0ee4 100644 --- a/source/blender/draw/modes/edit_mesh_mode.c +++ b/source/blender/draw/modes/edit_mesh_mode.c @@ -39,9 +39,13 @@ #include "BKE_object.h" +#include "BLI_dynstr.h" + + extern struct GPUUniformBuffer *globals_ubo; /* draw_common.c */ extern struct GlobalsUboStorage ts; /* draw_common.c */ +extern char datatoc_edit_mesh_overlay_common_lib_glsl[]; extern char datatoc_edit_mesh_overlay_frag_glsl[]; extern char datatoc_edit_mesh_overlay_vert_glsl[]; extern char datatoc_edit_mesh_overlay_geom_tri_glsl[]; @@ -87,16 +91,16 @@ typedef struct EDIT_MESH_Data { } EDIT_MESH_Data; /* *********** STATIC *********** */ +#define MAX_SHADERS 16 static struct { /* weight/vert-color */ GPUShader *vcolor_face_shader; - GPUShader *overlay_tri_sh; - GPUShader *overlay_tri_fast_sh; - GPUShader *overlay_tri_vcol_sh; - GPUShader *overlay_tri_vcol_fast_sh; - GPUShader *overlay_edge_sh; - GPUShader *overlay_edge_vcol_sh; + + /* Geometry */ + GPUShader *overlay_tri_sh_cache[MAX_SHADERS]; + GPUShader *overlay_loose_edge_sh_cache[MAX_SHADERS]; + GPUShader *overlay_vert_sh; GPUShader *overlay_facedot_sh; GPUShader *overlay_mix_sh; @@ -130,9 +134,99 @@ typedef struct EDIT_MESH_PrivateData { DRWShadingGroup *facedot_occluded_shgrp; DRWShadingGroup *facefill_occluded_shgrp; + bool do_zbufclip; } EDIT_MESH_PrivateData; /* Transient data */ /* *********** FUNCTIONS *********** */ +static int EDIT_MESH_sh_index(ToolSettings *tsettings, RegionView3D *rv3d, bool supports_fast_mode) +{ + int result = tsettings->selectmode << 1; + if (supports_fast_mode) { + SET_FLAG_FROM_TEST(result, (rv3d->rflag & RV3D_NAVIGATING), 1 << 0); + } + return result; +} + +static char *EDIT_MESH_sh_defines(ToolSettings *tsettings, RegionView3D *rv3d, bool anti_alias) +{ + const int selectmode = tsettings->selectmode; + const int fast_mode = rv3d->rflag & RV3D_NAVIGATING; + + char *str = NULL; + DynStr *ds = BLI_dynstr_new(); + + if (selectmode & SCE_SELECT_VERTEX) { + BLI_dynstr_append(ds, "#define VERTEX_SELECTION\n"); + } + + if (selectmode & SCE_SELECT_EDGE) { + BLI_dynstr_append(ds, "#define EDGE_SELECTION\n"); + } + + if (selectmode & SCE_SELECT_FACE) { + BLI_dynstr_append(ds, "#define FACE_SELECTION\n"); + } + + if (!fast_mode) { + BLI_dynstr_append(ds, "#define EDGE_FIX\n"); + } + + if (anti_alias) { + BLI_dynstr_append(ds, "#define ANTI_ALIASING\n"); + } + BLI_dynstr_append(ds, "#define VERTEX_FACING\n"); + + str = BLI_dynstr_get_cstring(ds); + BLI_dynstr_free(ds); + return str; +} +static char *EDIT_MESH_sh_lib(void) +{ + char *str = NULL; + DynStr *ds = BLI_dynstr_new(); + + BLI_dynstr_append(ds, datatoc_common_globals_lib_glsl); + BLI_dynstr_append(ds, datatoc_edit_mesh_overlay_common_lib_glsl); + + str = BLI_dynstr_get_cstring(ds); + BLI_dynstr_free(ds); + return str; +} + +static GPUShader *EDIT_MESH_ensure_shader(ToolSettings *tsettings, RegionView3D *rv3d, bool fast_mode, bool looseedge) +{ + const int index = EDIT_MESH_sh_index(tsettings, rv3d, fast_mode); + if (looseedge) { + if (!e_data.overlay_loose_edge_sh_cache[index]) { + char *defines = EDIT_MESH_sh_defines(tsettings, rv3d, true); + char *lib = EDIT_MESH_sh_lib(); + e_data.overlay_loose_edge_sh_cache[index] = DRW_shader_create_with_lib( + datatoc_edit_mesh_overlay_vert_glsl, + datatoc_edit_mesh_overlay_geom_edge_glsl, + datatoc_edit_mesh_overlay_frag_glsl, + lib, + defines); + MEM_freeN(lib); + MEM_freeN(defines); + } + return e_data.overlay_loose_edge_sh_cache[index]; + } + else { + if (!e_data.overlay_tri_sh_cache[index]) { + char *defines = EDIT_MESH_sh_defines(tsettings, rv3d, true); + char *lib = EDIT_MESH_sh_lib(); + e_data.overlay_tri_sh_cache[index] = DRW_shader_create_with_lib( + datatoc_edit_mesh_overlay_vert_glsl, + datatoc_edit_mesh_overlay_geom_tri_glsl, + datatoc_edit_mesh_overlay_frag_glsl, + lib, + defines); + MEM_freeN(lib); + MEM_freeN(defines); + } + return e_data.overlay_tri_sh_cache[index]; + } +} static void EDIT_MESH_engine_init(void *vedata) { @@ -155,70 +249,14 @@ static void EDIT_MESH_engine_init(void *vedata) e_data.vcolor_face_shader = GPU_shader_get_builtin_shader(GPU_SHADER_SIMPLE_LIGHTING_SMOOTH_COLOR_ALPHA); } - if (!e_data.overlay_tri_sh) { - e_data.overlay_tri_sh = DRW_shader_create_with_lib( - datatoc_edit_mesh_overlay_vert_glsl, - datatoc_edit_mesh_overlay_geom_tri_glsl, - datatoc_edit_mesh_overlay_frag_glsl, - datatoc_common_globals_lib_glsl, - "#define EDGE_FIX\n" - "#define ANTI_ALIASING\n" - "#define VERTEX_FACING"); - } - if (!e_data.overlay_tri_fast_sh) { - e_data.overlay_tri_fast_sh = DRW_shader_create_with_lib( - datatoc_edit_mesh_overlay_vert_glsl, - datatoc_edit_mesh_overlay_geom_tri_glsl, - datatoc_edit_mesh_overlay_frag_glsl, - datatoc_common_globals_lib_glsl, - "#define ANTI_ALIASING\n" - "#define VERTEX_FACING\n"); - } - if (!e_data.overlay_tri_vcol_sh) { - e_data.overlay_tri_vcol_sh = DRW_shader_create_with_lib( - datatoc_edit_mesh_overlay_vert_glsl, - datatoc_edit_mesh_overlay_geom_tri_glsl, - datatoc_edit_mesh_overlay_frag_glsl, - datatoc_common_globals_lib_glsl, - "#define EDGE_FIX\n" - "#define VERTEX_SELECTION\n" - "#define ANTI_ALIASING\n" - "#define VERTEX_FACING\n"); - } - if (!e_data.overlay_tri_vcol_fast_sh) { - e_data.overlay_tri_vcol_fast_sh = DRW_shader_create_with_lib( - datatoc_edit_mesh_overlay_vert_glsl, - datatoc_edit_mesh_overlay_geom_tri_glsl, - datatoc_edit_mesh_overlay_frag_glsl, - datatoc_common_globals_lib_glsl, - "#define VERTEX_SELECTION\n" - "#define ANTI_ALIASING\n" - "#define VERTEX_FACING\n"); - } - if (!e_data.overlay_edge_sh) { - e_data.overlay_edge_sh = DRW_shader_create_with_lib( - datatoc_edit_mesh_overlay_vert_glsl, - datatoc_edit_mesh_overlay_geom_edge_glsl, - datatoc_edit_mesh_overlay_frag_glsl, - datatoc_common_globals_lib_glsl, - "#define ANTI_ALIASING\n" - "#define VERTEX_FACING\n"); - } - if (!e_data.overlay_edge_vcol_sh) { - e_data.overlay_edge_vcol_sh = DRW_shader_create_with_lib( - datatoc_edit_mesh_overlay_vert_glsl, - datatoc_edit_mesh_overlay_geom_edge_glsl, - datatoc_edit_mesh_overlay_frag_glsl, - datatoc_common_globals_lib_glsl, - "#define VERTEX_SELECTION\n" - "#define VERTEX_FACING\n"); - } if (!e_data.overlay_vert_sh) { + char *lib = EDIT_MESH_sh_lib(); e_data.overlay_vert_sh = DRW_shader_create_with_lib( datatoc_edit_mesh_overlay_loosevert_vert_glsl, NULL, datatoc_edit_mesh_overlay_frag_glsl, - datatoc_common_globals_lib_glsl, + lib, "#define VERTEX_SELECTION\n"); + MEM_freeN(lib); } if (!e_data.overlay_facedot_sh) { e_data.overlay_facedot_sh = DRW_shader_create_with_lib( @@ -272,22 +310,8 @@ static DRWPass *edit_mesh_create_overlay_pass( Scene *scene = draw_ctx->scene; ToolSettings *tsettings = scene->toolsettings; - if ((tsettings->selectmode & SCE_SELECT_VERTEX) != 0) { - ledge_sh = e_data.overlay_edge_vcol_sh; - - if ((rv3d->rflag & RV3D_NAVIGATING) != 0) - tri_sh = e_data.overlay_tri_vcol_fast_sh; - else - tri_sh = e_data.overlay_tri_vcol_sh; - } - else { - ledge_sh = e_data.overlay_edge_sh; - - if ((rv3d->rflag & RV3D_NAVIGATING) != 0) - tri_sh = e_data.overlay_tri_fast_sh; - else - tri_sh = e_data.overlay_tri_sh; - } + ledge_sh = EDIT_MESH_ensure_shader(tsettings, rv3d, false, true); + tri_sh = EDIT_MESH_ensure_shader(tsettings, rv3d, true, false); DRWPass *pass = DRW_pass_create( "Edit Mesh Face Overlay Pass", @@ -329,8 +353,6 @@ static void EDIT_MESH_cache_init(void *vedata) const DRWContextState *draw_ctx = DRW_context_state_get(); View3D *v3d = draw_ctx->v3d; - bool do_zbufclip = ((v3d->flag & V3D_ZBUF_SELECT) == 0); - static float zero = 0.0f; if (!stl->g_data) { @@ -338,6 +360,11 @@ static void EDIT_MESH_cache_init(void *vedata) stl->g_data = MEM_mallocN(sizeof(*stl->g_data), __func__); } + + const bool xray_enabled = ((draw_ctx->v3d->shading.flag & V3D_SHADING_XRAY) != 0) && + (draw_ctx->v3d->drawtype < OB_MATERIAL); + stl->g_data->do_zbufclip = ((v3d->flag & V3D_ZBUF_SELECT) == 0) || xray_enabled; + { psl->vcolor_faces = DRW_pass_create( "Vert Color Pass", @@ -380,7 +407,7 @@ static void EDIT_MESH_cache_init(void *vedata) DRW_shgroup_uniform_vec4(stl->g_data->lnormals_shgrp, "color", ts.colorLNormal, 1); } - if (!do_zbufclip) { + if (!stl->g_data->do_zbufclip) { psl->edit_face_overlay = edit_mesh_create_overlay_pass( &face_mod, DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_WRITE_DEPTH | DRW_STATE_BLEND, &stl->g_data->face_overlay_shgrp, &stl->g_data->ledges_overlay_shgrp, @@ -435,7 +462,7 @@ static void edit_mesh_add_ob_to_pass( DRW_shgroup_call_add(lverts_shgrp, geo_ovl_lverts, ob->obmat); } - if ((tsettings->selectmode & SCE_SELECT_FACE) != 0) { + if (facedot_shgrp && (tsettings->selectmode & SCE_SELECT_FACE) != 0 ) { geo_ovl_fcenter = DRW_cache_face_centers_get(ob); DRW_shgroup_call_add(facedot_shgrp, geo_ovl_fcenter, ob->obmat); } @@ -496,7 +523,7 @@ static void EDIT_MESH_cache_populate(void *vedata, Object *ob) } } - if ((v3d->flag & V3D_ZBUF_SELECT) == 0) { + if (stl->g_data->do_zbufclip) { edit_mesh_add_ob_to_pass( scene, ob, stl->g_data->face_occluded_shgrp, stl->g_data->ledges_occluded_shgrp, stl->g_data->lverts_occluded_shgrp, stl->g_data->facedot_occluded_shgrp, @@ -505,7 +532,7 @@ static void EDIT_MESH_cache_populate(void *vedata, Object *ob) else { edit_mesh_add_ob_to_pass( scene, ob, stl->g_data->face_overlay_shgrp, stl->g_data->ledges_overlay_shgrp, - stl->g_data->lverts_overlay_shgrp, stl->g_data->facedot_overlay_shgrp, NULL); + stl->g_data->lverts_overlay_shgrp, NULL, NULL); } /* 3D text overlay */ @@ -527,6 +554,7 @@ static void EDIT_MESH_cache_populate(void *vedata, Object *ob) static void EDIT_MESH_draw_scene(void *vedata) { EDIT_MESH_PassList *psl = ((EDIT_MESH_Data *)vedata)->psl; + EDIT_MESH_StorageList *stl = ((EDIT_MESH_Data *)vedata)->stl; EDIT_MESH_FramebufferList *fbl = ((EDIT_MESH_Data *)vedata)->fbl; DefaultFramebufferList *dfbl = DRW_viewport_framebuffer_list_get(); @@ -534,7 +562,7 @@ static void EDIT_MESH_draw_scene(void *vedata) DRW_draw_pass(psl->depth_hidden_wire); - if (psl->edit_face_occluded) { + if (stl->g_data->do_zbufclip) { float clearcol[4] = {0.0f, 0.0f, 0.0f, 0.0f}; /* render facefill */ DRW_draw_pass(psl->facefill_occlude); @@ -557,12 +585,6 @@ static void EDIT_MESH_draw_scene(void *vedata) static void EDIT_MESH_engine_free(void) { - DRW_SHADER_FREE_SAFE(e_data.overlay_tri_sh); - DRW_SHADER_FREE_SAFE(e_data.overlay_tri_fast_sh); - DRW_SHADER_FREE_SAFE(e_data.overlay_tri_vcol_sh); - DRW_SHADER_FREE_SAFE(e_data.overlay_tri_vcol_fast_sh); - DRW_SHADER_FREE_SAFE(e_data.overlay_edge_sh); - DRW_SHADER_FREE_SAFE(e_data.overlay_edge_vcol_sh); DRW_SHADER_FREE_SAFE(e_data.overlay_vert_sh); DRW_SHADER_FREE_SAFE(e_data.overlay_facedot_sh); DRW_SHADER_FREE_SAFE(e_data.overlay_mix_sh); @@ -570,6 +592,11 @@ static void EDIT_MESH_engine_free(void) DRW_SHADER_FREE_SAFE(e_data.normals_loop_sh); DRW_SHADER_FREE_SAFE(e_data.normals_face_sh); DRW_SHADER_FREE_SAFE(e_data.normals_sh); + + for (int i = 0; i < MAX_SHADERS; i++) { + DRW_SHADER_FREE_SAFE(e_data.overlay_tri_sh_cache[i]); + DRW_SHADER_FREE_SAFE(e_data.overlay_loose_edge_sh_cache[i]); + } } static const DrawEngineDataSize EDIT_MESH_data_size = DRW_VIEWPORT_DATA_SIZE(EDIT_MESH_Data); diff --git a/source/blender/draw/modes/object_mode.c b/source/blender/draw/modes/object_mode.c index 0b90b9276b4..423b07cdb97 100644 --- a/source/blender/draw/modes/object_mode.c +++ b/source/blender/draw/modes/object_mode.c @@ -256,6 +256,7 @@ static struct { GPUShader *outline_resolve_sh; GPUShader *outline_resolve_aa_sh; GPUShader *outline_detect_sh; + GPUShader *outline_detect_wire_sh; GPUShader *outline_fade_sh; /* regular shaders */ @@ -364,6 +365,14 @@ static void OBJECT_engine_init(void *vedata) datatoc_common_globals_lib_glsl, "#extension GL_ARB_texture_gather : enable\n"); + e_data.outline_detect_wire_sh = DRW_shader_create_with_lib( + datatoc_common_fullscreen_vert_glsl, NULL, + datatoc_object_outline_detect_frag_glsl, + datatoc_common_globals_lib_glsl, + "#define WIRE\n" + "#extension GL_ARB_texture_gather : enable\n"); + + e_data.outline_fade_sh = DRW_shader_create_fullscreen(datatoc_object_outline_expand_frag_glsl, NULL); /* Empty images */ @@ -592,6 +601,7 @@ static void OBJECT_engine_free(void) DRW_SHADER_FREE_SAFE(e_data.outline_resolve_sh); DRW_SHADER_FREE_SAFE(e_data.outline_resolve_aa_sh); DRW_SHADER_FREE_SAFE(e_data.outline_detect_sh); + DRW_SHADER_FREE_SAFE(e_data.outline_detect_wire_sh); DRW_SHADER_FREE_SAFE(e_data.outline_fade_sh); DRW_SHADER_FREE_SAFE(e_data.object_empty_image_sh); DRW_SHADER_FREE_SAFE(e_data.object_empty_image_wire_sh); @@ -789,7 +799,7 @@ static void DRW_shgroup_empty_image( struct EmptyImageShadingGroupData *empty_image_data; GPUTexture *tex = ob->data ? - GPU_texture_from_blender(ob->data, ob->iuser, GL_TEXTURE_2D, false, false, false) : NULL; + GPU_texture_from_blender(ob->data, ob->iuser, GL_TEXTURE_2D, false, 0.0f) : NULL; void **val_p; /* Create on demand, 'tex' may be NULL. */ @@ -864,6 +874,8 @@ static void OBJECT_cache_init(void *vedata) DefaultTextureList *dtxl = DRW_viewport_texture_list_get(); OBJECT_PrivateData *g_data; const DRWContextState *draw_ctx = DRW_context_state_get(); + const bool xray_enabled = ((draw_ctx->v3d->shading.flag & V3D_SHADING_XRAY) != 0) && + (draw_ctx->v3d->drawtype < OB_MATERIAL); /* TODO : use dpi setting for enabling the second pass */ const bool do_outline_expand = false; @@ -880,7 +892,7 @@ static void OBJECT_cache_init(void *vedata) GPUShader *sh = e_data.outline_prepass_sh; - if (draw_ctx->v3d->shading.flag & V3D_SHADING_XRAY) { + if (xray_enabled) { sh = e_data.outline_prepass_wire_sh; } @@ -917,19 +929,21 @@ static void OBJECT_cache_init(void *vedata) { DRWState state = DRW_STATE_WRITE_COLOR; struct Gwn_Batch *quad = DRW_cache_fullscreen_quad_get(); - static float alphaOcclu = 0.35f; + /* Don't occlude the "outline" detection pass if in xray mode (too much flickering). */ + float alphaOcclu = (xray_enabled) ? 1.0f : 0.35f; /* Reminder : bool uniforms need to be 4 bytes. */ static const int bTrue = true; static const int bFalse = false; psl->outlines_search = DRW_pass_create("Outlines Detect Pass", state); - DRWShadingGroup *grp = DRW_shgroup_create(e_data.outline_detect_sh, psl->outlines_search); + GPUShader *sh = (xray_enabled) ? e_data.outline_detect_wire_sh : e_data.outline_detect_sh; + DRWShadingGroup *grp = DRW_shgroup_create(sh, psl->outlines_search); DRW_shgroup_uniform_texture_ref(grp, "outlineId", &e_data.outlines_id_tx); DRW_shgroup_uniform_texture_ref(grp, "outlineDepth", &e_data.outlines_depth_tx); DRW_shgroup_uniform_texture_ref(grp, "sceneDepth", &dtxl->depth); DRW_shgroup_uniform_block(grp, "globalsBlock", globals_ubo); - DRW_shgroup_uniform_float(grp, "alphaOcclu", &alphaOcclu, 1); + DRW_shgroup_uniform_float_copy(grp, "alphaOcclu", alphaOcclu); DRW_shgroup_uniform_int(grp, "idOffsets", &stl->g_data->id_ofs_active, 3); DRW_shgroup_call_add(grp, quad, NULL); @@ -2091,13 +2105,15 @@ static void OBJECT_cache_populate(void *vedata, Object *ob) return; } - bool do_outlines = ((ob->base_flag & BASE_SELECTED) != 0); + bool do_outlines = (draw_ctx->v3d->flag & V3D_SELECT_OUTLINE) && ((ob->base_flag & BASE_SELECTED) != 0); bool show_relations = ((draw_ctx->v3d->flag & V3D_HIDE_HELPLINES) == 0); if (do_outlines) { if ((ob != draw_ctx->object_edit) && !((ob == draw_ctx->obact) && (draw_ctx->object_mode & OB_MODE_ALL_PAINT))) { struct Gwn_Batch *geom; - if (v3d->shading.flag & V3D_SHADING_XRAY) { + const bool xray_enabled = ((v3d->shading.flag & V3D_SHADING_XRAY) != 0) && + (v3d->drawtype < OB_MATERIAL); + if (xray_enabled) { geom = DRW_cache_object_edge_detection_get(ob, NULL); } else { diff --git a/source/blender/draw/modes/paint_texture_mode.c b/source/blender/draw/modes/paint_texture_mode.c index 1d7f686a51c..bd8a1c71a6a 100644 --- a/source/blender/draw/modes/paint_texture_mode.c +++ b/source/blender/draw/modes/paint_texture_mode.c @@ -222,7 +222,7 @@ static void PAINT_TEXTURE_cache_init(void *vedata) Material *ma = give_current_material(ob, i + 1); Image *ima = (ma && ma->texpaintslot) ? ma->texpaintslot[ma->paint_active_slot].ima : NULL; GPUTexture *tex = ima ? - GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, false, false) : NULL; + GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, 0.0f) : NULL; if (tex) { DRWShadingGroup *grp = DRW_shgroup_create(e_data.image_sh, psl->image_faces); @@ -237,7 +237,7 @@ static void PAINT_TEXTURE_cache_init(void *vedata) else { Image *ima = scene->toolsettings->imapaint.canvas; GPUTexture *tex = ima ? - GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, false, false) : NULL; + GPU_texture_from_blender(ima, NULL, GL_TEXTURE_2D, false, 0.0f) : NULL; if (tex) { DRWShadingGroup *grp = DRW_shgroup_create(e_data.image_sh, psl->image_faces); diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_common_lib.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_common_lib.glsl new file mode 100644 index 00000000000..dabbb4a321a --- /dev/null +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_common_lib.glsl @@ -0,0 +1,51 @@ +#define EDGE_EXISTS (1 << 0) +#define EDGE_ACTIVE (1 << 1) +#define EDGE_SELECTED (1 << 2) +#define EDGE_SEAM (1 << 3) +#define EDGE_SHARP (1 << 4) +#define EDGE_VERTEX_ACTIVE (1 << (0 + 8)) +#define EDGE_VERTEX_SELECTED (1 << (1 + 8)) + +#define VERTEX_ACTIVE (1 << 0) +#define VERTEX_SELECTED (1 << 1) + + +vec4 EDIT_MESH_edge_color_outer(int edge_flag, bool face_active, float crease, float bweight) +{ + vec4 color = vec4(0.0); + color = ((edge_flag & EDGE_SHARP) != 0) ? colorEdgeSharp : color; + color = (crease > 0.0) ? vec4(colorEdgeCrease.rgb, crease) : color; + color = (bweight > 0.0) ? vec4(colorEdgeBWeight.rgb, bweight) : color; + color = ((edge_flag & EDGE_SEAM) != 0) ? colorEdgeSeam : color; + + if (face_active) + { + color = colorEditMeshActive; + } + return color; +} + +vec4 EDIT_MESH_edge_color_inner(int edge_flag, bool face_active) +{ +#ifdef EDGE_SELECTION + vec4 color = colorWireEdit; + color = ((edge_flag & EDGE_SELECTED) != 0) ? colorEdgeSelect : color; + color = ((edge_flag & EDGE_ACTIVE) != 0) ? colorEditMeshActive : color; + +#else + vec4 color = colorWireEdit; + color = ((edge_flag & EDGE_SELECTED) != 0) ? colorEdgeSelect : color; +#endif + return color; +} + +vec4 EDIT_MESH_vertex_color(int vertex_flag) +{ + if ((vertex_flag & (VERTEX_ACTIVE | VERTEX_SELECTED)) != 0) + { + return colorEdgeSelect; + } + else { + return colorWireEdit; + } +} diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_facedot_frag.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_facedot_frag.glsl index 07b36079884..71cc1ccde8d 100644 --- a/source/blender/draw/modes/shaders/edit_mesh_overlay_facedot_frag.glsl +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_facedot_frag.glsl @@ -11,7 +11,7 @@ void main() if (isSelected != 0) FragColor = colorFaceDot; else - FragColor = colorWireEdit; + FragColor = colorVertex; #ifdef VERTEX_FACING FragColor.a *= 1.0 - abs(facing) * 0.4; diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_frag.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_frag.glsl index 23b794d9b8b..2e729009a38 100644 --- a/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_frag.glsl +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_frag.glsl @@ -1,29 +1,7 @@ - -/* Solid Wirefram implementation - * Mike Erwin, Clément Foucault */ - -/* This shader follows the principles of - * http://developer.download.nvidia.com/SDK/10/direct3d/Source/SolidWireframe/Doc/SolidWireframe.pdf */ - flat in vec4 faceColor; -flat in int faceActive; - out vec4 FragColor; -const vec4 stipple_matrix[4] = vec4[4]( - vec4(1.0, 0.0, 0.0, 0.0), - vec4(0.0, 0.0, 0.0, 0.0), - vec4(0.0, 0.0, 1.0, 0.0), - vec4(0.0, 0.0, 0.0, 0.0) -); - void main() { FragColor = faceColor; - - if (faceActive == 1) { - int x = int(gl_FragCoord.x) & 0x3; /* mod 4 */ - int y = int(gl_FragCoord.y) & 0x3; /* mod 4 */ - FragColor *= stipple_matrix[x][y]; - } } diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_vert.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_vert.glsl index 3b9aa77306f..c9de6d29524 100644 --- a/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_vert.glsl +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_facefill_vert.glsl @@ -5,25 +5,11 @@ in vec3 pos; in ivec4 data; flat out vec4 faceColor; -flat out int faceActive; -#define FACE_ACTIVE (1 << 2) #define FACE_SELECTED (1 << 3) void main() { gl_Position = ModelViewProjectionMatrix * vec4(pos, 1.0); - - if ((data.x & FACE_ACTIVE) != 0) { - faceColor = colorEditMeshActive; - faceActive = 1; - } - else if ((data.x & FACE_SELECTED) != 0) { - faceColor = colorFaceSelect; - faceActive = 0; - } - else { - faceColor = colorFace; - faceActive = 0; - } + faceColor = ((data.x & FACE_SELECTED) != 0)? colorFaceSelect: colorFace; } diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_frag.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_frag.glsl index cf1051b70b3..09d0b0a910d 100644 --- a/source/blender/draw/modes/shaders/edit_mesh_overlay_frag.glsl +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_frag.glsl @@ -15,7 +15,6 @@ flat in vec3 edgesCrease; flat in vec3 edgesBweight; flat in vec4 faceColor; flat in ivec3 flag; -flat in int clipCase; #ifdef VERTEX_SELECTION in vec3 vertexColor; #endif @@ -23,82 +22,38 @@ in vec3 vertexColor; in float facing; #endif -/* We use a vec4[2] interface to pass edge data - * (without fragmenting memory accesses) - * - * There are 2 cases : - * - * - Simple case : geometry shader return edge distances - * in the first 2 components of the first vec4. - * This needs noperspective interpolation. - * The rest is filled with vertex screen positions. - * eData2[0] actually contain v2 - * eData2[1] actually contain v1 - * eData2[2] actually contain v0 - * - * - Hard case : two 2d edge corner are described by each - * vec4 as origin and direction. This is constant over - * the triangle and use to detect the correct case. */ - -noperspective in vec2 eData1; -flat in vec2 eData2[3]; +flat in vec2 ssPos[3]; out vec4 FragColor; -#define EDGE_EXISTS (1 << 0) -#define EDGE_ACTIVE (1 << 1) -#define EDGE_SELECTED (1 << 2) -#define EDGE_SEAM (1 << 3) -#define EDGE_SHARP (1 << 4) /* Vertex flag is shifted and combined with the edge flag */ -#define VERTEX_ACTIVE (1 << (0 + 8)) -#define VERTEX_SELECTED (1 << (1 + 8)) #define FACE_ACTIVE (1 << (2 + 8)) -/* Style Parameters in pixel */ +#define LARGE_EDGE_SIZE 3.0 -/* Array to retrieve vert/edge indices */ -const ivec3 clipEdgeIdx[6] = ivec3[6]( - ivec3(1, 0, 2), - ivec3(2, 0, 1), - ivec3(2, 1, 0), - ivec3(2, 1, 0), - ivec3(2, 0, 1), - ivec3(1, 0, 2) -); - -const ivec3 clipPointIdx[6] = ivec3[6]( - ivec3(0, 1, 2), - ivec3(0, 2, 1), - ivec3(0, 2, 1), - ivec3(1, 2, 0), - ivec3(1, 2, 0), - ivec3(2, 1, 0) -); - -const vec4 stipple_matrix[4] = vec4[4]( - vec4(1.0, 0.0, 0.0, 0.0), - vec4(0.0, 0.0, 0.0, 0.0), - vec4(0.0, 0.0, 1.0, 0.0), - vec4(0.0, 0.0, 0.0, 0.0) -); +/* Style Parameters in pixel */ -void colorDist(vec4 color, float dist) +void distToEdgeAndPoint(vec2 dir, vec2 ori, out float edge, out float point) { - FragColor = (dist < 0) ? color : FragColor; + dir = normalize(dir.xy); + vec2 of = gl_FragCoord.xy - ori; + point = dot(of, of); + float dof = dot(dir, of); + edge = sqrt(abs(point - dof * dof)); + point = sqrt(point); } -float distToEdge(vec2 o, vec2 dir) +void colorDist(vec4 color, float dist) { - vec2 af = gl_FragCoord.xy - o; - float daf = dot(dir, af); - return sqrt(abs(dot(af, af) - daf * daf)); + FragColor = (dist < 0) ? color : FragColor; } #ifdef ANTI_ALIASING void colorDistEdge(vec4 color, float dist) { + FragColor.rgb *= FragColor.a; FragColor = mix(color, FragColor, clamp(dist, 0.0, 1.0)); + FragColor.rgb /= max(1e-8, FragColor.a); } #else #define colorDistEdge colorDist @@ -109,64 +64,23 @@ void main() vec3 e, p; /* Step 1 : Computing Distances */ - - if (clipCase == 0) { - e.xy = eData1; - - /* computing missing distance */ - vec2 dir = normalize(eData2[2] - eData2[1]); - e.z = distToEdge(eData2[2], dir); - - p.x = distance(eData2[2], gl_FragCoord.xy); - p.y = distance(eData2[1], gl_FragCoord.xy); - p.z = distance(eData2[0], gl_FragCoord.xy); - } - else { - ivec3 eidxs = clipEdgeIdx[clipCase - 1]; - ivec3 pidxs = clipPointIdx[clipCase - 1]; - - e[eidxs.x] = distToEdge(eData1, eData2[0]); - e[eidxs.y] = distToEdge(eData2[1], eData2[2]); - - /* Three edges visible cases */ - if (clipCase == 1 || clipCase == 2 || clipCase == 4) { - e[eidxs.z] = distToEdge(eData1, normalize(eData2[1] - eData1)); - p[pidxs.y] = distance(eData2[1], gl_FragCoord.xy); - } - else { - e[eidxs.z] = 1e10; /* off screen */ - p[pidxs.y] = 1e10; /* off screen */ - } - - p[pidxs.x] = distance(eData1, gl_FragCoord.xy); - p[pidxs.z] = 1e10; /* off screen */ - } + distToEdgeAndPoint((ssPos[1] - ssPos[0]) + 1e-8, ssPos[0], e.z, p.x); + distToEdgeAndPoint((ssPos[2] - ssPos[1]) + 1e-8, ssPos[1], e.x, p.y); + distToEdgeAndPoint((ssPos[0] - ssPos[2]) + 1e-8, ssPos[2], e.y, p.z); /* Step 2 : coloring (order dependant) */ - /* First */ + /* Face */ FragColor = faceColor; - - if ((flag[0] & FACE_ACTIVE) != 0) { - int x = int(gl_FragCoord.x) & 0x3; /* mod 4 */ - int y = int(gl_FragCoord.y) & 0x3; /* mod 4 */ - FragColor *= stipple_matrix[x][y]; - } - else { - FragColor.a *= faceAlphaMod; - } + FragColor.a *= faceAlphaMod; /* Edges */ for (int v = 0; v < 3; ++v) { if ((flag[v] & EDGE_EXISTS) != 0) { /* Outer large edge */ - float largeEdge = e[v] - sizeEdge * 3.0; + float largeEdge = e[v] - sizeEdge * LARGE_EDGE_SIZE; - vec4 large_edge_color = vec4(0.0); - large_edge_color = ((flag[v] & EDGE_SHARP) != 0) ? colorEdgeSharp : large_edge_color; - large_edge_color = (edgesCrease[v] > 0.0) ? vec4(colorEdgeCrease.rgb, edgesCrease[v]) : large_edge_color; - large_edge_color = (edgesBweight[v] > 0.0) ? vec4(colorEdgeBWeight.rgb, edgesBweight[v]) : large_edge_color; - large_edge_color = ((flag[v] & EDGE_SEAM) != 0) ? colorEdgeSeam : large_edge_color; + vec4 large_edge_color = EDIT_MESH_edge_color_outer(flag[v], (flag[0]& FACE_ACTIVE) != 0, edgesCrease[v], edgesBweight[v]); if (large_edge_color.a != 0.0) { colorDistEdge(large_edge_color, largeEdge); @@ -175,16 +89,13 @@ void main() /* Inner thin edge */ float innerEdge = e[v] - sizeEdge; #ifdef ANTI_ALIASING - innerEdge += 0.125; + innerEdge += 0.4; #endif #ifdef VERTEX_SELECTION colorDistEdge(vec4(vertexColor, 1.0), innerEdge); #else - vec4 inner_edge_color = colorWireEdit; - inner_edge_color = ((flag[v] & EDGE_SELECTED) != 0) ? colorEdgeSelect : inner_edge_color; - inner_edge_color = ((flag[v] & EDGE_ACTIVE) != 0) ? vec4(colorEditMeshActive.xyz, 1.0) : inner_edge_color; - + vec4 inner_edge_color = EDIT_MESH_edge_color_inner(flag[v], (flag[0]& FACE_ACTIVE) != 0); colorDistEdge(inner_edge_color, innerEdge); #endif } @@ -196,8 +107,8 @@ void main() float size = p[v] - sizeVertex; vec4 point_color = colorVertex; - point_color = ((flag[v] & VERTEX_SELECTED) != 0) ? colorVertexSelect : point_color; - point_color = ((flag[v] & VERTEX_ACTIVE) != 0) ? vec4(colorEditMeshActive.xyz, 1.0) : point_color; + point_color = ((flag[v] & EDGE_VERTEX_SELECTED) != 0) ? colorVertexSelect : point_color; + point_color = ((flag[v] & EDGE_VERTEX_ACTIVE) != 0) ? vec4(colorEditMeshActive.xyz, 1.0) : point_color; colorDist(point_color, size); } diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_edge.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_edge.glsl index 77bc8a25695..88cb6c07a94 100644 --- a/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_edge.glsl +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_edge.glsl @@ -24,7 +24,6 @@ flat out vec3 edgesCrease; flat out vec3 edgesBweight; flat out vec4 faceColor; flat out ivec3 flag; -flat out int clipCase; #ifdef VERTEX_SELECTION out vec3 vertexColor; #endif @@ -33,56 +32,21 @@ out float facing; #endif /* See fragment shader */ -noperspective out vec2 eData1; -flat out vec2 eData2[3]; - -#define VERTEX_ACTIVE (1 << 0) -#define VERTEX_SELECTED (1 << 1) +flat out vec2 ssPos[3]; #define FACE_ACTIVE (1 << 2) #define FACE_SELECTED (1 << 3) -/* Table 1. Triangle Projection Cases */ -const ivec4 clipPointsIdx[6] = ivec4[6]( - ivec4(0, 1, 2, 2), - ivec4(0, 2, 1, 1), - ivec4(0, 0, 1, 2), - ivec4(1, 2, 0, 0), - ivec4(1, 1, 0, 2), - ivec4(2, 2, 0, 1) -); - /* project to screen space */ vec2 proj(vec4 pos) { return (0.5 * (pos.xy / pos.w) + 0.5) * viewportSize; } -float dist(vec2 pos[3], vec2 vpos, int v) -{ - /* endpoints of opposite edge */ - vec2 e1 = pos[(v + 1) % 3]; - vec2 e2 = pos[(v + 2) % 3]; - /* Edge normalized vector */ - vec2 dir = normalize(e2 - e1); - /* perpendicular to dir */ - vec2 orthogonal = vec2(-dir.y, dir.x); - - return abs(dot(vpos - e1, orthogonal)); -} - -vec3 getVertexColor(int v) -{ - if ((vData[v].x & (VERTEX_ACTIVE | VERTEX_SELECTED)) != 0) - return colorEdgeSelect.rgb; - else - return colorWireEdit.rgb; -} - void doVertex(int v, vec4 pos) { #ifdef VERTEX_SELECTION - vertexColor = getVertexColor(v); + vertexColor = EDIT_MESH_vertex_color(vData[v].x).rgb; #endif #ifdef VERTEX_FACING @@ -96,8 +60,6 @@ void doVertex(int v, vec4 pos) void main() { - clipCase = 0; - /* Face */ faceColor = vec4(0.0); @@ -128,19 +90,16 @@ void main() } /* Edge / Vert data */ - eData1 = vec2(1e10); - eData2[0] = vec2(1e10); - eData2[2] = pos[0]; - eData2[1] = pos[1]; - flag[0] = (vData[0].x << 8); + ssPos[0] = ssPos[2] = pos[0]; + ssPos[1] = pos[1]; + flag[0] = flag[2] = (vData[0].x << 8); flag[1] = (vData[1].x << 8); - flag[2] = 0; doVertex(0, pPos[0] + vec4(-dirs1.xy, 0.0, 0.0)); doVertex(0, pPos[0] + vec4( dirs1.zw, 0.0, 0.0)); doVertex(0, pPos[0] + vec4(-dirs1.zw, 0.0, 0.0)); - flag[2] = vData[0].y | (vData[0].x << 8); + flag[2] |= vData[0].y; edgesCrease[2] = vData[0].z / 255.0; edgesBweight[2] = vData[0].w / 255.0; diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_tri.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_tri.glsl index d9c902697b6..e0ec6e50dc2 100644 --- a/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_tri.glsl +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_geom_tri.glsl @@ -52,64 +52,21 @@ out float facing; #endif /* See fragment shader */ -noperspective out vec2 eData1; -flat out vec2 eData2[3]; - -#define VERTEX_ACTIVE (1 << 0) -#define VERTEX_SELECTED (1 << 1) +flat out vec2 ssPos[3]; #define FACE_ACTIVE (1 << 2) #define FACE_SELECTED (1 << 3) -/* Table 1. Triangle Projection Cases */ -const ivec4 clipPointsIdx[6] = ivec4[6]( - ivec4(0, 1, 2, 2), - ivec4(0, 2, 1, 1), - ivec4(0, 0, 1, 2), - ivec4(1, 2, 0, 0), - ivec4(1, 1, 0, 2), - ivec4(2, 2, 0, 1) -); - /* project to screen space */ vec2 proj(vec4 pos) { return (0.5 * (pos.xy / pos.w) + 0.5) * viewportSize; } -float dist(vec2 pos[3], vec2 vpos, int v) -{ - /* endpoints of opposite edge */ - vec2 e1 = pos[(v + 1) % 3]; - vec2 e2 = pos[(v + 2) % 3]; - /* Edge normalized vector */ - vec2 dir = normalize(e2 - e1); - /* perpendicular to dir */ - vec2 orthogonal = vec2(-dir.y, dir.x); - - return abs(dot(vpos - e1, orthogonal)); -} - -vec3 getVertexColor(int v) -{ - if ((vData[v].x & (VERTEX_ACTIVE | VERTEX_SELECTED)) != 0) - return colorEdgeSelect.rgb; - else - return colorWireEdit.rgb; -} - -vec4 getClipData(vec2 pos[3], ivec2 vidx) -{ - vec2 A = pos[vidx.x]; - vec2 Adir = normalize(A - pos[vidx.y]); - - return vec4(A, Adir); -} - void doVertex(int v) { #ifdef VERTEX_SELECTION - vertexColor = getVertexColor(v); + vertexColor = EDIT_MESH_vertex_color(vData[v].x).rgb; #endif #ifdef VERTEX_FACING @@ -138,21 +95,6 @@ void doLoopStrip(int v, vec3 offset) void main() { - /* First we detect which case we are in */ - clipCase = 0; - - /* if perspective */ - if (ProjectionMatrix[3][3] == 0.0) { - /* See Table 1. Triangle Projection Cases */ - clipCase += int(pPos[0].z / pPos[0].w < -1 || vPos[0].z > 0.0) * 4; - clipCase += int(pPos[1].z / pPos[1].w < -1 || vPos[1].z > 0.0) * 2; - clipCase += int(pPos[2].z / pPos[2].w < -1 || vPos[2].z > 0.0) * 1; - } - - /* If triangle is behind nearplane, early out */ - if (clipCase == 7) - return; - /* Edge */ ivec3 eflag; vec3 ecrease, ebweight; for (int v = 0; v < 3; ++v) { @@ -163,145 +105,104 @@ void main() /* Face */ if ((vData[0].x & FACE_ACTIVE) != 0) - faceColor = colorEditMeshActive; + faceColor = colorFaceSelect; else if ((vData[0].x & FACE_SELECTED) != 0) faceColor = colorFaceSelect; else faceColor = colorFace; /* Vertex */ - vec2 pos[3] = vec2[3](proj(pPos[0]), proj(pPos[1]), proj(pPos[2])); + vec2 pos[3]; + ssPos[0] = pos[0] = proj(pPos[0]); + ssPos[1] = pos[1] = proj(pPos[1]); + ssPos[2] = pos[2] = proj(pPos[2]); - /* Simple case : compute edge distances in geometry shader */ - if (clipCase == 0) { + doVertex(0); + doVertex(1); + doVertex(2); - /* Packing screen positions and 2 distances */ - eData2[0] = pos[2]; - eData2[1] = pos[1]; - eData2[2] = pos[0]; +#ifdef EDGE_FIX + vec2 fixvec[6]; + vec2 fixvecaf[6]; + vec2 cornervec[3]; + + /* This fix the case when 2 vertices are perfectly aligned + * and corner vectors have nowhere to go. + * ie: length(cornervec[i]) == 0 */ + const float epsilon = 1e-2; /* in pixel so not that much */ + const vec2 bias[3] = vec2[3]( + vec2( epsilon, epsilon), + vec2(-epsilon, epsilon), + vec2( 0.0, -epsilon) + ); + + for (int i = 0; i < 3; ++i) { + int i1 = (i + 1) % 3; + int i2 = (i + 2) % 3; + + vec2 v1 = ssPos[i] + bias[i]; + vec2 v2 = ssPos[i1] + bias[i1]; + vec2 v3 = ssPos[i2] + bias[i2]; + + /* Edge normalized vector */ + vec2 dir = normalize(v2 - v1); + vec2 dir2 = normalize(v3 - v1); + + cornervec[i] = -normalize(dir + dir2); + + /* perpendicular to dir */ + vec2 perp = vec2(-dir.y, dir.x); + + /* Backface case */ + if (dot(perp, dir2) > 0) { + perp = -perp; + } - /* Only pass the first 2 distances */ - for (int v = 0; v < 2; ++v) { - eData1[v] = dist(pos, pos[v], v); - doVertex(v); - eData1[v] = 0.0; + /* Make it view independent */ + perp *= sizeEdgeFix / viewportSize; + cornervec[i] *= sizeEdgeFix / viewportSize; + fixvec[i] = fixvecaf[i] = perp; + + /* Perspective */ + if (ProjectionMatrix[3][3] == 0.0) { + /* vPos[i].z is negative and we don't want + * our fixvec to be flipped */ + fixvec[i] *= -vPos[i].z; + fixvecaf[i] *= -vPos[i1].z; + cornervec[i] *= -vPos[i].z; } + } - /* and the last vertex */ - doVertex(2); + /* to not let face color bleed */ + faceColor.a = 0.0; -#ifdef EDGE_FIX - vec2 fixvec[6]; - vec2 fixvecaf[6]; - vec2 cornervec[3]; - - /* This fix the case when 2 vertices are perfectly aligned - * and corner vectors have nowhere to go. - * ie: length(cornervec[i]) == 0 */ - const float epsilon = 1e-2; /* in pixel so not that much */ - const vec2 bias[3] = vec2[3]( - vec2( epsilon, epsilon), - vec2(-epsilon, epsilon), - vec2( 0.0, -epsilon) - ); - - for (int i = 0; i < 3; ++i) { - int i1 = (i + 1) % 3; - int i2 = (i + 2) % 3; - - vec2 v1 = pos[i] + bias[i]; - vec2 v2 = pos[i1] + bias[i1]; - vec2 v3 = pos[i2] + bias[i2]; - - /* Edge normalized vector */ - vec2 dir = normalize(v2 - v1); - vec2 dir2 = normalize(v3 - v1); - - cornervec[i] = -normalize(dir + dir2); - - /* perpendicular to dir */ - vec2 perp = vec2(-dir.y, dir.x); - - /* Backface case */ - if (dot(perp, dir2) > 0) { - perp = -perp; - } - - /* Make it view independent */ - perp *= sizeEdgeFix / viewportSize; - cornervec[i] *= sizeEdgeFix / viewportSize; - fixvec[i] = fixvecaf[i] = perp; - - /* Perspective */ - if (ProjectionMatrix[3][3] == 0.0) { - /* vPos[i].z is negative and we don't want - * our fixvec to be flipped */ - fixvec[i] *= -vPos[i].z; - fixvecaf[i] *= -vPos[i1].z; - cornervec[i] *= -vPos[i].z; - } - } + /* Start with the same last vertex to create a + * degenerate triangle in order to "create" + * a new triangle strip */ + for (int i = 2; i < 5; ++i) { + int vbe = (i - 1) % 3; + int vaf = (i + 1) % 3; + int v = i % 3; + + doLoopStrip(v, vec3(fixvec[v], Z_OFFSET)); - /* to not let face color bleed */ - faceColor.a = 0.0; - - /* we don't want other edges : make them far */ - eData1 = vec2(1e10); - eData2[0] = vec2(1e10); - - /* Start with the same last vertex to create a - * degenerate triangle in order to "create" - * a new triangle strip */ - for (int i = 2; i < 5; ++i) { - int vbe = (i - 1) % 3; - int vaf = (i + 1) % 3; - int v = i % 3; - - /* Position of the "hidden" third vertex */ - eData2[0] = pos[vbe]; - doLoopStrip(v, vec3(fixvec[v], Z_OFFSET)); - - /* Now one triangle only shade one edge - * so we use the edge distance calculated - * in the fragment shader, the third edge; - * we do this because we need flat interp to - * draw a continuous triangle strip */ - eData2[1] = pos[vaf]; - eData2[2] = pos[v]; - flag[0] = (vData[v].x << 8); - flag[1] = (vData[vaf].x << 8); - flag[2] = eflag[vbe]; - edgesCrease[2] = ecrease[vbe]; - edgesBweight[2] = ebweight[vbe]; - - doLoopStrip(vaf, vec3(fixvecaf[v], Z_OFFSET)); - - /* corner vertices should not draw edges but draw point only */ - flag[2] = (vData[vbe].x << 8); + /* Only shade the edge that we are currently drawing. + * (fix corner bleeding) */ + flag[vbe] |= (EDGE_EXISTS & eflag[vbe]); + flag[vaf] &= ~EDGE_EXISTS; + flag[v] &= ~EDGE_EXISTS; + doLoopStrip(vaf, vec3(fixvecaf[v], Z_OFFSET)); + + /* corner vertices should not draw edges but draw point only */ + flag[vbe] &= ~EDGE_EXISTS; #ifdef VERTEX_SELECTION - doLoopStrip(vaf, vec3(cornervec[vaf], Z_OFFSET)); + doLoopStrip(vaf, vec3(cornervec[vaf], Z_OFFSET)); #endif - } + } - /* finish the loop strip */ - doLoopStrip(2, vec3(fixvec[2], Z_OFFSET)); + /* finish the loop strip */ + doLoopStrip(2, vec3(fixvec[2], Z_OFFSET)); #endif - } - /* Harder case : compute visible edges vectors */ - else { - ivec4 vindices = clipPointsIdx[clipCase - 1]; - - vec4 tmp; - tmp = getClipData(pos, vindices.xz); - eData1 = tmp.xy; - eData2[0] = tmp.zw; - tmp = getClipData(pos, vindices.yw); - eData2[1] = tmp.xy; - eData2[2] = tmp.zw; - - for (int v = 0; v < 3; ++v) - doVertex(v); - } EndPrimitive(); } diff --git a/source/blender/draw/modes/shaders/edit_mesh_overlay_loosevert_vert.glsl b/source/blender/draw/modes/shaders/edit_mesh_overlay_loosevert_vert.glsl index 53e5b09cb70..13d824c2410 100644 --- a/source/blender/draw/modes/shaders/edit_mesh_overlay_loosevert_vert.glsl +++ b/source/blender/draw/modes/shaders/edit_mesh_overlay_loosevert_vert.glsl @@ -17,14 +17,12 @@ flat out vec3 edgesCrease; flat out vec3 edgesBweight; flat out vec4 faceColor; flat out ivec3 flag; -flat out int clipCase; #ifdef VERTEX_SELECTION out vec3 vertexColor; #endif /* See fragment shader */ -noperspective out vec2 eData1; -flat out vec2 eData2[3]; +flat out vec2 ssPos[3]; /* project to screen space */ vec2 proj(vec4 pos) @@ -34,7 +32,6 @@ vec2 proj(vec4 pos) void main() { - clipCase = 0; edgesCrease = vec3(0.0); edgesBweight = vec3(0.0); @@ -47,14 +44,8 @@ void main() vertexColor = vec3(0.0); #endif - /* only vertex position 0 is used */ - eData1 = vec2(1e10); - eData2[0] = vec2(1e10); - eData2[1] = vec2(1e10); - eData2[2] = proj(pPos); - - flag[0] = (data.x << 8); - flag[1] = flag[2] = 0; + ssPos[0] = ssPos[1] = ssPos[2] = proj(pPos); + flag[0] = flag[1] = flag[2] = (data.x << 8); gl_PointSize = sizeEdgeFix; gl_Position = pPos; diff --git a/source/blender/draw/modes/shaders/object_outline_detect_frag.glsl b/source/blender/draw/modes/shaders/object_outline_detect_frag.glsl index 45bbdb18340..9a7856ecb13 100644 --- a/source/blender/draw/modes/shaders/object_outline_detect_frag.glsl +++ b/source/blender/draw/modes/shaders/object_outline_detect_frag.glsl @@ -51,6 +51,12 @@ void main() id.w = texelFetchOffset(outlineId, texel, 0, ivec2( 1, 0)).r; #endif +#ifdef WIRE + /* We want only 2px outlines. */ + /* TODO optimize, don't sample if we don't need to. */ + id.xy = uvec2(ref_id); +#endif + bool outline = any(notEqual(id, uvec4(ref_id))); ivec2 depth_texel = texel; diff --git a/source/blender/editors/animation/anim_markers.c b/source/blender/editors/animation/anim_markers.c index 624c6e9f5de..e957e84857a 100644 --- a/source/blender/editors/animation/anim_markers.c +++ b/source/blender/editors/animation/anim_markers.c @@ -76,6 +76,8 @@ #include "ED_transform.h" #include "ED_types.h" +#include "DEG_depsgraph.h" + /* ************* Marker API **************** */ /* helper function for getting the list of markers to work on */ @@ -1196,6 +1198,7 @@ static int ed_marker_select(bContext *C, const wmEvent *event, bool extend, bool } } + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } #else diff --git a/source/blender/editors/animation/anim_ops.c b/source/blender/editors/animation/anim_ops.c index 23563e7f15f..4402ca78976 100644 --- a/source/blender/editors/animation/anim_ops.c +++ b/source/blender/editors/animation/anim_ops.c @@ -268,7 +268,7 @@ static void ANIM_OT_change_frame(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR | OPTYPE_UNDO_GROUPED; - ot->undo_group = "FRAME_CHANGE"; + ot->undo_group = "Frame Change"; /* rna */ ot->prop = RNA_def_float(ot->srna, "frame", 0, MINAFRAME, MAXFRAME, "Frame", "", MINAFRAME, MAXFRAME); @@ -332,7 +332,7 @@ static void ANIM_OT_start_frame_set(wmOperatorType *ot) /* identifiers */ ot->name = "Set Start Frame"; ot->idname = "ANIM_OT_start_frame_set"; - ot->description = "Set the start frame"; + ot->description = "Set the current frame as the preview or scene start frame"; /* api callbacks */ ot->exec = anim_set_sfra_exec; @@ -376,7 +376,7 @@ static void ANIM_OT_end_frame_set(wmOperatorType *ot) /* identifiers */ ot->name = "Set End Frame"; ot->idname = "ANIM_OT_end_frame_set"; - ot->description = "Set the end frame"; + ot->description = "Set the current frame as the preview or scene end frame"; /* api callbacks */ ot->exec = anim_set_efra_exec; diff --git a/source/blender/editors/animation/drivers.c b/source/blender/editors/animation/drivers.c index 294cff43c56..f303be0dd76 100644 --- a/source/blender/editors/animation/drivers.c +++ b/source/blender/editors/animation/drivers.c @@ -449,6 +449,7 @@ int ANIM_add_driver(ReportList *reports, ID *id, const char rna_path[], int arra else fval = RNA_property_float_get_index(&ptr, prop, array_index); BLI_snprintf(expression, maxlen, "%s%.3f", dvar_prefix, fval); + BLI_str_rstrip_float_zero(expression, '\0'); } else if (flag & CREATEDRIVER_WITH_DEFAULT_DVAR) { BLI_strncpy(expression, "var", maxlen); diff --git a/source/blender/editors/animation/keyframing.c b/source/blender/editors/animation/keyframing.c index 1913eb944d9..fe5714aba2e 100644 --- a/source/blender/editors/animation/keyframing.c +++ b/source/blender/editors/animation/keyframing.c @@ -954,7 +954,7 @@ bool insert_keyframe_direct(Depsgraph *depsgraph, ReportList *reports, PointerRN if (RNA_path_resolved_create(&ptr, prop, fcu->array_index, &anim_rna)) { /* for making it easier to add corrective drivers... */ - cfra = evaluate_driver(&anim_rna, fcu->driver, cfra); + cfra = evaluate_driver(&anim_rna, fcu->driver, fcu->driver, cfra); } else { cfra = 0.0f; diff --git a/source/blender/editors/armature/armature_relations.c b/source/blender/editors/armature/armature_relations.c index 9282148e857..cc149d3e42f 100644 --- a/source/blender/editors/armature/armature_relations.c +++ b/source/blender/editors/armature/armature_relations.c @@ -377,7 +377,7 @@ int join_armature_exec(bContext *C, wmOperator *op) } else { /* merge in data - we'll fix the drivers manually */ - BKE_animdata_merge_copy(&ob->id, &base->object->id, ADT_MERGECOPY_KEEP_DST, false); + BKE_animdata_merge_copy(bmain, &ob->id, &base->object->id, ADT_MERGECOPY_KEEP_DST, false); } } @@ -388,7 +388,7 @@ int join_armature_exec(bContext *C, wmOperator *op) } else { /* merge in data - we'll fix the drivers manually */ - BKE_animdata_merge_copy(&arm->id, &curarm->id, ADT_MERGECOPY_KEEP_DST, false); + BKE_animdata_merge_copy(bmain, &arm->id, &curarm->id, ADT_MERGECOPY_KEEP_DST, false); } } @@ -403,6 +403,7 @@ int join_armature_exec(bContext *C, wmOperator *op) ED_armature_from_edit(bmain, arm); ED_armature_edit_free(arm); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); return OPERATOR_FINISHED; diff --git a/source/blender/editors/armature/armature_select.c b/source/blender/editors/armature/armature_select.c index 95acc8ab6ba..e295e1fd35a 100644 --- a/source/blender/editors/armature/armature_select.c +++ b/source/blender/editors/armature/armature_select.c @@ -254,7 +254,9 @@ void *get_nearest_bone( rect.xmin = rect.xmax = xy[0]; rect.ymin = rect.ymax = xy[1]; - hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, VIEW3D_SELECT_PICK_NEAREST); + hits = view3d_opengl_select( + &vc, buffer, MAXPICKBUF, &rect, + VIEW3D_SELECT_PICK_NEAREST, VIEW3D_SELECT_FILTER_NOP); *r_base = NULL; @@ -446,9 +448,11 @@ static EditBone *get_nearest_editbonepoint( { const int select_mode = (do_nearest ? VIEW3D_SELECT_PICK_NEAREST : VIEW3D_SELECT_PICK_ALL); + const eV3DSelectObjectFilter select_filter = VIEW3D_SELECT_FILTER_NOP; + rcti rect; BLI_rcti_init_pt_radius(&rect, vc->mval, 12); - const int hits12 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, select_mode); + const int hits12 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, select_mode, select_filter); if (hits12 == 1) { hits = selectbuffer_ret_hits_12(buffer, hits12); goto cache_end; @@ -458,7 +462,9 @@ static EditBone *get_nearest_editbonepoint( offs = 4 * hits12; BLI_rcti_init_pt_radius(&rect, vc->mval, 5); - const int hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode); + const int hits5 = view3d_opengl_select( + vc, buffer + offs, MAXPICKBUF - offs, &rect, + select_mode, select_filter); if (hits5 == 1) { hits = selectbuffer_ret_hits_5(buffer, hits12, hits5); @@ -717,6 +723,7 @@ bool ED_armature_edit_select_pick(bContext *C, const int mval[2], bool extend, b if (vc.view_layer->basact != basact) { vc.view_layer->basact = basact; + DEG_id_tag_update(&vc.scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, vc.scene); } } diff --git a/source/blender/editors/armature/pose_utils.c b/source/blender/editors/armature/pose_utils.c index b64c8528010..e280284a9ce 100644 --- a/source/blender/editors/armature/pose_utils.c +++ b/source/blender/editors/armature/pose_utils.c @@ -40,6 +40,7 @@ #include "BKE_action.h" #include "BKE_armature.h" #include "BKE_idprop.h" +#include "BKE_main.h" #include "BKE_context.h" diff --git a/source/blender/editors/curve/editcurve.c b/source/blender/editors/curve/editcurve.c index 616017dac0a..aa50916f5e0 100644 --- a/source/blender/editors/curve/editcurve.c +++ b/source/blender/editors/curve/editcurve.c @@ -2896,7 +2896,7 @@ static int hide_exec(bContext *C, wmOperator *op) } } - DEG_id_tag_update(obedit->data, 0); + DEG_id_tag_update(obedit->data, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); BKE_curve_nurb_vert_active_validate(obedit->data); @@ -2959,7 +2959,7 @@ static int reveal_exec(bContext *C, wmOperator *op) } } - DEG_id_tag_update(obedit->data, 0); + DEG_id_tag_update(obedit->data, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -4413,6 +4413,7 @@ bool ED_curve_editnurb_select_pick(bContext *C, const int mval[2], bool extend, BKE_curve_nurb_active_set(cu, nu); } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return true; @@ -5300,6 +5301,7 @@ static int duplicate_exec(bContext *C, wmOperator *op) if (BLI_listbase_is_empty(&newnurb) == false) { BLI_movelisttolist(object_editcurve_get(obedit), &newnurb); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } else { @@ -5803,7 +5805,7 @@ void CURVE_OT_delete(wmOperatorType *ot) /* properties */ prop = RNA_def_enum(ot->srna, "type", curve_delete_type_items, 0, "Type", "Which elements to delete"); RNA_def_enum_funcs(prop, rna_curve_delete_type_itemf); - + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); ot->prop = prop; } @@ -6148,6 +6150,7 @@ int join_curve_exec(bContext *C, wmOperator *op) DEG_relations_tag_update(bmain); // because we removed object(s), call before editmode! DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); diff --git a/source/blender/editors/curve/editcurve_select.c b/source/blender/editors/curve/editcurve_select.c index 58fb6d50575..0fae39776a9 100644 --- a/source/blender/editors/curve/editcurve_select.c +++ b/source/blender/editors/curve/editcurve_select.c @@ -55,10 +55,10 @@ #include "curve_intern.h" - #include "RNA_access.h" #include "RNA_define.h" +#include "DEG_depsgraph.h" /* returns 1 in case (de)selection was successful */ bool select_beztriple(BezTriple *bezt, bool selstatus, short flag, eVisible_Types hidden) @@ -404,6 +404,7 @@ static int de_select_first_exec(bContext *C, wmOperator *UNUSED(op)) Object *obedit = CTX_data_edit_object(C); selectend_nurb(obedit, FIRST, true, DESELECT); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); BKE_curve_nurb_vert_active_validate(obedit->data); @@ -430,6 +431,7 @@ static int de_select_last_exec(bContext *C, wmOperator *UNUSED(op)) Object *obedit = CTX_data_edit_object(C); selectend_nurb(obedit, LAST, true, DESELECT); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); BKE_curve_nurb_vert_active_validate(obedit->data); @@ -488,6 +490,7 @@ static int de_select_all_exec(bContext *C, wmOperator *op) break; } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); BKE_curve_nurb_vert_active_validate(cu); } @@ -540,6 +543,7 @@ static int select_linked_exec(bContext *C, wmOperator *UNUSED(op)) } if (changed) { + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } } @@ -608,6 +612,7 @@ static int select_linked_pick_invoke(bContext *C, wmOperator *op, const wmEvent } } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); if (!select) { BKE_curve_nurb_vert_active_validate(obedit->data); @@ -670,6 +675,7 @@ static int select_row_exec(bContext *C, wmOperator *UNUSED(op)) } } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -698,6 +704,7 @@ static int select_next_exec(bContext *C, wmOperator *UNUSED(op)) ListBase *editnurb = object_editcurve_get(obedit); select_adjacent_cp(editnurb, 1, 0, SELECT); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -726,6 +733,7 @@ static int select_previous_exec(bContext *C, wmOperator *UNUSED(op)) ListBase *editnurb = object_editcurve_get(obedit); select_adjacent_cp(editnurb, -1, 0, SELECT); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -814,6 +822,7 @@ static int select_more_exec(bContext *C, wmOperator *UNUSED(op)) select_adjacent_cp(editnurb, -1, 0, SELECT); } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -1001,6 +1010,7 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op)) } } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); BKE_curve_nurb_vert_active_validate(obedit->data); @@ -1087,6 +1097,7 @@ static int curve_select_random_exec(bContext *C, wmOperator *op) curve_select_random(editnurb, randfac, seed_iter, select); BKE_curve_nurb_vert_active_validate(obedit->data); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -1197,6 +1208,7 @@ static int select_nth_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -1503,6 +1515,7 @@ static int curve_select_similar_exec(bContext *C, wmOperator *op) } if (changed) { + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; } @@ -1744,6 +1757,7 @@ static int edcu_shortest_path_pick_invoke(bContext *C, wmOperator *op, const wmE BKE_curve_nurb_vert_active_set(cu, nu_dst, vert_dst_p); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; } diff --git a/source/blender/editors/curve/editfont.c b/source/blender/editors/curve/editfont.c index 7cdfafdad43..75efdec3dd2 100644 --- a/source/blender/editors/curve/editfont.c +++ b/source/blender/editors/curve/editfont.c @@ -246,7 +246,6 @@ static int insert_into_textbuf(Object *obedit, uintptr_t c) static void text_update_edited(bContext *C, Object *obedit, int mode) { - struct Main *bmain = CTX_data_main(C); Curve *cu = obedit->data; EditFont *ef = cu->editfont; @@ -259,7 +258,7 @@ static void text_update_edited(bContext *C, Object *obedit, int mode) } else { /* depsgraph runs above, but since we're not tagging for update, call direct */ - BKE_vfont_to_curve(bmain, obedit, mode); + BKE_vfont_to_curve(obedit, mode); } cu->curinfo = ef->textbufinfo[ef->pos ? ef->pos - 1 : 0]; @@ -982,16 +981,14 @@ static int move_cursor(bContext *C, int type, const bool select) /* apply virtical cursor motion to position immediately * otherwise the selection will lag behind */ if (FO_CURS_IS_MOTION(cursmove)) { - struct Main *bmain = CTX_data_main(C); - BKE_vfont_to_curve(bmain, obedit, cursmove); + BKE_vfont_to_curve(obedit, cursmove); cursmove = FO_CURS; } if (select == 0) { if (ef->selstart) { - struct Main *bmain = CTX_data_main(C); ef->selstart = ef->selend = 0; - BKE_vfont_to_curve(bmain, obedit, FO_SELCHANGE); + BKE_vfont_to_curve(obedit, FO_SELCHANGE); } } diff --git a/source/blender/editors/datafiles/CMakeLists.txt b/source/blender/editors/datafiles/CMakeLists.txt index 23b328aa8e0..98b57fcbd71 100644 --- a/source/blender/editors/datafiles/CMakeLists.txt +++ b/source/blender/editors/datafiles/CMakeLists.txt @@ -681,32 +681,6 @@ if(WITH_BLENDER) data_to_c_simple(../../../../release/datafiles/brushicons/twist.png SRC) data_to_c_simple(../../../../release/datafiles/brushicons/vertexdraw.png SRC) - # matcap - data_to_c_simple(../../../../release/datafiles/matcaps/mc01.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc02.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc03.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc04.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc05.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc06.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc07.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc08.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc09.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc10.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc11.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc12.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc13.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc14.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc15.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc16.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc17.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc18.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc19.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc20.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc21.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc22.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc23.jpg SRC) - data_to_c_simple(../../../../release/datafiles/matcaps/mc24.jpg SRC) - endif() data_to_c_simple(../../../../release/datafiles/startup.blend SRC) diff --git a/source/blender/editors/gpencil/gpencil_brush.c b/source/blender/editors/gpencil/gpencil_brush.c index c2e532be0b3..f9284d71db3 100644 --- a/source/blender/editors/gpencil/gpencil_brush.c +++ b/source/blender/editors/gpencil/gpencil_brush.c @@ -44,6 +44,8 @@ #include "BLI_rand.h" #include "BLI_utildefines.h" +#include "PIL_time.h" + #include "BLT_translation.h" #include "DNA_scene_types.h" @@ -138,6 +140,8 @@ typedef struct tGP_BrushEditData { /* Timer for in-place accumulation of brush effect */ wmTimer *timer; bool timerTick; /* is this event from a timer */ + + RNG *rng; } tGP_BrushEditData; @@ -658,7 +662,7 @@ static bool gp_brush_randomize_apply(tGP_BrushEditData *gso, bGPDstroke *gps, in * as well as the strength of the brush */ const float inf = gp_brush_influence_calc(gso, radius, co) / 2.0f; - const float fac = BLI_frand() * inf; + const float fac = BLI_rng_get_float(gso->rng) * inf; /* need one flag enabled by default */ if ((gso->settings->flag & (GP_BRUSHEDIT_FLAG_APPLY_POSITION | GP_BRUSHEDIT_FLAG_APPLY_STRENGTH | @@ -685,7 +689,7 @@ static bool gp_brush_randomize_apply(tGP_BrushEditData *gso, bGPDstroke *gps, in svec[1] = mvec[0]; /* scale the displacement by the random displacement, and apply */ - if (BLI_frand() > 0.5f) { + if (BLI_rng_get_float(gso->rng) > 0.5f) { mul_v2_fl(svec, -fac); } else { @@ -724,7 +728,7 @@ static bool gp_brush_randomize_apply(tGP_BrushEditData *gso, bGPDstroke *gps, in } /* apply random to strength */ if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_STRENGTH) { - if (BLI_frand() > 0.5f) { + if (BLI_rng_get_float(gso->rng) > 0.5f) { pt->strength += fac; } else { @@ -735,7 +739,7 @@ static bool gp_brush_randomize_apply(tGP_BrushEditData *gso, bGPDstroke *gps, in } /* apply random to thickness (use pressure) */ if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_THICKNESS) { - if (BLI_frand() > 0.5f) { + if (BLI_rng_get_float(gso->rng) > 0.5f) { pt->pressure += fac; } else { @@ -1061,6 +1065,10 @@ static bool gpsculpt_brush_init(bContext *C, wmOperator *op) gso->brush_type = gso->settings->brushtype; + /* Random generator, only init once. */ + uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); + rng_seed ^= GET_UINT_FROM_POINTER(gso); + gso->rng = BLI_rng_new(rng_seed); gso->is_painting = false; gso->first = true; @@ -1163,6 +1171,10 @@ static void gpsculpt_brush_exit(bContext *C, wmOperator *op) WM_event_remove_timer(CTX_wm_manager(C), win, gso->timer); } + if (gso->rng != NULL) { + BLI_rng_free(gso->rng); + } + /* disable cursor and headerprints */ ED_area_headerprint(CTX_wm_area(C), NULL); WM_cursor_modal_restore(win); diff --git a/source/blender/editors/gpencil/gpencil_convert.c b/source/blender/editors/gpencil/gpencil_convert.c index dfaa1420d68..d2301337c0e 100644 --- a/source/blender/editors/gpencil/gpencil_convert.c +++ b/source/blender/editors/gpencil/gpencil_convert.c @@ -1374,6 +1374,7 @@ static int gp_convert_layer_exec(bContext *C, wmOperator *op) } /* notifiers */ + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_OBJECT | NA_ADDED, NULL); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); diff --git a/source/blender/editors/gpencil/gpencil_data.c b/source/blender/editors/gpencil/gpencil_data.c index 2e8e48b2f15..9f437f28f0f 100644 --- a/source/blender/editors/gpencil/gpencil_data.c +++ b/source/blender/editors/gpencil/gpencil_data.c @@ -52,14 +52,15 @@ #include "DNA_view3d_types.h" #include "DNA_gpencil_types.h" +#include "BKE_colortools.h" #include "BKE_context.h" #include "BKE_gpencil.h" #include "BKE_library.h" +#include "BKE_main.h" #include "BKE_object.h" #include "BKE_report.h" #include "BKE_scene.h" #include "BKE_screen.h" -#include "BKE_colortools.h" #include "UI_interface.h" #include "UI_resources.h" @@ -83,6 +84,7 @@ /* add new datablock - wrapper around API */ static int gp_data_add_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); bGPdata **gpd_ptr = ED_gpencil_data_get_pointers(C, NULL); ToolSettings *ts = CTX_data_tool_settings(C); @@ -95,7 +97,7 @@ static int gp_data_add_exec(bContext *C, wmOperator *op) bGPdata *gpd = (*gpd_ptr); id_us_min(&gpd->id); - *gpd_ptr = BKE_gpencil_data_addnew(DATA_("GPencil")); + *gpd_ptr = BKE_gpencil_data_addnew(bmain, DATA_("GPencil")); /* if not exist brushes, create a new set */ if (ts) { @@ -183,6 +185,7 @@ void GPENCIL_OT_data_unlink(wmOperatorType *ot) /* add new layer - wrapper around API */ static int gp_layer_add_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); bGPdata **gpd_ptr = ED_gpencil_data_get_pointers(C, NULL); ToolSettings *ts = CTX_data_tool_settings(C); @@ -192,7 +195,7 @@ static int gp_layer_add_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; } if (*gpd_ptr == NULL) - *gpd_ptr = BKE_gpencil_data_addnew(DATA_("GPencil")); + *gpd_ptr = BKE_gpencil_data_addnew(bmain, DATA_("GPencil")); /* if not exist brushes, create a new set */ if (ts) { @@ -1376,6 +1379,7 @@ void GPENCIL_OT_brush_select(wmOperatorType *ot) /* add new palette - wrapper around API */ static int gp_palette_add_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); bGPdata **gpd_ptr = ED_gpencil_data_get_pointers(C, NULL); /* if there's no existing Grease-Pencil data there, add some */ @@ -1384,7 +1388,7 @@ static int gp_palette_add_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; } if (*gpd_ptr == NULL) - *gpd_ptr = BKE_gpencil_data_addnew(DATA_("GPencil")); + *gpd_ptr = BKE_gpencil_data_addnew(bmain, DATA_("GPencil")); /* add new palette now */ BKE_gpencil_palette_addnew(*gpd_ptr, DATA_("GP_Palette"), true); @@ -1588,6 +1592,7 @@ void GPENCIL_OT_palette_lock_layer(wmOperatorType *ot) /* add new palette - wrapper around API */ static int gp_palettecolor_add_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); bGPdata **gpd_ptr = ED_gpencil_data_get_pointers(C, NULL); /* if there's no existing Grease-Pencil data there, add some */ @@ -1596,7 +1601,7 @@ static int gp_palettecolor_add_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; } if (*gpd_ptr == NULL) - *gpd_ptr = BKE_gpencil_data_addnew(DATA_("GPencil")); + *gpd_ptr = BKE_gpencil_data_addnew(bmain, DATA_("GPencil")); /* verify palette */ bGPDpalette *palette = BKE_gpencil_palette_getactive(*gpd_ptr); diff --git a/source/blender/editors/gpencil/gpencil_intern.h b/source/blender/editors/gpencil/gpencil_intern.h index 33af6cab915..67b88efa285 100644 --- a/source/blender/editors/gpencil/gpencil_intern.h +++ b/source/blender/editors/gpencil/gpencil_intern.h @@ -41,6 +41,7 @@ struct bGPDstroke; struct bGPDspoint; struct GHash; +struct RNG; struct ARegion; struct View2D; @@ -117,7 +118,7 @@ bool gp_smooth_stroke(bGPDstroke *gps, int i, float inf, bool affect_pressure); bool gp_smooth_stroke_strength(bGPDstroke *gps, int i, float inf); bool gp_smooth_stroke_thickness(bGPDstroke *gps, int i, float inf); void gp_subdivide_stroke(bGPDstroke *gps, const int new_totpoints); -void gp_randomize_stroke(bGPDstroke *gps, bGPDbrush *brush); +void gp_randomize_stroke(bGPDstroke *gps, bGPDbrush *brush, struct RNG *rng); /* Layers Enums -------------------------------------- */ diff --git a/source/blender/editors/gpencil/gpencil_paint.c b/source/blender/editors/gpencil/gpencil_paint.c index 437d5cef6f8..c8f1901d075 100644 --- a/source/blender/editors/gpencil/gpencil_paint.c +++ b/source/blender/editors/gpencil/gpencil_paint.c @@ -169,6 +169,8 @@ typedef struct tGPsdata { short straight[2]; /* 1: line horizontal, 2: line vertical, other: not defined, second element position */ int lock_axis; /* lock drawing to one axis */ + RNG *rng; + short keymodifier; /* key used for invoking the operator */ } tGPsdata; @@ -408,7 +410,8 @@ static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3] } /* apply jitter to stroke */ -static void gp_brush_jitter(bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const int mval[2], int r_mval[2]) +static void gp_brush_jitter( + bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const int mval[2], int r_mval[2], RNG *rng) { float pressure = pt->pressure; float tmp_pressure = pt->pressure; @@ -417,7 +420,7 @@ static void gp_brush_jitter(bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const tmp_pressure = curvef * brush->draw_sensitivity; } const float exfactor = (brush->draw_jitter + 2.0f) * (brush->draw_jitter + 2.0f); /* exponential value */ - const float fac = BLI_frand() * exfactor * tmp_pressure; + const float fac = BLI_rng_get_float(rng) * exfactor * tmp_pressure; /* Jitter is applied perpendicular to the mouse movement vector (2D space) */ float mvec[2], svec[2]; /* mouse movement in ints -> floats */ @@ -434,7 +437,7 @@ static void gp_brush_jitter(bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const svec[0] = -mvec[1]; svec[1] = mvec[0]; /* scale the displacement by the random, and apply */ - if (BLI_frand() > 0.5f) { + if (BLI_rng_get_float(rng) > 0.5f) { mul_v2_fl(svec, -fac); } else { @@ -550,7 +553,7 @@ static short gp_stroke_addpoint( /* Apply jitter to position */ if (brush->draw_jitter > 0.0f) { int r_mval[2]; - gp_brush_jitter(gpd, brush, pt, mval, r_mval); + gp_brush_jitter(gpd, brush, pt, mval, r_mval, p->rng); copy_v2_v2_int(&pt->x, r_mval); } else { @@ -560,11 +563,11 @@ static short gp_stroke_addpoint( if ((brush->draw_random_press > 0.0f) && (brush->flag & GP_BRUSH_USE_RANDOM_PRESSURE)) { float curvef = curvemapping_evaluateF(brush->cur_sensitivity, 0, pressure); float tmp_pressure = curvef * brush->draw_sensitivity; - if (BLI_frand() > 0.5f) { - pt->pressure -= tmp_pressure * brush->draw_random_press * BLI_frand(); + if (BLI_rng_get_float(p->rng) > 0.5f) { + pt->pressure -= tmp_pressure * brush->draw_random_press * BLI_rng_get_float(p->rng); } else { - pt->pressure += tmp_pressure * brush->draw_random_press * BLI_frand(); + pt->pressure += tmp_pressure * brush->draw_random_press * BLI_rng_get_float(p->rng); } CLAMP(pt->pressure, GPENCIL_STRENGTH_MIN, 1.0f); } @@ -588,11 +591,11 @@ static short gp_stroke_addpoint( /* apply randomness to color strength */ if ((brush->draw_random_press > 0.0f) && (brush->flag & GP_BRUSH_USE_RANDOM_STRENGTH)) { - if (BLI_frand() > 0.5f) { - pt->strength -= pt->strength * brush->draw_random_press * BLI_frand(); + if (BLI_rng_get_float(p->rng) > 0.5f) { + pt->strength -= pt->strength * brush->draw_random_press * BLI_rng_get_float(p->rng); } else { - pt->strength += pt->strength * brush->draw_random_press * BLI_frand(); + pt->strength += pt->strength * brush->draw_random_press * BLI_rng_get_float(p->rng); } CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f); } @@ -978,7 +981,7 @@ static void gp_stroke_newfrombuffer(tGPsdata *p) } /* apply randomness to stroke */ if (brush->draw_random_sub > 0.0f) { - gp_randomize_stroke(gps, brush); + gp_randomize_stroke(gps, brush, p->rng); } /* smooth stroke after subdiv - only if there's something to do @@ -1387,6 +1390,7 @@ static void gp_init_palette(tGPsdata *p) /* (re)init new painting data */ static bool gp_session_initdata(bContext *C, tGPsdata *p) { + Main *bmain = CTX_data_main(C); bGPdata **gpd_ptr = NULL; ScrArea *curarea = CTX_wm_area(C); ARegion *ar = CTX_wm_region(C); @@ -1537,7 +1541,7 @@ static bool gp_session_initdata(bContext *C, tGPsdata *p) else { /* if no existing GPencil block exists, add one */ if (*gpd_ptr == NULL) - *gpd_ptr = BKE_gpencil_data_addnew("GPencil"); + *gpd_ptr = BKE_gpencil_data_addnew(bmain, "GPencil"); p->gpd = *gpd_ptr; } @@ -1582,6 +1586,11 @@ static tGPsdata *gp_session_initpaint(bContext *C) */ p->radius = U.gp_eraser; + /* Random generator, only init once. */ + uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); + rng_seed ^= GET_UINT_FROM_POINTER(p); + p->rng = BLI_rng_new(rng_seed); + /* return context data for running paint operator */ return p; } @@ -1608,6 +1617,15 @@ static void gp_session_cleanup(tGPsdata *p) p->inittime = 0.0; } +static void gp_session_free(tGPsdata *p) +{ + if (p->rng != NULL) { + BLI_rng_free(p->rng); + } + MEM_freeN(p); +} + + /* init new stroke */ static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph) { @@ -1948,9 +1966,7 @@ static void gpencil_draw_exit(bContext *C, wmOperator *op) /* cleanup */ gp_paint_cleanup(p); gp_session_cleanup(p); - - /* finally, free the temp data */ - MEM_freeN(p); + gp_session_free(p); } op->customdata = NULL; diff --git a/source/blender/editors/gpencil/gpencil_undo.c b/source/blender/editors/gpencil/gpencil_undo.c index 5e2be7c41f0..d35df8bc380 100644 --- a/source/blender/editors/gpencil/gpencil_undo.c +++ b/source/blender/editors/gpencil/gpencil_undo.c @@ -179,7 +179,7 @@ void gpencil_undo_push(bGPdata *gpd) /* create new undo node */ undo_node = MEM_callocN(sizeof(bGPundonode), "gpencil undo node"); - undo_node->gpd = BKE_gpencil_data_duplicate(G.main, gpd, true); + undo_node->gpd = BKE_gpencil_data_duplicate(NULL, gpd, true); cur_node = undo_node; diff --git a/source/blender/editors/gpencil/gpencil_utils.c b/source/blender/editors/gpencil/gpencil_utils.c index f6d72d9e575..4ee3bdd587e 100644 --- a/source/blender/editors/gpencil/gpencil_utils.c +++ b/source/blender/editors/gpencil/gpencil_utils.c @@ -965,7 +965,7 @@ void gp_subdivide_stroke(bGPDstroke *gps, const int new_totpoints) * \param gps Stroke data * \param brush Brush data */ -void gp_randomize_stroke(bGPDstroke *gps, bGPDbrush *brush) +void gp_randomize_stroke(bGPDstroke *gps, bGPDbrush *brush, RNG *rng) { bGPDspoint *pt1, *pt2, *pt3; float v1[3]; @@ -998,10 +998,10 @@ void gp_randomize_stroke(bGPDstroke *gps, bGPDbrush *brush) for (int i = 1; i < gps->totpoints - 1; ++i) { bGPDspoint *pt = &gps->points[i]; /* get vector with shift (apply a division because random is too sensitive */ - const float fac = BLI_frand() * (brush->draw_random_sub / 10.0f); + const float fac = BLI_rng_get_float(rng) * (brush->draw_random_sub / 10.0f); float svec[3]; copy_v3_v3(svec, ortho); - if (BLI_frand() > 0.5f) { + if (BLI_rng_get_float(rng) > 0.5f) { mul_v3_fl(svec, -fac); } else { diff --git a/source/blender/editors/include/ED_manipulator_library.h b/source/blender/editors/include/ED_manipulator_library.h index b67af4274a6..fca0f5c8806 100644 --- a/source/blender/editors/include/ED_manipulator_library.h +++ b/source/blender/editors/include/ED_manipulator_library.h @@ -73,11 +73,18 @@ enum { ED_MANIPULATOR_ARROW_STYLE_CONE = 3, }; +/* transform */ enum { /* inverted offset during interaction - if set it also sets constrained below */ - ED_MANIPULATOR_ARROW_STYLE_INVERTED = (1 << 3), + ED_MANIPULATOR_ARROW_XFORM_FLAG_INVERTED = (1 << 3), /* clamp arrow interaction to property width */ - ED_MANIPULATOR_ARROW_STYLE_CONSTRAINED = (1 << 4), + ED_MANIPULATOR_ARROW_XFORM_FLAG_CONSTRAINED = (1 << 4), +}; + +/* draw_options */ +enum { + /* Show arrow stem. */ + ED_MANIPULATOR_ARROW_DRAW_FLAG_STEM = (1 << 0), }; void ED_manipulator_arrow3d_set_ui_range(struct wmManipulator *mpr, const float min, const float max); diff --git a/source/blender/editors/include/ED_mesh.h b/source/blender/editors/include/ED_mesh.h index 0d323258a19..a9c9e8c0fbd 100644 --- a/source/blender/editors/include/ED_mesh.h +++ b/source/blender/editors/include/ED_mesh.h @@ -83,7 +83,7 @@ void EDBM_mesh_clear(struct BMEditMesh *em); void EDBM_selectmode_to_scene(struct bContext *C); void EDBM_mesh_make(struct Object *ob, const int select_mode, const bool add_key_index); void EDBM_mesh_free(struct BMEditMesh *em); -void EDBM_mesh_load(struct Object *ob); +void EDBM_mesh_load(struct Main *bmain, struct Object *ob); struct DerivedMesh *EDBM_mesh_deform_dm_get(struct BMEditMesh *em); /* flushes based on the current select mode. if in vertex select mode, diff --git a/source/blender/editors/include/ED_object.h b/source/blender/editors/include/ED_object.h index f1311233f23..29f7edaebf0 100644 --- a/source/blender/editors/include/ED_object.h +++ b/source/blender/editors/include/ED_object.h @@ -40,6 +40,7 @@ struct Base; struct EnumPropertyItem; struct ID; struct Main; +struct Menu; struct ModifierData; struct Object; struct ReportList; @@ -58,12 +59,14 @@ struct PointerRNA; struct PropertyRNA; struct EnumPropertyItem; struct Depsgraph; +struct uiLayout; #include "DNA_object_enums.h" /* object_edit.c */ struct Object *ED_object_context(struct bContext *C); /* context.object */ struct Object *ED_object_active_context(struct bContext *C); /* context.object or context.active_object */ +void ED_hide_collections_menu_draw(const struct bContext *C, struct uiLayout *layout); /* object_ops.c */ void ED_operatortypes_object(void); @@ -245,7 +248,7 @@ int ED_object_modifier_convert( struct ReportList *reports, struct Main *bmain, struct Scene *scene, struct ViewLayer *view_layer, struct Object *ob, struct ModifierData *md); int ED_object_modifier_apply( - struct ReportList *reports, struct Depsgraph *depsgraph, struct Scene *scene, + struct Main *bmain, struct ReportList *reports, struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, struct ModifierData *md, int mode); int ED_object_modifier_copy(struct ReportList *reports, struct Object *ob, struct ModifierData *md); @@ -277,7 +280,4 @@ void ED_object_facemap_face_remove(struct Object *ob, struct bFaceMap *fmap, int } #endif -/* Don't allow switching object-modes when selecting objects. */ -#define USE_OBJECT_MODE_STRICT - #endif /* __ED_OBJECT_H__ */ diff --git a/source/blender/editors/include/ED_screen.h b/source/blender/editors/include/ED_screen.h index a741f12c112..204c5fa5956 100644 --- a/source/blender/editors/include/ED_screen.h +++ b/source/blender/editors/include/ED_screen.h @@ -69,22 +69,33 @@ void ED_region_do_layout(struct bContext *C, struct ARegion *ar); void ED_region_do_draw(struct bContext *C, struct ARegion *ar); void ED_region_exit(struct bContext *C, struct ARegion *ar); void ED_region_pixelspace(struct ARegion *ar); -void ED_region_update_rect(struct bContext *C, struct ARegion *ar); -void ED_region_init(struct bContext *C, struct ARegion *ar); +void ED_region_update_rect(struct ARegion *ar); +void ED_region_init(struct ARegion *ar); void ED_region_tag_redraw(struct ARegion *ar); void ED_region_tag_redraw_partial(struct ARegion *ar, const struct rcti *rct); void ED_region_tag_redraw_overlay(struct ARegion *ar); void ED_region_tag_redraw_no_rebuild(struct ARegion *ar); void ED_region_tag_refresh_ui(struct ARegion *ar); -void ED_region_panels_init(struct wmWindowManager *wm, struct ARegion *ar); -void ED_region_panels( - const struct bContext *C, struct ARegion *ar, - const char *contexts[], int contextnr, - const bool vertical); -void ED_region_header_init(struct ARegion *ar); -void ED_region_header(const struct bContext *C, struct ARegion *ar); -void ED_region_header_layout(const struct bContext *C, struct ARegion *ar); -void ED_region_header_draw(const struct bContext *C, struct ARegion *ar); + +void ED_region_panels_init(struct wmWindowManager *wm, struct ARegion *ar); +void ED_region_panels_ex( + const struct bContext *C, struct ARegion *ar, + const char *contexts[], int contextnr, const bool vertical); +void ED_region_panels( + const struct bContext *C, struct ARegion *ar); +void ED_region_panels_layout_ex( + const struct bContext *C, struct ARegion *ar, + const char *contexts[], int contextnr, const bool vertical); +void ED_region_panels_layout( + const struct bContext *C, struct ARegion *ar); +void ED_region_panels_draw( + const struct bContext *C, struct ARegion *ar); + +void ED_region_header_init(struct ARegion *ar); +void ED_region_header(const struct bContext *C, struct ARegion *ar); +void ED_region_header_layout(const struct bContext *C, struct ARegion *ar); +void ED_region_header_draw(const struct bContext *C, struct ARegion *ar); + void ED_region_cursor_set(struct wmWindow *win, struct ScrArea *sa, struct ARegion *ar); void ED_region_toggle_hidden(struct bContext *C, struct ARegion *ar); void ED_region_visibility_change_update(struct bContext *C, struct ARegion *ar); @@ -308,6 +319,11 @@ void ED_region_cache_draw_background(const struct ARegion *ar); void ED_region_cache_draw_curfra_label(const int framenr, const float x, const float y); void ED_region_cache_draw_cached_segments(const struct ARegion *ar, const int num_segments, const int *points, const int sfra, const int efra); +/* interface_region_hud.c */ +struct ARegionType *ED_area_type_hud(int space_type); +void ED_area_type_hud_clear(struct wmWindowManager *wm, ScrArea *sa_keep); +void ED_area_type_hud_ensure(struct bContext *C, struct ScrArea *sa); + /* default keymaps, bitflags */ #define ED_KEYMAP_UI 1 #define ED_KEYMAP_VIEW2D 2 diff --git a/source/blender/editors/include/ED_undo.h b/source/blender/editors/include/ED_undo.h index 5103ac97361..37744e7eb0f 100644 --- a/source/blender/editors/include/ED_undo.h +++ b/source/blender/editors/include/ED_undo.h @@ -52,14 +52,6 @@ int ED_undo_operator_repeat(struct bContext *C, struct wmOperator *op); void ED_undo_operator_repeat_cb(struct bContext *C, void *arg_op, void *arg_unused); void ED_undo_operator_repeat_cb_evt(struct bContext *C, void *arg_op, int arg_unused); -/* Context sanity helpers for operator repeat. */ -typedef struct OperatorRepeatContextHandle OperatorRepeatContextHandle; - -const OperatorRepeatContextHandle *ED_operator_repeat_prepare_context( - struct bContext *C, struct wmOperator *op) ATTR_WARN_UNUSED_RESULT; -void ED_operator_repeat_reset_context( - struct bContext *C, const OperatorRepeatContextHandle *context_info); - bool ED_undo_is_valid(const struct bContext *C, const char *undoname); struct UndoStack *ED_undo_stack_get(void); diff --git a/source/blender/editors/include/ED_view3d.h b/source/blender/editors/include/ED_view3d.h index 24e5b3e2662..343bffa0082 100644 --- a/source/blender/editors/include/ED_view3d.h +++ b/source/blender/editors/include/ED_view3d.h @@ -351,12 +351,19 @@ typedef enum { VIEW3D_SELECT_PICK_NEAREST = 2, } eV3DSelectMode; +typedef enum { + /* Don't exclude anything. */ + VIEW3D_SELECT_FILTER_NOP = 0, + /* Don't select objects outside the current mode. */ + VIEW3D_SELECT_FILTER_OBJECT_MODE_LOCK = 1, +} eV3DSelectObjectFilter; + void view3d_opengl_select_cache_begin(void); void view3d_opengl_select_cache_end(void); int view3d_opengl_select( struct ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const struct rcti *input, - eV3DSelectMode select_mode); + eV3DSelectMode select_mode, eV3DSelectObjectFilter select_filter); /* view3d_select.c */ float ED_view3d_select_dist_px(void); diff --git a/source/blender/editors/include/UI_icons.h b/source/blender/editors/include/UI_icons.h index 3bc1255d23f..03c99bb7f0d 100644 --- a/source/blender/editors/include/UI_icons.h +++ b/source/blender/editors/include/UI_icons.h @@ -113,9 +113,7 @@ DEF_ICON(FILE_TICK) DEF_ICON(QUIT) DEF_ICON(URL) DEF_ICON(RECOVER_LAST) -#ifndef DEF_ICON_BLANK_SKIP - DEF_ICON(BLANK038) -#endif +DEF_ICON(PRESET) DEF_ICON(FULLSCREEN_ENTER) DEF_ICON(FULLSCREEN_EXIT) DEF_ICON(BLANK1) // Not actually blank - this is used all over the place @@ -294,8 +292,10 @@ DEF_ICON(RNA_ADD) DEF_ICON(BLANK112) DEF_ICON(BLANK113) DEF_ICON(BLANK114) - DEF_ICON(BLANK115) - DEF_ICON(BLANK116) +#endif +DEF_ICON(RESTRICT_VIEW_OFF) +DEF_ICON(RESTRICT_VIEW_ON) +#ifndef DEF_ICON_BLANK_SKIP DEF_ICON(BLANK116b) #endif @@ -321,8 +321,8 @@ DEF_ICON(OUTLINER_OB_LIGHTPROBE) #endif DEF_ICON(RESTRICT_COLOR_OFF) DEF_ICON(RESTRICT_COLOR_ON) -DEF_ICON(RESTRICT_VIEW_OFF) -DEF_ICON(RESTRICT_VIEW_ON) +DEF_ICON(HIDE_OFF) +DEF_ICON(HIDE_ON) DEF_ICON(RESTRICT_SELECT_OFF) DEF_ICON(RESTRICT_SELECT_ON) DEF_ICON(RESTRICT_RENDER_OFF) diff --git a/source/blender/editors/include/UI_interface.h b/source/blender/editors/include/UI_interface.h index c82a320268f..0b4817c8049 100644 --- a/source/blender/editors/include/UI_interface.h +++ b/source/blender/editors/include/UI_interface.h @@ -830,6 +830,7 @@ struct Panel *UI_panel_begin(struct ScrArea *sa, struct ARegion *ar, struct List void UI_panel_end(uiBlock *block, int width, int height); void UI_panels_scale(struct ARegion *ar, float new_width); void UI_panel_label_offset(struct uiBlock *block, int *x, int *y); +int UI_panel_size_y(const struct Panel *pa); bool UI_panel_category_is_visible(struct ARegion *ar); void UI_panel_category_add(struct ARegion *ar, const char *name); @@ -905,7 +906,7 @@ void UI_exit(void); #define UI_ITEM_O_DEPRESS (1 << 9) #define UI_ITEM_R_COMPACT (1 << 10) -#define UI_HEADER_OFFSET_START ((void)0, 0.4f * UI_UNIT_X) +#define UI_HEADER_OFFSET ((void)0, 0.2f * UI_UNIT_X) /* uiLayoutOperatorButs flags */ enum { @@ -963,6 +964,7 @@ void uiLayoutSetScaleX(uiLayout *layout, float scale); void uiLayoutSetScaleY(uiLayout *layout, float scale); void uiLayoutSetEmboss(uiLayout *layout, char emboss); void uiLayoutSetPropSep(uiLayout *layout, bool is_sep); +void uiLayoutSetPropDecorate(uiLayout *layout, bool is_sep); int uiLayoutGetOperatorContext(uiLayout *layout); bool uiLayoutGetActive(uiLayout *layout); @@ -975,6 +977,7 @@ float uiLayoutGetScaleX(uiLayout *layout); float uiLayoutGetScaleY(uiLayout *layout); int uiLayoutGetEmboss(uiLayout *layout); bool uiLayoutGetPropSep(uiLayout *layout); +bool uiLayoutGetPropDecorate(uiLayout *layout); /* layout specifiers */ uiLayout *uiLayoutRow(uiLayout *layout, int align); @@ -1030,6 +1033,7 @@ 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 uiTemplateIcon(uiLayout *layout, int icon_value, float icon_scale); void uiTemplateIconView(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int 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); @@ -1255,5 +1259,7 @@ void UI_widgetbase_draw_cache_end(void); #define USE_UI_POPOVER_ONCE bool UI_but_is_tool(const uiBut *but); +#define UI_but_is_decorator(but) \ + ((but)->func == ui_but_anim_decorate_cb) #endif /* __UI_INTERFACE_H__ */ diff --git a/source/blender/editors/interface/CMakeLists.txt b/source/blender/editors/interface/CMakeLists.txt index 49fe6bfb2dc..07ba3b90e11 100644 --- a/source/blender/editors/interface/CMakeLists.txt +++ b/source/blender/editors/interface/CMakeLists.txt @@ -58,6 +58,7 @@ set(SRC interface_panel.c interface_regions.c interface_region_color_picker.c + interface_region_hud.c interface_region_menu_pie.c interface_region_menu_popup.c interface_region_popover.c diff --git a/source/blender/editors/interface/interface.c b/source/blender/editors/interface/interface.c index 811bd4457d8..8c37054098b 100644 --- a/source/blender/editors/interface/interface.c +++ b/source/blender/editors/interface/interface.c @@ -243,19 +243,44 @@ static void ui_update_flexible_spacing(const ARegion *region, uiBlock *block) rcti rect; ui_but_to_pixelrect(&rect, region, block, block->buttons.last); - const float buttons_width = (float)rect.xmax + UI_HEADER_OFFSET_START; + const float buttons_width = (float)rect.xmax + UI_HEADER_OFFSET; const float region_width = (float)region->sizex * U.dpi_fac; if (region_width <= buttons_width) { return; } - const float spacing = ((region_width - buttons_width) / (float)sepr_flex_len); - float offset = 0; + /* We could get rid of this loop if we agree on a max number of spacer */ + int *spacers_pos = alloca(sizeof(*spacers_pos) * (size_t)sepr_flex_len); + int i = 0; + for (uiBut *but = block->buttons.first; but; but = but->next) { + if (but->type == UI_BTYPE_SEPR_SPACER) { + ui_but_to_pixelrect(&rect, region, block, but); + spacers_pos[i] = rect.xmax + UI_HEADER_OFFSET; + i++; + } + } + + const float segment_width = region_width / (float)sepr_flex_len; + float offset = 0, remaining_space = region_width - buttons_width; + i = 0; for (uiBut *but = block->buttons.first; but; but = but->next) { BLI_rctf_translate(&but->rect, offset, 0); if (but->type == UI_BTYPE_SEPR_SPACER) { - offset += spacing; + /* How much the next block overlap with the current segment */ + int overlap = ( + (i == sepr_flex_len - 1) ? + buttons_width - spacers_pos[i] : + (spacers_pos[i + 1] - spacers_pos[i]) / 2); + int segment_end = segment_width * (i + 1); + int spacer_end = segment_end - overlap; + int spacer_sta = spacers_pos[i] + offset; + if (spacer_end > spacer_sta) { + float step = min_ff(remaining_space, spacer_end - spacer_sta); + remaining_space -= step; + offset += step; + } + i++; } } ui_block_bounds_calc(block); @@ -1247,6 +1272,9 @@ void UI_block_end_ex(const bContext *C, uiBlock *block, const int xy[2], int r_x ui_but_anim_flag(but, (scene) ? scene->r.cfra : 0.0f); ui_but_override_flag(but); + if (UI_but_is_decorator(but)) { + ui_but_anim_decorate_update_from_flag(but); + } } diff --git a/source/blender/editors/interface/interface_anim.c b/source/blender/editors/interface/interface_anim.c index fc0ad7e5dce..cda70d405ad 100644 --- a/source/blender/editors/interface/interface_anim.c +++ b/source/blender/editors/interface/interface_anim.c @@ -103,6 +103,30 @@ void ui_but_anim_flag(uiBut *but, float cfra) } } +void ui_but_anim_decorate_update_from_flag(uiBut *but) +{ + BLI_assert(UI_but_is_decorator(but) && but->prev); + int flag = but->prev->flag; + if (flag & UI_BUT_DRIVEN) { + but->icon = ICON_AUTO; + } + else if (flag & UI_BUT_ANIMATED_KEY) { + but->icon = ICON_SPACE2; + } + else if (flag & UI_BUT_ANIMATED) { + but->icon = ICON_SPACE3; + } + else if (flag & UI_BUT_OVERRIDEN) { + but->icon = ICON_LIBRARY_DATA_OVERRIDE; + } + else { + but->icon = ICON_DOT; + } + + const int flag_copy = (UI_BUT_DISABLED | UI_BUT_INACTIVE); + but->flag = (but->flag & ~flag_copy) | (flag & flag_copy); +} + /** * \a str can be NULL to only perform check if \a but has an expression at all. * \return if button has an expression. @@ -299,3 +323,38 @@ void ui_but_anim_paste_driver(bContext *C) /* this operator calls UI_context_active_but_prop_get */ WM_operator_name_call(C, "ANIM_OT_paste_driver_button", WM_OP_INVOKE_DEFAULT, NULL); } + +void ui_but_anim_decorate_cb(bContext *C, void *arg_but, void *UNUSED(arg_dummy)) +{ + wmWindowManager *wm = CTX_wm_manager(C); + uiBut *but = arg_but; + but = but->prev; + + /* FIXME(campbell), swapping active pointer is weak. */ + SWAP(struct uiHandleButtonData *, but->active, but->next->active); + wm->op_undo_depth++; + + if (but->flag & UI_BUT_DRIVEN) { + /* pass */ + /* TODO: report? */ + } + else if (but->flag & UI_BUT_ANIMATED_KEY) { + PointerRNA props_ptr; + wmOperatorType *ot = WM_operatortype_find("ANIM_OT_keyframe_delete_button", false); + WM_operator_properties_create_ptr(&props_ptr, ot); + RNA_boolean_set(&props_ptr, "all", but->rnaindex == -1); + WM_operator_name_call_ptr(C, ot, WM_OP_INVOKE_DEFAULT, &props_ptr); + WM_operator_properties_free(&props_ptr); + } + else { + PointerRNA props_ptr; + wmOperatorType *ot = WM_operatortype_find("ANIM_OT_keyframe_insert_button", false); + WM_operator_properties_create_ptr(&props_ptr, ot); + RNA_boolean_set(&props_ptr, "all", but->rnaindex == -1); + WM_operator_name_call_ptr(C, ot, WM_OP_INVOKE_DEFAULT, &props_ptr); + WM_operator_properties_free(&props_ptr); + } + + SWAP(struct uiHandleButtonData *, but->active, but->next->active); + wm->op_undo_depth--; +} diff --git a/source/blender/editors/interface/interface_handlers.c b/source/blender/editors/interface/interface_handlers.c index 02844f5e861..63bf29a26ea 100644 --- a/source/blender/editors/interface/interface_handlers.c +++ b/source/blender/editors/interface/interface_handlers.c @@ -58,6 +58,7 @@ #include "PIL_time.h" +#include "BKE_addon.h" #include "BKE_colorband.h" #include "BKE_blender_undo.h" #include "BKE_brush.h" @@ -1267,6 +1268,34 @@ static void ui_multibut_states_apply(bContext *C, uiHandleButtonData *data, uiBl #ifdef USE_DRAG_TOGGLE +/* Helpers that wrap boolean functions, to support different kinds of buttons. */ + +static bool ui_drag_toggle_but_is_supported(const uiBut *but) +{ + if (ui_but_is_bool(but)) { + return true; + } + else if (UI_but_is_decorator(but)) { + return ELEM(but->icon, ICON_SPACE2, ICON_SPACE3, ICON_DOT, ICON_LIBRARY_DATA_OVERRIDE); + } + else { + return false; + } +} + +static bool ui_drag_toggle_but_is_pushed(uiBut *but) +{ + if (ui_but_is_bool(but)) { + return ui_but_is_pushed(but); + } + else if (UI_but_is_decorator(but)) { + return (but->icon == ICON_SPACE2); + } + else { + return false; + } +} + typedef struct uiDragToggleHandle { /* init */ bool is_init; @@ -1304,10 +1333,9 @@ static bool ui_drag_toggle_set_xy_xy( if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) { /* execute the button */ - if (ui_but_is_bool(but) && but->type == but_type_start) { + if (ui_drag_toggle_but_is_supported(but) && but->type == but_type_start) { /* is it pressed? */ - bool is_set_but = ui_but_is_pushed(but); - BLI_assert(ui_but_is_bool(but) == true); + bool is_set_but = ui_drag_toggle_but_is_pushed(but); if (is_set_but != is_set) { UI_but_execute(C, but); if (do_check) { @@ -1437,7 +1465,7 @@ static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void static bool ui_but_is_drag_toggle(const uiBut *but) { - return ((ui_but_is_bool(but) == true) && + return ((ui_drag_toggle_but_is_supported(but) == true) && /* menu check is importnt so the button dragged over isn't removed instantly */ (ui_block_is_menu(but->block) == false)); } @@ -1745,7 +1773,7 @@ static bool ui_but_drag_init( button_activate_state(C, but, BUTTON_STATE_EXIT); data->cancel = true; #ifdef USE_DRAG_TOGGLE - if (ui_but_is_bool(but)) { + if (ui_drag_toggle_but_is_supported(but)) { uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__); ARegion *ar_prev; @@ -1753,7 +1781,7 @@ static bool ui_but_drag_init( * typically 'button_activate_exit()' handles this */ ui_apply_but_autokey(C, but); - drag_info->is_set = ui_but_is_pushed(but); + drag_info->is_set = ui_drag_toggle_but_is_pushed(but); drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect); drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect); drag_info->but_type_start = but->type; @@ -3585,10 +3613,50 @@ static uiBut *ui_but_list_row_text_activate( /* ***************** events for different button types *************** */ +#ifdef USE_DRAG_TOGGLE +/* Shared by any button that supports drag-toggle. */ +static bool ui_do_but_ANY_drag_toggle( + bContext *C, uiBut *but, + uiHandleButtonData *data, const wmEvent *event, + int *r_retval) +{ + if (data->state == BUTTON_STATE_HIGHLIGHT) { + if (event->type == LEFTMOUSE && event->val == KM_PRESS && ui_but_is_drag_toggle(but)) { +#if 0 /* UNUSED */ + data->togdual = event->ctrl; + data->togonly = !event->shift; +#endif + ui_apply_but(C, but->block, but, data, true); + button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG); + data->dragstartx = event->x; + data->dragstarty = event->y; + *r_retval = WM_UI_HANDLER_BREAK; + return true; + } + } + else if (data->state == BUTTON_STATE_WAIT_DRAG) { + /* note: the 'BUTTON_STATE_WAIT_DRAG' part of 'ui_do_but_EXIT' could be refactored into its own function */ + data->applied = false; + *r_retval = ui_do_but_EXIT(C, but, data, event); + return true; + } + return false; +} +#endif /* USE_DRAG_TOGGLE */ + static int ui_do_but_BUT( bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event) { +#ifdef USE_DRAG_TOGGLE + { + int retval; + if (ui_do_but_ANY_drag_toggle(C, but, data, event, &retval)) { + return retval; + } + } +#endif + if (data->state == BUTTON_STATE_HIGHLIGHT) { if (event->type == LEFTMOUSE && event->val == KM_PRESS) { button_activate_state(C, but, BUTTON_STATE_WAIT_RELEASE); @@ -3836,25 +3904,14 @@ static int ui_do_but_TOG( uiHandleButtonData *data, const wmEvent *event) { #ifdef USE_DRAG_TOGGLE - if (data->state == BUTTON_STATE_HIGHLIGHT) { - if (event->type == LEFTMOUSE && event->val == KM_PRESS && ui_but_is_drag_toggle(but)) { -#if 0 /* UNUSED */ - data->togdual = event->ctrl; - data->togonly = !event->shift; -#endif - ui_apply_but(C, but->block, but, data, true); - button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG); - data->dragstartx = event->x; - data->dragstarty = event->y; - return WM_UI_HANDLER_BREAK; + { + int retval; + if (ui_do_but_ANY_drag_toggle(C, but, data, event, &retval)) { + return retval; } } - else if (data->state == BUTTON_STATE_WAIT_DRAG) { - /* note: the 'BUTTON_STATE_WAIT_DRAG' part of 'ui_do_but_EXIT' could be refactored into its own function */ - data->applied = false; - return ui_do_but_EXIT(C, but, data, event); - } #endif + if (data->state == BUTTON_STATE_HIGHLIGHT) { if (ELEM(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) { #if 0 /* UNUSED */ @@ -4277,10 +4334,14 @@ static int ui_do_but_NUM( retval = WM_UI_HANDLER_BREAK; /* allow accumulating values, otherwise scrolling gets preference */ else if (type == WHEELDOWNMOUSE && event->ctrl) { mx = but->rect.xmin; + but->drawflag &= ~UI_BUT_ACTIVE_RIGHT; + but->drawflag |= UI_BUT_ACTIVE_LEFT; click = 1; } else if (type == WHEELUPMOUSE && event->ctrl) { mx = but->rect.xmax; + but->drawflag &= ~UI_BUT_ACTIVE_LEFT; + but->drawflag |= UI_BUT_ACTIVE_RIGHT; click = 1; } else if (event->val == KM_PRESS) { @@ -5086,12 +5147,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); @@ -5810,12 +5871,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); } @@ -7010,7 +7071,10 @@ static bool ui_but_menu(bContext *C, uiBut *but) 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); + + if (BKE_addon_find(&U.addons, "ui_translate")) { + 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) { @@ -8167,6 +8231,10 @@ void UI_context_update_anim_flag(const bContext *C) for (but = block->buttons.first; but; but = but->next) { ui_but_anim_flag(but, (scene) ? scene->r.cfra : 0.0f); ui_but_override_flag(but); + if (UI_but_is_decorator(but)) { + ui_but_anim_decorate_update_from_flag(but); + } + ED_region_tag_redraw(ar); if (but->active) { @@ -9136,7 +9204,7 @@ static int ui_handle_menu_event( add_v2_v2v2_int(menu->popup_create_vars.event_xy, menu->popup_create_vars.event_xy, mdiff); - ui_popup_translate(C, ar, mdiff); + ui_popup_translate(ar, mdiff); } return retval; diff --git a/source/blender/editors/interface/interface_icons.c b/source/blender/editors/interface/interface_icons.c index c2ada1e3733..64fca05c082 100644 --- a/source/blender/editors/interface/interface_icons.c +++ b/source/blender/editors/interface/interface_icons.c @@ -77,6 +77,9 @@ #include "UI_interface.h" #include "UI_interface_icons.h" +#include "WM_api.h" +#include "WM_types.h" + #include "interface_intern.h" #ifndef WITH_HEADLESS @@ -451,49 +454,6 @@ static void icon_verify_datatoc(IconImage *iimg) } } -static void init_matcap_icons(void) -{ - /* dynamic allocation now, tucking datatoc pointers in DrawInfo */ -#define INIT_MATCAP_ICON(icon_id, name) \ - { \ - unsigned char *rect = (unsigned char *)datatoc_ ##name## _jpg; \ - int size = datatoc_ ##name## _jpg_size; \ - DrawInfo *di; \ - \ - di = def_internal_icon(NULL, icon_id, 0, 0, 96, ICON_TYPE_BUFFER); \ - di->data.buffer.image->datatoc_rect = rect; \ - di->data.buffer.image->datatoc_size = size; \ - } (void)0 - - INIT_MATCAP_ICON(ICON_MATCAP_01, mc01); - INIT_MATCAP_ICON(ICON_MATCAP_02, mc02); - INIT_MATCAP_ICON(ICON_MATCAP_03, mc03); - INIT_MATCAP_ICON(ICON_MATCAP_04, mc04); - INIT_MATCAP_ICON(ICON_MATCAP_05, mc05); - INIT_MATCAP_ICON(ICON_MATCAP_06, mc06); - INIT_MATCAP_ICON(ICON_MATCAP_07, mc07); - INIT_MATCAP_ICON(ICON_MATCAP_08, mc08); - INIT_MATCAP_ICON(ICON_MATCAP_09, mc09); - INIT_MATCAP_ICON(ICON_MATCAP_10, mc10); - INIT_MATCAP_ICON(ICON_MATCAP_11, mc11); - INIT_MATCAP_ICON(ICON_MATCAP_12, mc12); - INIT_MATCAP_ICON(ICON_MATCAP_13, mc13); - INIT_MATCAP_ICON(ICON_MATCAP_14, mc14); - INIT_MATCAP_ICON(ICON_MATCAP_15, mc15); - INIT_MATCAP_ICON(ICON_MATCAP_16, mc16); - INIT_MATCAP_ICON(ICON_MATCAP_17, mc17); - INIT_MATCAP_ICON(ICON_MATCAP_18, mc18); - INIT_MATCAP_ICON(ICON_MATCAP_19, mc19); - INIT_MATCAP_ICON(ICON_MATCAP_20, mc20); - INIT_MATCAP_ICON(ICON_MATCAP_21, mc21); - INIT_MATCAP_ICON(ICON_MATCAP_22, mc22); - INIT_MATCAP_ICON(ICON_MATCAP_23, mc23); - INIT_MATCAP_ICON(ICON_MATCAP_24, mc24); - -#undef INIT_MATCAP_ICON - -} - static void init_internal_icons(void) { // bTheme *btheme = UI_GetTheme(); @@ -645,7 +605,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 @@ -777,14 +737,7 @@ static DrawInfo *icon_create_drawinfo(Icon *icon) di->type = ICON_TYPE_GEOM; } else if (icon_data_type == ICON_DATA_STUDIOLIGHT) { - const int STUDIOLIGHT_SIZE = 96; - StudioLight *sl = icon->obj; di->type = ICON_TYPE_BUFFER; - IconImage *img = MEM_mallocN(sizeof(IconImage), __func__); - img->w = STUDIOLIGHT_SIZE; - img->h = STUDIOLIGHT_SIZE; - img->rect = BKE_studiolight_preview(sl, STUDIOLIGHT_SIZE, icon->id_type); - di->data.buffer.image = img; } else { BLI_assert(0); @@ -850,7 +803,6 @@ void UI_icons_init(int first_dyn_id) init_iconfile_list(&iconfilelist); init_internal_icons(); init_brush_icons(); - init_matcap_icons(); #endif } @@ -890,6 +842,41 @@ static void icon_create_rect(struct PreviewImage *prv_img, enum eIconSizes size) static void ui_id_preview_image_render_size( const bContext *C, Scene *scene, ID *id, PreviewImage *pi, int size, const bool use_job); +static void ui_studiolight_icon_job_exec(void *customdata, short *UNUSED(stop), short *UNUSED(do_update), float *UNUSED(progress)) +{ + Icon **tmp = (Icon **)customdata; + Icon *icon = *tmp; + DrawInfo *di = icon_ensure_drawinfo(icon); + StudioLight *sl = icon->obj; + BKE_studiolight_preview(di->data.buffer.image->rect, sl, icon->id_type); +} + +static void ui_studiolight_kill_icon_preview_job(wmWindowManager *wm, int icon_id) +{ + Icon *icon = BKE_icon_get(icon_id); + WM_jobs_kill_type(wm, icon, WM_JOB_TYPE_STUDIOLIGHT); + icon->obj = NULL; +} + +static void ui_studiolight_free_function(StudioLight * sl, void* data) +{ + wmWindowManager *wm = data; + + // get icons_id, get icons and kill wm jobs + if (sl->icon_id_radiance) { + ui_studiolight_kill_icon_preview_job(wm, sl->icon_id_radiance); + } + if (sl->icon_id_irradiance) { + ui_studiolight_kill_icon_preview_job(wm, sl->icon_id_irradiance); + } + if (sl->icon_id_matcap) { + ui_studiolight_kill_icon_preview_job(wm, sl->icon_id_matcap); + } + if (sl->icon_id_matcap_flipped) { + ui_studiolight_kill_icon_preview_job(wm, sl->icon_id_matcap_flipped); + } +} + void ui_icon_ensure_deferred(const bContext *C, const int icon_id, const bool big) { Icon *icon = BKE_icon_get(icon_id); @@ -916,6 +903,33 @@ void ui_icon_ensure_deferred(const bContext *C, const int icon_id, const bool bi } break; } + case ICON_TYPE_BUFFER: + { + if (icon->obj_type == ICON_DATA_STUDIOLIGHT) { + if (di->data.buffer.image == NULL) { + wmWindowManager *wm = CTX_wm_manager(C); + StudioLight *sl = icon->obj; + BKE_studiolight_set_free_function(sl, &ui_studiolight_free_function, wm); + IconImage *img = MEM_mallocN(sizeof(IconImage), __func__); + + img->w = STUDIOLIGHT_ICON_SIZE; + img->h = STUDIOLIGHT_ICON_SIZE; + size_t size = STUDIOLIGHT_ICON_SIZE * STUDIOLIGHT_ICON_SIZE * sizeof(uint); + img->rect = MEM_mallocN(size, __func__); + memset(img->rect, 0, size); + di->data.buffer.image = img; + + wmJob *wm_job = WM_jobs_get(wm, CTX_wm_window(C), icon, "StudioLight Icon", 0, WM_JOB_TYPE_STUDIOLIGHT); + Icon** tmp = MEM_callocN(sizeof(Icon*), __func__); + *tmp = icon; + WM_jobs_customdata_set(wm_job, tmp, MEM_freeN); + WM_jobs_timer(wm_job, 0.01, 0, NC_WINDOW); + WM_jobs_callbacks(wm_job, ui_studiolight_icon_job_exec, NULL, NULL, NULL); + WM_jobs_start(CTX_wm_manager(C), wm_job); + } + } + break; + } } } } @@ -1479,7 +1493,7 @@ int UI_rnaptr_icon_get(bContext *C, PointerRNA *ptr, int rnaicon, const bool big id = RNA_pointer_get(ptr, "texture").data; } else if (RNA_struct_is_a(ptr->type, &RNA_DynamicPaintSurface)) { - DynamicPaintSurface *surface = (DynamicPaintSurface *)ptr->data; + DynamicPaintSurface *surface = ptr->data; if (surface->format == MOD_DPAINT_SURFACE_F_PTEX) return ICON_TEXTURE_SHADED; @@ -1488,6 +1502,18 @@ int UI_rnaptr_icon_get(bContext *C, PointerRNA *ptr, int rnaicon, const bool big else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) return ICON_FILE_IMAGE; } + else if (RNA_struct_is_a(ptr->type, &RNA_StudioLight)) { + StudioLight *sl = ptr->data; + switch (sl->flag & STUDIOLIGHT_FLAG_ORIENTATIONS) { + case STUDIOLIGHT_ORIENTATION_CAMERA: + return sl->icon_id_irradiance; + case STUDIOLIGHT_ORIENTATION_WORLD: + default: + return sl->icon_id_radiance; + case STUDIOLIGHT_ORIENTATION_VIEWNORMAL: + return sl->icon_id_matcap; + } + } /* get icon from ID */ if (id) { diff --git a/source/blender/editors/interface/interface_intern.h b/source/blender/editors/interface/interface_intern.h index b5bf9be737b..6f029b81e92 100644 --- a/source/blender/editors/interface/interface_intern.h +++ b/source/blender/editors/interface/interface_intern.h @@ -652,7 +652,7 @@ void ui_pie_menu_level_create( const EnumPropertyItem *items, int totitem, int context, int flag); /* interface_region_popup.c */ -void ui_popup_translate(struct bContext *C, struct ARegion *ar, const int mdiff[2]); +void ui_popup_translate(struct ARegion *ar, const int mdiff[2]); void ui_popup_block_free(struct bContext *C, uiPopupBlockHandle *handle); void ui_popup_block_scrolltest(struct uiBlock *block); @@ -757,8 +757,13 @@ void ui_draw_menu_back(struct uiStyle *style, uiBlock *block, rcti *rect); void ui_draw_popover_back(ARegion *ar, struct uiStyle *style, uiBlock *block, rcti *rect); void ui_draw_pie_center(uiBlock *block); uiWidgetColors *ui_tooltip_get_theme(void); + +void ui_draw_widget_back_color( + uiWidgetTypeEnum type, bool use_shadow, const rcti *rect, + const float color[4]); +void ui_draw_widget_back( + uiWidgetTypeEnum type, bool use_shadow, const rcti *rect); void ui_draw_tooltip_background(uiStyle *UNUSED(style), uiBlock *block, rcti *rect); -void ui_draw_search_back(struct uiStyle *style, uiBlock *block, rcti *rect); extern void ui_draw_but(const struct bContext *C, ARegion *ar, struct uiStyle *style, uiBut *but, rcti *rect); /* theme color init */ @@ -810,6 +815,9 @@ 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); +void ui_but_anim_decorate_cb(struct bContext *C, void *arg_but, void *arg_dummy); +void ui_but_anim_decorate_update_from_flag(uiBut *but); + /* interface_eyedropper.c */ struct wmKeyMap *eyedropper_modal_keymap(struct wmKeyConfig *keyconf); struct wmKeyMap *eyedropper_colorband_modal_keymap(struct wmKeyConfig *keyconf); diff --git a/source/blender/editors/interface/interface_layout.c b/source/blender/editors/interface/interface_layout.c index 9888c6d65cc..3784ab635be 100644 --- a/source/blender/editors/interface/interface_layout.c +++ b/source/blender/editors/interface/interface_layout.c @@ -50,6 +50,7 @@ #include "BKE_global.h" #include "BKE_idprop.h" #include "BKE_screen.h" +#include "BKE_animsys.h" #include "RNA_access.h" @@ -63,6 +64,10 @@ #include "interface_intern.h" +/* Show an icon button after each RNA button to use to quickly set keyframes, + * this is a way to display animation/driven/override status, see T54951. */ +#define UI_PROP_DECORATE + /************************ Structs and Defines *************************/ #define UI_OPERATOR_ERROR_RET(_ot, _opname, return_statement) \ @@ -132,6 +137,9 @@ enum { UI_ITEM_BOX_ITEM = 1 << 2, /* The item is "inside" a box item */ UI_ITEM_PROP_SEP = 1 << 3, + /* Show an icon button next to each property (to set keyframes, show status). + * Enabled by default, depends on 'UI_ITEM_PROP_SEP'. */ + UI_ITEM_PROP_DECORATE = 1 << 4, }; typedef struct uiButtonItem { @@ -1477,6 +1485,19 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index bool is_array; const bool use_prop_sep = ((layout->item.flag & UI_ITEM_PROP_SEP) != 0); +#ifdef UI_PROP_DECORATE + struct { + bool use_prop_decorate; + int len; + uiLayout *layout; + uiBut *but; + } ui_decorate = { + .use_prop_decorate = ( + ((layout->item.flag & UI_ITEM_PROP_DECORATE) != 0) && + (use_prop_sep && ptr->id.data && id_can_have_animdata(ptr->id.data))), + }; +#endif /* UI_PROP_DECORATE */ + UI_block_layout_set_current(block, layout); /* retrieve info */ @@ -1558,14 +1579,25 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index /* Split the label / property. */ if (use_prop_sep) { + uiLayout *layout_row = NULL; +#ifdef UI_PROP_DECORATE + if (ui_decorate.use_prop_decorate) { + layout_row = uiLayoutRow(layout, true); + layout_row->space = 0; + ui_decorate.len = max_ii(1, len); + } +#endif /* UI_PROP_DECORATE */ + if (name[0] == '\0') { /* Ensure we get a column when text is not set. */ - layout = uiLayoutColumn(layout, true); + layout = uiLayoutColumn(layout_row ? layout_row : layout, true); layout->space = 0; } else { const PropertySubType subtype = RNA_property_subtype(prop); - uiLayout *layout_split = uiLayoutSplit(layout, UI_ITEM_PROP_SEP_DIVIDE, true); + uiLayout *layout_split = uiLayoutSplit( + layout_row ? layout_row : layout, + UI_ITEM_PROP_SEP_DIVIDE, true); layout_split->space = 0; uiLayout *layout_sub = uiLayoutColumn(layout_split, true); layout_sub->space = 0; @@ -1605,8 +1637,22 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index /* Watch out! We can only write into the new column now. */ layout = uiLayoutColumn(layout_split, true); layout->space = 0; - name = ""; + if ((type == PROP_ENUM) && (flag & UI_ITEM_R_EXPAND)) { + /* pass (expanded enums each have their own name) */ + } + else { + name = ""; + } } + +#ifdef UI_PROP_DECORATE + if (ui_decorate.use_prop_decorate) { + ui_decorate.layout = uiLayoutColumn(layout_row, true); + ui_decorate.layout->space = 0; + UI_block_layout_set_current(block, layout); + ui_decorate.but = block->buttons.last; + } +#endif /* UI_PROP_DECORATE */ } /* End split. */ @@ -1655,6 +1701,40 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index UI_but_flag_enable(but, UI_BUT_LIST_ITEM); } +#ifdef UI_PROP_DECORATE + if (ui_decorate.use_prop_decorate) { + const bool is_anim = RNA_property_animateable(ptr, prop); + uiBut *but_decorate = ui_decorate.but ? ui_decorate.but->next : block->buttons.first; + uiLayout *layout_col = uiLayoutColumn(ui_decorate.layout, false); + layout_col->space = 0; + layout_col->emboss = UI_EMBOSS_NONE; + int i; + for (i = 0; i < ui_decorate.len && but_decorate; i++) { + /* The icons are set in 'ui_but_anim_flag' */ + if (is_anim) { + but = uiDefIconBut( + block, UI_BTYPE_BUT, 0, ICON_DOT, 0, 0, UI_UNIT_X, UI_UNIT_Y, + NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Animate property")); + UI_but_func_set(but, ui_but_anim_decorate_cb, but, NULL); + but->flag |= UI_BUT_UNDO | UI_BUT_DRAG_LOCK; + } + else { + /* We may show other information here in future, for now use empty space. */ + but = uiDefIconBut( + block, UI_BTYPE_BUT, 0, ICON_BLANK1, 0, 0, UI_UNIT_X, UI_UNIT_Y, + NULL, 0.0, 0.0, 0.0, 0.0, ""); + but->flag |= UI_BUT_DISABLED; + } + /* Order the decorator after the button we decorate, this is used so we can always + * do a quick lookup. */ + BLI_remlink(&block->buttons, but); + BLI_insertlinkafter(&block->buttons, but_decorate, but); + but_decorate = but->next; + } + BLI_assert(ELEM(i, 1, ui_decorate.len)); + } +#endif /* UI_PROP_DECORATE */ + if (no_bg) { layout->emboss = prev_emboss; } @@ -1811,7 +1891,8 @@ static void search_id_collection(StructRNA *ptype, PointerRNA *ptr, PropertyRNA StructRNA *srna; /* look for collection property in Main */ - RNA_main_pointer_create(G.main, ptr); + /* Note: using global Main is OK-ish here, UI shall not access other Mains anyay... */ + RNA_main_pointer_create(G_MAIN, ptr); *prop = NULL; @@ -1985,12 +2066,15 @@ static uiBut *ui_item_menu( h = UI_UNIT_Y; if (layout->root->type == UI_LAYOUT_HEADER) { /* ugly .. */ - if (force_menu) { - w += UI_UNIT_Y; + if (icon == ICON_NONE && force_menu) { + /* pass */ + } + else if (force_menu) { + w += UI_UNIT_X; } else { if (name[0]) { - w -= UI_UNIT_Y / 2; + w -= UI_UNIT_X / 2; } } } @@ -3014,10 +3098,16 @@ static void ui_litem_grid_flow_compute( const float wfac = (float)(parameters->litem_w - (parameters->tot_columns - 1) * parameters->space_x) / tot_w; for (int col = 0; col < parameters->tot_columns; col++) { - results->cos_x_array[col] = col ? results->cos_x_array[col - 1] + results->widths_array[col - 1] + parameters->space_x : parameters->litem_x; + results->cos_x_array[col] = ( + col ? + results->cos_x_array[col - 1] + results->widths_array[col - 1] + parameters->space_x : + parameters->litem_x + ); if (parameters->even_columns) { - /* (< remaining width > - < space between remaining columns >) / < remaining columns > */ - results->widths_array[col] = ((parameters->litem_w - (results->cos_x_array[col] - parameters->litem_x)) - (parameters->tot_columns - col - 1) * parameters->space_x) / (parameters->tot_columns - col); + /* (< remaining width > - < space between remaining columns >) / < remaining columns > */ + results->widths_array[col] = ( + ((parameters->litem_w - (results->cos_x_array[col] - parameters->litem_x)) - + (parameters->tot_columns - col - 1) * parameters->space_x) / (parameters->tot_columns - col)); } else if (col == parameters->tot_columns - 1) { /* Last column copes width rounding errors... */ @@ -3036,7 +3126,10 @@ static void ui_litem_grid_flow_compute( else { results->heights_array[row] = max_h[row]; } - results->cos_y_array[row] = row ? results->cos_y_array[row - 1] - parameters->space_y - results->heights_array[row] : parameters->litem_y - results->heights_array[row]; + results->cos_y_array[row] = ( + row ? + results->cos_y_array[row - 1] - parameters->space_y - results->heights_array[row] : + parameters->litem_y - results->heights_array[row]); } } @@ -3068,22 +3161,22 @@ static void ui_litem_estimate_grid_flow(uiLayout *litem) int max_h; ui_litem_grid_flow_compute( - &litem->items, - &((UILayoutGridFlowInput) { - .row_major = gflow->row_major, - .even_columns = gflow->even_columns, - .even_rows = gflow->even_rows, - .litem_w = litem->w, - .litem_x = litem->x, - .litem_y = litem->y, - .space_x = space_x, - .space_y = space_y, - }), - &((UILayoutGridFlowOutput) { - .tot_items = &gflow->tot_items, - .global_avg_w = &avg_w, - .global_max_h = &max_h, - })); + &litem->items, + &((UILayoutGridFlowInput) { + .row_major = gflow->row_major, + .even_columns = gflow->even_columns, + .even_rows = gflow->even_rows, + .litem_w = litem->w, + .litem_x = litem->x, + .litem_y = litem->y, + .space_x = space_x, + .space_y = space_y, + }), + &((UILayoutGridFlowOutput) { + .tot_items = &gflow->tot_items, + .global_avg_w = &avg_w, + .global_max_h = &max_h, + })); if (gflow->tot_items == 0) { litem->w = litem->h = 0; @@ -3153,23 +3246,23 @@ static void ui_litem_estimate_grid_flow(uiLayout *litem) int tot_w, tot_h; ui_litem_grid_flow_compute( - &litem->items, - &((UILayoutGridFlowInput) { - .row_major = gflow->row_major, - .even_columns = gflow->even_columns, - .even_rows = gflow->even_rows, - .litem_w = litem->w, - .litem_x = litem->x, - .litem_y = litem->y, - .space_x = space_x, - .space_y = space_y, - .tot_columns = gflow->tot_columns, - .tot_rows = gflow->tot_rows, - }), - &((UILayoutGridFlowOutput) { - .tot_w = &tot_w, - .tot_h = &tot_h, - })); + &litem->items, + &((UILayoutGridFlowInput) { + .row_major = gflow->row_major, + .even_columns = gflow->even_columns, + .even_rows = gflow->even_rows, + .litem_w = litem->w, + .litem_x = litem->x, + .litem_y = litem->y, + .space_x = space_x, + .space_y = space_y, + .tot_columns = gflow->tot_columns, + .tot_rows = gflow->tot_rows, + }), + &((UILayoutGridFlowOutput) { + .tot_w = &tot_w, + .tot_h = &tot_h, + })); litem->w = tot_w; litem->h = tot_h; @@ -3201,25 +3294,25 @@ static void ui_litem_layout_grid_flow(uiLayout *litem) /* This time we directly compute coordinates and sizes of all cells. */ ui_litem_grid_flow_compute( - &litem->items, - &((UILayoutGridFlowInput) { - .row_major = gflow->row_major, - .even_columns = gflow->even_columns, - .even_rows = gflow->even_rows, - .litem_w = litem->w, - .litem_x = litem->x, - .litem_y = litem->y, - .space_x = space_x, - .space_y = space_y, - .tot_columns = gflow->tot_columns, - .tot_rows = gflow->tot_rows, - }), - &((UILayoutGridFlowOutput) { - .cos_x_array = cos_x, - .cos_y_array = cos_y, - .widths_array = widths, - .heights_array = heights, - })); + &litem->items, + &((UILayoutGridFlowInput) { + .row_major = gflow->row_major, + .even_columns = gflow->even_columns, + .even_rows = gflow->even_rows, + .litem_w = litem->w, + .litem_x = litem->x, + .litem_y = litem->y, + .space_x = space_x, + .space_y = space_y, + .tot_columns = gflow->tot_columns, + .tot_rows = gflow->tot_rows, + }), + &((UILayoutGridFlowOutput) { + .cos_x_array = cos_x, + .cos_y_array = cos_y, + .widths_array = widths, + .heights_array = heights, + })); for (item = litem->items.first, i = 0; item; item = item->next, i++) { const int col = gflow->row_major ? i % gflow->tot_columns : i / gflow->tot_rows; @@ -3422,7 +3515,7 @@ static void ui_litem_init_from_parent(uiLayout *litem, uiLayout *layout, int ali litem->redalert = layout->redalert; litem->w = layout->w; litem->emboss = layout->emboss; - litem->item.flag = (layout->item.flag & UI_ITEM_PROP_SEP); + litem->item.flag = (layout->item.flag & (UI_ITEM_PROP_SEP | UI_ITEM_PROP_DECORATE)); BLI_addtail(&layout->items, litem); } @@ -3687,6 +3780,16 @@ void uiLayoutSetPropSep(uiLayout *layout, bool is_sep) SET_FLAG_FROM_TEST(layout->item.flag, is_sep, UI_ITEM_PROP_SEP); } +bool uiLayoutGetPropDecorate(uiLayout *layout) +{ + return (layout->item.flag & UI_ITEM_PROP_DECORATE) != 0; +} + +void uiLayoutSetPropDecorate(uiLayout *layout, bool is_sep) +{ + SET_FLAG_FROM_TEST(layout->item.flag, is_sep, UI_ITEM_PROP_DECORATE); +} + bool uiLayoutGetActive(uiLayout *layout) { return layout->active; @@ -3989,6 +4092,9 @@ uiLayout *UI_block_layout(uiBlock *block, int dir, int type, int x, int y, int s layout = MEM_callocN(sizeof(uiLayout), "uiLayout"); layout->item.type = ITEM_LAYOUT_ROOT; + /* Only used when 'UI_ITEM_PROP_SEP' is set. */ + layout->item.flag = UI_ITEM_PROP_DECORATE; + layout->x = x; layout->y = y; layout->root = root; diff --git a/source/blender/editors/interface/interface_ops.c b/source/blender/editors/interface/interface_ops.c index 6fcede58737..aad48d13277 100644 --- a/source/blender/editors/interface/interface_ops.c +++ b/source/blender/editors/interface/interface_ops.c @@ -1004,6 +1004,7 @@ static int editsource_exec(bContext *C, wmOperator *op) ui_editsource_active_but_set(but); /* redraw and get active button python info */ + ED_region_do_layout(C, ar); ED_region_do_draw(C, ar); ar->do_draw = false; diff --git a/source/blender/editors/interface/interface_panel.c b/source/blender/editors/interface/interface_panel.c index dbdf2a0863c..e383ae42f8c 100644 --- a/source/blender/editors/interface/interface_panel.c +++ b/source/blender/editors/interface/interface_panel.c @@ -110,7 +110,7 @@ typedef struct uiHandlePanelData { int startsizex, startsizey; } uiHandlePanelData; -static int get_panel_real_size_y(Panel *pa); +static int get_panel_real_size_y(const Panel *pa); static void panel_activate_state(const bContext *C, Panel *pa, uiHandlePanelState state); /*********************** space specific code ************************/ @@ -855,7 +855,7 @@ void ui_draw_aligned_panel(uiStyle *style, uiBlock *block, const rcti *rect, con /************************** panel alignment *************************/ -static int get_panel_header(Panel *pa) +static int get_panel_header(const Panel *pa) { if (pa->type && (pa->type->flag & PNL_NO_HEADER)) return 0; @@ -863,7 +863,7 @@ static int get_panel_header(Panel *pa) return PNL_HEADER; } -static int get_panel_size_y(Panel *pa) +static int get_panel_size_y(const Panel *pa) { if (pa->type && (pa->type->flag & PNL_NO_HEADER)) return pa->sizey; @@ -871,7 +871,7 @@ static int get_panel_size_y(Panel *pa) return PNL_HEADER + pa->sizey; } -static int get_panel_real_size_y(Panel *pa) +static int get_panel_real_size_y(const Panel *pa) { int sizey = (pa->flag & PNL_CLOSED) ? 0 : pa->sizey; @@ -881,6 +881,11 @@ static int get_panel_real_size_y(Panel *pa) return PNL_HEADER + sizey; } +int UI_panel_size_y(const Panel *pa) +{ + return get_panel_real_size_y(pa); +} + /* this function is needed because uiBlock and Panel itself don't * change sizey or location when closed */ static int get_panel_real_ofsy(Panel *pa) @@ -1596,6 +1601,10 @@ static void ui_handle_panel_header(const bContext *C, uiBlock *block, int mx, in ED_region_tag_redraw(ar); } else if (show_drag && BLI_rctf_isect_x(&rect_drag, mx)) { + /* XXX, for now don't allow dragging in floating windows yet. */ + if (ar->alignment == RGN_ALIGN_FLOAT) { + return; + } panel_activate_state(C, block->panel, PANEL_STATE_DRAG); } else if (show_pin && BLI_rctf_isect_x(&rect_pin, mx)) { diff --git a/source/blender/editors/interface/interface_region_color_picker.c b/source/blender/editors/interface/interface_region_color_picker.c index 4309e913d9e..00462b456ea 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_hud.c b/source/blender/editors/interface/interface_region_hud.c new file mode 100644 index 00000000000..1a49010ad9d --- /dev/null +++ b/source/blender/editors/interface/interface_region_hud.c @@ -0,0 +1,338 @@ +/* + * ***** 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) 2008 Blender Foundation. + * All rights reserved. + * + * Contributor(s): Blender Foundation + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/editors/interface/interface_region_hud.c + * \ingroup edinterface + * + * Floating Persistent Region + */ + +#include <string.h> + +#include "MEM_guardedalloc.h" + +#include "DNA_userdef_types.h" + +#include "BLI_string.h" +#include "BLI_rect.h" +#include "BLI_listbase.h" +#include "BLI_utildefines.h" + +#include "BKE_context.h" +#include "BKE_screen.h" +#include "BKE_main.h" + +#include "WM_api.h" +#include "WM_types.h" + +#include "RNA_access.h" + +#include "BIF_gl.h" + +#include "UI_interface.h" +#include "UI_view2d.h" + +#include "BLT_translation.h" + +#include "ED_screen.h" +#include "ED_undo.h" + +#include "interface_intern.h" + + +/* -------------------------------------------------------------------- */ +/** \name Utilities + * \{ */ + +static bool last_redo_poll(const bContext *C) +{ + wmOperator *op = WM_operator_last_redo(C); + if (op == NULL) { + return false; + } + bool success = false; + if (WM_operator_repeat_check(C, op) && + WM_operator_check_ui_empty(op->type) == false) + { + success = WM_operator_poll((bContext *)C, op->type); + } + return success; +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Redo Panel + * \{ */ + +static int hud_panel_operator_redo_poll(const bContext *C, PanelType *UNUSED(pt)) +{ + return last_redo_poll(C); +} + +static void hud_panel_operator_redo_draw_header(const bContext *C, Panel *pa) +{ + wmOperator *op = WM_operator_last_redo(C); + BLI_strncpy(pa->drawname, RNA_struct_ui_name(op->type->srna), sizeof(pa->drawname)); +} + +static void hud_panel_operator_redo_draw(const bContext *C, Panel *pa) +{ + wmOperator *op = WM_operator_last_redo(C); + if (op == NULL) { + return; + } + if (!WM_operator_check_ui_enabled(C, op->type->name)) { + uiLayoutSetEnabled(pa->layout, false); + } + uiLayout *col = uiLayoutColumn(pa->layout, false); + uiTemplateOperatorRedoProperties(col, C); +} + +static void hud_panels_register(ARegionType *art, int space_type, int region_type) +{ + PanelType *pt; + + pt = MEM_callocN(sizeof(PanelType), __func__); + strcpy(pt->idname, "OPERATOR_PT_redo"); + strcpy(pt->label, N_("Redo")); + strcpy(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA); + pt->draw_header = hud_panel_operator_redo_draw_header; + pt->draw = hud_panel_operator_redo_draw; + pt->poll = hud_panel_operator_redo_poll; + pt->space_type = space_type; + pt->region_type = region_type; + BLI_addtail(&art->paneltypes, pt); +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Callbacks for Floating Region + * \{ */ + +struct HudRegionData { + short regionid; +}; + +static void hud_region_init(wmWindowManager *wm, ARegion *ar) +{ + ED_region_panels_init(wm, ar); + UI_region_handlers_add(&ar->handlers); + ar->flag |= RGN_FLAG_TEMP_REGIONDATA; +} + +static void hud_region_free(ARegion *ar) +{ + MEM_SAFE_FREE(ar->regiondata); +} + +static void hud_region_layout(const bContext *C, ARegion *ar) +{ + bool ok = false; + + { + struct HudRegionData *hrd = ar->regiondata; + if (hrd != NULL) { + ScrArea *sa = CTX_wm_area(C); + ARegion *ar_op = (hrd->regionid != -1) ? BKE_area_find_region_type(sa, hrd->regionid) : NULL; + ARegion *ar_prev = CTX_wm_region(C); + CTX_wm_region_set((bContext *)C, ar_op); + ok = last_redo_poll(C); + CTX_wm_region_set((bContext *)C, ar_prev); + } + } + + if (!ok) { + ED_region_tag_redraw(ar); + ar->flag |= RGN_FLAG_HIDDEN; + return; + } + + int size_y = ar->sizey; + + ED_region_panels_layout(C, ar); + + if (ar->panels.first && (ar->sizey != size_y)) { + View2D *v2d = &ar->v2d; + ar->winx = ar->sizex; + ar->winy = ar->sizey; + + ar->winrct.xmax = (ar->winrct.xmin + ar->winx) - 1; + ar->winrct.ymax = (ar->winrct.ymin + ar->winy) - 1; + + UI_view2d_region_reinit(v2d, V2D_COMMONVIEW_PANELS_UI, ar->winx, ar->winy); + } + + /* restore view matrix */ + UI_view2d_view_restore(C); +} + +static void hud_region_draw(const bContext *C, ARegion *ar) +{ + UI_view2d_view_ortho(&ar->v2d); + wmOrtho2_region_pixelspace(ar); + glClearColor(0, 0, 0, 0.0f); + glClear(GL_COLOR_BUFFER_BIT); + + if ((ar->flag & RGN_FLAG_HIDDEN) == 0) { + float color[4]; + UI_GetThemeColor4fv(TH_BUTBACK, color); + if ((U.uiflag2 & USER_REGION_OVERLAP) == 0) { + color[3] = 1.0f; + } + ui_draw_widget_back_color(UI_WTYPE_BOX, false, &(rcti){.xmax = ar->winx, .ymax = ar->winy}, color); + ED_region_panels_draw(C, ar); + } +} + +ARegionType *ED_area_type_hud(int space_type) +{ + ARegionType *art = MEM_callocN(sizeof(ARegionType), __func__); + art->regionid = RGN_TYPE_HUD; + art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D; + art->layout = hud_region_layout; + art->draw = hud_region_draw; + art->init = hud_region_init; + art->free = hud_region_free; + + hud_panels_register(art, space_type, art->regionid); + + art->lock = 1; /* can become flag, see BKE_spacedata_draw_locks */ + return art; +} + +static ARegion *hud_region_add(ScrArea *sa) +{ + ARegion *ar = MEM_callocN(sizeof(ARegion), "area region"); + ARegion *ar_win = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW); + if (ar_win) { + BLI_insertlinkbefore(&sa->regionbase, ar_win, ar); + } + else { + BLI_addtail(&sa->regionbase, ar); + } + ar->regiontype = RGN_TYPE_HUD; + ar->alignment = RGN_ALIGN_FLOAT; + ar->overlap = true; + ar->flag |= RGN_FLAG_DYNAMIC_SIZE; + + return ar; +} + +void ED_area_type_hud_clear(wmWindowManager *wm, ScrArea *sa_keep) +{ + for (wmWindow *win = wm->windows.first; win; win = win->next) { + bScreen *screen = WM_window_get_active_screen(win); + for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) { + if (sa != sa_keep) { + for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) { + if (ar->regiontype == RGN_TYPE_HUD) { + if ((ar->flag & RGN_FLAG_HIDDEN) == 0) { + ar->flag |= RGN_FLAG_HIDDEN; + ED_region_tag_redraw(ar); + ED_area_tag_redraw(sa); + } + } + } + } + } + } +} + +void ED_area_type_hud_ensure(bContext *C, ScrArea *sa) +{ + wmWindowManager *wm = CTX_wm_manager(C); + ED_area_type_hud_clear(wm, sa); + + ARegionType *art = BKE_regiontype_from_id(sa->type, RGN_TYPE_HUD); + if (art == NULL) { + return; + } + + bool init = false; + ARegion *ar = BKE_area_find_region_type(sa, RGN_TYPE_HUD); + if (!last_redo_poll(C)) { + if (ar) { + ED_region_tag_redraw(ar); + ar->flag |= RGN_FLAG_HIDDEN; + } + return; + } + + if (ar == NULL) { + init = true; + ar = hud_region_add(sa); + ar->type = art; + } + + ED_region_init(ar); + ED_region_tag_redraw(ar); + + /* Reset zoom level (not well supported). */ + ar->v2d.cur = ar->v2d.tot = (rctf){.xmax = ar->winx, .ymax = ar->winy}; + ar->v2d.minzoom = 1.0f; + ar->v2d.maxzoom = 1.0f; + + /* Let 'ED_area_update_region_sizes' do the work of placing the region. + * Otherwise we could set the 'ar->winrct' & 'ar->winx/winy' here. */ + if (init) { + sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE; + } + else { + if (ar->flag & RGN_FLAG_HIDDEN) { + sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE; + } + ar->flag &= ~RGN_FLAG_HIDDEN; + } + + { + ARegion *ar_op = CTX_wm_region(C); + BLI_assert((ar_op == NULL) || (ar_op->regiontype != RGN_TYPE_HUD)); + struct HudRegionData *hrd = ar->regiondata; + if (hrd == NULL) { + hrd = MEM_callocN(sizeof(*hrd), __func__); + ar->regiondata = hrd; + } + if (ar_op) { + hrd->regionid = ar_op->regiontype; + } + else { + hrd->regionid = -1; + } + } + + /* XXX, should be handled in more general way. */ + ar->visible = !((ar->flag & RGN_FLAG_HIDDEN) || (ar->flag & RGN_FLAG_TOO_SMALL)); + + /* We shouldn't need to do this every time :S */ + /* XXX, this is evil! - it also makes the menu show on first draw. :( */ + ARegion *ar_prev = CTX_wm_region(C); + CTX_wm_region_set((bContext *)C, ar); + hud_region_layout(C, ar); + CTX_wm_region_set((bContext *)C, ar_prev); +} + +/** \} */ diff --git a/source/blender/editors/interface/interface_region_popover.c b/source/blender/editors/interface/interface_region_popover.c index e769d367b45..fb14ca745c6 100644 --- a/source/blender/editors/interface/interface_region_popover.c +++ b/source/blender/editors/interface/interface_region_popover.c @@ -168,11 +168,17 @@ static uiBlock *ui_block_func_POPOVER(bContext *C, uiPopupBlockHandle *handle, v block->my = handle->prev_my; } - /* Prefer popover from header to be positioned into the editor. */ if (!slideout) { ScrArea *sa = CTX_wm_area(C); - if (sa && ED_area_header_alignment(sa) == RGN_ALIGN_BOTTOM) { - ARegion *ar = CTX_wm_region(C); + ARegion *ar = CTX_wm_region(C); + + if (ar && ar->panels.first) { + /* For regions with panels, prefer to open to top so we can + * see the values of the buttons below changing. */ + UI_block_direction_set(block, UI_DIR_UP | UI_DIR_CENTER_X); + } + else if (sa && ED_area_header_alignment(sa) == RGN_ALIGN_BOTTOM) { + /* Prefer popover from header to be positioned into the editor. */ if (ar && ar->regiontype == RGN_TYPE_HEADER) { UI_block_direction_set(block, UI_DIR_UP | UI_DIR_CENTER_X); } diff --git a/source/blender/editors/interface/interface_region_popup.c b/source/blender/editors/interface/interface_region_popup.c index 654dc5e4d30..0ac4d4d28ec 100644 --- a/source/blender/editors/interface/interface_region_popup.c +++ b/source/blender/editors/interface/interface_region_popup.c @@ -63,13 +63,13 @@ /** * Translate any popup regions (so we can drag them). */ -void ui_popup_translate(bContext *C, ARegion *ar, const int mdiff[2]) +void ui_popup_translate(ARegion *ar, const int mdiff[2]) { uiBlock *block; BLI_rcti_translate(&ar->winrct, UNPACK2(mdiff)); - ED_region_update_rect(C, ar); + ED_region_update_rect(ar); ED_region_tag_redraw(ar); @@ -625,7 +625,7 @@ uiBlock *ui_popup_block_refresh( ui_popup_block_scrolltest(block); /* adds subwindow */ - ED_region_init(C, ar); + ED_region_init(ar); /* get winmat now that we actually have the subwindow */ wmGetProjectionMatrix(block->winmat, &ar->winrct); @@ -633,7 +633,7 @@ uiBlock *ui_popup_block_refresh( /* notify change and redraw */ ED_region_tag_redraw(ar); - ED_region_update_rect(C, ar); + ED_region_update_rect(ar); #ifdef DEBUG window->eventstate = event_back; diff --git a/source/blender/editors/interface/interface_region_search.c b/source/blender/editors/interface/interface_region_search.c index f14f9af8785..e0dc149be17 100644 --- a/source/blender/editors/interface/interface_region_search.c +++ b/source/blender/editors/interface/interface_region_search.c @@ -404,8 +404,9 @@ static void ui_searchbox_region_draw_cb(const bContext *C, ARegion *ar) /* pixel space */ wmOrtho2_region_pixelspace(ar); - if (data->noback == false) - ui_draw_search_back(NULL, NULL, &data->bbox); /* style not used yet */ + if (data->noback == false) { + ui_draw_widget_back(UI_WTYPE_BOX, true, &data->bbox); + } /* draw text */ if (data->items.totitem) { @@ -625,7 +626,7 @@ ARegion *ui_searchbox_create_generic(bContext *C, ARegion *butregion, uiBut *but } /* adds subwindow */ - ED_region_init(C, ar); + ED_region_init(ar); /* notify change and redraw */ ED_region_tag_redraw(ar); @@ -681,8 +682,9 @@ static void ui_searchbox_region_draw_cb__operator(const bContext *UNUSED(C), ARe /* pixel space */ wmOrtho2_region_pixelspace(ar); - if (data->noback == false) - ui_draw_search_back(NULL, NULL, &data->bbox); /* style not used yet */ + if (data->noback == false) { + ui_draw_widget_back(UI_WTYPE_BOX, true, &data->bbox); + } /* draw text */ if (data->items.totitem) { diff --git a/source/blender/editors/interface/interface_region_tooltip.c b/source/blender/editors/interface/interface_region_tooltip.c index aa8fe173638..ed83a715c7e 100644 --- a/source/blender/editors/interface/interface_region_tooltip.c +++ b/source/blender/editors/interface/interface_region_tooltip.c @@ -867,7 +867,7 @@ static ARegion *ui_tooltip_create_with_data( } /* adds subwindow */ - ED_region_init(C, ar); + ED_region_init(ar); /* notify change and redraw */ ED_region_tag_redraw(ar); diff --git a/source/blender/editors/interface/interface_templates.c b/source/blender/editors/interface/interface_templates.c index 9978726fa74..59cb2229905 100644 --- a/source/blender/editors/interface/interface_templates.c +++ b/source/blender/editors/interface/interface_templates.c @@ -500,6 +500,7 @@ static void template_id_cb(bContext *C, void *arg_litem, void *arg_event) Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); ED_object_single_user(bmain, scene, (struct Object *)id); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); DEG_relations_tag_update(bmain); } @@ -1578,12 +1579,16 @@ void uiTemplateOperatorRedoProperties(uiLayout *layout, const bContext *C) #endif if (WM_operator_repeat_check(C, op)) { + int layout_flags = 0; + if (block->panel == NULL) { + layout_flags = UI_TEMPLATE_OP_PROPS_SHOW_TITLE; + } #if 0 bool has_advanced = false; #endif UI_block_func_set(block, ED_undo_operator_repeat_cb, op, NULL); - template_operator_redo_property_buts_draw(C, op, layout, UI_TEMPLATE_OP_PROPS_COMPACT, NULL /* &has_advanced */ ); + template_operator_redo_property_buts_draw(C, op, layout, layout_flags, NULL /* &has_advanced */ ); UI_block_func_set(block, NULL, NULL, NULL); /* may want to reset to old state instead of NULLing all */ #if 0 @@ -1743,7 +1748,7 @@ static uiLayout *draw_constraint(uiLayout *layout, Object *ob, bConstraint *con) /* enabled */ UI_block_emboss_set(block, UI_EMBOSS_NONE); uiItemR(row, &ptr, "mute", 0, "", - (con->flag & CONSTRAINT_OFF) ? ICON_RESTRICT_VIEW_ON : ICON_RESTRICT_VIEW_OFF); + (con->flag & CONSTRAINT_OFF) ? ICON_HIDE_ON : ICON_HIDE_OFF); UI_block_emboss_set(block, UI_EMBOSS); uiLayoutSetOperatorContext(row, WM_OP_INVOKE_DEFAULT); @@ -2180,6 +2185,19 @@ void uiTemplateColorRamp(uiLayout *layout, PointerRNA *ptr, const char *propname MEM_freeN(cb); } +/********************* Icon Template ************************/ +/** + * \param icon_scale: Scale of the icon, 1x == button height. + */ +void uiTemplateIcon(uiLayout *layout, int icon_value, float icon_scale) +{ + uiBlock *block; + uiBut *but; + + block = uiLayoutAbsoluteBlock(layout); + but = uiDefIconBut(block, UI_BTYPE_LABEL, 0, ICON_X, 0, 0, UI_UNIT_X * icon_scale, UI_UNIT_Y * icon_scale, NULL, 0.0, 0.0, 0.0, 0.0, ""); + ui_def_but_icon(but, icon_value, UI_HAS_ICON | UI_BUT_ICON_PREVIEW); +} /********************* Icon viewer Template ************************/ typedef struct IconViewMenuArgs { @@ -2266,13 +2284,20 @@ void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname, value = RNA_property_enum_get(ptr, prop); RNA_enum_icon_from_value(items, value, &icon); - cb_args = MEM_callocN(sizeof(IconViewMenuArgs), __func__); - cb_args->ptr = *ptr; - cb_args->prop = prop; - cb_args->show_labels = show_labels; - cb_args->icon_scale = icon_scale; - but = uiDefBlockButN(block, ui_icon_view_menu_cb, cb_args, "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, ""); + if (RNA_property_editable(ptr, prop)) { + cb_args = MEM_callocN(sizeof(IconViewMenuArgs), __func__); + cb_args->ptr = *ptr; + cb_args->prop = prop; + cb_args->show_labels = show_labels; + cb_args->icon_scale = icon_scale; + + but = uiDefBlockButN(block, ui_icon_view_menu_cb, cb_args, "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, ""); + } + else { + but = uiDefIconBut(block, UI_BTYPE_LABEL, 0, ICON_X, 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, NULL, 0.0, 0.0, 0.0, 0.0, ""); + } + ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW); @@ -3945,6 +3970,8 @@ eAutoPropButsReturn uiTemplateOperatorPropertyButs( RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); + uiLayoutSetPropSep(layout, true); + /* main draw call */ return_info = uiDefAutoButsRNA(layout, &ptr, check_prop, label_align, (flag & UI_TEMPLATE_OP_PROPS_COMPACT)); diff --git a/source/blender/editors/interface/interface_widgets.c b/source/blender/editors/interface/interface_widgets.c index ac8d900f560..3b7ccb68fd4 100644 --- a/source/blender/editors/interface/interface_widgets.c +++ b/source/blender/editors/interface/interface_widgets.c @@ -230,16 +230,16 @@ static const uint g_shape_preset_hold_action_face[2][3] = {{2, 0, 1}, {3, 5, 4}} static const int tria_ofs[ROUNDBOX_TRIA_MAX] = { [ROUNDBOX_TRIA_NONE] = 0, [ROUNDBOX_TRIA_ARROWS] = 0, - [ROUNDBOX_TRIA_SCROLL] = 6, - [ROUNDBOX_TRIA_MENU] = 22, - [ROUNDBOX_TRIA_CHECK] = 28, - [ROUNDBOX_TRIA_HOLD_ACTION_ARROW] = 34, + [ROUNDBOX_TRIA_SCROLL] = 12, + [ROUNDBOX_TRIA_MENU] = 28, + [ROUNDBOX_TRIA_CHECK] = 34, + [ROUNDBOX_TRIA_HOLD_ACTION_ARROW] = 40, }; static const int tria_vcount[ROUNDBOX_TRIA_MAX] = { [ROUNDBOX_TRIA_NONE] = 0, - [ROUNDBOX_TRIA_ARROWS] = 3, + [ROUNDBOX_TRIA_ARROWS] = 6, [ROUNDBOX_TRIA_SCROLL] = 16, - [ROUNDBOX_TRIA_MENU] = 3, + [ROUNDBOX_TRIA_MENU] = 6, [ROUNDBOX_TRIA_CHECK] = 6, [ROUNDBOX_TRIA_HOLD_ACTION_ARROW] = 3, }; @@ -296,8 +296,8 @@ static uint32_t set_tria_vertex( int tria_type, int tria_v, int tria_id, int jit_v) { uint32_t *data = GWN_vertbuf_raw_step(vflag_step); - if (ELEM(tria_type, ROUNDBOX_TRIA_ARROWS, ROUNDBOX_TRIA_MENU)) { - tria_v += tria_id * 3; + if (ELEM(tria_type, ROUNDBOX_TRIA_ARROWS)) { + tria_v += tria_id * tria_vcount[ROUNDBOX_TRIA_ARROWS]; } *data = tria_ofs[tria_type] + tria_v; *data |= jit_v << 6; @@ -308,7 +308,7 @@ static uint32_t set_tria_vertex( static void roundbox_batch_add_tria(Gwn_VertBufRaw *vflag_step, int tria, uint32_t last_data) { - const int tria_num = ELEM(tria, ROUNDBOX_TRIA_CHECK, ROUNDBOX_TRIA_HOLD_ACTION_ARROW) ? 1 : 2; + const int tria_num = ELEM(tria, ROUNDBOX_TRIA_CHECK, ROUNDBOX_TRIA_HOLD_ACTION_ARROW, ROUNDBOX_TRIA_MENU) ? 1 : 2; /* for each tria */ for (int t = 0; t < tria_num; ++t) { for (int j = 0; j < WIDGET_AA_JITTER; j++) { @@ -335,7 +335,7 @@ Gwn_Batch *ui_batch_roundbox_widget_get(int tria) vcount += ((WIDGET_CURVE_RESOLU * 2) * 2) * WIDGET_AA_JITTER; /* emboss */ if (tria) { vcount += (tria_vcount[tria] + 2) * WIDGET_AA_JITTER; /* tria1 */ - if (!ELEM(tria, ROUNDBOX_TRIA_CHECK, ROUNDBOX_TRIA_HOLD_ACTION_ARROW)) { + if (!ELEM(tria, ROUNDBOX_TRIA_CHECK, ROUNDBOX_TRIA_HOLD_ACTION_ARROW, ROUNDBOX_TRIA_MENU)) { vcount += (tria_vcount[tria] + 2) * WIDGET_AA_JITTER; /* tria2 */ } } @@ -2657,18 +2657,22 @@ static void widget_state_pie_menu_item(uiWidgetType *wt, int state) copy_v4_v4_char(wt->wcol.inner, wt->wcol.item); wt->wcol.inner[3] = 64; } - /* regular disabled */ - else if (state & (UI_BUT_DISABLED | UI_BUT_INACTIVE)) { - widget_state_blend(wt->wcol.text, wt->wcol.inner, 0.5f); - } - /* regular active */ - else if (state & UI_SELECT) { - copy_v4_v4_char(wt->wcol.outline, wt->wcol.inner_sel); - copy_v3_v3_char(wt->wcol.text, wt->wcol.text_sel); - } - else if (state & UI_ACTIVE) { - copy_v4_v4_char(wt->wcol.inner, wt->wcol.item); - copy_v3_v3_char(wt->wcol.text, wt->wcol.text_sel); + else { + /* regular active */ + if (state & (UI_SELECT | UI_ACTIVE)) { + copy_v3_v3_char(wt->wcol.text, wt->wcol.text_sel); + } + else if (state & (UI_BUT_DISABLED | UI_BUT_INACTIVE)) { + /* regular disabled */ + widget_state_blend(wt->wcol.text, wt->wcol.inner, 0.5f); + } + + if (state & UI_SELECT) { + copy_v4_v4_char(wt->wcol.outline, wt->wcol.inner_sel); + } + else if (state & UI_ACTIVE) { + copy_v4_v4_char(wt->wcol.inner, wt->wcol.item); + } } } @@ -2685,14 +2689,19 @@ static void widget_state_menu_item(uiWidgetType *wt, int state) copy_v4_v4_char(wt->wcol.inner, wt->wcol.inner_sel); wt->wcol.inner[3] = 64; } - /* regular disabled */ - else if (state & (UI_BUT_DISABLED | UI_BUT_INACTIVE)) { - widget_state_blend(wt->wcol.text, wt->wcol.inner, 0.5f); - } - /* regular active */ - else if (state & UI_ACTIVE) { - copy_v4_v4_char(wt->wcol.inner, wt->wcol.inner_sel); - copy_v3_v3_char(wt->wcol.text, wt->wcol.text_sel); + else { + /* regular active */ + if (state & UI_ACTIVE) { + copy_v3_v3_char(wt->wcol.text, wt->wcol.text_sel); + } + else if (state & (UI_BUT_DISABLED | UI_BUT_INACTIVE)) { + /* regular disabled */ + widget_state_blend(wt->wcol.text, wt->wcol.inner, 0.5f); + } + + if (state & UI_ACTIVE) { + copy_v4_v4_char(wt->wcol.inner, wt->wcol.inner_sel); + } } } @@ -2825,7 +2834,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; } @@ -4916,30 +4925,41 @@ uiWidgetColors *ui_tooltip_get_theme(void) return wt->wcol_theme; } -void ui_draw_tooltip_background(uiStyle *UNUSED(style), uiBlock *UNUSED(block), rcti *rect) +/** + * Generic drawing for background. + */ +void ui_draw_widget_back_color( + uiWidgetTypeEnum type, bool use_shadow, const rcti *rect, + const float color[4]) { - uiWidgetType *wt = widget_type(UI_WTYPE_TOOLTIP); + uiWidgetType *wt = widget_type(type); + + if (use_shadow) { + glEnable(GL_BLEND); + widget_softshadow(rect, UI_CNR_ALL, 0.25f * U.widget_unit); + glDisable(GL_BLEND); + } + + rcti rect_copy = *rect; wt->state(wt, 0); - /* wt->draw ends up using same function to draw the tooltip as menu_back */ - wt->draw(&wt->wcol, rect, 0, 0); + if (color) { + rgba_float_to_uchar((unsigned char *)wt->wcol.inner, color); + } + wt->draw(&wt->wcol, &rect_copy, 0, UI_CNR_ALL); } - -void ui_draw_search_back(uiStyle *UNUSED(style), uiBlock *block, rcti *rect) +void ui_draw_widget_back(uiWidgetTypeEnum type, bool use_shadow, const rcti *rect) { - uiWidgetType *wt = widget_type(UI_WTYPE_BOX); - - glEnable(GL_BLEND); - widget_softshadow(rect, UI_CNR_ALL, 0.25f * U.widget_unit); - glDisable(GL_BLEND); + ui_draw_widget_back_color(type, use_shadow, rect, NULL); +} +void ui_draw_tooltip_background(uiStyle *UNUSED(style), uiBlock *UNUSED(block), rcti *rect) +{ + uiWidgetType *wt = widget_type(UI_WTYPE_TOOLTIP); wt->state(wt, 0); - if (block) - wt->draw(&wt->wcol, rect, block->flag, UI_CNR_ALL); - else - wt->draw(&wt->wcol, rect, 0, UI_CNR_ALL); + /* wt->draw ends up using same function to draw the tooltip as menu_back */ + wt->draw(&wt->wcol, rect, 0, 0); } - /* helper call to draw a menu item without button */ /* state: UI_ACTIVE or 0 */ void ui_draw_menu_item(uiFontStyle *fstyle, rcti *rect, const char *name, int iconid, int state, bool use_sep) diff --git a/source/blender/editors/interface/resources.c b/source/blender/editors/interface/resources.c index 2a61be21589..8bd41b874f5 100644 --- a/source/blender/editors/interface/resources.c +++ b/source/blender/editors/interface/resources.c @@ -3031,6 +3031,7 @@ void init_userdef_do_versions(Main *bmain) rgba_char_args_set(ts->panelcolors.sub_back, 0, 0, 0, 25); } } + U.gpu_viewport_antialias = USER_AA_FXAA; } /** diff --git a/source/blender/editors/interface/view2d_ops.c b/source/blender/editors/interface/view2d_ops.c index fbc8fe790c9..b9e6d43aa87 100644 --- a/source/blender/editors/interface/view2d_ops.c +++ b/source/blender/editors/interface/view2d_ops.c @@ -1123,7 +1123,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); diff --git a/source/blender/editors/io/io_alembic.c b/source/blender/editors/io/io_alembic.c index 4440b99f211..91fc1e9fe6a 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 b13eaced843..221142a6cf8 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 aca380c3123..8f05495bb7f 100644 --- a/source/blender/editors/io/io_collada.c +++ b/source/blender/editors/io/io_collada.c @@ -72,7 +72,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); } @@ -119,7 +119,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 */ @@ -337,8 +337,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_select.c b/source/blender/editors/lattice/editlattice_select.c index 2ba1dde243b..6f1c864130d 100644 --- a/source/blender/editors/lattice/editlattice_select.c +++ b/source/blender/editors/lattice/editlattice_select.c @@ -59,6 +59,8 @@ #include "WM_api.h" #include "WM_types.h" +#include "DEG_depsgraph.h" + #include "lattice_intern.h" /* -------------------------------------------------------------------- */ @@ -118,6 +120,7 @@ static int lattice_select_random_exec(bContext *C, wmOperator *op) BLI_rng_free(rng); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -209,6 +212,7 @@ static int lattice_select_mirror_exec(bContext *C, wmOperator *op) } /* TODO, only notify changes */ + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); @@ -295,6 +299,7 @@ static int lattice_select_more_less(bContext *C, const bool select) MEM_freeN(selpoints); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; } @@ -411,6 +416,7 @@ static int lattice_select_all_exec(bContext *C, wmOperator *op) } break; } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); @@ -470,6 +476,7 @@ static int lattice_select_ungrouped_exec(bContext *C, wmOperator *op) } } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -568,6 +575,7 @@ bool ED_lattice_select_pick(bContext *C, const int mval[2], bool extend, bool de lt->actbp = LT_ACTBP_NONE; } + DEG_id_tag_update(vc.obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data); return true; diff --git a/source/blender/editors/manipulator_library/manipulator_types/arrow3d_manipulator.c b/source/blender/editors/manipulator_library/manipulator_types/arrow3d_manipulator.c index 409a2c3ca83..8516b9d8244 100644 --- a/source/blender/editors/manipulator_library/manipulator_types/arrow3d_manipulator.c +++ b/source/blender/editors/manipulator_library/manipulator_types/arrow3d_manipulator.c @@ -92,6 +92,7 @@ static void arrow_draw_geom(const ArrowManipulator3D *arrow, const bool select, uint pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT); bool unbind_shader = true; const int draw_style = RNA_enum_get(arrow->manipulator.ptr, "draw_style"); + const int draw_options = RNA_enum_get(arrow->manipulator.ptr, "draw_options"); immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR); @@ -131,9 +132,13 @@ static void arrow_draw_geom(const ArrowManipulator3D *arrow, const bool select, {0.0f, 0.0f, arrow_length}, }; - glLineWidth(arrow->manipulator.line_width); - wm_manipulator_vec_draw(color, vec, ARRAY_SIZE(vec), pos, GWN_PRIM_LINE_STRIP); - + if (draw_options & ED_MANIPULATOR_ARROW_DRAW_FLAG_STEM) { + glLineWidth(arrow->manipulator.line_width); + wm_manipulator_vec_draw(color, vec, ARRAY_SIZE(vec), pos, GWN_PRIM_LINE_STRIP); + } + else { + immUniformColor4fv(color); + } /* *** draw arrow head *** */ @@ -303,9 +308,9 @@ static int manipulator_arrow_modal( /* set the property for the operator and call its modal function */ if (WM_manipulator_target_property_is_valid(mpr_prop)) { - const int draw_options = RNA_enum_get(arrow->manipulator.ptr, "draw_options"); - const bool constrained = (draw_options & ED_MANIPULATOR_ARROW_STYLE_CONSTRAINED) != 0; - const bool inverted = (draw_options & ED_MANIPULATOR_ARROW_STYLE_INVERTED) != 0; + const int transform_flag = RNA_enum_get(arrow->manipulator.ptr, "transform"); + const bool constrained = (transform_flag & ED_MANIPULATOR_ARROW_XFORM_FLAG_CONSTRAINED) != 0; + const bool inverted = (transform_flag & ED_MANIPULATOR_ARROW_XFORM_FLAG_INVERTED) != 0; const bool use_precision = (tweak_flag & WM_MANIPULATOR_TWEAK_PRECISE) != 0; float value = manipulator_value_from_offset(data, inter, ofs_new, constrained, inverted, use_precision); @@ -363,9 +368,9 @@ static int manipulator_arrow_invoke( static void manipulator_arrow_property_update(wmManipulator *mpr, wmManipulatorProperty *mpr_prop) { ArrowManipulator3D *arrow = (ArrowManipulator3D *)mpr; - const int draw_options = RNA_enum_get(arrow->manipulator.ptr, "draw_options"); - const bool constrained = (draw_options & ED_MANIPULATOR_ARROW_STYLE_CONSTRAINED) != 0; - const bool inverted = (draw_options & ED_MANIPULATOR_ARROW_STYLE_INVERTED) != 0; + const int transform_flag = RNA_enum_get(arrow->manipulator.ptr, "transform"); + const bool constrained = (transform_flag & ED_MANIPULATOR_ARROW_XFORM_FLAG_CONSTRAINED) != 0; + const bool inverted = (transform_flag & ED_MANIPULATOR_ARROW_XFORM_FLAG_INVERTED) != 0; manipulator_property_data_update(mpr, &arrow->data, mpr_prop, constrained, inverted); } @@ -448,21 +453,35 @@ static void MANIPULATOR_WT_arrow_3d(wmManipulatorType *wt) wt->struct_size = sizeof(ArrowManipulator3D); /* rna */ - static EnumPropertyItem rna_enum_draw_style[] = { + static EnumPropertyItem rna_enum_draw_style_items[] = { {ED_MANIPULATOR_ARROW_STYLE_NORMAL, "NORMAL", 0, "Normal", ""}, {ED_MANIPULATOR_ARROW_STYLE_CROSS, "CROSS", 0, "Cross", ""}, {ED_MANIPULATOR_ARROW_STYLE_BOX, "BOX", 0, "Box", ""}, {ED_MANIPULATOR_ARROW_STYLE_CONE, "CONE", 0, "Cone", ""}, {0, NULL, 0, NULL, NULL} }; - static EnumPropertyItem rna_enum_draw_options[] = { - {ED_MANIPULATOR_ARROW_STYLE_INVERTED, "INVERT", 0, "Inverted", ""}, - {ED_MANIPULATOR_ARROW_STYLE_CONSTRAINED, "CONSTRAIN", 0, "Constrained", ""}, + static EnumPropertyItem rna_enum_draw_options_items[] = { + {ED_MANIPULATOR_ARROW_DRAW_FLAG_STEM, "STEM", 0, "Stem", ""}, + {0, NULL, 0, NULL, NULL} + }; + static EnumPropertyItem rna_enum_transform_items[] = { + {ED_MANIPULATOR_ARROW_XFORM_FLAG_INVERTED, "INVERT", 0, "Inverted", ""}, + {ED_MANIPULATOR_ARROW_XFORM_FLAG_CONSTRAINED, "CONSTRAIN", 0, "Constrained", ""}, {0, NULL, 0, NULL, NULL} }; - RNA_def_enum(wt->srna, "draw_style", rna_enum_draw_style, ED_MANIPULATOR_ARROW_STYLE_NORMAL, "Draw Style", ""); - RNA_def_enum_flag(wt->srna, "draw_options", rna_enum_draw_options, 0, "Draw Options", ""); + RNA_def_enum( + wt->srna, "draw_style", rna_enum_draw_style_items, + ED_MANIPULATOR_ARROW_STYLE_NORMAL, + "Draw Style", ""); + RNA_def_enum_flag( + wt->srna, "draw_options", rna_enum_draw_options_items, + ED_MANIPULATOR_ARROW_DRAW_FLAG_STEM, + "Draw Options", ""); + RNA_def_enum_flag( + wt->srna, "transform", rna_enum_transform_items, + 0, + "Transform", ""); RNA_def_float(wt->srna, "length", 1.0f, 0.0f, FLT_MAX, "Arrow Line Length", "", 0.0f, FLT_MAX); RNA_def_float_vector(wt->srna, "aspect", 2, NULL, 0, FLT_MAX, "Aspect", "Cone/box style only", 0.0f, FLT_MAX); diff --git a/source/blender/editors/manipulator_library/manipulator_types/dial3d_manipulator.c b/source/blender/editors/manipulator_library/manipulator_types/dial3d_manipulator.c index a3034597f56..643a379cbb0 100644 --- a/source/blender/editors/manipulator_library/manipulator_types/dial3d_manipulator.c +++ b/source/blender/editors/manipulator_library/manipulator_types/dial3d_manipulator.c @@ -94,6 +94,9 @@ typedef struct DialInteraction { #define DIAL_WIDTH 1.0f #define DIAL_RESOLUTION 48 +/* Could make option, negative to clip more (don't show when view aligned). */ +#define DIAL_CLIP_BIAS 0.02 + /** * We can't use this for the #wmManipulatorType.matrix_basis_get callback, it conflicts with depth picking. */ @@ -347,6 +350,7 @@ static void manipulator_dial_draw_select(const bContext *C, wmManipulator *mpr, copy_v3_v3(clip_plane, rv3d->viewinv[2]); clip_plane[3] = -dot_v3v3(rv3d->viewinv[2], mpr->matrix_basis[3]); + clip_plane[3] += DIAL_CLIP_BIAS * mpr->scale_final; glEnable(GL_CLIP_DISTANCE0); } @@ -373,7 +377,7 @@ static void manipulator_dial_draw(const bContext *C, wmManipulator *mpr) copy_v3_v3(clip_plane, rv3d->viewinv[2]); clip_plane[3] = -dot_v3v3(rv3d->viewinv[2], mpr->matrix_basis[3]); - clip_plane[3] -= 0.02f * mpr->scale_final; + clip_plane[3] += DIAL_CLIP_BIAS * mpr->scale_final; glEnable(GL_CLIP_DISTANCE0); } diff --git a/source/blender/editors/mesh/editface.c b/source/blender/editors/mesh/editface.c index 7e31b6a3774..cf4d8ebf05d 100644 --- a/source/blender/editors/mesh/editface.c +++ b/source/blender/editors/mesh/editface.c @@ -52,6 +52,8 @@ #include "GPU_draw.h" +#include "DEG_depsgraph.h" + /* own include */ /* copy the face flags, most importantly selection from the mesh to the final derived mesh, @@ -382,6 +384,7 @@ bool paintface_mouse_select(struct bContext *C, Object *ob, const int mval[2], b /* image window redraw */ paintface_flush_flags(ob, SELECT); + DEG_id_tag_update(ob->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data); ED_region_tag_redraw(CTX_wm_region(C)); // XXX - should redraw all 3D views return true; diff --git a/source/blender/editors/mesh/editmesh_intersect.c b/source/blender/editors/mesh/editmesh_intersect.c index ad76f0c66f1..9af700aa6bf 100644 --- a/source/blender/editors/mesh/editmesh_intersect.c +++ b/source/blender/editors/mesh/editmesh_intersect.c @@ -197,18 +197,18 @@ static int edbm_intersect_exec(bContext *C, wmOperator *op) } has_isect = BM_mesh_intersect( - em->bm, - em->looptris, em->tottri, - test_fn, NULL, - use_self, use_separate_all, true, true, true, - -1, - eps); + em->bm, + em->looptris, em->tottri, + test_fn, NULL, + use_self, use_separate_all, true, true, true, true, + -1, + eps); if (use_separate_cut) { /* detach selected/un-selected faces */ BM_mesh_separate_faces( - em->bm, - BM_elem_cb_check_hflag_enabled_simple(const BMFace *, BM_ELEM_SELECT)); + em->bm, + BM_elem_cb_check_hflag_enabled_simple(const BMFace *, BM_ELEM_SELECT)); } if (has_isect) { @@ -300,12 +300,12 @@ static int edbm_intersect_boolean_exec(bContext *C, wmOperator *op) } has_isect = BM_mesh_intersect( - em->bm, - em->looptris, em->tottri, - test_fn, NULL, - false, false, true, true, true, - boolean_operation, - eps); + em->bm, + em->looptris, em->tottri, + test_fn, NULL, + false, false, true, true, false, true, + boolean_operation, + eps); if (has_isect) { diff --git a/source/blender/editors/mesh/editmesh_loopcut.c b/source/blender/editors/mesh/editmesh_loopcut.c index 3e787b2055a..7dac9a09b97 100644 --- a/source/blender/editors/mesh/editmesh_loopcut.c +++ b/source/blender/editors/mesh/editmesh_loopcut.c @@ -400,6 +400,7 @@ static void edgering_select(RingSelOpData *lcd) Object *ob_iter = lcd->objects[ob_index]; BMEditMesh *em = BKE_editmesh_from_object(ob_iter); EDBM_flag_disable_all(em, BM_ELEM_SELECT); + DEG_id_tag_update(ob_iter->data, DEG_TAG_SELECT_UPDATE); WM_main_add_notifier(NC_GEOM | ND_SELECT, ob_iter->data); } } @@ -496,6 +497,7 @@ static void ringsel_finish(bContext *C, wmOperator *op) BM_select_history_store(em->bm, lcd->eed); EDBM_selectmode_flush(lcd->em); + DEG_id_tag_update(lcd->ob->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, lcd->ob->data); } } @@ -868,7 +870,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; @@ -876,7 +878,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_select.c b/source/blender/editors/mesh/editmesh_select.c index 634c65485e9..99a95c27b7b 100644 --- a/source/blender/editors/mesh/editmesh_select.c +++ b/source/blender/editors/mesh/editmesh_select.c @@ -1414,6 +1414,7 @@ static int edbm_select_similar_region_exec(bContext *C, wmOperator *op) MEM_freeN(group_index); if (changed) { + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } else { @@ -1621,6 +1622,7 @@ static int edbm_loop_multiselect_exec(bContext *C, wmOperator *op) MEM_freeN(edarray); // if (EM_texFaceCheck()) + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); @@ -1824,6 +1826,7 @@ static bool mouse_mesh_loop(bContext *C, const int mval[2], bool extend, bool de } } + DEG_id_tag_update(vc.obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data); return true; @@ -1930,6 +1933,7 @@ static int edbm_select_all_exec(bContext *C, wmOperator *op) EDBM_selectmode_flush(em); break; } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -1975,6 +1979,7 @@ static int edbm_faces_select_interior_exec(bContext *C, wmOperator *UNUSED(op)) continue; } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); @@ -2032,6 +2037,7 @@ bool EDBM_select_pick(bContext *C, const int mval[2], bool extend, bool deselect Object *ob_iter = objects[ob_index]; EDBM_flag_disable_all(BKE_editmesh_from_object(ob_iter), BM_ELEM_SELECT); if (basact->object != ob_iter) { + DEG_id_tag_update(ob_iter->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob_iter->data); } } @@ -2150,8 +2156,10 @@ bool EDBM_select_pick(bContext *C, const int mval[2], bool extend, bool deselect * switch UV layers, vgroups for eg. */ if (vc.view_layer->basact != basact) { vc.view_layer->basact = basact; + DEG_id_tag_update(&vc.scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, vc.scene); } + DEG_id_tag_update(vc.obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data); return true; @@ -2482,7 +2490,7 @@ bool EDBM_selectmode_toggle( Object *ob_iter = objects[ob_index]; BMEditMesh *em_iter = BKE_editmesh_from_object(ob_iter); EDBM_selectmode_set(em_iter); - DEG_id_tag_update(ob_iter->data, DEG_TAG_COPY_ON_WRITE); + DEG_id_tag_update(ob_iter->data, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob_iter->data); } WM_main_add_notifier(NC_SCENE | ND_TOOLSETTINGS, NULL); @@ -2932,6 +2940,7 @@ static int edbm_select_linked_exec(bContext *C, wmOperator *op) select_linked_delimit_end(em); } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3143,6 +3152,7 @@ static int edbm_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmE * index selections isn't very common. */ RNA_int_set(op->ptr, "index", index); + DEG_id_tag_update(basact->object->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, basact->object->data); return OPERATOR_FINISHED; @@ -3172,6 +3182,7 @@ static int edbm_select_linked_pick_exec(bContext *C, wmOperator *op) edbm_select_linked_pick_ex(em, ele, sel, delimit); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -3260,6 +3271,7 @@ static int edbm_select_face_by_sides_exec(bContext *C, wmOperator *op) EDBM_selectmode_flush(em); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3357,6 +3369,7 @@ static int edbm_select_loose_exec(bContext *C, wmOperator *op) EDBM_selectmode_flush(em); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3420,6 +3433,8 @@ static int edbm_select_mirror_exec(bContext *C, wmOperator *op) if (tot_mirr_iter) { EDBM_selectmode_flush(em); + + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3480,6 +3495,7 @@ static int edbm_select_more_exec(bContext *C, wmOperator *op) } EDBM_select_more(em, use_face_step); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3530,6 +3546,7 @@ static int edbm_select_less_exec(bContext *C, wmOperator *op) } EDBM_select_less(em, use_face_step); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3855,6 +3872,7 @@ static int edbm_select_sharp_edges_exec(bContext *C, wmOperator *op) else { EDBM_selectmode_flush(em); } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); @@ -3953,6 +3971,7 @@ static int edbm_select_linked_flat_faces_exec(bContext *C, wmOperator *op) BLI_LINKSTACK_FREE(stack); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); @@ -4049,6 +4068,7 @@ static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op) } } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); EDBM_selectmode_flush(em); @@ -4152,6 +4172,7 @@ static int edbm_select_random_exec(bContext *C, wmOperator *op) EDBM_deselect_flush(em); } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -4246,6 +4267,7 @@ static int edbm_select_ungrouped_exec(bContext *C, wmOperator *op) if (changed) { EDBM_selectmode_flush(em); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } } @@ -4418,6 +4440,7 @@ static int edbm_region_to_loop_exec(bContext *C, wmOperator *UNUSED(op)) EDBM_selectmode_to_scene(C); } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); @@ -4625,6 +4648,7 @@ static int edbm_loop_to_region_exec(bContext *C, wmOperator *op) EDBM_selectmode_flush(em); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } MEM_freeN(objects); diff --git a/source/blender/editors/mesh/editmesh_tools.c b/source/blender/editors/mesh/editmesh_tools.c index bbeb80fa8af..15840f8f9d6 100644 --- a/source/blender/editors/mesh/editmesh_tools.c +++ b/source/blender/editors/mesh/editmesh_tools.c @@ -104,13 +104,13 @@ static int edbm_subdivide_exec(bContext *C, wmOperator *op) const float fractal = RNA_float_get(op->ptr, "fractal") / 2.5f; const float along_normal = RNA_float_get(op->ptr, "fractal_along_normal"); - if (RNA_boolean_get(op->ptr, "quadtri") && + if (RNA_boolean_get(op->ptr, "ngon") && RNA_enum_get(op->ptr, "quadcorner") == SUBD_CORNER_STRAIGHT_CUT) { RNA_enum_set(op->ptr, "quadcorner", SUBD_CORNER_INNERVERT); } const int quad_corner_type = RNA_enum_get(op->ptr, "quadcorner"); - const bool use_quad_tri = RNA_boolean_get(op->ptr, "quadtri"); + const bool use_quad_tri = !RNA_boolean_get(op->ptr, "ngon"); const int seed = RNA_int_get(op->ptr, "seed"); ViewLayer *view_layer = CTX_data_view_layer(C); @@ -176,7 +176,7 @@ void MESH_OT_subdivide(wmOperatorType *ot) WM_operatortype_props_advanced_begin(ot); - RNA_def_boolean(ot->srna, "quadtri", 0, "Quad/Tri Mode", "Tries to prevent ngons"); + RNA_def_boolean(ot->srna, "ngon", true, "Create N-Gons", "When disabled, newly created faces are limited to 3-4 sided faces"); RNA_def_enum(ot->srna, "quadcorner", prop_mesh_cornervert_types, SUBD_CORNER_STRAIGHT_CUT, "Quad Corner Type", "How to subdivide quad corners (anything other than Straight Cut will prevent ngons)"); @@ -518,6 +518,7 @@ void MESH_OT_delete(wmOperatorType *ot) /* props */ ot->prop = RNA_def_enum(ot->srna, "type", prop_mesh_delete_types, MESH_DELETE_VERT, "Type", "Method used for deleting mesh data"); + RNA_def_property_flag(ot->prop, PROP_HIDDEN | PROP_SKIP_SAVE); } /** \} */ @@ -1036,7 +1037,7 @@ void MESH_OT_mark_seam(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", 0, "Clear", ""); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); WM_operatortype_props_advanced_begin(ot); } @@ -1109,7 +1110,7 @@ void MESH_OT_mark_sharp(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", ""); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); prop = RNA_def_boolean(ot->srna, "use_verts", false, "Vertices", "Consider vertices instead of edges to select which edges to (un)tag as sharp"); RNA_def_property_flag(prop, PROP_SKIP_SAVE); @@ -3647,7 +3648,7 @@ static Base *mesh_separate_tagged(Main *bmain, Scene *scene, ViewLayer *view_lay BM_mesh_normals_update(bm_new); - BM_mesh_bm_to_me(bm_new, base_new->object->data, (&(struct BMeshToMeshParams){0})); + BM_mesh_bm_to_me(bmain, bm_new, base_new->object->data, (&(struct BMeshToMeshParams){0})); BM_mesh_free(bm_new); ((Mesh *)base_new->object->data)->edit_btmesh = NULL; @@ -3960,7 +3961,7 @@ static int edbm_separate_exec(bContext *C, wmOperator *op) if (retval_iter) { BM_mesh_bm_to_me( - bm_old, me, + bmain, bm_old, me, (&(struct BMeshToMeshParams){ .calc_object_remap = true, })); @@ -6835,7 +6836,7 @@ void MESH_OT_mark_freestyle_edge(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", ""); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } /** \} */ @@ -6918,7 +6919,7 @@ void MESH_OT_mark_freestyle_face(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", ""); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } /** \} */ diff --git a/source/blender/editors/mesh/editmesh_undo.c b/source/blender/editors/mesh/editmesh_undo.c index 6fb7a713ce0..33864cd1e95 100644 --- a/source/blender/editors/mesh/editmesh_undo.c +++ b/source/blender/editors/mesh/editmesh_undo.c @@ -511,8 +511,8 @@ static void *undomesh_from_editmesh(UndoMesh *um, BMEditMesh *em, Key *key) /* BM_mesh_validate(em->bm); */ /* for troubleshooting */ BM_mesh_bm_to_me( - em->bm, &um->me, (&(struct BMeshToMeshParams){ - /* Undo code should not be manipulating 'G.main->object' hooks/vertex-parent. */ + NULL, em->bm, &um->me, (&(struct BMeshToMeshParams){ + /* Undo code should not be manipulating 'G_MAIN->object' hooks/vertex-parent. */ .calc_object_remap = false, .cd_mask_extra = CD_MASK_SHAPE_KEYINDEX, })); diff --git a/source/blender/editors/mesh/editmesh_utils.c b/source/blender/editors/mesh/editmesh_utils.c index 16c1a2c45ec..9524d1b0791 100644 --- a/source/blender/editors/mesh/editmesh_utils.c +++ b/source/blender/editors/mesh/editmesh_utils.c @@ -43,6 +43,7 @@ #include "BKE_DerivedMesh.h" #include "BKE_context.h" +#include "BKE_main.h" #include "BKE_mesh.h" #include "BKE_mesh_mapping.h" #include "BKE_report.h" @@ -172,6 +173,10 @@ bool EDBM_op_finish(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const bool BKE_editmesh_tessface_calc(em); } + if (em->ob) { + DEG_id_tag_update(&((Mesh *)em->ob->data)->id, DEG_TAG_COPY_ON_WRITE); + } + return false; } else { @@ -326,7 +331,7 @@ void EDBM_mesh_make(Object *ob, const int select_mode, const bool add_key_index) * \warning This can invalidate the #DerivedMesh cache of other objects (for linked duplicates). * Most callers should run #DEG_id_tag_update on \a ob->data, see: T46738, T46913 */ -void EDBM_mesh_load(Object *ob) +void EDBM_mesh_load(Main *bmain, Object *ob) { Mesh *me = ob->data; BMesh *bm = me->edit_btmesh->bm; @@ -338,7 +343,7 @@ void EDBM_mesh_load(Object *ob) } BM_mesh_bm_to_me( - bm, me, (&(struct BMeshToMeshParams){ + bmain, bm, me, (&(struct BMeshToMeshParams){ .calc_object_remap = true, })); @@ -358,7 +363,7 @@ void EDBM_mesh_load(Object *ob) * cycles. */ #if 0 - for (Object *other_object = G.main->object.first; + for (Object *other_object = bmain->object.first; other_object != NULL; other_object = other_object->id.next) { diff --git a/source/blender/editors/mesh/mesh_data.c b/source/blender/editors/mesh/mesh_data.c index d2410c7d97b..46b84f328cc 100644 --- a/source/blender/editors/mesh/mesh_data.c +++ b/source/blender/editors/mesh/mesh_data.c @@ -538,6 +538,7 @@ void MESH_OT_uv_texture_add(wmOperatorType *ot) static int drop_named_image_invoke(bContext *C, wmOperator *op, const wmEvent *event) { + Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); View3D *v3d = CTX_wm_view3d(C); Base *base; @@ -578,7 +579,7 @@ static int drop_named_image_invoke(bContext *C, wmOperator *op, const wmEvent *e return OPERATOR_CANCELLED; if (exitmode) { - EDBM_mesh_load(obedit); + EDBM_mesh_load(bmain, obedit); EDBM_mesh_free(me->edit_btmesh); MEM_freeN(me->edit_btmesh); me->edit_btmesh = NULL; diff --git a/source/blender/editors/mesh/meshtools.c b/source/blender/editors/mesh/meshtools.c index 41e1ca13b79..6c8de1a481e 100644 --- a/source/blender/editors/mesh/meshtools.c +++ b/source/blender/editors/mesh/meshtools.c @@ -373,7 +373,7 @@ int join_mesh_exec(bContext *C, wmOperator *op) } else if (haskey) { /* add a new key-block and add to the mesh */ - key = me->key = BKE_key_add((ID *)me); + key = me->key = BKE_key_add(bmain, (ID *)me); key->type = KEY_RELATIVE; } @@ -593,6 +593,7 @@ int join_mesh_exec(bContext *C, wmOperator *op) DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); return OPERATOR_FINISHED; @@ -605,6 +606,7 @@ int join_mesh_exec(bContext *C, wmOperator *op) int join_mesh_shapes_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); Object *ob = CTX_data_active_object(C); Depsgraph *depsgraph = CTX_data_depsgraph(C); @@ -639,7 +641,7 @@ int join_mesh_shapes_exec(bContext *C, wmOperator *op) } if (key == NULL) { - key = me->key = BKE_key_add((ID *)me); + key = me->key = BKE_key_add(bmain, (ID *)me); key->type = KEY_RELATIVE; /* first key added, so it was the basis. initialize it with the existing mesh */ @@ -670,6 +672,7 @@ int join_mesh_shapes_exec(bContext *C, wmOperator *op) } CTX_DATA_END; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); return OPERATOR_FINISHED; diff --git a/source/blender/editors/metaball/mball_edit.c b/source/blender/editors/metaball/mball_edit.c index 65bf258f334..1ae122a3801 100644 --- a/source/blender/editors/metaball/mball_edit.c +++ b/source/blender/editors/metaball/mball_edit.c @@ -154,6 +154,7 @@ static int mball_select_all_exec(bContext *C, wmOperator *op) break; } + DEG_id_tag_update(&mb->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, mb); return OPERATOR_FINISHED; @@ -335,6 +336,7 @@ static int mball_select_similar_exec(bContext *C, wmOperator *op) } if (changed) { + DEG_id_tag_update(&mb->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, mb); } @@ -403,6 +405,7 @@ static int select_random_metaelems_exec(bContext *C, wmOperator *op) BLI_rng_free(rng); + DEG_id_tag_update(&mb->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, mb); } MEM_freeN(objects); @@ -614,7 +617,9 @@ bool ED_mball_select_pick(bContext *C, const int mval[2], bool extend, bool dese BLI_rcti_init_pt_radius(&rect, mval, 12); - hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, VIEW3D_SELECT_PICK_NEAREST); + hits = view3d_opengl_select( + &vc, buffer, MAXPICKBUF, &rect, + VIEW3D_SELECT_PICK_NEAREST, VIEW3D_SELECT_FILTER_NOP); /* does startelem exist? */ ml = mb->editelems->first; @@ -670,6 +675,7 @@ bool ED_mball_select_pick(bContext *C, const int mval[2], bool extend, bool dese mb->lastelem = ml_act; + DEG_id_tag_update(&mb->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, mb); return true; @@ -678,5 +684,3 @@ bool ED_mball_select_pick(bContext *C, const int mval[2], bool extend, bool dese return false; } - - diff --git a/source/blender/editors/object/object_add.c b/source/blender/editors/object/object_add.c index 9ce7f556448..dd358b95722 100644 --- a/source/blender/editors/object/object_add.c +++ b/source/blender/editors/object/object_add.c @@ -931,6 +931,7 @@ static int empty_drop_named_image_invoke(bContext *C, wmOperator *op, const wmEv /* if empty under cursor, then set object */ if (base && base->object->type == OB_EMPTY) { ob = base->object; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); } else { @@ -1098,6 +1099,7 @@ static int collection_instance_add_exec(bContext *C, wmOperator *op) DEG_relations_tag_update(bmain); DEG_id_tag_update(&collection->id, 0); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); return OPERATOR_FINISHED; @@ -1294,6 +1296,7 @@ static int object_delete_exec(bContext *C, wmOperator *op) DEG_relations_tag_update(bmain); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene); } @@ -1846,7 +1849,7 @@ static int convert_exec(bContext *C, wmOperator *op) * datablock, but for until we've got granular update * lets take care by selves. */ - BKE_vfont_to_curve(bmain, newob, FO_EDIT); + BKE_vfont_to_curve(newob, FO_EDIT); newob->type = OB_CURVE; cu->type = OB_CURVE; @@ -2018,6 +2021,7 @@ static int convert_exec(bContext *C, wmOperator *op) } DEG_relations_tag_update(bmain); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); @@ -2098,7 +2102,7 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, ViewLayer /* duplicates using userflags */ if (dupflag & USER_DUP_ACT) { - BKE_animdata_copy_id_action(&obn->id, true); + BKE_animdata_copy_id_action(bmain, &obn->id, true); } if (dupflag & USER_DUP_MAT) { @@ -2112,7 +2116,7 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, ViewLayer id_us_min(id); if (dupflag & USER_DUP_ACT) { - BKE_animdata_copy_id_action(&obn->mat[a]->id, true); + BKE_animdata_copy_id_action(bmain, &obn->mat[a]->id, true); } } } @@ -2128,7 +2132,7 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, ViewLayer } if (dupflag & USER_DUP_ACT) { - BKE_animdata_copy_id_action(&psys->part->id, true); + BKE_animdata_copy_id_action(bmain, &psys->part->id, true); } id_us_min(id); @@ -2256,9 +2260,9 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, ViewLayer } if (dupflag & USER_DUP_ACT) { - BKE_animdata_copy_id_action((ID *)obn->data, true); + BKE_animdata_copy_id_action(bmain, (ID *)obn->data, true); if (key) { - BKE_animdata_copy_id_action((ID *)key, true); + BKE_animdata_copy_id_action(bmain, (ID *)key, true); } } @@ -2353,8 +2357,7 @@ static int duplicate_exec(bContext *C, wmOperator *op) BKE_main_id_clear_newpoins(bmain); DEG_relations_tag_update(bmain); - /* TODO(sergey): Use proper flag for tagging here. */ - DEG_id_tag_update(&scene->id, 0); + DEG_id_tag_update(&scene->id, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); @@ -2436,6 +2439,7 @@ static int add_named_exec(bContext *C, wmOperator *op) /* TODO(sergey): Only update relations for the current scene. */ DEG_relations_tag_update(bmain); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); diff --git a/source/blender/editors/object/object_data_transfer.c b/source/blender/editors/object/object_data_transfer.c index db81c51cc90..788f0826848 100644 --- a/source/blender/editors/object/object_data_transfer.c +++ b/source/blender/editors/object/object_data_transfer.c @@ -40,7 +40,6 @@ #include "BKE_context.h" #include "BKE_data_transfer.h" -#include "BKE_DerivedMesh.h" #include "BKE_mesh_mapping.h" #include "BKE_mesh_remap.h" #include "BKE_mesh_runtime.h" @@ -137,20 +136,17 @@ static const EnumPropertyItem *dt_layers_select_src_itemf( Scene *scene = CTX_data_scene(C); if (ob_src) { - DerivedMesh *dm_src; - CustomData *ldata; + Mesh *me_eval; int num_data, i; - /* XXX Is this OK? */ - dm_src = mesh_get_derived_final(depsgraph, scene, ob_src, CD_MASK_BAREMESH | CD_MLOOPUV); - ldata = dm_src->getLoopDataLayout(dm_src); - num_data = CustomData_number_of_layers(ldata, CD_MLOOPUV); + me_eval = mesh_get_eval_final(depsgraph, scene, ob_src, CD_MASK_BAREMESH | CD_MLOOPUV); + num_data = CustomData_number_of_layers(&me_eval->ldata, CD_MLOOPUV); RNA_enum_item_add_separator(&item, &totitem); for (i = 0; i < num_data; i++) { tmp_item.value = i; - tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(ldata, CD_MLOOPUV, i); + tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(&me_eval->ldata, CD_MLOOPUV, i); RNA_enum_item_add(&item, &totitem, &tmp_item); } } @@ -160,20 +156,17 @@ static const EnumPropertyItem *dt_layers_select_src_itemf( Scene *scene = CTX_data_scene(C); if (ob_src) { - DerivedMesh *dm_src; - CustomData *ldata; + Mesh *me_eval; int num_data, i; - /* XXX Is this OK? */ - dm_src = mesh_get_derived_final(depsgraph, scene, ob_src, CD_MASK_BAREMESH | CD_MLOOPCOL); - ldata = dm_src->getLoopDataLayout(dm_src); - num_data = CustomData_number_of_layers(ldata, CD_MLOOPCOL); + me_eval = mesh_get_eval_final(depsgraph, scene, ob_src, CD_MASK_BAREMESH | CD_MLOOPCOL); + num_data = CustomData_number_of_layers(&me_eval->ldata, CD_MLOOPCOL); RNA_enum_item_add_separator(&item, &totitem); for (i = 0; i < num_data; i++) { tmp_item.value = i; - tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(ldata, CD_MLOOPCOL, i); + tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(&me_eval->ldata, CD_MLOOPCOL, i); RNA_enum_item_add(&item, &totitem, &tmp_item); } } diff --git a/source/blender/editors/object/object_edit.c b/source/blender/editors/object/object_edit.c index b7f59285186..f050297ee2f 100644 --- a/source/blender/editors/object/object_edit.c +++ b/source/blender/editors/object/object_edit.c @@ -146,6 +146,228 @@ Object *ED_object_active_context(bContext *C) return ob; } +/* ********************** object hiding *************************** */ + +static int object_hide_poll(bContext *C) +{ + if (CTX_wm_space_outliner(C) != NULL) { + return ED_outliner_collections_editor_poll(C); + } + else { + return ED_operator_view3d_active(C); + } +} + +static int object_hide_view_clear_exec(bContext *C, wmOperator *op) +{ + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + const bool select = RNA_boolean_get(op->ptr, "select"); + bool changed = false; + + for (Base *base = view_layer->object_bases.first; base; base = base->next) { + if (base->flag & BASE_HIDE) { + base->flag &= ~BASE_HIDE; + changed = true; + + if (select) { + ED_object_base_select(base, BA_SELECT); + } + } + } + + if (!changed) { + return OPERATOR_CANCELLED; + } + + BKE_layer_collection_sync(scene, view_layer); + DEG_id_tag_update(&scene->id, DEG_TAG_BASE_FLAGS_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); + + return OPERATOR_FINISHED; +} + +void OBJECT_OT_hide_view_clear(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Show Hidden Objects"; + ot->description = "Reveal temporarily hidden objects"; + ot->idname = "OBJECT_OT_hide_view_clear"; + + /* api callbacks */ + ot->exec = object_hide_view_clear_exec; + ot->poll = object_hide_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + PropertyRNA *prop = RNA_def_boolean(ot->srna, "select", false, "Select", ""); + RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN); +} + +static int object_hide_view_set_exec(bContext *C, wmOperator *op) +{ + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + const bool unselected = RNA_boolean_get(op->ptr, "unselected"); + bool changed = false; + + for (Base *base = view_layer->object_bases.first; base; base = base->next) { + if (!(base->flag & BASE_VISIBLED)) { + continue; + } + + if (!unselected) { + if (base->flag & BASE_SELECTED) { + ED_object_base_select(base, BA_DESELECT); + base->flag |= BASE_HIDE; + changed = true; + } + } + else { + if (!(base->flag & BASE_SELECTED)) { + ED_object_base_select(base, BA_DESELECT); + base->flag |= BASE_HIDE; + changed = true; + } + } + } + + if (!changed) { + return OPERATOR_CANCELLED; + } + + BKE_layer_collection_sync(scene, view_layer); + DEG_id_tag_update(&scene->id, DEG_TAG_BASE_FLAGS_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); + + return OPERATOR_FINISHED; +} + +void OBJECT_OT_hide_view_set(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Hide Objects"; + ot->description = "Temporarily hide objects from the viewport"; + ot->idname = "OBJECT_OT_hide_view_set"; + + /* api callbacks */ + ot->exec = object_hide_view_set_exec; + ot->poll = object_hide_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + PropertyRNA *prop; + prop = RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected objects"); + RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN); +} + +static int object_hide_collection_exec(bContext *C, wmOperator *op) +{ + int index = RNA_int_get(op->ptr, "collection_index"); + bool extend = (CTX_wm_window(C)->eventstate->shift != 0); + + if (CTX_wm_window(C)->eventstate->alt != 0) { + index += 10; + } + + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + LayerCollection *lc = BKE_layer_collection_from_index(view_layer, index); + + if (!lc) { + return OPERATOR_CANCELLED; + } + + BKE_layer_collection_set_visible(scene, view_layer, lc, extend); + + DEG_id_tag_update(&scene->id, DEG_TAG_BASE_FLAGS_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); + + return OPERATOR_FINISHED; +} + +#define COLLECTION_INVALID_INDEX -1 + +void ED_hide_collections_menu_draw(const bContext *C, uiLayout *layout) +{ + ViewLayer *view_layer = CTX_data_view_layer(C); + LayerCollection *lc_scene = view_layer->layer_collections.first; + + uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN); + + for (LayerCollection *lc = lc_scene->layer_collections.first; lc; lc = lc->next) { + int index = BKE_layer_collection_findindex(view_layer, lc); + uiLayout *row = uiLayoutRow(layout, false); + + if (lc->collection->flag & COLLECTION_RESTRICT_VIEW) { + continue; + } + + if ((view_layer->runtime_flag & VIEW_LAYER_HAS_HIDE) && + !(lc->runtime_flag & LAYER_COLLECTION_HAS_VISIBLE_OBJECTS)) { + uiLayoutSetActive(row, false); + } + + int icon = ICON_NONE; + if (BKE_layer_collection_has_selected_objects(view_layer, lc)) { + icon = ICON_LAYER_ACTIVE; + } + else if (lc->runtime_flag & LAYER_COLLECTION_HAS_OBJECTS) { + icon = ICON_LAYER_USED; + } + + uiItemIntO(row, + lc->collection->id.name + 2, + icon, + "OBJECT_OT_hide_collection", + "collection_index", + index); + } +} + +static int object_hide_collection_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) +{ + /* Immediately execute if collection index was specified. */ + int index = RNA_int_get(op->ptr, "collection_index"); + if (index != COLLECTION_INVALID_INDEX) { + return object_hide_collection_exec(C, op); + } + + /* Open popup menu. */ + const char *title = CTX_IFACE_(op->type->translation_context, op->type->name); + uiPopupMenu *pup = UI_popup_menu_begin(C, title, ICON_GROUP); + uiLayout *layout = UI_popup_menu_layout(pup); + + ED_hide_collections_menu_draw(C, layout); + + UI_popup_menu_end(C, pup); + + return OPERATOR_INTERFACE; +} + +void OBJECT_OT_hide_collection(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Hide Objects By Collection"; + ot->description = "Show only objects in collection (Shift to extend)"; + ot->idname = "OBJECT_OT_hide_collection"; + + /* api callbacks */ + ot->exec = object_hide_collection_exec; + ot->invoke = object_hide_collection_invoke; + ot->poll = ED_operator_view3d_active; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* Properties. */ + PropertyRNA *prop; + prop = RNA_def_int(ot->srna, "collection_index", COLLECTION_INVALID_INDEX, COLLECTION_INVALID_INDEX, INT_MAX, + "Collection Index", "Index of the collection to change visibility", 0, INT_MAX); + RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN); +} /* ******************* toggle editmode operator ***************** */ @@ -191,7 +413,7 @@ static bool ED_object_editmode_load_ex(Main *bmain, Object *obedit, const bool f return false; } - EDBM_mesh_load(obedit); + EDBM_mesh_load(bmain, obedit); if (freedata) { EDBM_mesh_free(me->edit_btmesh); @@ -1548,8 +1770,6 @@ bool ED_object_editmode_calc_active_center(Object *obedit, const bool select_onl return false; } -#define COLLECTION_INVALID_INDEX -1 - static int move_to_collection_poll(bContext *C) { if (CTX_wm_space_outliner(C) != NULL) { @@ -1631,7 +1851,7 @@ static int move_to_collection_exec(bContext *C, wmOperator *op) collection->id.name + 2); DEG_relations_tag_update(CTX_data_main(C)); - DEG_id_tag_update(&scene->id, 0); + DEG_id_tag_update(&scene->id, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_LAYER, scene); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); @@ -1870,4 +2090,3 @@ void OBJECT_OT_link_to_collection(wmOperatorType *ot) RNA_def_property_flag(prop, PROP_SKIP_SAVE); } -#undef COLLECTION_INVALID_INDEX diff --git a/source/blender/editors/object/object_hook.c b/source/blender/editors/object/object_hook.c index 31e8685e323..6a3cb9aa097 100644 --- a/source/blender/editors/object/object_hook.c +++ b/source/blender/editors/object/object_hook.c @@ -318,7 +318,7 @@ static bool object_hook_index_array(Main *bmain, Scene *scene, Object *obedit, BMEditMesh *em; - EDBM_mesh_load(obedit); + EDBM_mesh_load(bmain, obedit); EDBM_mesh_make(obedit, scene->toolsettings->selectmode, true); DEG_id_tag_update(obedit->data, 0); @@ -619,6 +619,7 @@ static int object_add_hook_newob_exec(bContext *C, wmOperator *op) Object *obedit = CTX_data_edit_object(C); if (add_hook_object(C, bmain, scene, view_layer, obedit, NULL, OBJECT_ADDHOOK_NEWOB, op->reports)) { + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, obedit); return OPERATOR_FINISHED; @@ -889,6 +890,7 @@ static int object_hook_select_exec(bContext *C, wmOperator *op) /* select functionality */ object_hook_select(ob, hmd); + DEG_id_tag_update(ob->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data); return OPERATOR_FINISHED; diff --git a/source/blender/editors/object/object_intern.h b/source/blender/editors/object/object_intern.h index 18251a25b73..f7179912f52 100644 --- a/source/blender/editors/object/object_intern.h +++ b/source/blender/editors/object/object_intern.h @@ -76,6 +76,9 @@ void OBJECT_OT_drop_named_material(struct wmOperatorType *ot); void OBJECT_OT_unlink_data(struct wmOperatorType *ot); /* object_edit.c */ +void OBJECT_OT_hide_view_set(struct wmOperatorType *ot); +void OBJECT_OT_hide_view_clear(struct wmOperatorType *ot); +void OBJECT_OT_hide_collection(struct wmOperatorType *ot); void OBJECT_OT_mode_set(struct wmOperatorType *ot); void OBJECT_OT_mode_set_or_submode(struct wmOperatorType *ot); void OBJECT_OT_editmode_toggle(struct wmOperatorType *ot); diff --git a/source/blender/editors/object/object_modifier.c b/source/blender/editors/object/object_modifier.c index 1b9af3725ca..425a0acff17 100644 --- a/source/blender/editors/object/object_modifier.c +++ b/source/blender/editors/object/object_modifier.c @@ -119,7 +119,7 @@ ModifierData *ED_object_modifier_add(ReportList *reports, Main *bmain, Scene *sc /* don't need to worry about the new modifier's name, since that is set to the number * of particle systems which shouldn't have too many duplicates */ - new_md = object_add_particle_system(scene, ob, name); + new_md = object_add_particle_system(bmain, scene, ob, name); } else { /* get new modifier data to add */ @@ -524,7 +524,8 @@ int ED_object_modifier_convert(ReportList *UNUSED(reports), Main *bmain, Scene * return 1; } -static int modifier_apply_shape(ReportList *reports, Depsgraph *depsgraph, Scene *scene, Object *ob, ModifierData *md) +static int modifier_apply_shape( + Main *bmain, ReportList *reports, Depsgraph *depsgraph, Scene *scene, Object *ob, ModifierData *md) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); @@ -564,7 +565,7 @@ static int modifier_apply_shape(ReportList *reports, Depsgraph *depsgraph, Scene } if (key == NULL) { - key = me->key = BKE_key_add((ID *)me); + key = me->key = BKE_key_add(bmain, (ID *)me); key->type = KEY_RELATIVE; /* if that was the first key block added, then it was the basis. * Initialize it with the mesh, and add another for the modifier */ @@ -673,7 +674,7 @@ static int modifier_apply_obdata(ReportList *reports, Depsgraph *depsgraph, Scen } int ED_object_modifier_apply( - ReportList *reports, Depsgraph *depsgraph, + Main *bmain, ReportList *reports, Depsgraph *depsgraph, Scene *scene, Object *ob, ModifierData *md, int mode) { int prev_mode; @@ -702,7 +703,7 @@ int ED_object_modifier_apply( md->mode |= eModifierMode_Realtime; if (mode == MODIFIER_APPLY_SHAPE) { - if (!modifier_apply_shape(reports, depsgraph, scene, ob, md)) { + if (!modifier_apply_shape(bmain, reports, depsgraph, scene, ob, md)) { md->mode = prev_mode; return 0; } @@ -1017,13 +1018,14 @@ void OBJECT_OT_modifier_move_down(wmOperatorType *ot) static int modifier_apply_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); Depsgraph *depsgraph = CTX_data_depsgraph(C); Scene *scene = CTX_data_scene(C); Object *ob = ED_object_active_context(C); ModifierData *md = edit_modifier_property_get(op, ob, 0); int apply_as = RNA_enum_get(op->ptr, "apply_as"); - if (!md || !ED_object_modifier_apply(op->reports, depsgraph, scene, ob, md, apply_as)) { + if (!md || !ED_object_modifier_apply(bmain, op->reports, depsgraph, scene, ob, md, apply_as)) { return OPERATOR_CANCELLED; } diff --git a/source/blender/editors/object/object_ops.c b/source/blender/editors/object/object_ops.c index af572824068..89dd54b6f64 100644 --- a/source/blender/editors/object/object_ops.c +++ b/source/blender/editors/object/object_ops.c @@ -247,6 +247,10 @@ void ED_operatortypes_object(void) WM_operatortype_append(OBJECT_OT_data_transfer); WM_operatortype_append(OBJECT_OT_datalayout_transfer); WM_operatortype_append(OBJECT_OT_surfacedeform_bind); + + WM_operatortype_append(OBJECT_OT_hide_view_clear); + WM_operatortype_append(OBJECT_OT_hide_view_set); + WM_operatortype_append(OBJECT_OT_hide_collection); } void ED_operatormacros_object(void) @@ -289,11 +293,11 @@ void ED_keymap_object(wmKeyConfig *keyconf) keymap = WM_keymap_find(keyconf, "Object Non-modal", 0, 0); /* modes */ - kmi = WM_keymap_add_item(keymap, "OBJECT_OT_mode_set", TABKEY, KM_RELEASE, 0, 0); + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_mode_set", TABKEY, KM_CLICK, 0, 0); RNA_enum_set(kmi->ptr, "mode", OB_MODE_EDIT); RNA_boolean_set(kmi->ptr, "toggle", true); - kmi = WM_keymap_add_menu_pie(keymap, "VIEW3D_PIE_object_mode", TABKEY, KM_CLICK_DRAG, 0, 0); + kmi = WM_keymap_add_menu_pie(keymap, "VIEW3D_MT_object_mode_pie", TABKEY, KM_CLICK_DRAG, 0, 0); WM_keymap_add_item(keymap, "OBJECT_OT_origin_set", CKEY, KM_PRESS, KM_ALT | KM_SHIFT | KM_CTRL, 0); @@ -404,6 +408,19 @@ void ED_keymap_object(wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "OBJECT_OT_move_to_collection", MKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "OBJECT_OT_link_to_collection", MKEY, KM_PRESS, KM_SHIFT, 0); + + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_view_clear", HKEY, KM_PRESS, KM_ALT, 0); + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_view_set", HKEY, KM_PRESS, 0, 0); + RNA_boolean_set(kmi->ptr, "unselected", false); + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_view_set", HKEY, KM_PRESS, KM_SHIFT, 0); + RNA_boolean_set(kmi->ptr, "unselected", true); + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_collection", HKEY, KM_PRESS, KM_CTRL, 0); + + /* Collection switching. */ + for (int i = 0; i < 10; i++) { + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_collection", ZEROKEY + i, KM_PRESS, KM_ANY, 0); + RNA_int_set(kmi->ptr, "collection_index", (i == 0) ? 10 : i); + } } void ED_keymap_proportional_cycle(struct wmKeyConfig *UNUSED(keyconf), struct wmKeyMap *keymap) diff --git a/source/blender/editors/object/object_relations.c b/source/blender/editors/object/object_relations.c index 4f441826bfd..a114b2cc6d5 100644 --- a/source/blender/editors/object/object_relations.c +++ b/source/blender/editors/object/object_relations.c @@ -145,7 +145,7 @@ static int vertex_parent_set_exec(bContext *C, wmOperator *op) Mesh *me = obedit->data; BMEditMesh *em; - EDBM_mesh_load(obedit); + EDBM_mesh_load(bmain, obedit); EDBM_mesh_make(obedit, scene->toolsettings->selectmode, true); DEG_id_tag_update(obedit->data, 0); @@ -1786,7 +1786,7 @@ static void single_obdata_users(Main *bmain, Scene *scene, ViewLayer *view_layer /* Needed to remap texcomesh below. */ me = ob->data = ID_NEW_SET(ob->data, BKE_mesh_copy(bmain, ob->data)); if (me->key) /* We do not need to set me->key->id.newid here... */ - BKE_animdata_copy_id_action((ID *)me->key, false); + BKE_animdata_copy_id_action(bmain, (ID *)me->key, false); break; case OB_MBALL: ob->data = ID_NEW_SET(ob->data, BKE_mball_copy(bmain, ob->data)); @@ -1798,12 +1798,12 @@ static void single_obdata_users(Main *bmain, Scene *scene, ViewLayer *view_layer ID_NEW_REMAP(cu->bevobj); ID_NEW_REMAP(cu->taperobj); if (cu->key) /* We do not need to set cu->key->id.newid here... */ - BKE_animdata_copy_id_action((ID *)cu->key, false); + BKE_animdata_copy_id_action(bmain, (ID *)cu->key, false); break; case OB_LATTICE: ob->data = lat = ID_NEW_SET(ob->data, BKE_lattice_copy(bmain, ob->data)); if (lat->key) /* We do not need to set lat->key->id.newid here... */ - BKE_animdata_copy_id_action((ID *)lat->key, false); + BKE_animdata_copy_id_action(bmain, (ID *)lat->key, false); break; case OB_ARMATURE: DEG_id_tag_update(&ob->id, OB_RECALC_DATA); @@ -1830,7 +1830,7 @@ static void single_obdata_users(Main *bmain, Scene *scene, ViewLayer *view_layer * AnimData structure, which is not what we want. * (sergey) */ - BKE_animdata_copy_id_action((ID *)ob->data, false); + BKE_animdata_copy_id_action(bmain, (ID *)ob->data, false); id_us_min(id); } @@ -1845,13 +1845,13 @@ static void single_obdata_users(Main *bmain, Scene *scene, ViewLayer *view_layer } } -static void single_object_action_users(Scene *scene, ViewLayer *view_layer, const int flag) +static void single_object_action_users(Main *bmain, Scene *scene, ViewLayer *view_layer, const int flag) { FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, flag, ob) { if (!ID_IS_LINKED(ob)) { DEG_id_tag_update(&ob->id, OB_RECALC_DATA); - BKE_animdata_copy_id_action(&ob->id, false); + BKE_animdata_copy_id_action(bmain, &ob->id, false); } } FOREACH_OBJECT_FLAG_END; @@ -1872,7 +1872,7 @@ static void single_mat_users(Main *bmain, Scene *scene, ViewLayer *view_layer, c if (ma->id.us > 1) { man = BKE_material_copy(bmain, ma); - BKE_animdata_copy_id_action(&man->id, false); + BKE_animdata_copy_id_action(bmain, &man->id, false); man->id.us = 0; assign_material(bmain, ob, man, a, BKE_MAT_ASSIGN_USERPREF); @@ -1916,7 +1916,7 @@ void ED_object_single_users(Main *bmain, Scene *scene, const bool full, const bo if (full) { single_obdata_users(bmain, scene, NULL, 0); - single_object_action_users(scene, NULL, 0); + single_object_action_users(bmain, scene, NULL, 0); single_mat_users_expand(bmain); } @@ -2457,7 +2457,7 @@ static int make_single_user_exec(bContext *C, wmOperator *op) } if (RNA_boolean_get(op->ptr, "animation")) { - single_object_action_users(scene, view_layer, flag); + single_object_action_users(bmain, scene, view_layer, flag); } BKE_main_id_clear_newpoins(bmain); diff --git a/source/blender/editors/object/object_select.c b/source/blender/editors/object/object_select.c index bac1ba0e37d..ce29125ac79 100644 --- a/source/blender/editors/object/object_select.c +++ b/source/blender/editors/object/object_select.c @@ -129,6 +129,7 @@ void ED_object_base_activate(bContext *C, Base *base) else { WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, NULL); } + DEG_id_tag_update(&CTX_data_scene(C)->id, DEG_TAG_SELECT_UPDATE); } /********************** Selection Operators **********************/ @@ -172,7 +173,9 @@ static int object_select_by_type_exec(bContext *C, wmOperator *op) } CTX_DATA_END; - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } @@ -365,7 +368,9 @@ void ED_object_select_linked_by_id(bContext *C, ID *id) } if (changed) { - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } } @@ -439,6 +444,7 @@ static int object_select_linked_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; if (changed) { + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } @@ -809,6 +815,7 @@ static int object_select_grouped_exec(bContext *C, wmOperator *op) } if (changed) { + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } @@ -878,7 +885,9 @@ static int object_select_all_exec(bContext *C, wmOperator *op) } CTX_DATA_END; - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } @@ -930,7 +939,9 @@ static int object_select_same_collection_exec(bContext *C, wmOperator *op) } CTX_DATA_END; - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } @@ -986,6 +997,7 @@ static int object_select_mirror_exec(bContext *C, wmOperator *op) CTX_DATA_END; /* undo? */ + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; @@ -1073,7 +1085,9 @@ static int object_select_more_exec(bContext *C, wmOperator *UNUSED(op)) bool changed = object_select_more_less(C, true); if (changed) { - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } else { @@ -1101,7 +1115,9 @@ static int object_select_less_exec(bContext *C, wmOperator *UNUSED(op)) bool changed = object_select_more_less(C, false); if (changed) { - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } else { @@ -1147,7 +1163,9 @@ static int object_select_random_exec(bContext *C, wmOperator *op) BLI_rng_free(rng); - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } diff --git a/source/blender/editors/object/object_shapekey.c b/source/blender/editors/object/object_shapekey.c index 03fe6e9de65..4f985293ec3 100644 --- a/source/blender/editors/object/object_shapekey.c +++ b/source/blender/editors/object/object_shapekey.c @@ -78,8 +78,9 @@ static void ED_object_shape_key_add(bContext *C, Object *ob, const bool from_mix) { + Main *bmain = CTX_data_main(C); KeyBlock *kb; - if ((kb = BKE_object_shapekey_insert(ob, NULL, from_mix))) { + if ((kb = BKE_object_shapekey_insert(bmain, ob, NULL, from_mix))) { Key *key = BKE_key_from_object(ob); /* for absolute shape keys, new keys may not be added last */ ob->shapenr = BLI_findindex(&key->block, kb) + 1; diff --git a/source/blender/editors/object/object_vgroup.c b/source/blender/editors/object/object_vgroup.c index 84786024160..a6f688c49fb 100644 --- a/source/blender/editors/object/object_vgroup.c +++ b/source/blender/editors/object/object_vgroup.c @@ -2820,6 +2820,7 @@ static int vertex_group_select_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; vgroup_select_verts(ob, 1); + DEG_id_tag_update(ob->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data); return OPERATOR_FINISHED; @@ -2845,6 +2846,7 @@ static int vertex_group_deselect_exec(bContext *C, wmOperator *UNUSED(op)) Object *ob = ED_object_context(C); vgroup_select_verts(ob, 0); + DEG_id_tag_update(ob->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data); return OPERATOR_FINISHED; diff --git a/source/blender/editors/physics/dynamicpaint_ops.c b/source/blender/editors/physics/dynamicpaint_ops.c index f45ee050ef9..7f74dd4666a 100644 --- a/source/blender/editors/physics/dynamicpaint_ops.c +++ b/source/blender/editors/physics/dynamicpaint_ops.c @@ -316,7 +316,7 @@ static void dpaint_bake_endjob(void *customdata) G.is_rendering = false; BKE_spacedata_draw_locks(false); - WM_set_locked_interface(G.main->wm.first, false); + WM_set_locked_interface(G_MAIN->wm.first, false); /* Bake was successful: * Report for ended bake and how long it took */ diff --git a/source/blender/editors/physics/particle_edit.c b/source/blender/editors/physics/particle_edit.c index 359e9365ea7..08eaaa7284f 100644 --- a/source/blender/editors/physics/particle_edit.c +++ b/source/blender/editors/physics/particle_edit.c @@ -49,6 +49,7 @@ #include "BLI_string.h" #include "BLI_kdtree.h" #include "BLI_rand.h" +#include "BLI_task.h" #include "BLI_utildefines.h" #include "BKE_context.h" @@ -56,6 +57,7 @@ #include "BKE_global.h" #include "BKE_object.h" #include "BKE_library.h" +#include "BKE_main.h" #include "BKE_mesh.h" #include "BKE_mesh_runtime.h" #include "BKE_modifier.h" @@ -91,6 +93,8 @@ #include "DEG_depsgraph_query.h" +#include "PIL_time_utildefines.h" + #include "physics_intern.h" #include "particle_edit_utildefines.h" @@ -117,7 +121,7 @@ int PE_hair_poll(bContext *C) if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT)) { return 0; } - edit= PE_get_current(scene, ob); + edit = PE_get_current(scene, ob); return (edit && edit->psys); } @@ -213,6 +217,31 @@ PTCacheEdit *PE_get_current_from_psys(ParticleSystem *psys) return NULL; } +/* NOTE: Similar to creation of edit, but only updates pointers in the + * existing struct. + */ +static void pe_update_hair_particle_edit_pointers(PTCacheEdit *edit) +{ + ParticleSystem *psys = edit->psys; + ParticleData *pa = psys->particles; + for (int p = 0; p < edit->totpoint; p++) { + PTCacheEditPoint *point = &edit->points[p]; + HairKey *hair_key = pa->hair; + for (int k = 0; k < point->totkey; k++) { + PTCacheEditKey *key = &point->keys[k]; + key->co = hair_key->co; + key->time = &hair_key->time; + key->flag = hair_key->editflag; + if (!(psys->flag & PSYS_GLOBAL_HAIR)) { + key->flag |= PEK_USE_WCO; + hair_key->editflag |= PEK_USE_WCO; + } + hair_key++; + } + pa++; + } +} + /* always gets at least the first particlesystem even if PSYS_CURRENT flag is not set * * note: this function runs on poll, therefor it can runs many times a second @@ -298,8 +327,16 @@ static PTCacheEdit *pe_get_current( } } - if (edit) + if (edit) { edit->pid = *pid; + if (edit->flags & PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL) { + if (edit->psys != NULL) { + psys_copy_particles(edit->psys, edit->psys_eval); + pe_update_hair_particle_edit_pointers(edit); + } + edit->flags &= ~PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL; + } + } BLI_freelistN(&pidlist); @@ -364,6 +401,7 @@ typedef struct PEData { ViewContext vc; const bContext *context; + Main *bmain; Scene *scene; ViewLayer *view_layer; Object *ob; @@ -372,6 +410,8 @@ typedef struct PEData { BVHTreeFromMesh shape_bvh; Depsgraph *depsgraph; + RNG *rng; + const int *mval; rcti *rect; float rad; @@ -400,6 +440,7 @@ 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->view_layer = CTX_data_view_layer(C); data->ob = CTX_data_active_object(C); @@ -445,6 +486,22 @@ static void PE_free_shape_tree(PEData *data) free_bvhtree_from_mesh(&data->shape_bvh); } +static void PE_create_random_generator(PEData *data) +{ + uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); + rng_seed ^= GET_UINT_FROM_POINTER(data->ob); + rng_seed ^= GET_UINT_FROM_POINTER(data->edit); + data->rng = BLI_rng_new(rng_seed); +} + +static void PE_free_random_generator(PEData *data) +{ + if (data->rng != NULL) { + BLI_rng_free(data->rng); + data->rng = NULL; + } +} + /*************************** selection utilities *******************************/ static bool key_test_depth(PEData *data, const float co[3], const int screen_co[2]) @@ -642,61 +699,87 @@ static void foreach_mouse_hit_point(PEData *data, ForPointFunc func, int selecte } } -static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected) +typedef struct KeyIterData { + PEData *data; + PTCacheEdit *edit; + int selected; + ForKeyMatFunc func; +} KeyIterData; + +static void foreach_mouse_hit_key_iter( + void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) { + KeyIterData *iter_data = (KeyIterData *)iter_data_v; + PEData *data = iter_data->data; PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if (point->flag & PEP_HIDE) { + return; + } ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd = NULL; - ParticleEditSettings *pset= PE_settings(data->scene); - POINT_P; KEY_K; + ParticleSystemModifierData *psmd_eval = iter_data->edit->psmd_eval; + ParticleEditSettings *pset = PE_settings(data->scene); + const int selected = iter_data->selected; float mat[4][4], imat[4][4]; - unit_m4(mat); unit_m4(imat); - - if (edit->psys) - psmd= psys_get_modifier(data->ob, edit->psys); - - /* all is selected in path mode */ - if (pset->selectmode==SCE_SELECT_PATH) - selected= 0; - - LOOP_VISIBLE_POINTS { - if (pset->selectmode==SCE_SELECT_END) { - if (point->totkey) { - /* only do end keys */ - key= point->keys + point->totkey-1; - - 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->mesh_final, psys->part->from, psys->particles + p, mat); - invert_m4_m4(imat, mat); - } - - func(data, mat, imat, p, point->totkey-1, key); + if (pset->selectmode==SCE_SELECT_END) { + if (point->totkey) { + /* only do end keys */ + PTCacheEditKey *key = point->keys + point->totkey-1; + + 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_eval->mesh_final, psys->part->from, psys->particles + iter, mat); + invert_m4_m4(imat, mat); } + iter_data->func(data, mat, imat, iter, point->totkey-1, key); } } } - else { - /* do all keys */ - LOOP_VISIBLE_KEYS { - 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->mesh_final, psys->part->from, psys->particles + p, mat); - invert_m4_m4(imat, mat); - } - - func(data, mat, imat, p, k, key); + } + else { + /* do all keys */ + PTCacheEditKey *key; + int k; + LOOP_VISIBLE_KEYS { + 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_eval->mesh_final, psys->part->from, psys->particles + iter, mat); + invert_m4_m4(imat, mat); } + iter_data->func(data, mat, imat, iter, k, key); } } } } } +static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected) +{ + PTCacheEdit *edit = data->edit; + ParticleEditSettings *pset = PE_settings(data->scene); + /* all is selected in path mode */ + if (pset->selectmode == SCE_SELECT_PATH) { + selected = 0; + } + + KeyIterData iter_data; + iter_data.data = data; + iter_data.edit = edit; + iter_data.selected = selected; + iter_data.func = func; + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, foreach_mouse_hit_key_iter, &settings); +} + static void foreach_selected_point(PEData *data, ForPointFunc func) { PTCacheEdit *edit = data->edit; @@ -760,7 +843,7 @@ static int count_selected_keys(Scene *scene, PTCacheEdit *edit) static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) { PTCacheEdit *edit; - ParticleSystemModifierData *psmd; + ParticleSystemModifierData *psmd_eval; KDTree *tree; KDTreeNearest nearest; HairKey *key; @@ -769,10 +852,10 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) int index, totpart; edit= psys->edit; - psmd= psys_get_modifier(ob, psys); + psmd_eval = edit->psmd_eval; totpart= psys->totpart; - if (!psmd->mesh_final) + if (!psmd_eval->mesh_final) return; tree= BLI_kdtree_new(totpart); @@ -780,7 +863,7 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) /* insert particles into kd tree */ LOOP_PARTICLES { key = pa->hair; - psys_mat_hair_to_orco(ob, psmd->mesh_final, psys->part->from, pa, mat); + psys_mat_hair_to_orco(ob, psmd_eval->mesh_final, psys->part->from, pa, mat); copy_v3_v3(co, key->co); mul_m4_v3(mat, co); BLI_kdtree_insert(tree, p, co); @@ -794,7 +877,7 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) LOOP_PARTICLES { key = pa->hair; - psys_mat_hair_to_orco(ob, psmd->mesh_final, psys->part->from, pa, mat); + psys_mat_hair_to_orco(ob, psmd_eval->mesh_final, psys->part->from, pa, mat); copy_v3_v3(co, key->co); mul_m4_v3(mat, co); co[0] = -co[0]; @@ -900,16 +983,16 @@ static void PE_mirror_particle(Object *ob, Mesh *mesh, ParticleSystem *psys, Par static void PE_apply_mirror(Object *ob, ParticleSystem *psys) { PTCacheEdit *edit; - ParticleSystemModifierData *psmd; + ParticleSystemModifierData *psmd_eval; POINT_P; if (!psys) return; edit= psys->edit; - psmd= psys_get_modifier(ob, psys); + psmd_eval= edit->psmd_eval; - if (!psmd->mesh_final) + if (!psmd_eval->mesh_final) return; if (!edit->mirror_cache) @@ -922,7 +1005,7 @@ static void PE_apply_mirror(Object *ob, ParticleSystem *psys) * to avoid doing mirror twice */ LOOP_POINTS { if (point->flag & PEP_EDIT_RECALC) { - PE_mirror_particle(ob, psmd->mesh_final, psys, psys->particles + p, NULL); + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); if (edit->mirror_cache[p] != -1) edit->points[edit->mirror_cache[p]].flag &= ~PEP_EDIT_RECALC; @@ -939,110 +1022,152 @@ static void PE_apply_mirror(Object *ob, ParticleSystem *psys) /************************************************/ /* Edit Calculation */ /************************************************/ -/* 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); + +typedef struct DeflectEmitterIter { + Object *object; ParticleSystem *psys; - ParticleSystemModifierData *psmd; - POINT_P; KEY_K; + PTCacheEdit *edit; + float dist; + float emitterdist; +} DeflectEmitterIter; + +static void deflect_emitter_iter( + void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) + { + DeflectEmitterIter *iter_data = (DeflectEmitterIter *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if ((point->flag & PEP_EDIT_RECALC) == 0) { + return; + } + Object *object = iter_data->object; + ParticleSystem *psys = iter_data->psys; + ParticleSystemModifierData *psmd_eval = iter_data->edit->psmd_eval; + PTCacheEditKey *key; + int k; + float hairimat[4][4], hairmat[4][4]; int index; 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)) - return; - - psys = edit->psys; - psmd = psys_get_modifier(ob, psys); - - if (!psmd->mesh_final) - return; + const float dist = iter_data->dist; + const float emitterdist = iter_data->emitterdist; + psys_mat_hair_to_object(object, + psmd_eval->mesh_final, + psys->part->from, + psys->particles + iter, + hairmat); - LOOP_EDITED_POINTS { - psys_mat_hair_to_object(ob, psmd->mesh_final, psys->part->from, psys->particles + p, hairmat); + LOOP_KEYS { + mul_m4_v3(hairmat, key->co); + } - LOOP_KEYS { - mul_m4_v3(hairmat, key->co); + LOOP_KEYS { + if (k == 0) { + dist_1st = len_v3v3((key + 1)->co, key->co); + dist_1st *= dist * emitterdist; } + else { + index = BLI_kdtree_find_nearest(edit->emitter_field, key->co, NULL); - LOOP_KEYS { - 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); - - 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); + sub_v3_v3v3(dvec, key->co, vec); - dot=dot_v3v3(dvec, nor); - copy_v3_v3(dvec, nor); + dot = dot_v3v3(dvec, nor); + copy_v3_v3(dvec, nor); - if (dot>0.0f) { - if (dot<dist_1st) { - normalize_v3(dvec); - mul_v3_fl(dvec, dist_1st-dot); - add_v3_v3(key->co, dvec); - } - } - else { + 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); } - if (k==1) - dist_1st*=1.3333f; + } + else { + normalize_v3(dvec); + mul_v3_fl(dvec, dist_1st - dot); + add_v3_v3(key->co, dvec); + } + if (k == 1) { + dist_1st *= 1.3333f; } } + } - invert_m4_m4(hairimat, hairmat); + invert_m4_m4(hairimat, hairmat); - LOOP_KEYS { - mul_m4_v3(hairimat, key->co); - } + LOOP_KEYS { + mul_m4_v3(hairimat, key->co); } } -/* force set distances between neighboring keys */ -static void PE_apply_lengths(Scene *scene, PTCacheEdit *edit) -{ - ParticleEditSettings *pset=PE_settings(scene); - POINT_P; KEY_K; - float dv1[3]; +/* 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); + ParticleSystem *psys; + const float dist = ED_view3d_select_dist_px() * 0.01f; - if (edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0) + if (edit == NULL || edit->psys == NULL || + (pset->flag & PE_DEFLECT_EMITTER) == 0 || + (edit->psys->flag & PSYS_GLOBAL_HAIR)) + { return; + } - if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) + psys = edit->psys; + + if (!edit->psmd_eval->mesh_final) { return; + } - LOOP_EDITED_POINTS { - LOOP_KEYS { - if (k) { - sub_v3_v3v3(dv1, key->co, (key - 1)->co); - normalize_v3(dv1); - mul_v3_fl(dv1, (key - 1)->length); - add_v3_v3v3(key->co, (key - 1)->co, dv1); - } + DeflectEmitterIter iter_data; + iter_data.object = ob; + iter_data.psys = psys; + iter_data.edit = edit; + iter_data.dist = dist; + iter_data.emitterdist = pset->emitterdist; + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, deflect_emitter_iter, &settings); +} + +typedef struct ApplyLengthsIterData { + PTCacheEdit *edit; +} ApplyLengthsIterData; + +static void apply_lengths_iter( + void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) + { + ApplyLengthsIterData *iter_data = (ApplyLengthsIterData *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if ((point->flag & PEP_EDIT_RECALC) == 0) { + return; + } + PTCacheEditKey *key; + int k; + LOOP_KEYS { + if (k) { + float dv1[3]; + sub_v3_v3v3(dv1, key->co, (key - 1)->co); + normalize_v3(dv1); + mul_v3_fl(dv1, (key - 1)->length); + add_v3_v3v3(key->co, (key - 1)->co, dv1); } } } -/* try to find a nice solution to keep distances between neighboring keys */ -static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit) + +/* force set distances between neighboring keys */ +static void PE_apply_lengths(Scene *scene, PTCacheEdit *edit) { ParticleEditSettings *pset=PE_settings(scene); - POINT_P; - PTCacheEditKey *key; - int j, k; - float tlen; - float dv0[3] = {0.0f, 0.0f, 0.0f}; - 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) return; @@ -1050,43 +1175,91 @@ static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit) if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) return; - LOOP_EDITED_POINTS { - 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; - dv1[0] = dv1[1] = dv1[2] = 0.0; - } - else { - key= point->keys; - k= 0; - dv0[0] = dv0[1] = dv0[2] = 0.0; - } - - for (; k<point->totkey; k++, key++) { - if (k) { - sub_v3_v3v3(dv0, (key - 1)->co, key->co); - tlen= normalize_v3(dv0); - mul_v3_fl(dv0, (mul * (tlen - (key - 1)->length))); - } + ApplyLengthsIterData iter_data; + iter_data.edit = edit; - if (k < point->totkey - 1) { - sub_v3_v3v3(dv2, (key + 1)->co, key->co); - tlen= normalize_v3(dv2); - mul_v3_fl(dv2, mul * (tlen - key->length)); - } + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, apply_lengths_iter, &settings); +} - if (k) { - add_v3_v3((key-1)->co, dv1); - } +typedef struct IterateLengthsIterData { + PTCacheEdit *edit; + ParticleEditSettings *pset; +} IterateLengthsIterData; + +static void iterate_lengths_iter( + void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + IterateLengthsIterData *iter_data = (IterateLengthsIterData *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if ((point->flag & PEP_EDIT_RECALC) == 0) { + return; + } + ParticleEditSettings *pset = iter_data->pset; + float tlen; + float dv0[3] = {0.0f, 0.0f, 0.0f}; + float dv1[3] = {0.0f, 0.0f, 0.0f}; + float dv2[3] = {0.0f, 0.0f, 0.0f}; + for (int j = 1; j < point->totkey; j++) { + PTCacheEditKey *key; + int k; + float mul = 1.0f / (float)point->totkey; + if (pset->flag & PE_LOCK_FIRST) { + key = point->keys + 1; + k = 1; + dv1[0] = dv1[1] = dv1[2] = 0.0; + } + else { + key = point->keys; + k = 0; + dv0[0] = dv0[1] = dv0[2] = 0.0; + } - add_v3_v3v3(dv1, dv0, dv2); + for (; k < point->totkey; k++, key++) { + if (k) { + sub_v3_v3v3(dv0, (key - 1)->co, key->co); + 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); + mul_v3_fl(dv2, mul * (tlen - key->length)); + } + if (k) { + add_v3_v3((key-1)->co, dv1); } + add_v3_v3v3(dv1, dv0, dv2); } } } + +/* 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); + if (edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0) { + return; + } + if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) { + return; + } + + IterateLengthsIterData iter_data; + iter_data.edit = edit; + iter_data.pset = pset; + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, iterate_lengths_iter, &settings); +} + /* set current distances to be kept between neighbouting keys */ void recalc_lengths(PTCacheEdit *edit) { @@ -1104,10 +1277,10 @@ void recalc_lengths(PTCacheEdit *edit) } /* calculate a tree for finding nearest emitter's vertice */ -void recalc_emitter_field(Depsgraph *UNUSED(depsgraph), Object *ob, ParticleSystem *psys) +void recalc_emitter_field(Depsgraph *UNUSED(depsgraph), Object *UNUSED(ob), ParticleSystem *psys) { - Mesh *mesh = psys_get_modifier(ob, psys)->mesh_final; PTCacheEdit *edit = psys->edit; + Mesh *mesh = edit->psmd_eval->mesh_final; float *vec, *nor; int i, totface /*, totvert*/; @@ -1197,16 +1370,16 @@ static void PE_update_selection(Depsgraph *depsgraph, Scene *scene, Object *ob, void update_world_cos(Depsgraph *UNUSED(depsgraph), Object *ob, PTCacheEdit *edit) { ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; POINT_P; KEY_K; float hairmat[4][4]; - if (psys == 0 || psys->edit == 0 || psmd->mesh_final == NULL) + if (psys == 0 || psys->edit == 0 || psmd_eval->mesh_final == NULL) return; LOOP_POINTS { if (!(psys->flag & PSYS_GLOBAL_HAIR)) - psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, psys->particles+p, hairmat); + psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, psys->particles+p, hairmat); LOOP_KEYS { copy_v3_v3(key->world_co, key->co); @@ -1638,8 +1811,6 @@ static int select_random_exec(bContext *C, wmOperator *op) { PEData data; int type; - Scene *scene; - Object *ob; /* used by LOOP_VISIBLE_POINTS, LOOP_VISIBLE_KEYS and LOOP_KEYS */ PTCacheEdit *edit; @@ -1657,9 +1828,7 @@ static int select_random_exec(bContext *C, wmOperator *op) PE_set_data(C, &data); data.select_action = SEL_SELECT; - scene = CTX_data_scene(C); - ob = CTX_data_active_object(C); - edit = PE_get_current(scene, ob); + edit = PE_get_current(data.scene, data.ob); rng = BLI_rng_new_srandom(seed); @@ -1833,7 +2002,7 @@ int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, bool ParticleEditSettings *pset= PE_settings(scene); PTCacheEdit *edit = PE_get_current(scene, ob); ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; POINT_P; KEY_K; float co[3], mat[4][4]; int screen_co[2]; @@ -1853,7 +2022,7 @@ int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, bool LOOP_VISIBLE_POINTS { if (edit->psys && !(psys->flag & PSYS_GLOBAL_HAIR)) - psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, psys->particles + p, mat); + psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); if (pset->selectmode==SCE_SELECT_POINT) { LOOP_KEYS { @@ -2290,15 +2459,15 @@ static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror) ParticleData *pa, *npa=0, *new_pars=0; POINT_P; PTCacheEditPoint *npoint=0, *new_points=0; - ParticleSystemModifierData *psmd; + ParticleSystemModifierData *psmd_eval; int i, new_totpart= psys->totpart, removed= 0; if (mirror) { /* mirror tags */ - psmd= psys_get_modifier(ob, psys); + psmd_eval = edit->psmd_eval; LOOP_TAGGED_POINTS { - PE_mirror_particle(ob, psmd->mesh_final, psys, psys->particles + p, NULL); + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); } } @@ -2369,16 +2538,16 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) HairKey *hkey, *nhkey, *new_hkeys=0; POINT_P; KEY_K; PTCacheEditKey *nkey, *new_keys; - ParticleSystemModifierData *psmd; + ParticleSystemModifierData *psmd_eval; short new_totkey; if (pe_x_mirror(ob)) { /* mirror key tags */ - psmd= psys_get_modifier(ob, psys); + psmd_eval = psys_get_modifier(ob, psys); LOOP_POINTS { LOOP_TAGGED_KEYS { - PE_mirror_particle(ob, psmd->mesh_final, psys, psys->particles + p, NULL); + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); break; } } @@ -2572,7 +2741,7 @@ static int remove_doubles_exec(bContext *C, wmOperator *op) Object *ob= CTX_data_active_object(C); PTCacheEdit *edit= PE_get_current(scene, ob); ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd; + ParticleSystemModifierData *psmd_eval; KDTree *tree; KDTreeNearest nearest[10]; POINT_P; @@ -2583,7 +2752,7 @@ static int remove_doubles_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; edit= psys->edit; - psmd= psys_get_modifier(ob, psys); + psmd_eval = edit->psmd_eval; totremoved= 0; do { @@ -2593,7 +2762,7 @@ static int remove_doubles_exec(bContext *C, wmOperator *op) /* insert particles into kd tree */ LOOP_SELECTED_POINTS { - psys_mat_hair_to_object(ob, psmd->mesh_final, psys->part->from, psys->particles+p, mat); + psys_mat_hair_to_object(ob, psmd_eval->mesh_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); @@ -2603,7 +2772,7 @@ static int remove_doubles_exec(bContext *C, wmOperator *op) /* tag particles to be removed */ LOOP_SELECTED_POINTS { - psys_mat_hair_to_object(ob, psmd->mesh_final, psys->part->from, psys->particles+p, mat); + psys_mat_hair_to_object(ob, psmd_eval->mesh_final, psys->part->from, psys->particles+p, mat); copy_v3_v3(co, point->keys->co); mul_m4_v3(mat, co); @@ -2824,7 +2993,7 @@ static void PE_mirror_x( Scene *scene, Object *ob, int tagged) { Mesh *me= (Mesh *)(ob->data); - ParticleSystemModifierData *psmd; + ParticleSystemModifierData *psmd_eval; PTCacheEdit *edit = PE_get_current(scene, ob); ParticleSystem *psys = edit->psys; ParticleData *pa, *newpa, *new_pars; @@ -2837,18 +3006,18 @@ static void PE_mirror_x( if (psys->flag & PSYS_GLOBAL_HAIR) return; - psmd= psys_get_modifier(ob, psys); - if (!psmd->mesh_final) + psmd_eval = edit->psmd_eval; + if (!psmd_eval->mesh_final) return; - const bool use_dm_final_indices = (psys->part->use_modifier_stack && !psmd->mesh_final->runtime.deformed_only); + const bool use_dm_final_indices = (psys->part->use_modifier_stack && !psmd_eval->mesh_final->runtime.deformed_only); /* NOTE: this is not nice to use tessfaces but hard to avoid since pa->num uses tessfaces */ BKE_mesh_tessface_ensure(me); /* Note: In case psys uses Mesh tessface indices, we mirror final Mesh itself, not orig mesh. Avoids an (impossible) * mesh -> orig -> mesh tessface indices conversion... */ - mirrorfaces = mesh_get_x_mirror_faces__real_mesh(ob, NULL, use_dm_final_indices ? psmd->mesh_final : NULL); + mirrorfaces = mesh_get_x_mirror_faces__real_mesh(ob, NULL, use_dm_final_indices ? psmd_eval->mesh_final : NULL); if (!edit->mirror_cache) PE_update_mirror_cache(ob, psys); @@ -2862,7 +3031,7 @@ static void PE_mirror_x( if (point_is_selected(point)) { if (edit->mirror_cache[p] != -1) { /* already has a mirror, don't need to duplicate */ - PE_mirror_particle(ob, psmd->mesh_final, psys, pa, NULL); + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, pa, NULL); continue; } else @@ -2875,7 +3044,7 @@ static void PE_mirror_x( } if (newtotpart != psys->totpart) { - MFace *mtessface = use_dm_final_indices ? psmd->mesh_final->mface : me->mface; + MFace *mtessface = use_dm_final_indices ? psmd_eval->mesh_final->mface : me->mface; /* allocate new arrays and copy existing */ new_pars= MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new"); @@ -2944,7 +3113,7 @@ static void PE_mirror_x( } else { newpa->num_dmcache = psys_particle_dm_face_lookup( - psmd->mesh_final, psmd->mesh_original, newpa->num, newpa->fuv, NULL); + psmd_eval->mesh_final, psmd_eval->mesh_original, newpa->num, newpa->fuv, NULL); } /* update edit key pointers */ @@ -2955,7 +3124,7 @@ static void PE_mirror_x( } /* map key positions as mirror over x axis */ - PE_mirror_particle(ob, psmd->mesh_final, psys, pa, newpa); + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, pa, newpa); newpa++; newpoint++; @@ -3030,8 +3199,11 @@ static void brush_cut(PEData *data, int pa_index) int k, cut, keys= (int)pow(2.0, (double)pset->draw_step); int screen_co[2]; + BLI_assert(data->rng != NULL); /* blunt scissors */ - if (BLI_frand() > data->cutfac) return; + if (BLI_rng_get_float(data->rng) > data->cutfac) { + return; + } /* don't cut hidden */ if (edit->points[pa_index].flag & PEP_HIDE) @@ -3360,14 +3532,13 @@ static void intersect_dm_quad_weights(const float v1[3], const float v2[3], cons } /* check intersection with a derivedmesh */ -static int particle_intersect_mesh(const bContext *C, Scene *scene, Object *ob, Mesh *mesh, - float *vert_cos, - const float co1[3], const float co2[3], - float *min_d, int *min_face, float *min_w, - float *face_minmax, float *pa_minmax, - float radius, float *ipoint) +static int particle_intersect_mesh(Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *mesh, + float *vert_cos, + const float co1[3], const float co2[3], + float *min_d, int *min_face, float *min_w, + float *face_minmax, float *pa_minmax, + float radius, float *ipoint) { - Depsgraph *depsgraph = CTX_data_depsgraph(C); MFace *mface= NULL; MVert *mvert= NULL; int i, totface, intersect=0; @@ -3496,6 +3667,109 @@ static int particle_intersect_mesh(const bContext *C, Scene *scene, Object *ob, return intersect; } +typedef struct BrushAddCountIterData { + Depsgraph *depsgraph; + Scene *scene; + Object *object; + Mesh *mesh; + PEData *data; + int number; + short size; + float imat[4][4]; + ParticleData *add_pars; + int num_added; +} BrushAddCountIterData; + +typedef struct BrushAddCountIterTLSData { + RNG *rng; + int num_added; +} BrushAddCountIterTLSData; + +static void brush_add_count_iter( + void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict tls_v) +{ + BrushAddCountIterData *iter_data = (BrushAddCountIterData *)iter_data_v; + Depsgraph *depsgraph = iter_data->depsgraph; + PEData *data = iter_data->data; + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; + ParticleData *add_pars = iter_data->add_pars; + BrushAddCountIterTLSData *tls = tls_v->userdata_chunk; + const int number = iter_data->number; + const short size = iter_data->size; + const short size2 = size*size; + float dmx, dmy; + if (number > 1) { + dmx = size; + dmy = size; + if (tls->rng == NULL) { + tls->rng = BLI_rng_new_srandom( + psys->seed + data->mval[0] + data->mval[1] + tls_v->thread_id); + } + /* rejection sampling to get points in circle */ + while (dmx*dmx + dmy*dmy > size2) { + dmx = (2.0f*BLI_rng_get_float(tls->rng) - 1.0f)*size; + dmy = (2.0f*BLI_rng_get_float(tls->rng) - 1.0f)*size; + } + } + else { + dmx = 0.0f; + dmy = 0.0f; + } + + float mco[2]; + mco[0] = data->mval[0] + dmx; + mco[1] = data->mval[1] + dmy; + + float co1[3], co2[3]; + ED_view3d_win_to_segment(depsgraph, data->vc.ar, data->vc.v3d, mco, co1, co2, true); + + mul_m4_v3(iter_data->imat, co1); + mul_m4_v3(iter_data->imat, co2); + float min_d = 2.0; + + /* warning, returns the derived mesh face */ + BLI_assert(iter_data->mesh != NULL); + if (particle_intersect_mesh(depsgraph, iter_data->scene, iter_data->object, iter_data->mesh, + 0, co1, co2, + &min_d, + &add_pars[iter].num_dmcache, + add_pars[iter].fuv, + 0, 0, 0, 0)) { + if (psys->part->use_modifier_stack && !psmd_eval->mesh_final->runtime.deformed_only) { + add_pars[iter].num = add_pars[iter].num_dmcache; + add_pars[iter].num_dmcache = DMCACHE_ISCHILD; + } + else if (iter_data->mesh == psmd_eval->mesh_original) { + /* Final DM is not same topology as orig mesh, we have to map num_dmcache to real final dm. */ + add_pars[iter].num = add_pars[iter].num_dmcache; + add_pars[iter].num_dmcache = psys_particle_dm_face_lookup( + psmd_eval->mesh_final, psmd_eval->mesh_original, + add_pars[iter].num, add_pars[iter].fuv, NULL); + } + else { + add_pars[iter].num = add_pars[iter].num_dmcache; + } + if (add_pars[iter].num != DMCACHE_NOTFOUND) { + tls->num_added++; + } + } +} + +static void brush_add_count_iter_finalize(void *__restrict userdata_v, + void *__restrict userdata_chunk_v) +{ + BrushAddCountIterData *iter_data = (BrushAddCountIterData *)userdata_v; + BrushAddCountIterTLSData *tls = (BrushAddCountIterTLSData *)userdata_chunk_v; + iter_data->num_added += tls->num_added; + if (tls->rng != NULL) { + BLI_rng_free(tls->rng); + } +} + static int brush_add(const bContext *C, PEData *data, short number) { Depsgraph *depsgraph = CTX_data_depsgraph(C); @@ -3505,16 +3779,13 @@ static int brush_add(const bContext *C, PEData *data, short number) PTCacheEdit *edit = data->edit; ParticleSystem *psys= edit->psys; ParticleData *add_pars; - ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys); + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; 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 co1[3], imat[4][4]; float framestep, timestep; short size= pset->brush[PE_BRUSH_ADD].size; - short size2= size*size; RNG *rng; invert_m4_m4(imat, ob->obmat); @@ -3527,67 +3798,65 @@ static int brush_add(const bContext *C, PEData *data, short number) rng = BLI_rng_new_srandom(psys->seed+data->mval[0]+data->mval[1]); sim.depsgraph = depsgraph; - sim.scene= scene; - sim.ob= ob; - sim.psys= psys; - sim.psmd= psmd; + sim.scene = scene; + sim.ob = ob; + sim.psys = psys; + sim.psmd = psmd_eval; - timestep= psys_get_timestep(&sim); + timestep = psys_get_timestep(&sim); - if (psys->part->use_modifier_stack || psmd->mesh_final->runtime.deformed_only) { - mesh = psmd->mesh_final; + if (psys->part->use_modifier_stack || psmd_eval->mesh_final->runtime.deformed_only) { + mesh = psmd_eval->mesh_final; } else { - mesh = psmd->mesh_original; + mesh = psmd_eval->mesh_original; } BLI_assert(mesh); - 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; - } + /* Calculate positions of new particles to add, based on brush interseciton + * with object. New particle data is assigned to a correponding to check + * index element of add_pars array. This means, that add_pars is a sparse + * array. + */ + BrushAddCountIterData iter_data; + iter_data.depsgraph = depsgraph; + iter_data.scene = scene; + iter_data.object = ob; + iter_data.mesh = mesh; + iter_data.data = data; + iter_data.number = number; + iter_data.size = size; + iter_data.add_pars = add_pars; + iter_data.num_added = 0; + copy_m4_m4(iter_data.imat, imat); + + BrushAddCountIterTLSData tls = {NULL}; + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + settings.userdata_chunk = &tls; + settings.userdata_chunk_size = sizeof(BrushAddCountIterTLSData); + settings.func_finalize = brush_add_count_iter_finalize; + BLI_task_parallel_range(0, number, &iter_data, brush_add_count_iter, &settings); + + /* Convert add_parse to a dense array, where all new particles are in the + * beginnign of the array. + */ + n = iter_data.num_added; + for (int current_iter = 0, new_index = 0; current_iter < number; current_iter++) { + if (add_pars[current_iter].num == DMCACHE_NOTFOUND) { + continue; } - else { - dmx = 0.0f; - dmy = 0.0f; - } - - mco[0] = data->mval[0] + dmx; - mco[1] = data->mval[1] + dmy; - ED_view3d_win_to_segment(depsgraph, data->vc.ar, data->vc.v3d, mco, co1, co2, true); - - mul_m4_v3(imat, co1); - mul_m4_v3(imat, co2); - min_d=2.0; - - /* warning, returns the derived mesh face */ - if (particle_intersect_mesh(C, scene, ob, mesh, 0, co1, co2, &min_d, &add_pars[n].num_dmcache, add_pars[n].fuv, 0, 0, 0, 0)) { - if (psys->part->use_modifier_stack && !psmd->mesh_final->runtime.deformed_only) { - add_pars[n].num = add_pars[n].num_dmcache; - add_pars[n].num_dmcache = DMCACHE_ISCHILD; - } - else if (mesh == psmd->mesh_original) { - /* 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->mesh_final, psmd->mesh_original, - add_pars[n].num, add_pars[n].fuv, NULL); - } - else { - add_pars[n].num = add_pars[n].num_dmcache; - } - - if (add_pars[n].num != DMCACHE_NOTFOUND) { - n++; - } + if (new_index != current_iter) { + new_index++; + continue; } + memcpy(add_pars + new_index, add_pars + current_iter, sizeof(ParticleData)); + new_index++; } + + /* TODO(sergey): Consider multi-threading this part as well. */ if (n) { int newtotpart=totpart+n; float hairmat[4][4], cur_co[3]; @@ -3618,7 +3887,7 @@ static int brush_add(const bContext *C, PEData *data, short number) tree=BLI_kdtree_new(psys->totpart); for (i=0, pa=psys->particles; i<totpart; i++, pa++) { - psys_particle_on_dm(psmd->mesh_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, cur_co, 0, 0, 0, 0); + psys_particle_on_dm(psmd_eval->mesh_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, cur_co, 0, 0, 0, 0); BLI_kdtree_insert(tree, i, cur_co); } @@ -3662,7 +3931,7 @@ static int brush_add(const bContext *C, PEData *data, short number) int w, maxw; float maxd, totw=0.0, weight[3]; - psys_particle_on_dm(psmd->mesh_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, co1, 0, 0, 0, 0); + psys_particle_on_dm(psmd_eval->mesh_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, co1, 0, 0, 0, 0); maxw = BLI_kdtree_find_nearest_n(tree, co1, ptn, 3); maxd= ptn[maxw-1].dist; @@ -3727,7 +3996,7 @@ static int brush_add(const bContext *C, PEData *data, short number) } } for (k=0, hkey=pa->hair; k<pset->totaddkey; k++, hkey++) { - psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, pa, hairmat); + psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, pa, hairmat); invert_m4_m4(imat, hairmat); mul_m4_v3(imat, hkey->co); } @@ -3792,6 +4061,7 @@ static int brush_edit_init(bContext *C, wmOperator *op) /* cache view depths and settings for re-use */ PE_set_view3d_data(C, &bedit->data); + PE_create_random_generator(&bedit->data); return 1; } @@ -3804,7 +4074,7 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) Object *ob= bedit->ob; PTCacheEdit *edit= bedit->edit; ParticleEditSettings *pset= PE_settings(scene); - ParticleSystemModifierData *psmd= edit->psys ? psys_get_modifier(ob, edit->psys) : NULL; + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; ParticleBrushData *brush= &pset->brush[pset->brushtype]; ARegion *ar= CTX_wm_region(C); float vec[3], mousef[2]; @@ -3840,7 +4110,7 @@ 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; data.context = C; // TODO(mai): why isnt this set in bedit->data? view3d_operator_needs_opengl(C); @@ -3919,7 +4189,7 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) case PE_BRUSH_PUFF: { if (edit->psys) { - data.mesh = psmd->mesh_final; + data.mesh = psmd_eval->mesh_final; data.mval= mval; data.rad= pe_brush_size_get(scene, brush); data.select= selected; @@ -3975,7 +4245,7 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) case PE_BRUSH_WEIGHT: { if (edit->psys) { - data.mesh = psmd->mesh_final; + data.mesh = psmd_eval->mesh_final; data.mval= mval; data.rad= pe_brush_size_get(scene, brush); @@ -4006,7 +4276,7 @@ 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); BKE_particle_batch_cache_dirty(edit->psys, BKE_PARTICLE_BATCH_DIRTY_ALL); - DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE); + DEG_id_tag_update(&ob->id, DEG_TAG_SELECT_UPDATE); } else { DEG_id_tag_update(&ob->id, OB_RECALC_DATA); @@ -4025,6 +4295,7 @@ static void brush_edit_exit(wmOperator *op) { BrushEdit *bedit= op->customdata; + PE_free_random_generator(&bedit->data); MEM_freeN(bedit); } @@ -4079,8 +4350,11 @@ static int brush_edit_modal(bContext *C, wmOperator *op, const wmEvent *event) case LEFTMOUSE: case MIDDLEMOUSE: case RIGHTMOUSE: // XXX hardcoded - brush_edit_exit(op); - return OPERATOR_FINISHED; + if (event->val == KM_RELEASE) { + brush_edit_exit(op); + return OPERATOR_FINISHED; + } + break; case MOUSEMOVE: brush_edit_apply_event(C, op, event); break; @@ -4271,7 +4545,7 @@ static int shape_cut_exec(bContext *C, wmOperator *UNUSED(op)) if (edit->psys) { WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); BKE_particle_batch_cache_dirty(edit->psys, BKE_PARTICLE_BATCH_DIRTY_ALL); - DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE); + DEG_id_tag_update(&ob->id, DEG_TAG_SELECT_UPDATE); } else { DEG_id_tag_update(&ob->id, OB_RECALC_DATA); @@ -4308,7 +4582,7 @@ int PE_minmax(Scene *scene, ViewLayer *view_layer, float min[3], float max[3]) Object *ob= OBACT(view_layer); PTCacheEdit *edit= PE_get_current(scene, ob); ParticleSystem *psys; - ParticleSystemModifierData *psmd = NULL; + ParticleSystemModifierData *psmd_eval = NULL; POINT_P; KEY_K; float co[3], mat[4][4]; int ok= 0; @@ -4316,13 +4590,13 @@ int PE_minmax(Scene *scene, ViewLayer *view_layer, float min[3], float max[3]) if (!edit) return ok; if ((psys = edit->psys)) - psmd= psys_get_modifier(ob, psys); + psmd_eval = edit->psmd_eval; else unit_m4(mat); LOOP_VISIBLE_POINTS { if (psys) - psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, psys->particles+p, mat); + psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, psys->particles+p, mat); LOOP_SELECTED_KEYS { copy_v3_v3(co, key->co); @@ -4342,19 +4616,43 @@ int PE_minmax(Scene *scene, ViewLayer *view_layer, float min[3], float max[3]) /************************ particle edit toggle operator ************************/ +static struct ParticleSystem *psys_eval_get(Depsgraph *depsgraph, + Object *object, + ParticleSystem *psys) +{ + Object *object_eval = DEG_get_evaluated_object(depsgraph, object); + if (object_eval == object) { + return psys; + } + ParticleSystem *psys_eval = object_eval->particlesystem.first; + while (psys_eval != NULL) { + if (psys_eval->orig_psys == psys) { + return psys_eval; + } + psys_eval = psys_eval->next; + } + return psys_eval; +} + /* initialize needed data for bake edit */ void PE_create_particle_edit( Depsgraph *depsgraph, Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys) { + Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); PTCacheEdit *edit; ParticleSystemModifierData *psmd = (psys) ? psys_get_modifier(ob, psys) : NULL; + ParticleSystemModifierData *psmd_eval = NULL; POINT_P; KEY_K; ParticleData *pa = NULL; HairKey *hkey; int totpoint; + if (psmd != NULL) { + psmd_eval = (ParticleSystemModifierData *)modifiers_findByName(ob_eval, psmd->modifier.name); + } + /* no psmd->dm happens in case particle system modifier is not enabled */ - if (!(psys && psmd && psmd->mesh_final) && !cache) + if (!(psys && psmd && psmd_eval->mesh_final) && !cache) return; if (cache && cache->flag & PTCACHE_DISK_CACHE) @@ -4366,6 +4664,9 @@ void PE_create_particle_edit( edit = (psys) ? psys->edit : cache->edit; if (!edit) { + ParticleSystem *psys_eval = psys_eval_get(depsgraph, ob, psys); + psys_copy_particles(psys, psys_eval); + totpoint = psys ? psys->totpart : (int)((PTCacheMem *)cache->mem_cache.first)->totpoint; edit= MEM_callocN(sizeof(PTCacheEdit), "PE_create_particle_edit"); @@ -4373,8 +4674,11 @@ void PE_create_particle_edit( edit->totpoint = totpoint; if (psys && !cache) { - psys->edit= edit; + edit->psmd = psmd; + edit->psmd_eval = psmd_eval; + psys->edit = edit; edit->psys = psys; + edit->psys_eval = psys_eval; psys->free_edit= PE_free_ptcache_edit; @@ -4439,9 +4743,14 @@ void PE_create_particle_edit( psys = NULL; } + /* Causes assert on startup. */ +#if 0 UI_GetThemeColor3ubv(TH_EDGE_SELECT, edit->sel_col); UI_GetThemeColor3ubv(TH_WIRE, edit->nosel_col); - +#else + memset(edit->sel_col, 0xff, sizeof(edit->sel_col)); + memset(edit->nosel_col, 0x00, sizeof(edit->nosel_col)); +#endif recalc_lengths(edit); if (psys && !cache) recalc_emitter_field(depsgraph, ob, psys); @@ -4484,14 +4793,6 @@ static int particle_edit_toggle_exec(bContext *C, wmOperator *op) if (!is_mode_set) { PTCacheEdit *edit; - /* Particle edit mode requires original object to have all strands - * cached. A bit annoying to do update here, but is simpler than - * rewriting the while edit mode code. - */ - ob->id.recalc |= (ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY); - BKE_scene_graph_update_tagged(depsgraph, CTX_data_main(C)); - BKE_object_eval_transform_all(depsgraph, scene, ob); - BKE_object_handle_data_update(depsgraph, scene, ob); ob->mode |= mode_flag; edit= PE_create_current(depsgraph, scene, ob); @@ -4678,7 +4979,6 @@ static int unify_length_exec(bContext *C, wmOperator *UNUSED(op)) } scale_points_to_length(edit, average_length); - PE_update_object(depsgraph, scene, ob, 1); if (edit->psys) { WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); diff --git a/source/blender/editors/physics/particle_edit_undo.c b/source/blender/editors/physics/particle_edit_undo.c index 6576d692f70..fdf765e4557 100644 --- a/source/blender/editors/physics/particle_edit_undo.c +++ b/source/blender/editors/physics/particle_edit_undo.c @@ -44,9 +44,9 @@ #include "BLI_string.h" #include "BLI_utildefines.h" +#include "BKE_context.h" #include "BKE_particle.h" #include "BKE_pointcache.h" -#include "BKE_context.h" #include "BKE_undo_system.h" #include "DEG_depsgraph.h" diff --git a/source/blender/editors/physics/particle_object.c b/source/blender/editors/physics/particle_object.c index fbccdcfcdba..8a9eb369e66 100644 --- a/source/blender/editors/physics/particle_object.c +++ b/source/blender/editors/physics/particle_object.c @@ -82,13 +82,14 @@ 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); Scene *scene = CTX_data_scene(C); if (!scene || !ob) return OPERATOR_CANCELLED; - object_add_particle_system(scene, ob, NULL); + 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); @@ -113,6 +114,7 @@ void OBJECT_OT_particle_system_add(wmOperatorType *ot) static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op)) { + Main *bmain = CTX_data_main(C); Object *ob = ED_object_context(C); Scene *scene = CTX_data_scene(C); ViewLayer *view_layer = CTX_data_view_layer(C); @@ -122,7 +124,7 @@ static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; mode_orig = ob->mode; - object_remove_particle_system(scene, ob); + object_remove_particle_system(bmain, scene, ob); /* possible this isn't the active object * object_remove_particle_system() clears the mode on the last psys diff --git a/source/blender/editors/physics/physics_fluid.c b/source/blender/editors/physics/physics_fluid.c index 130dcba060d..904e4242ed1 100644 --- a/source/blender/editors/physics/physics_fluid.c +++ b/source/blender/editors/physics/physics_fluid.c @@ -399,7 +399,7 @@ static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), Fluid /* XXX: This can't be used due to an anim sys optimization that ignores recalc object animation, * leaving it for the depgraph (this ignores object animation such as modifier properties though... :/ ) - * --> BKE_animsys_evaluate_all_animation(G.main, eval_time); + * --> BKE_animsys_evaluate_all_animation(CTX_data_main(C), eval_time); * This doesn't work with drivers: * --> BKE_animsys_evaluate_animdata(&fsDomain->id, fsDomain->adt, eval_time, ADT_RECALC_ALL); */ diff --git a/source/blender/editors/physics/physics_pointcache.c b/source/blender/editors/physics/physics_pointcache.c index 45172774d55..343804726bf 100644 --- a/source/blender/editors/physics/physics_pointcache.c +++ b/source/blender/editors/physics/physics_pointcache.c @@ -140,7 +140,7 @@ static void ptcache_job_endjob(void *customdata) G.is_rendering = false; BKE_spacedata_draw_locks(false); - WM_set_locked_interface(G.main->wm.first, false); + WM_set_locked_interface(G_MAIN->wm.first, false); WM_main_add_notifier(NC_SCENE | ND_FRAME, scene); WM_main_add_notifier(NC_OBJECT | ND_POINTCACHE, job->baker->pid.ob); @@ -164,7 +164,7 @@ static PTCacheBaker *ptcache_baker_create(bContext *C, wmOperator *op, bool all) { PTCacheBaker *baker = MEM_callocN(sizeof(PTCacheBaker), "PTCacheBaker"); - baker->main = CTX_data_main(C); + baker->bmain = CTX_data_main(C); baker->scene = CTX_data_scene(C); baker->view_layer = CTX_data_view_layer(C); baker->depsgraph = CTX_data_depsgraph(C); diff --git a/source/blender/editors/physics/rigidbody_object.c b/source/blender/editors/physics/rigidbody_object.c index 99976898ac1..bdfbc47b22f 100644 --- a/source/blender/editors/physics/rigidbody_object.c +++ b/source/blender/editors/physics/rigidbody_object.c @@ -110,6 +110,7 @@ bool ED_rigidbody_object_add(Main *bmain, Scene *scene, Object *ob, int type, Re } if (rbw->group == NULL) { rbw->group = BKE_collection_add(bmain, NULL, "RigidBodyWorld"); + id_fake_user_set(&rbw->group->id); } /* make rigidbody object settings */ @@ -130,11 +131,7 @@ bool ED_rigidbody_object_add(Main *bmain, Scene *scene, Object *ob, int type, Re void ED_rigidbody_object_remove(Main *bmain, Scene *scene, Object *ob) { - RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); - - BKE_rigidbody_remove_object(scene, ob); - if (rbw) - BKE_collection_object_remove(bmain, rbw->group, ob, false); + BKE_rigidbody_remove_object(bmain, scene, ob); DEG_relations_tag_update(bmain); DEG_id_tag_update(&ob->id, OB_RECALC_OB); diff --git a/source/blender/editors/render/render_internal.c b/source/blender/editors/render/render_internal.c index d990f0b34d0..6a5844e323f 100644 --- a/source/blender/editors/render/render_internal.c +++ b/source/blender/editors/render/render_internal.c @@ -673,14 +673,14 @@ static void render_endjob(void *rjv) * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */ RE_InitRenderCB(rj->re); - if (rj->main != G.main) + if (rj->main != G_MAIN) BKE_main_free(rj->main); /* else the frame will not update for the original value */ if (rj->anim && !(rj->scene->r.scemode & R_NO_FRAME_UPDATE)) { /* possible this fails of loading new file while rendering */ - if (G.main->wm.first) { - ED_update_for_newframe(G.main, rj->depsgraph); + if (G_MAIN->wm.first) { + ED_update_for_newframe(G_MAIN, rj->depsgraph); } } @@ -741,7 +741,7 @@ static void render_endjob(void *rjv) * and using one from Global will unlock exactly the same manager as * was locked before running the job. */ - WM_set_locked_interface(G.main->wm.first, false); + WM_set_locked_interface(G_MAIN->wm.first, false); /* We've freed all the derived caches before rendering, which is * effectively the same as if we re-loaded the file. @@ -749,11 +749,11 @@ static void render_endjob(void *rjv) * So let's not try being smart here and just reset all updated * scene layers and use generic DAG_on_visible_update. */ - for (scene = G.main->scene.first; scene; scene = scene->id.next) { + for (scene = G_MAIN->scene.first; scene; scene = scene->id.next) { scene->lay_updated = 0; } - DEG_on_visible_update(G.main, false); + DEG_on_visible_update(G_MAIN, false); } } diff --git a/source/blender/editors/render/render_preview.c b/source/blender/editors/render/render_preview.c index 4a3c7a3fd4b..cdd79f43a72 100644 --- a/source/blender/editors/render/render_preview.c +++ b/source/blender/editors/render/render_preview.c @@ -176,6 +176,9 @@ typedef struct ShaderPreview { Main *bmain; Main *pr_main; + + void *gl_context; + bool gl_context_owner; } ShaderPreview; typedef struct IconPreviewSize { @@ -191,6 +194,8 @@ typedef struct IconPreview { void *owner; ID *id; ListBase sizes; + + void *gl_context; } IconPreview; /* *************************** Preview for buttons *********************** */ @@ -741,6 +746,10 @@ static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int firs /* set this for all previews, default is react to G.is_break still */ RE_test_break_cb(re, sp, shader_preview_break); + if (sp->gl_context) { + RE_gl_context_set(re, sp->gl_context); + } + /* lens adjust */ oldlens = ((Camera *)sce->camera->data)->lens; if (sizex > sp->sizey) @@ -860,6 +869,10 @@ static void shader_preview_free(void *customdata) } MEM_freeN(sp->lampcopy); } + if (sp->gl_context_owner && sp->gl_context) { + WM_opengl_context_dispose(sp->gl_context); + sp->gl_context = NULL; + } MEM_freeN(sp); } @@ -1075,6 +1088,8 @@ static void icon_preview_startjob_all_sizes(void *customdata, short *stop, short sp->pr_rect = cur_size->rect; sp->id = ip->id; sp->bmain = ip->bmain; + sp->gl_context = ip->gl_context; + sp->gl_context_owner = false; if (is_render) { BLI_assert(ip->id); @@ -1091,6 +1106,11 @@ static void icon_preview_startjob_all_sizes(void *customdata, short *stop, short common_preview_startjob(sp, stop, do_update, progress); shader_preview_free(sp); } + + if (ip->gl_context) { + WM_opengl_context_dispose(ip->gl_context); + ip->gl_context = NULL; + } } static void icon_preview_endjob(void *customdata) @@ -1174,8 +1194,17 @@ void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *r /* render all resolutions from suspended job too */ old_ip = WM_jobs_customdata_get(wm_job); - if (old_ip) + if (old_ip) { BLI_movelisttolist(&ip->sizes, &old_ip->sizes); + /* NOTE: This assumes that it will be the same thread + * that will be used when resuming the job. */ + ip->gl_context = old_ip->gl_context; + } + + if (ip->gl_context == NULL) { + /* Create context in the main thread. */ + ip->gl_context = WM_opengl_context_create(); + } /* customdata for preview thread */ ip->bmain = CTX_data_main(C); @@ -1206,7 +1235,7 @@ void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, M { Object *ob = CTX_data_active_object(C); wmJob *wm_job; - ShaderPreview *sp; + ShaderPreview *sp, *old_sp; Scene *scene = CTX_data_scene(C); short id_type = GS(id->name); @@ -1223,6 +1252,21 @@ void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, M WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW); sp = MEM_callocN(sizeof(ShaderPreview), "shader preview"); + /* Reuse previous gl context. */ + old_sp = WM_jobs_customdata_get(wm_job); + if (old_sp) { + /* NOTE: This assumes that it will be the same thread + * that will be used when resuming the job. */ + old_sp->gl_context_owner = false; /* Don't free it */ + sp->gl_context = old_sp->gl_context; + } + + if (sp->gl_context == NULL) { + /* Create context in the main thread. */ + sp->gl_context = WM_opengl_context_create(); + } + sp->gl_context_owner = true; + /* customdata for preview thread */ sp->scene = scene; sp->depsgraph = CTX_data_depsgraph(C); diff --git a/source/blender/editors/render/render_shading.c b/source/blender/editors/render/render_shading.c index 3f32242cd1b..a822dabf7b4 100644 --- a/source/blender/editors/render/render_shading.c +++ b/source/blender/editors/render/render_shading.c @@ -303,6 +303,7 @@ static int material_slot_de_select(bContext *C, bool select) } } + DEG_id_tag_update(ob->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data); return OPERATOR_FINISHED; diff --git a/source/blender/editors/screen/area.c b/source/blender/editors/screen/area.c index f73ce24c24b..d9851487569 100644 --- a/source/blender/editors/screen/area.c +++ b/source/blender/editors/screen/area.c @@ -953,6 +953,9 @@ static void region_overlap_fix(ScrArea *sa, ARegion *ar) } if (ar1->overlap && ((ar1->alignment & RGN_SPLIT_PREV) == 0)) { + if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) { + continue; + } align1 = ar1->alignment; if (BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) { if (align1 != align) { @@ -994,6 +997,9 @@ static void region_overlap_fix(ScrArea *sa, ARegion *ar) if (ar1->flag & (RGN_FLAG_HIDDEN)) { continue; } + if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) { + continue; + } if (ar1->overlap && (ar1->alignment & RGN_SPLIT_PREV) == 0) { if ((ar1->alignment != align) && BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) { @@ -1008,6 +1014,9 @@ static void region_overlap_fix(ScrArea *sa, ARegion *ar) /* overlapping regions only in the following restricted cases */ bool ED_region_is_overlap(int spacetype, int regiontype) { + if (regiontype == RGN_TYPE_HUD) { + return 1; + } if (U.uiflag2 & USER_REGION_OVERLAP) { if (ELEM(spacetype, SPACE_VIEW3D, SPACE_SEQ, SPACE_IMAGE)) { if (ELEM(regiontype, RGN_TYPE_TOOLS, RGN_TYPE_UI, RGN_TYPE_TOOL_PROPS)) @@ -1052,8 +1061,9 @@ static void region_rect_recursive(wmWindow *win, ScrArea *sa, ARegion *ar, rcti /* clear state flags first */ ar->flag &= ~RGN_FLAG_TOO_SMALL; /* user errors */ - if (ar->next == NULL && alignment != RGN_ALIGN_QSPLIT) + if ((ar->next == NULL) && !ELEM(alignment, RGN_ALIGN_QSPLIT, RGN_ALIGN_FLOAT)) { alignment = RGN_ALIGN_NONE; + } /* prefsize, taking into account DPI */ prefsizex = UI_DPI_FAC * ((ar->sizex > 1) ? ar->sizex + 0.5f : ar->type->prefsizex); @@ -1076,7 +1086,28 @@ static void region_rect_recursive(wmWindow *win, ScrArea *sa, ARegion *ar, rcti /* hidden is user flag */ } else if (alignment == RGN_ALIGN_FLOAT) { - /* XXX floating area region, not handled yet here */ + /** + * \note Currently this window type is only used for #RGN_TYPE_HUD, + * We expect the panel to resize it's self to be larger. + * + * This aligns to the lower left of the area. + */ + rcti overlap_remainder_margin = *overlap_remainder; + BLI_rcti_resize( + &overlap_remainder_margin, + max_ii(0, BLI_rcti_size_x(overlap_remainder) - UI_UNIT_X / 2), + max_ii(0, BLI_rcti_size_y(overlap_remainder) - UI_UNIT_Y / 2)); + ar->winrct.xmin = overlap_remainder_margin.xmin; + ar->winrct.ymin = overlap_remainder_margin.ymin; + ar->winrct.xmax = ar->winrct.xmin + ar->sizex - 1; + ar->winrct.ymax = ar->winrct.ymin + ar->sizey - 1; + + BLI_rcti_isect(&ar->winrct, &overlap_remainder_margin, &ar->winrct); + if (BLI_rcti_size_x(&ar->winrct) < UI_UNIT_X || + BLI_rcti_size_y(&ar->winrct) < UI_UNIT_Y) + { + ar->flag |= RGN_FLAG_TOO_SMALL; + } } else if (rct_fits(remainder, 'v', 1) < 0 || rct_fits(remainder, 'h', 1) < 0) { /* remainder is too small for any usage */ @@ -1215,7 +1246,7 @@ static void region_rect_recursive(wmWindow *win, ScrArea *sa, ARegion *ar, rcti if (ar->winy > 1) ar->sizey = (ar->winy + 0.5f) / UI_DPI_FAC; /* exception for multiple overlapping regions on same spot */ - if (ar->overlap) { + if (ar->overlap & (alignment != RGN_ALIGN_FLOAT)) { region_overlap_fix(sa, ar); } @@ -1424,7 +1455,7 @@ void ED_area_initialize(wmWindowManager *wm, wmWindow *win, ScrArea *sa) } for (ar = sa->regionbase.first; ar; ar = ar->next) - ar->type = BKE_regiontype_from_id(sa->type, ar->regiontype); + ar->type = BKE_regiontype_from_id_or_first(sa->type, ar->regiontype); /* area sizes */ area_calc_totrct(sa, &window_rect); @@ -1480,13 +1511,13 @@ static void region_update_rect(ARegion *ar) /** * Call to move a popup window (keep OpenGL context free!) */ -void ED_region_update_rect(bContext *UNUSED(C), ARegion *ar) +void ED_region_update_rect(ARegion *ar) { region_update_rect(ar); } /* externally called for floating regions like menus */ -void ED_region_init(bContext *UNUSED(C), ARegion *ar) +void ED_region_init(ARegion *ar) { /* refresh can be called before window opened */ region_subwindow(ar); @@ -1781,7 +1812,10 @@ static ThemeColorID region_background_color_id(const bContext *C, const ARegion static void region_clear_color(const bContext *C, const ARegion *ar, ThemeColorID colorid) { - if (ar->overlap) { + if (ar->alignment == RGN_ALIGN_FLOAT) { + /* handle our own drawing. */ + } + else if (ar->overlap) { /* view should be in pixelspace */ UI_view2d_view_restore(C); @@ -1806,15 +1840,16 @@ BLI_INLINE bool streq_array_any(const char *s, const char *arr[]) return false; } -static void ed_panel_draw(const bContext *C, - ScrArea *sa, - ARegion *ar, - ListBase *lb, - PanelType *pt, - Panel *panel, - int w, - int em, - bool vertical) +static void ed_panel_draw( + const bContext *C, + ScrArea *sa, + ARegion *ar, + ListBase *lb, + PanelType *pt, + Panel *panel, + int w, + int em, + bool vertical) { uiStyle *style = UI_style_get_dpi(); @@ -1827,6 +1862,21 @@ static void ed_panel_draw(const bContext *C, /* bad fixed values */ int xco, yco, h = 0; + if (pt->draw_header_preset && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) { + /* for preset menu */ + panel->layout = UI_block_layout( + block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER, + 0, (UI_UNIT_Y * 1.1f) + style->panelspace, UI_UNIT_Y, 1, 0, style); + + pt->draw_header_preset(C, panel); + + int headerend = w - UI_UNIT_X; + + UI_block_layout_resolve(block, &xco, &yco); + UI_block_translate(block, headerend - xco, 0); + panel->layout = NULL; + } + if (pt->draw_header && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) { int labelx, labely; UI_panel_label_offset(block, &labelx, &labely); @@ -1891,13 +1941,16 @@ static void ed_panel_draw(const bContext *C, * Matching against any of these strings will draw the panel. * Can be NULL to skip context checks. */ -void ED_region_panels(const bContext *C, ARegion *ar, const char *contexts[], int contextnr, const bool vertical) +void ED_region_panels_layout_ex( + const bContext *C, ARegion *ar, + const char *contexts[], int contextnr, const bool vertical) { + ar->runtime.category = NULL; + const WorkSpace *workspace = CTX_wm_workspace(C); ScrArea *sa = CTX_wm_area(C); PanelType *pt; View2D *v2d = &ar->v2d; - View2DScrollers *scrollers; int x, y, w, em; bool is_context_new = 0; int scroll; @@ -1908,6 +1961,7 @@ void ED_region_panels(const bContext *C, ARegion *ar, const char *contexts[], in const char *category = NULL; const int category_tabs_width = UI_PANEL_CATEGORY_MARGIN_WIDTH; int margin_x = 0; + const bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE; BLI_SMALLSTACK_DECLARE(pt_stack, PanelType *); @@ -2018,7 +2072,28 @@ void ED_region_panels(const bContext *C, ARegion *ar, const char *contexts[], in UI_panels_end(C, ar, &x, &y); /* before setting the view */ - if (vertical) { + if (region_layout_based) { + /* XXX, only single panel support atm. + * Can't use x/y values calculated above because they're not using the real height of panels, + * instead they calculate offsets for the next panel to start drawing. */ + Panel *panel = ar->panels.last; + if (panel != NULL) { + int size_dyn[2] = { + UI_UNIT_X * ((panel->flag & PNL_CLOSED) ? 8 : 14), + UI_panel_size_y(panel), + }; + /* region size is layout based and needs to be updated */ + if ((ar->sizex != size_dyn[0]) || + (ar->sizey != size_dyn[1])) + { + ar->sizex = size_dyn[0]; + ar->sizey = size_dyn[1]; + sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE; + } + y = ABS(ar->sizey - 1); + } + } + else if (vertical) { /* we always keep the scroll offset - so the total view gets increased with the scrolled away part */ if (v2d->cur.ymax < -FLT_EPSILON) { /* Clamp to lower view boundary */ @@ -2059,7 +2134,22 @@ void ED_region_panels(const bContext *C, ARegion *ar, const char *contexts[], in #endif } - region_clear_color(C, ar, (ar->type->regionid == RGN_TYPE_PREVIEW) ? TH_PREVIEW_BACK : TH_BACK); + if (use_category_tabs) { + ar->runtime.category = category; + } +} +void ED_region_panels_layout(const bContext *C, ARegion *ar) +{ + ED_region_panels_layout_ex(C, ar, NULL, -1, true); +} + +void ED_region_panels_draw(const bContext *C, ARegion *ar) +{ + View2D *v2d = &ar->v2d; + + if (ar->alignment != RGN_ALIGN_FLOAT) { + region_clear_color(C, ar, (ar->type->regionid == RGN_TYPE_PREVIEW) ? TH_PREVIEW_BACK : TH_BACK); + } /* reset line width for drawing tabs */ glLineWidth(1.0f); @@ -2073,16 +2163,34 @@ void ED_region_panels(const bContext *C, ARegion *ar, const char *contexts[], in /* restore view matrix */ UI_view2d_view_restore(C); - if (use_category_tabs) { - UI_panel_category_draw_all(ar, category); + /* Set in layout. */ + if (ar->runtime.category) { + UI_panel_category_draw_all(ar, ar->runtime.category); } /* scrollers */ - scrollers = UI_view2d_scrollers_calc(C, v2d, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY); + View2DScrollers *scrollers = UI_view2d_scrollers_calc( + C, v2d, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY); UI_view2d_scrollers_draw(C, v2d, scrollers); UI_view2d_scrollers_free(scrollers); } +void ED_region_panels_ex( + const bContext *C, ARegion *ar, + const char *contexts[], int contextnr, const bool vertical) +{ + /* TODO: remove? */ + ED_region_panels_layout_ex(C, ar, contexts, contextnr, vertical); + ED_region_panels_draw(C, ar); +} + +void ED_region_panels(const bContext *C, ARegion *ar) +{ + /* TODO: remove? */ + ED_region_panels_layout(C, ar); + ED_region_panels_draw(C, ar); +} + void ED_region_panels_init(wmWindowManager *wm, ARegion *ar) { wmKeyMap *keymap; @@ -2102,13 +2210,12 @@ void ED_region_header_layout(const bContext *C, ARegion *ar) Header header = {NULL}; int maxco, xco, yco; int headery = ED_area_headersize(); - const int start_ofs = UI_HEADER_OFFSET_START; bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE; /* set view2d view matrix for scrolling (without scrollers) */ UI_view2d_view_ortho(&ar->v2d); - xco = maxco = start_ofs; + xco = maxco = UI_HEADER_OFFSET; yco = headery + (ar->winy - headery) / 2 - floor(0.2f * UI_UNIT_Y); /* XXX workaround for 1 px alignment issue. Not sure what causes it... Would prefer a proper fix - Julian */ @@ -2139,7 +2246,7 @@ void ED_region_header_layout(const bContext *C, ARegion *ar) if (xco > maxco) maxco = xco; - int new_sizex = (maxco + start_ofs) / UI_DPI_FAC; + int new_sizex = (maxco + UI_HEADER_OFFSET) / UI_DPI_FAC; if (region_layout_based && (ar->sizex != new_sizex)) { /* region size is layout based and needs to be updated */ @@ -2152,8 +2259,12 @@ void ED_region_header_layout(const bContext *C, ARegion *ar) UI_block_end(C, block); } + if (!region_layout_based) { + maxco += UI_HEADER_OFFSET; + } + /* always as last */ - UI_view2d_totRect_set(&ar->v2d, maxco + (region_layout_based ? 0 : UI_UNIT_X + 80), headery); + UI_view2d_totRect_set(&ar->v2d, maxco, headery); /* restore view matrix */ UI_view2d_view_restore(C); @@ -2161,11 +2272,11 @@ void ED_region_header_layout(const bContext *C, ARegion *ar) void ED_region_header_draw(const bContext *C, ARegion *ar) { - UI_view2d_view_ortho(&ar->v2d); - /* clear */ region_clear_color(C, ar, region_background_color_id(C, ar)); + UI_view2d_view_ortho(&ar->v2d); + /* View2D matrix might have changed due to dynamic sized regions. */ UI_blocklist_update_window_matrix(C, &ar->uiblocks); @@ -2687,6 +2798,9 @@ void ED_region_visible_rect(ARegion *ar, rcti *rect) rect->ymax = arn->winrct.ymin; } } + else if (arn->alignment == RGN_ALIGN_FLOAT) { + /* Skip floating. */ + } else { BLI_assert(!"Region overlap with unknown alignment"); } diff --git a/source/blender/editors/screen/screen_edit.c b/source/blender/editors/screen/screen_edit.c index ac4ab3461a3..53abe3ed4ea 100644 --- a/source/blender/editors/screen/screen_edit.c +++ b/source/blender/editors/screen/screen_edit.c @@ -832,13 +832,13 @@ void ED_screen_refresh(wmWindowManager *wm, wmWindow *win) } /* file read, set all screens, ... */ -void ED_screens_initialize(Main *UNUSED(bmain), wmWindowManager *wm) +void ED_screens_initialize(Main *bmain, wmWindowManager *wm) { wmWindow *win; for (win = wm->windows.first; win; win = win->next) { if (WM_window_get_active_workspace(win) == NULL) { - WM_window_set_active_workspace(win, G.main->workspaces.first); + WM_window_set_active_workspace(win, bmain->workspaces.first); } if (BLI_listbase_is_empty(&win->global_areas.areabase)) { @@ -961,7 +961,7 @@ static void screen_cursor_set(wmWindow *win, const int xy[2]) ScrArea *sa; for (sa = screen->areabase.first; sa; sa = sa->next) - if ((az = is_in_area_actionzone(sa, xy))) + if ((az = ED_area_actionzone_find_xy(sa, xy))) break; if (sa) { @@ -1003,7 +1003,7 @@ void ED_screen_set_active_region(bContext *C, wmWindow *win, const int xy[2]) ED_screen_areas_iter(win, scr, area_iter) { if (xy[0] > area_iter->totrct.xmin && xy[0] < area_iter->totrct.xmax) { if (xy[1] > area_iter->totrct.ymin && xy[1] < area_iter->totrct.ymax) { - if (is_in_area_actionzone(area_iter, xy) == NULL) { + if (ED_area_actionzone_refresh_xy(area_iter, xy) == NULL) { sa = area_iter; break; } @@ -1073,7 +1073,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) diff --git a/source/blender/editors/screen/screen_intern.h b/source/blender/editors/screen/screen_intern.h index b02198764e0..2c343fb9d70 100644 --- a/source/blender/editors/screen/screen_intern.h +++ b/source/blender/editors/screen/screen_intern.h @@ -67,7 +67,8 @@ ScrEdge *screen_find_active_scredge( const wmWindow *win, const bScreen *screen, 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( diff --git a/source/blender/editors/screen/screen_ops.c b/source/blender/editors/screen/screen_ops.c index 1ecc3f72355..e08755c84c6 100644 --- a/source/blender/editors/screen/screen_ops.c +++ b/source/blender/editors/screen/screen_ops.c @@ -679,7 +679,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; @@ -687,102 +687,117 @@ 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) { + if (click_isect) { az->alpha = 1.0f; } - else if (mouse_radius < fadein_radius) { - 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_no_rebuild(sa); - break; } else if (az->type == AZONE_REGION_SCROLL) { ARegion *ar = az->ar; View2D *v2d = &ar->v2d; const short isect_value = UI_view2d_mouse_in_scrollers(ar, v2d, xy[0], xy[1]); - bool redraw = false; - - if (isect_value == 'h') { - if (az->direction == AZ_SCROLL_HOR) { - az->alpha = 1.0f; - v2d->alpha_hor = 255; - v2d->size_hor = V2D_SCROLL_HEIGHT; - redraw = true; - } - } - else if (isect_value == 'v') { - if (az->direction == AZ_SCROLL_VERT) { - az->alpha = 1.0f; - v2d->alpha_vert = 255; - v2d->size_vert = V2D_SCROLL_WIDTH; - redraw = true; + if (test_only) { + if (isect_value != 0) { + break; } } else { - const int local_xy[2] = {xy[0] - ar->winrct.xmin, xy[1] - ar->winrct.ymin}; - float dist_fac = 0.0f, alpha = 0.0f; - - if (az->direction == AZ_SCROLL_HOR) { - dist_fac = BLI_rcti_length_y(&v2d->hor, local_xy[1]) / AZONEFADEIN; - CLAMP(dist_fac, 0.0f, 1.0f); - alpha = 1.0f - dist_fac; + bool redraw = false; - v2d->alpha_hor = alpha * 255; - v2d->size_hor = round_fl_to_int(V2D_SCROLL_HEIGHT - - ((V2D_SCROLL_HEIGHT - V2D_SCROLL_HEIGHT_MIN) * dist_fac)); + if (isect_value == 'h') { + if (az->direction == AZ_SCROLL_HOR) { + az->alpha = 1.0f; + v2d->alpha_hor = 255; + v2d->size_hor = V2D_SCROLL_HEIGHT; + redraw = true; + } } - else if (az->direction == AZ_SCROLL_VERT) { - dist_fac = BLI_rcti_length_x(&v2d->vert, local_xy[0]) / AZONEFADEIN; - CLAMP(dist_fac, 0.0f, 1.0f); - alpha = 1.0f - dist_fac; - - v2d->alpha_vert = alpha * 255; - v2d->size_vert = round_fl_to_int(V2D_SCROLL_WIDTH - - ((V2D_SCROLL_WIDTH - V2D_SCROLL_WIDTH_MIN) * dist_fac)); + else if (isect_value == 'v') { + if (az->direction == AZ_SCROLL_VERT) { + az->alpha = 1.0f; + v2d->alpha_vert = 255; + v2d->size_vert = V2D_SCROLL_WIDTH; + redraw = true; + } + } + else { + const int local_xy[2] = {xy[0] - ar->winrct.xmin, xy[1] - ar->winrct.ymin}; + float dist_fac = 0.0f, alpha = 0.0f; + + if (az->direction == AZ_SCROLL_HOR) { + dist_fac = BLI_rcti_length_y(&v2d->hor, local_xy[1]) / AZONEFADEIN; + CLAMP(dist_fac, 0.0f, 1.0f); + alpha = 1.0f - dist_fac; + + v2d->alpha_hor = alpha * 255; + v2d->size_hor = round_fl_to_int( + V2D_SCROLL_HEIGHT - + ((V2D_SCROLL_HEIGHT - V2D_SCROLL_HEIGHT_MIN) * dist_fac)); + } + else if (az->direction == AZ_SCROLL_VERT) { + dist_fac = BLI_rcti_length_x(&v2d->vert, local_xy[0]) / AZONEFADEIN; + CLAMP(dist_fac, 0.0f, 1.0f); + alpha = 1.0f - dist_fac; + + v2d->alpha_vert = alpha * 255; + v2d->size_vert = round_fl_to_int( + V2D_SCROLL_WIDTH - + ((V2D_SCROLL_WIDTH - V2D_SCROLL_WIDTH_MIN) * dist_fac)); + } + az->alpha = alpha; + redraw = true; } - az->alpha = alpha; - redraw = true; - } - if (redraw) { - ED_area_tag_redraw_no_rebuild(sa); + if (redraw) { + ED_area_tag_redraw_no_rebuild(sa); + } + /* Don't return! */ } - /* Don't return! */ } } } @@ -790,6 +805,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) { @@ -827,7 +851,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 */ @@ -888,7 +912,7 @@ static int actionzone_modal(bContext *C, wmOperator *op, const wmEvent *event) WM_window_screen_rect_calc(win, &screen_rect); /* 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_area_map_find_active_scredge( AREAMAP_FROM_SCREEN(sc), &screen_rect, event->x, event->y) == NULL)); } @@ -2262,7 +2286,7 @@ static int region_scale_modal(bContext *C, wmOperator *op, const wmEvent *event) case MOUSEMOVE: { const float aspect = BLI_rctf_size_x(&rmd->ar->v2d.cur) / (BLI_rcti_size_x(&rmd->ar->v2d.mask) + 1); - const int snap_size_threshold = (U.widget_unit * 3) / aspect; + const int snap_size_threshold = (U.widget_unit * 2) / aspect; if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT) { delta = event->x - rmd->origx; if (rmd->edge == AE_LEFT_TO_TOPRIGHT) delta = -delta; @@ -2454,7 +2478,7 @@ static void SCREEN_OT_frame_offset(wmOperatorType *ot) ot->poll = ED_operator_screenactive_norender; ot->flag = OPTYPE_UNDO_GROUPED; - ot->undo_group = "FRAME_CHANGE"; + ot->undo_group = "Frame Change"; /* rna */ RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX); @@ -2513,7 +2537,7 @@ static void SCREEN_OT_frame_jump(wmOperatorType *ot) ot->poll = ED_operator_screenactive_norender; ot->flag = OPTYPE_UNDO_GROUPED; - ot->undo_group = "FRAME_CHANGE"; + ot->undo_group = "Frame Change"; /* rna */ RNA_def_boolean(ot->srna, "end", 0, "Last Frame", "Jump to the last frame of the frame range"); @@ -2626,7 +2650,7 @@ static void SCREEN_OT_keyframe_jump(wmOperatorType *ot) ot->poll = ED_operator_screenactive_norender; ot->flag = OPTYPE_UNDO_GROUPED; - ot->undo_group = "FRAME_CHANGE"; + ot->undo_group = "Frame Change"; /* properties */ RNA_def_boolean(ot->srna, "next", true, "Next Keyframe", ""); @@ -2693,7 +2717,7 @@ static void SCREEN_OT_marker_jump(wmOperatorType *ot) ot->poll = ED_operator_screenactive_norender; ot->flag = OPTYPE_UNDO_GROUPED; - ot->undo_group = "FRAME_CHANGE"; + ot->undo_group = "Frame Change"; /* properties */ RNA_def_boolean(ot->srna, "next", true, "Next Marker", ""); diff --git a/source/blender/editors/screen/screendump.c b/source/blender/editors/screen/screendump.c index 7e50f8d41c4..e7b075dd5d0 100644 --- a/source/blender/editors/screen/screendump.c +++ b/source/blender/editors/screen/screendump.c @@ -234,7 +234,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); diff --git a/source/blender/editors/screen/workspace_layout_edit.c b/source/blender/editors/screen/workspace_layout_edit.c index 0c7431cb2e7..6d504c05dd1 100644 --- a/source/blender/editors/screen/workspace_layout_edit.c +++ b/source/blender/editors/screen/workspace_layout_edit.c @@ -57,7 +57,7 @@ WorkSpaceLayout *ED_workspace_layout_add( WM_window_screen_rect_calc(win, &screen_rect); screen = screen_add(bmain, name, &screen_rect); - return BKE_workspace_layout_add(workspace, screen, name); + return BKE_workspace_layout_add(bmain, workspace, screen, name); } WorkSpaceLayout *ED_workspace_layout_duplicate( diff --git a/source/blender/editors/sculpt_paint/paint_image_proj.c b/source/blender/editors/sculpt_paint/paint_image_proj.c index f6cf0f56764..62bc379241f 100644 --- a/source/blender/editors/sculpt_paint/paint_image_proj.c +++ b/source/blender/editors/sculpt_paint/paint_image_proj.c @@ -354,28 +354,30 @@ typedef struct ProjPaintState { SpinLock *tile_lock; - DerivedMesh *dm; - int dm_totlooptri; - int dm_totpoly; - int dm_totedge; - int dm_totvert; - bool dm_release; + Mesh *me_eval; + int totlooptri_eval; + int totpoly_eval; + int totedge_eval; + int totvert_eval; - const MVert *dm_mvert; - const MEdge *dm_medge; - const MPoly *dm_mpoly; - const MLoop *dm_mloop; - const MLoopTri *dm_mlooptri; + const MVert *mvert_eval; + const MEdge *medge_eval; + const MPoly *mpoly_eval; + const MLoop *mloop_eval; + const MLoopTri *mlooptri_eval; - const MLoopUV *dm_mloopuv_stencil; + const MLoopUV *mloopuv_stencil_eval; /** - * \note These UV layers are aligned to \a dm_mpoly + * \note These UV layers are aligned to \a mpoly_eval * but each pointer references the start of the layer, * so a loop indirection is needed as well. */ - const MLoopUV **dm_mloopuv; - const MLoopUV **dm_mloopuv_clone; /* other UV map, use for cloning between layers */ + const MLoopUV **poly_to_loop_uv; + const MLoopUV **poly_to_loop_uv_clone; /* other UV map, use for cloning between layers */ + + /* Actual material for each index, either from object or Mesh datablock... */ + Material **mat_array; bool use_colormanagement; } ProjPaintState; @@ -441,13 +443,13 @@ typedef struct { BLI_INLINE const MPoly *ps_tri_index_to_mpoly(const ProjPaintState *ps, int tri_index) { - return &ps->dm_mpoly[ps->dm_mlooptri[tri_index].poly]; + return &ps->mpoly_eval[ps->mlooptri_eval[tri_index].poly]; } #define PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) \ - ps->dm_mloop[lt->tri[0]].v, \ - ps->dm_mloop[lt->tri[1]].v, \ - ps->dm_mloop[lt->tri[2]].v, + ps->mloop_eval[lt->tri[0]].v, \ + ps->mloop_eval[lt->tri[1]].v, \ + ps->mloop_eval[lt->tri[2]].v, #define PS_LOOPTRI_AS_UV_3(uvlayer, lt) \ uvlayer[lt->poly][lt->tri[0]].uv, \ @@ -469,7 +471,7 @@ BLI_INLINE const MPoly *ps_tri_index_to_mpoly(const ProjPaintState *ps, int tri_ static TexPaintSlot *project_paint_face_paint_slot(const ProjPaintState *ps, int tri_index) { const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index); - Material *ma = ps->dm->mat[mp->mat_nr]; + Material *ma = ps->mat_array[mp->mat_nr]; return ma ? ma->texpaintslot + ma->paint_active_slot : NULL; } @@ -480,7 +482,7 @@ static Image *project_paint_face_paint_image(const ProjPaintState *ps, int tri_i } else { const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index); - Material *ma = ps->dm->mat[mp->mat_nr]; + Material *ma = ps->mat_array[mp->mat_nr]; TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_active_slot : NULL; return slot ? slot->ima : ps->canvas_ima; } @@ -489,14 +491,14 @@ static Image *project_paint_face_paint_image(const ProjPaintState *ps, int tri_i static TexPaintSlot *project_paint_face_clone_slot(const ProjPaintState *ps, int tri_index) { const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index); - Material *ma = ps->dm->mat[mp->mat_nr]; + Material *ma = ps->mat_array[mp->mat_nr]; return ma ? ma->texpaintslot + ma->paint_clone_slot : NULL; } static Image *project_paint_face_clone_image(const ProjPaintState *ps, int tri_index) { const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index); - Material *ma = ps->dm->mat[mp->mat_nr]; + Material *ma = ps->mat_array[mp->mat_nr]; TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_clone_slot : NULL; return slot ? slot->ima : ps->clone_ima; } @@ -597,11 +599,11 @@ static int project_paint_PickFace( for (node = ps->bucketFaces[bucket_index]; node; node = node->next) { const int tri_index = GET_INT_FROM_POINTER(node->link); - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; const float *vtri_ss[3] = { - ps->screenCoords[ps->dm_mloop[lt->tri[0]].v], - ps->screenCoords[ps->dm_mloop[lt->tri[1]].v], - ps->screenCoords[ps->dm_mloop[lt->tri[2]].v], + ps->screenCoords[ps->mloop_eval[lt->tri[0]].v], + ps->screenCoords[ps->mloop_eval[lt->tri[1]].v], + ps->screenCoords[ps->mloop_eval[lt->tri[2]].v], }; @@ -656,8 +658,8 @@ static bool project_paint_PickColor( if (tri_index == -1) return 0; - lt = &ps->dm_mlooptri[tri_index]; - PS_LOOPTRI_ASSIGN_UV_3(lt_tri_uv, ps->dm_mloopuv, lt); + lt = &ps->mlooptri_eval[tri_index]; + PS_LOOPTRI_ASSIGN_UV_3(lt_tri_uv, ps->poly_to_loop_uv, lt); interp_v2_v2v2v2(uv, UNPACK3(lt_tri_uv), w); @@ -813,19 +815,19 @@ static bool project_bucket_point_occluded( const int tri_index = GET_INT_FROM_POINTER(bucketFace->link); if (orig_face != tri_index) { - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; const float *vtri_ss[3] = { - ps->screenCoords[ps->dm_mloop[lt->tri[0]].v], - ps->screenCoords[ps->dm_mloop[lt->tri[1]].v], - ps->screenCoords[ps->dm_mloop[lt->tri[2]].v], + ps->screenCoords[ps->mloop_eval[lt->tri[0]].v], + ps->screenCoords[ps->mloop_eval[lt->tri[1]].v], + ps->screenCoords[ps->mloop_eval[lt->tri[2]].v], }; float w[3]; if (do_clip) { const float *vtri_co[3] = { - ps->dm_mvert[ps->dm_mloop[lt->tri[0]].v].co, - ps->dm_mvert[ps->dm_mloop[lt->tri[1]].v].co, - ps->dm_mvert[ps->dm_mloop[lt->tri[2]].v].co, + ps->mvert_eval[ps->mloop_eval[lt->tri[0]].v].co, + ps->mvert_eval[ps->mloop_eval[lt->tri[1]].v].co, + ps->mvert_eval[ps->mloop_eval[lt->tri[2]].v].co, }; isect_ret = project_paint_occlude_ptv_clip( pixelScreenCo, UNPACK3(vtri_ss), UNPACK3(vtri_co), @@ -1005,8 +1007,8 @@ static bool pixel_bounds_array(float (*uv)[2], rcti *bounds_px, const int ibuf_x static void project_face_winding_init(const ProjPaintState *ps, const int tri_index) { /* detect the winding of faces in uv space */ - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; - const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->dm_mloopuv, lt) }; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; + const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) }; float winding = cross_tri_v2(lt_tri_uv[0], lt_tri_uv[1], lt_tri_uv[2]); if (winding > 0) @@ -1022,11 +1024,11 @@ static bool check_seam( const int orig_face, const int orig_i1_fidx, const int orig_i2_fidx, int *other_face, int *orig_fidx) { - const MLoopTri *orig_lt = &ps->dm_mlooptri[orig_face]; - const float *orig_lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->dm_mloopuv, orig_lt) }; + const MLoopTri *orig_lt = &ps->mlooptri_eval[orig_face]; + const float *orig_lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, orig_lt) }; /* vert indices from face vert order indices */ - const unsigned int i1 = ps->dm_mloop[orig_lt->tri[orig_i1_fidx]].v; - const unsigned int i2 = ps->dm_mloop[orig_lt->tri[orig_i2_fidx]].v; + const unsigned int i1 = ps->mloop_eval[orig_lt->tri[orig_i1_fidx]].v; + const unsigned int i2 = ps->mloop_eval[orig_lt->tri[orig_i2_fidx]].v; LinkNode *node; int i1_fidx = -1, i2_fidx = -1; /* index in face */ @@ -1034,7 +1036,7 @@ static bool check_seam( const int tri_index = GET_INT_FROM_POINTER(node->link); if (tri_index != orig_face) { - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) }; /* could check if the 2 faces images match here, * but then there wouldn't be a way to return the opposite face's info */ @@ -1047,7 +1049,7 @@ static bool check_seam( /* Only need to check if 'i2_fidx' is valid because we know i1_fidx is the same vert on both faces */ if (i2_fidx != -1) { - const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->dm_mloopuv, lt) }; + const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) }; Image *tpage = project_paint_face_paint_image(ps, tri_index); Image *orig_tpage = project_paint_face_paint_image(ps, orig_face); @@ -1351,8 +1353,8 @@ static float project_paint_uvpixel_mask( Image *other_tpage = ps->stencil_ima; if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) { - const MLoopTri *lt_other = &ps->dm_mlooptri[tri_index]; - const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->dm_mloopuv, lt_other) }; + const MLoopTri *lt_other = &ps->mlooptri_eval[tri_index]; + const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt_other) }; /* BKE_image_acquire_ibuf - TODO - this may be slow */ unsigned char rgba_ub[4]; @@ -1385,7 +1387,7 @@ static float project_paint_uvpixel_mask( } if (ps->do_mask_cavity) { - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) }; float ca1, ca2, ca3, ca_mask; ca1 = ps->cavities[lt_vtri[0]]; @@ -1400,16 +1402,16 @@ static float project_paint_uvpixel_mask( /* calculate mask */ if (ps->do_mask_normal) { - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) }; - const MPoly *mp = &ps->dm_mpoly[lt->poly]; + const MPoly *mp = &ps->mpoly_eval[lt->poly]; float no[3], angle_cos; if (mp->flag & ME_SMOOTH) { const short *no1, *no2, *no3; - no1 = ps->dm_mvert[lt_vtri[0]].no; - no2 = ps->dm_mvert[lt_vtri[1]].no; - no3 = ps->dm_mvert[lt_vtri[2]].no; + no1 = ps->mvert_eval[lt_vtri[0]].no; + no2 = ps->mvert_eval[lt_vtri[1]].no; + no3 = ps->mvert_eval[lt_vtri[2]].no; no[0] = w[0] * no1[0] + w[1] * no2[0] + w[2] * no3[0]; no[1] = w[0] * no1[1] + w[1] * no2[1] + w[2] * no3[1]; @@ -1421,9 +1423,9 @@ static float project_paint_uvpixel_mask( #if 1 /* normalizing per pixel isn't optimal, we could cache or check ps->*/ normal_tri_v3(no, - ps->dm_mvert[lt_vtri[0]].co, - ps->dm_mvert[lt_vtri[1]].co, - ps->dm_mvert[lt_vtri[2]].co); + ps->mvert_eval[lt_vtri[0]].co, + ps->mvert_eval[lt_vtri[1]].co, + ps->mvert_eval[lt_vtri[2]].co); #else /* don't use because some modifiers dont have normal data (subsurf for eg) */ copy_v3_v3(no, (float *)ps->dm->getTessFaceData(ps->dm, tri_index, CD_NORMAL)); @@ -1442,9 +1444,9 @@ static float project_paint_uvpixel_mask( /* Annoying but for the perspective view we need to get the pixels location in 3D space :/ */ float viewDirPersp[3]; const float *co1, *co2, *co3; - co1 = ps->dm_mvert[lt_vtri[0]].co; - co2 = ps->dm_mvert[lt_vtri[1]].co; - co3 = ps->dm_mvert[lt_vtri[2]].co; + co1 = ps->mvert_eval[lt_vtri[0]].co; + co2 = ps->mvert_eval[lt_vtri[1]].co; + co3 = ps->mvert_eval[lt_vtri[2]].co; /* Get the direction from the viewPoint to the pixel and normalize */ viewDirPersp[0] = (ps->viewPos[0] - (w[0] * co1[0] + w[1] * co2[0] + w[2] * co3[0])); @@ -1613,13 +1615,13 @@ static ProjPixel *project_paint_uvpixel_init( /* done with view3d_project_float inline */ if (ps->tool == PAINT_TOOL_CLONE) { - if (ps->dm_mloopuv_clone) { + if (ps->poly_to_loop_uv_clone) { ImBuf *ibuf_other; Image *other_tpage = project_paint_face_clone_image(ps, tri_index); if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) { - const MLoopTri *lt_other = &ps->dm_mlooptri[tri_index]; - const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->dm_mloopuv_clone, lt_other) }; + const MLoopTri *lt_other = &ps->mlooptri_eval[tri_index]; + const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv_clone, lt_other) }; /* BKE_image_acquire_ibuf - TODO - this may be slow */ @@ -2510,9 +2512,9 @@ static void project_paint_face_init( ps->projImages + image_index }; - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) }; - const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->dm_mloopuv, lt) }; + const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) }; /* UV/pixel seeking data */ int x; /* Image X-Pixel */ @@ -2546,9 +2548,9 @@ static void project_paint_face_init( const bool do_backfacecull = ps->do_backfacecull; const bool do_clip = ps->rv3d ? ps->rv3d->rflag & RV3D_CLIPPING : 0; - vCo[0] = ps->dm_mvert[lt_vtri[0]].co; - vCo[1] = ps->dm_mvert[lt_vtri[1]].co; - vCo[2] = ps->dm_mvert[lt_vtri[2]].co; + vCo[0] = ps->mvert_eval[lt_vtri[0]].co; + vCo[1] = ps->mvert_eval[lt_vtri[1]].co; + vCo[2] = ps->mvert_eval[lt_vtri[2]].co; /* Use lt_uv_pxoffset instead of lt_tri_uv so we can offset the UV half a pixel @@ -2632,9 +2634,9 @@ static void project_paint_face_init( if (do_clip || do_3d_mapping) { interp_v3_v3v3v3( wco, - ps->dm_mvert[lt_vtri[0]].co, - ps->dm_mvert[lt_vtri[1]].co, - ps->dm_mvert[lt_vtri[2]].co, + ps->mvert_eval[lt_vtri[0]].co, + ps->mvert_eval[lt_vtri[1]].co, + ps->mvert_eval[lt_vtri[2]].co, w); if (do_clip && ED_view3d_clipping_test(ps->rv3d, wco, true)) { continue; /* Watch out that no code below this needs to run */ @@ -2814,7 +2816,7 @@ static void project_paint_face_init( !project_bucket_point_occluded(ps, bucketFaceNodes, tri_index, pixelScreenCo)) { /* Only bother calculating the weights if we intersect */ - if (ps->do_mask_normal || ps->dm_mloopuv_clone) { + if (ps->do_mask_normal || ps->poly_to_loop_uv_clone) { const float uv_fac = fac1 + (fac * (fac2 - fac1)); #if 0 /* get the UV on the line since we want to copy the pixels from there for bleeding */ @@ -3067,24 +3069,6 @@ static void project_paint_delayed_face_init(ProjPaintState *ps, const MLoopTri * #endif } -/** - * \note when using subsurf or multires, some arrays are thrown away, we need to keep a copy - */ -static void proj_paint_state_non_cddm_init(ProjPaintState *ps) -{ - if (ps->dm->type != DM_TYPE_CDDM) { - ps->dm_mvert = MEM_dupallocN(ps->dm_mvert); - ps->dm_mpoly = MEM_dupallocN(ps->dm_mpoly); - ps->dm_mloop = MEM_dupallocN(ps->dm_mloop); - /* looks like these are ok for now.*/ -#if 0 - ps->dm_mloopuv = MEM_dupallocN(ps->dm_mloopuv); - ps->dm_mloopuv_clone = MEM_dupallocN(ps->dm_mloopuv_clone); - ps->dm_mloopuv_stencil = MEM_dupallocN(ps->dm_mloopuv_stencil); -#endif - } -} - static void proj_paint_state_viewport_init( ProjPaintState *ps, const Depsgraph *depsgraph, const char symmetry_flag) { @@ -3204,11 +3188,11 @@ static void proj_paint_state_screen_coords_init(ProjPaintState *ps, const int di INIT_MINMAX2(ps->screenMin, ps->screenMax); - ps->screenCoords = MEM_mallocN(sizeof(float) * ps->dm_totvert * 4, "ProjectPaint ScreenVerts"); + ps->screenCoords = MEM_mallocN(sizeof(float) * ps->totvert_eval * 4, "ProjectPaint ScreenVerts"); projScreenCo = *ps->screenCoords; if (ps->is_ortho) { - for (a = 0, mv = ps->dm_mvert; a < ps->dm_totvert; a++, mv++, projScreenCo += 4) { + for (a = 0, mv = ps->mvert_eval; a < ps->totvert_eval; a++, mv++, projScreenCo += 4) { mul_v3_m4v3(projScreenCo, ps->projectMat, mv->co); /* screen space, not clamped */ @@ -3218,7 +3202,7 @@ static void proj_paint_state_screen_coords_init(ProjPaintState *ps, const int di } } else { - for (a = 0, mv = ps->dm_mvert; a < ps->dm_totvert; a++, mv++, projScreenCo += 4) { + for (a = 0, mv = ps->mvert_eval; a < ps->totvert_eval; a++, mv++, projScreenCo += 4) { copy_v3_v3(projScreenCo, mv->co); projScreenCo[3] = 1.0f; @@ -3279,21 +3263,21 @@ static void proj_paint_state_cavity_init(ProjPaintState *ps) int a; if (ps->do_mask_cavity) { - int *counter = MEM_callocN(sizeof(int) * ps->dm_totvert, "counter"); - float (*edges)[3] = MEM_callocN(sizeof(float) * 3 * ps->dm_totvert, "edges"); - ps->cavities = MEM_mallocN(sizeof(float) * ps->dm_totvert, "ProjectPaint Cavities"); + int *counter = MEM_callocN(sizeof(int) * ps->totvert_eval, "counter"); + float (*edges)[3] = MEM_callocN(sizeof(float) * 3 * ps->totvert_eval, "edges"); + ps->cavities = MEM_mallocN(sizeof(float) * ps->totvert_eval, "ProjectPaint Cavities"); cavities = ps->cavities; - for (a = 0, me = ps->dm_medge; a < ps->dm_totedge; a++, me++) { + for (a = 0, me = ps->medge_eval; a < ps->totedge_eval; a++, me++) { float e[3]; - sub_v3_v3v3(e, ps->dm_mvert[me->v1].co, ps->dm_mvert[me->v2].co); + sub_v3_v3v3(e, ps->mvert_eval[me->v1].co, ps->mvert_eval[me->v2].co); normalize_v3(e); add_v3_v3(edges[me->v2], e); counter[me->v2]++; sub_v3_v3(edges[me->v1], e); counter[me->v1]++; } - for (a = 0, mv = ps->dm_mvert; a < ps->dm_totvert; a++, mv++) { + for (a = 0, mv = ps->mvert_eval; a < ps->totvert_eval; a++, mv++) { if (counter[a] > 0) { float no[3]; mul_v3_fl(edges[a], 1.0f / counter[a]); @@ -3314,10 +3298,10 @@ static void proj_paint_state_cavity_init(ProjPaintState *ps) static void proj_paint_state_seam_bleed_init(ProjPaintState *ps) { if (ps->seam_bleed_px > 0.0f) { - ps->vertFaces = MEM_callocN(sizeof(LinkNode *) * ps->dm_totvert, "paint-vertFaces"); - ps->faceSeamFlags = MEM_callocN(sizeof(char) * ps->dm_totlooptri, "paint-faceSeamFlags"); - ps->faceWindingFlags = MEM_callocN(sizeof(char) * ps->dm_totlooptri, "paint-faceWindindFlags"); - ps->faceSeamUVs = MEM_mallocN(sizeof(float[3][2]) * ps->dm_totlooptri, "paint-faceSeamUVs"); + ps->vertFaces = MEM_callocN(sizeof(LinkNode *) * ps->totvert_eval, "paint-vertFaces"); + ps->faceSeamFlags = MEM_callocN(sizeof(char) * ps->totlooptri_eval, "paint-faceSeamFlags"); + ps->faceWindingFlags = MEM_callocN(sizeof(char) * ps->totlooptri_eval, "paint-faceWindindFlags"); + ps->faceSeamUVs = MEM_mallocN(sizeof(float[3][2]) * ps->totlooptri_eval, "paint-faceSeamUVs"); } } #endif @@ -3361,9 +3345,9 @@ static void proj_paint_state_vert_flags_init(ProjPaintState *ps) float no[3]; int a; - ps->vertFlags = MEM_callocN(sizeof(char) * ps->dm_totvert, "paint-vertFlags"); + ps->vertFlags = MEM_callocN(sizeof(char) * ps->totvert_eval, "paint-vertFlags"); - for (a = 0, mv = ps->dm_mvert; a < ps->dm_totvert; a++, mv++) { + for (a = 0, mv = ps->mvert_eval; a < ps->totvert_eval; a++, mv++) { normal_short_to_float_v3(no, mv->no); if (UNLIKELY(ps->is_flip_object)) { negate_v3(no); @@ -3408,58 +3392,63 @@ static void project_paint_bleed_add_face_user( } #endif -/* Return true if DM can be painted on, false otherwise */ -static bool proj_paint_state_dm_init(const bContext *C, ProjPaintState *ps) +/* Return true if evaluated mesh can be painted on, false otherwise */ +static bool proj_paint_state_mesh_eval_init(const bContext *C, ProjPaintState *ps) { Depsgraph *depsgraph = CTX_data_depsgraph(C); + Scene *sce = ps->scene; + Object *ob = ps->ob; /* Workaround for subsurf selection, try the display mesh first */ + /* XXX Don't think this is easily doable with new system, and not sure why that was needed in the first place :/ */ +#if 0 if (ps->source == PROJ_SRC_IMAGE_CAM) { /* using render mesh, assume only camera was rendered from */ - ps->dm = mesh_create_derived_render(depsgraph, ps->scene, ps->ob, ps->scene->customdata_mask | CD_MASK_MTFACE); + ps->dm = mesh_create_derived_render( + depsgraph, 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( depsgraph, 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)) { - - if (ps->dm_release) - ps->dm->release(ps->dm); - - ps->dm = NULL; +#endif + ps->me_eval = mesh_get_eval_final( + depsgraph, sce, ob, + sce->customdata_mask | CD_MASK_MLOOPUV | CD_MASK_MTFACE | (ps->do_face_sel ? CD_MASK_ORIGINDEX : 0)); + if (!CustomData_has_layer(&ps->me_eval->ldata, CD_MLOOPUV)) { + ps->me_eval = NULL; return false; } - DM_update_materials(ps->dm, ps->ob); - - ps->dm_mvert = ps->dm->getVertArray(ps->dm); - - if (ps->do_mask_cavity) - ps->dm_medge = ps->dm->getEdgeArray(ps->dm); + /* Build final material array, we use this a lot here. */ + const int totmat = ob->totcol + 1; /* materials start from 1, default material is 0 */ + ps->mat_array = MEM_malloc_arrayN(totmat, sizeof(*ps->mat_array), __func__); + /* We leave last material as empty - rationale here is being able to index + * the materials by using the mf->mat_nr directly and leaving the last + * material as NULL in case no materials exist on mesh, so indexing will not fail. */ + for (int i = 0; i < totmat - 1; i++) { + ps->mat_array[i] = give_current_material(ob, i + 1); + } + ps->mat_array[totmat - 1] = NULL; - ps->dm_mloop = ps->dm->getLoopArray(ps->dm); - ps->dm_mpoly = ps->dm->getPolyArray(ps->dm); + ps->mvert_eval = ps->me_eval->mvert; + if (ps->do_mask_cavity) { + ps->medge_eval = ps->me_eval->medge; + } + ps->mloop_eval = ps->me_eval->mloop; + ps->mpoly_eval = ps->me_eval->mpoly; - ps->dm_mlooptri = ps->dm->getLoopTriArray(ps->dm); + ps->totvert_eval = ps->me_eval->totvert; + ps->totedge_eval = ps->me_eval->totedge; + ps->totpoly_eval = ps->me_eval->totpoly; - ps->dm_totvert = ps->dm->getNumVerts(ps->dm); - ps->dm_totedge = ps->dm->getNumEdges(ps->dm); - ps->dm_totpoly = ps->dm->getNumPolys(ps->dm); - ps->dm_totlooptri = ps->dm->getNumLoopTri(ps->dm); + ps->mlooptri_eval = BKE_mesh_runtime_looptri_ensure(ps->me_eval); + ps->totlooptri_eval = ps->me_eval->runtime.looptris.len; - ps->dm_mloopuv = MEM_mallocN(ps->dm_totpoly * sizeof(MLoopUV *), "proj_paint_mtfaces"); + ps->poly_to_loop_uv = MEM_mallocN(ps->totpoly_eval * sizeof(MLoopUV *), "proj_paint_mtfaces"); return true; } @@ -3480,14 +3469,14 @@ static void proj_paint_layer_clone_init( if (ps->do_layer_clone) { const int layer_num = CustomData_get_clone_layer(&((Mesh *)ps->ob->data)->ldata, CD_MLOOPUV); - ps->dm_mloopuv_clone = MEM_mallocN(ps->dm_totpoly * sizeof(MLoopUV *), "proj_paint_mtfaces"); + ps->poly_to_loop_uv_clone = MEM_mallocN(ps->totpoly_eval * sizeof(MLoopUV *), "proj_paint_mtfaces"); if (layer_num != -1) - mloopuv_clone_base = CustomData_get_layer_n(&ps->dm->loopData, CD_MLOOPUV, layer_num); + mloopuv_clone_base = CustomData_get_layer_n(&ps->me_eval->ldata, CD_MLOOPUV, layer_num); if (mloopuv_clone_base == NULL) { /* get active instead */ - mloopuv_clone_base = CustomData_get_layer(&ps->dm->loopData, CD_MLOOPUV); + mloopuv_clone_base = CustomData_get_layer(&ps->me_eval->ldata, CD_MLOOPUV); } } @@ -3517,17 +3506,17 @@ static bool project_paint_clone_face_skip( if (lc->slot_clone != lc->slot_last_clone) { if (!slot->uvname || !(lc->mloopuv_clone_base = CustomData_get_layer_named( - &ps->dm->loopData, CD_MLOOPUV, + &ps->me_eval->ldata, CD_MLOOPUV, lc->slot_clone->uvname))) { - lc->mloopuv_clone_base = CustomData_get_layer(&ps->dm->loopData, CD_MLOOPUV); + lc->mloopuv_clone_base = CustomData_get_layer(&ps->me_eval->ldata, CD_MLOOPUV); } lc->slot_last_clone = lc->slot_clone; } } /* will set multiple times for 4+ sided poly */ - ps->dm_mloopuv_clone[ps->dm_mlooptri[tri_index].poly] = lc->mloopuv_clone_base; + ps->poly_to_loop_uv_clone[ps->mlooptri_eval[tri_index].poly] = lc->mloopuv_clone_base; } return false; } @@ -3544,7 +3533,7 @@ static void proj_paint_face_lookup_init( { memset(face_lookup, 0, sizeof(*face_lookup)); if (ps->do_face_sel) { - face_lookup->index_mp_to_orig = ps->dm->getPolyDataArray(ps->dm, CD_ORIGINDEX); + face_lookup->index_mp_to_orig = CustomData_get_layer(&ps->me_eval->pdata, CD_ORIGINDEX); face_lookup->mpoly_orig = ((Mesh *)ps->ob->data)->mpoly; } } @@ -3565,7 +3554,7 @@ static bool project_paint_check_face_sel( mp = &face_lookup->mpoly_orig[orig_index]; } else { - mp = &ps->dm_mpoly[lt->poly]; + mp = &ps->mpoly_eval[lt->poly]; } return ((mp->flag & ME_FACE_SEL) != 0); @@ -3679,7 +3668,7 @@ static void project_paint_prepare_all_faces( int image_index = -1, tri_index; int prev_poly = -1; - for (tri_index = 0, lt = ps->dm_mlooptri; tri_index < ps->dm_totlooptri; tri_index++, lt++) { + for (tri_index = 0, lt = ps->mlooptri_eval; tri_index < ps->totlooptri_eval; tri_index++, lt++) { bool is_face_sel; #ifndef PROJ_DEBUG_NOSEAMBLEED @@ -3692,13 +3681,13 @@ static void project_paint_prepare_all_faces( slot = project_paint_face_paint_slot(ps, tri_index); /* all faces should have a valid slot, reassert here */ if (slot == NULL) { - mloopuv_base = CustomData_get_layer(&ps->dm->loopData, CD_MLOOPUV); + mloopuv_base = CustomData_get_layer(&ps->me_eval->ldata, CD_MLOOPUV); tpage = ps->canvas_ima; } else { if (slot != slot_last) { - if (!slot->uvname || !(mloopuv_base = CustomData_get_layer_named(&ps->dm->loopData, CD_MLOOPUV, slot->uvname))) - mloopuv_base = CustomData_get_layer(&ps->dm->loopData, CD_MLOOPUV); + if (!slot->uvname || !(mloopuv_base = CustomData_get_layer_named(&ps->me_eval->ldata, CD_MLOOPUV, slot->uvname))) + mloopuv_base = CustomData_get_layer(&ps->me_eval->ldata, CD_MLOOPUV); slot_last = slot; } @@ -3706,7 +3695,7 @@ static void project_paint_prepare_all_faces( if (slot->ima == ps->stencil_ima) { /* While this shouldn't be used, face-winding reads all polys. * It's less trouble to set all faces to valid UV's, avoiding NULL checks all over. */ - ps->dm_mloopuv[lt->poly] = mloopuv_base; + ps->poly_to_loop_uv[lt->poly] = mloopuv_base; continue; } @@ -3717,7 +3706,7 @@ static void project_paint_prepare_all_faces( tpage = ps->stencil_ima; } - ps->dm_mloopuv[lt->poly] = mloopuv_base; + ps->poly_to_loop_uv[lt->poly] = mloopuv_base; if (project_paint_clone_face_skip(ps, layer_clone, slot, tri_index)) { continue; @@ -3748,11 +3737,11 @@ static void project_paint_prepare_all_faces( if (prev_poly != lt->poly) { int iloop; bool culled = true; - const MPoly *poly = ps->dm_mpoly + lt->poly; + const MPoly *poly = ps->mpoly_eval + lt->poly; int poly_loops = poly->totloop; prev_poly = lt->poly; for (iloop = 0; iloop < poly_loops; iloop++) { - if (!(ps->vertFlags[ps->dm_mloop[poly->loopstart + iloop].v] & PROJ_VERT_CULL)) { + if (!(ps->vertFlags[ps->mloop_eval[poly->loopstart + iloop].v] & PROJ_VERT_CULL)) { culled = false; break; } @@ -3831,7 +3820,7 @@ static void project_paint_begin( /* paint onto the derived mesh */ if (ps->is_shared_user == false) { - if (!proj_paint_state_dm_init(C, ps)) { + if (!proj_paint_state_mesh_eval_init(C, ps)) { return; } } @@ -3840,24 +3829,22 @@ static void project_paint_begin( proj_paint_layer_clone_init(ps, &layer_clone); if (ps->do_layer_stencil || ps->do_stencil_brush) { - //int layer_num = CustomData_get_stencil_layer(&ps->dm->loopData, CD_MLOOPUV); + //int layer_num = CustomData_get_stencil_layer(&ps->me_eval->ldata, CD_MLOOPUV); int layer_num = CustomData_get_stencil_layer(&((Mesh *)ps->ob->data)->ldata, CD_MLOOPUV); if (layer_num != -1) - ps->dm_mloopuv_stencil = CustomData_get_layer_n(&ps->dm->loopData, CD_MLOOPUV, layer_num); + ps->mloopuv_stencil_eval = CustomData_get_layer_n(&ps->me_eval->ldata, CD_MLOOPUV, layer_num); - if (ps->dm_mloopuv_stencil == NULL) { + if (ps->mloopuv_stencil_eval == NULL) { /* get active instead */ - ps->dm_mloopuv_stencil = CustomData_get_layer(&ps->dm->loopData, CD_MLOOPUV); + ps->mloopuv_stencil_eval = CustomData_get_layer(&ps->me_eval->ldata, CD_MLOOPUV); } if (ps->do_stencil_brush) - mloopuv_base = ps->dm_mloopuv_stencil; + mloopuv_base = ps->mloopuv_stencil_eval; } /* when using subsurf or multires, mface arrays are thrown away, we need to keep a copy */ if (ps->is_shared_user == false) { - proj_paint_state_non_cddm_init(ps); - proj_paint_state_cavity_init(ps); } @@ -3947,14 +3934,17 @@ static void project_paint_end(ProjPaintState *ps) MEM_freeN(ps->bucketFlags); if (ps->is_shared_user == false) { + if (ps->mat_array != NULL) { + MEM_freeN(ps->mat_array); + } /* must be set for non-shared */ - BLI_assert(ps->dm_mloopuv || ps->is_shared_user); - if (ps->dm_mloopuv) - MEM_freeN((void *)ps->dm_mloopuv); + BLI_assert(ps->poly_to_loop_uv || ps->is_shared_user); + if (ps->poly_to_loop_uv) + MEM_freeN((void *)ps->poly_to_loop_uv); if (ps->do_layer_clone) - MEM_freeN((void *)ps->dm_mloopuv_clone); + MEM_freeN((void *)ps->poly_to_loop_uv_clone); if (ps->thread_tot > 1) { BLI_spin_end(ps->tile_lock); MEM_freeN((void *)ps->tile_lock); @@ -3974,22 +3964,6 @@ static void project_paint_end(ProjPaintState *ps) if (ps->do_mask_cavity) { MEM_freeN(ps->cavities); } - - /* copy for subsurf/multires, so throw away */ - if (ps->dm->type != DM_TYPE_CDDM) { - if (ps->dm_mvert) MEM_freeN((void *)ps->dm_mvert); - if (ps->dm_mpoly) MEM_freeN((void *)ps->dm_mpoly); - if (ps->dm_mloop) MEM_freeN((void *)ps->dm_mloop); - /* looks like these don't need copying */ -#if 0 - if (ps->dm_mloopuv) MEM_freeN(ps->dm_mloopuv); - if (ps->dm_mloopuv_clone) MEM_freeN(ps->dm_mloopuv_clone); - if (ps->dm_mloopuv_stencil) MEM_freeN(ps->dm_mloopuv_stencil); -#endif - } - - if (ps->dm_release) - ps->dm->release(ps->dm); } if (ps->blurkernel) { @@ -4864,7 +4838,7 @@ static bool project_paint_op(void *state, const float lastpos[2], const float po struct ImagePool *pool; if (!project_bucket_iter_init(ps, pos)) { - return 0; + return touch_any; } if (ps->thread_tot > 1) @@ -4930,16 +4904,16 @@ static bool project_paint_op(void *state, const float lastpos[2], const float po tri_index = project_paint_PickFace(ps, pos, w); if (tri_index != -1) { - const MLoopTri *lt = &ps->dm_mlooptri[tri_index]; + const MLoopTri *lt = &ps->mlooptri_eval[tri_index]; const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) }; float world[3]; UnifiedPaintSettings *ups = &ps->scene->toolsettings->unified_paint_settings; interp_v3_v3v3v3( world, - ps->dm_mvert[lt_vtri[0]].co, - ps->dm_mvert[lt_vtri[1]].co, - ps->dm_mvert[lt_vtri[2]].co, + ps->mvert_eval[lt_vtri[0]].co, + ps->mvert_eval[lt_vtri[1]].co, + ps->mvert_eval[lt_vtri[2]].co, w); ups->average_stroke_counter++; @@ -5228,13 +5202,11 @@ void *paint_proj_new_stroke(bContext *C, Object *ob, const float mouse[2], int m } project_paint_begin(C, ps, is_multi_view, symmetry_flag_views[i]); - - paint_proj_begin_clone(ps, mouse); - - if (ps->dm == NULL) { + if (ps->me_eval == NULL) { goto fail; - return NULL; } + + paint_proj_begin_clone(ps, mouse); } paint_brush_init_tex(ps_handle->brush); @@ -5382,8 +5354,9 @@ static int texture_paint_camera_project_exec(bContext *C, wmOperator *op) /* allocate and initialize spatial data structures */ project_paint_begin(C, &ps, false, 0); - if (ps.dm == NULL) { + if (ps.me_eval == NULL) { BKE_brush_size_set(scene, ps.brush, orig_brush_size); + BKE_report(op->reports, RPT_ERROR, "Could not get valid evaluated mesh"); return OPERATOR_CANCELLED; } else { @@ -5791,6 +5764,7 @@ void PAINT_OT_add_texture_paint_slot(wmOperatorType *ot) static int add_simple_uvs_exec(bContext *C, wmOperator *UNUSED(op)) { /* no checks here, poll function does them for us */ + Main *bmain = CTX_data_main(C); Object *ob = CTX_data_active_object(C); Scene *scene = CTX_data_scene(C); Mesh *me = ob->data; @@ -5815,7 +5789,7 @@ static int add_simple_uvs_exec(bContext *C, wmOperator *UNUSED(op)) /* set the margin really quickly before the packing operation*/ scene->toolsettings->uvcalc_margin = 0.001f; ED_uvedit_pack_islands(scene, ob, bm, false, false, true); - BM_mesh_bm_to_me(bm, me, (&(struct BMeshToMeshParams){0})); + BM_mesh_bm_to_me(bmain, bm, me, (&(struct BMeshToMeshParams){0})); BM_mesh_free(bm); if (synch_selection) diff --git a/source/blender/editors/sculpt_paint/paint_stroke.c b/source/blender/editors/sculpt_paint/paint_stroke.c index b63f9461401..a7aa19807dd 100644 --- a/source/blender/editors/sculpt_paint/paint_stroke.c +++ b/source/blender/editors/sculpt_paint/paint_stroke.c @@ -38,6 +38,8 @@ #include "BLI_rand.h" #include "BLI_listbase.h" +#include "PIL_time.h" + #include "DNA_object_types.h" #include "DNA_scene_types.h" #include "DNA_brush_types.h" @@ -86,6 +88,7 @@ typedef struct PaintStroke { void *mode_data; void *stroke_cursor; wmTimer *timer; + struct RNG *rng; /* Cached values */ ViewContext vc; @@ -403,17 +406,24 @@ static bool paint_brush_update(bContext *C, } } + if ((do_random || do_random_mask) && stroke->rng == NULL) { + /* Lazy initialization. */ + uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); + rng_seed ^= (uint)GET_INT_FROM_POINTER(brush); + stroke->rng = BLI_rng_new(rng_seed); + } + 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(); + brush->mtex.random_angle * BLI_rng_get_float(stroke->rng); } } 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(); + brush->mask_mtex.random_angle * BLI_rng_get_float(stroke->rng); } } @@ -785,6 +795,10 @@ static void stroke_done(struct bContext *C, struct wmOperator *op) stroke->timer); } + if (stroke->rng) { + BLI_rng_free(stroke->rng); + } + if (stroke->stroke_cursor) WM_paint_cursor_end(CTX_wm_manager(C), stroke->stroke_cursor); diff --git a/source/blender/editors/sculpt_paint/paint_vertex.c b/source/blender/editors/sculpt_paint/paint_vertex.c index ac6bfe019a1..85a1f11be4b 100644 --- a/source/blender/editors/sculpt_paint/paint_vertex.c +++ b/source/blender/editors/sculpt_paint/paint_vertex.c @@ -967,15 +967,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(Depsgraph *depsgraph, Scene *scene, Object *ob) +static void vertex_paint_init_session(Depsgraph *depsgraph, 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(depsgraph, 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(depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); +} + +static void vertex_paint_init_stroke(Depsgraph *depsgraph, Scene *scene, Object *ob) +{ + BKE_sculpt_update_mesh_elements(depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); } static void vertex_paint_init_session_data(const ToolSettings *ts, Object *ob) @@ -986,12 +991,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; @@ -1113,7 +1118,7 @@ static void ed_vwpaintmode_enter_generic( BKE_sculptsession_free(ob); } - vertex_paint_init_session(depsgraph, scene, ob); + vertex_paint_init_session(depsgraph, scene, ob, mode_flag); /* Flush object mode. */ DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE); @@ -1556,7 +1561,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(depsgraph, scene, ob); + vertex_paint_init_stroke(depsgraph, scene, ob); vwpaint_update_cache_invariants(C, vp, ss, op, mouse); vertex_paint_init_session_data(ts, ob); @@ -2545,7 +2550,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(depsgraph, scene, ob); + vertex_paint_init_stroke(depsgraph, scene, ob); vwpaint_update_cache_invariants(C, vp, ss, op, mouse); vertex_paint_init_session_data(ts, 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 7c2977a0788..01c62704db3 100644 --- a/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c +++ b/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c @@ -51,6 +51,7 @@ #include "BKE_context.h" #include "BKE_deform.h" #include "BKE_mesh.h" +#include "BKE_mesh_iterators.h" #include "BKE_mesh_mapping.h" #include "BKE_mesh_runtime.h" #include "BKE_modifier.h" @@ -534,21 +535,21 @@ void PAINT_OT_weight_set(wmOperatorType *ot) * \{ */ /* *** VGroups Gradient *** */ -typedef struct DMGradient_vertStore { +typedef struct WPGradient_vertStore { float sco[2]; float weight_orig; enum { VGRAD_STORE_NOP = 0, VGRAD_STORE_DW_EXIST = (1 << 0) } flag; -} DMGradient_vertStore; +} WPGradient_vertStore; -typedef struct DMGradient_vertStoreBase { +typedef struct WPGradient_vertStoreBase { struct WPaintPrev wpp; - DMGradient_vertStore elem[0]; -} DMGradient_vertStoreBase; + WPGradient_vertStore elem[0]; +} WPGradient_vertStoreBase; -typedef struct DMGradient_userData { +typedef struct WPGradient_userData { struct ARegion *ar; Scene *scene; Mesh *me; @@ -558,7 +559,7 @@ typedef struct DMGradient_userData { float sco_line_div; /* store (1.0f / len_v2v2(sco_start, sco_end)) */ int def_nr; bool is_init; - DMGradient_vertStoreBase *vert_cache; + WPGradient_vertStoreBase *vert_cache; /* only for init */ BLI_bitmap *vert_visit; @@ -566,12 +567,12 @@ typedef struct DMGradient_userData { short use_select; short type; float weightpaint; -} DMGradient_userData; +} WPGradient_userData; -static void gradientVert_update(DMGradient_userData *grad_data, int index) +static void gradientVert_update(WPGradient_userData *grad_data, int index) { Mesh *me = grad_data->me; - DMGradient_vertStore *vs = &grad_data->vert_cache->elem[index]; + WPGradient_vertStore *vs = &grad_data->vert_cache->elem[index]; float alpha; if (grad_data->type == WPAINT_GRADIENT_TYPE_LINEAR) { @@ -619,10 +620,10 @@ static void gradientVertUpdate__mapFunc( void *userData, int index, const float UNUSED(co[3]), const float UNUSED(no_f[3]), const short UNUSED(no_s[3])) { - DMGradient_userData *grad_data = userData; + WPGradient_userData *grad_data = userData; Mesh *me = grad_data->me; if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) { - DMGradient_vertStore *vs = &grad_data->vert_cache->elem[index]; + WPGradient_vertStore *vs = &grad_data->vert_cache->elem[index]; if (vs->sco[0] != FLT_MAX) { gradientVert_update(grad_data, index); } @@ -633,7 +634,7 @@ static void gradientVertInit__mapFunc( void *userData, int index, const float co[3], const float UNUSED(no_f[3]), const short UNUSED(no_s[3])) { - DMGradient_userData *grad_data = userData; + WPGradient_userData *grad_data = userData; Mesh *me = grad_data->me; if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) { @@ -642,7 +643,7 @@ static void gradientVertInit__mapFunc( * updating the mesh may move them about (entering feedback loop) */ if (BLI_BITMAP_TEST(grad_data->vert_visit, index) == 0) { - DMGradient_vertStore *vs = &grad_data->vert_cache->elem[index]; + WPGradient_vertStore *vs = &grad_data->vert_cache->elem[index]; if (ED_view3d_project_float_object(grad_data->ar, co, vs->sco, V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) @@ -675,7 +676,7 @@ static void gradientVertInit__mapFunc( static int paint_weight_gradient_modal(bContext *C, wmOperator *op, const wmEvent *event) { wmGesture *gesture = op->customdata; - DMGradient_vertStoreBase *vert_cache = gesture->userdata; + WPGradient_vertStoreBase *vert_cache = gesture->userdata; int ret = WM_gesture_straightline_modal(C, op, event); if (ret & OPERATOR_RUNNING_MODAL) { @@ -711,7 +712,7 @@ static int paint_weight_gradient_modal(bContext *C, wmOperator *op, const wmEven static int paint_weight_gradient_exec(bContext *C, wmOperator *op) { wmGesture *gesture = op->customdata; - DMGradient_vertStoreBase *vert_cache; + WPGradient_vertStoreBase *vert_cache; struct ARegion *ar = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); Object *ob = CTX_data_active_object(C); @@ -726,20 +727,18 @@ static int paint_weight_gradient_exec(bContext *C, wmOperator *op) Depsgraph *depsgraph = CTX_data_depsgraph(C); - DerivedMesh *dm = mesh_get_derived_final(depsgraph, scene, ob, scene->customdata_mask); - - DMGradient_userData data = {NULL}; + WPGradient_userData data = {NULL}; if (is_interactive) { if (gesture->userdata == NULL) { gesture->userdata = MEM_mallocN( - sizeof(DMGradient_vertStoreBase) + - (sizeof(DMGradient_vertStore) * me->totvert), + sizeof(WPGradient_vertStoreBase) + + (sizeof(WPGradient_vertStore) * me->totvert), __func__); gesture->userdata_free = false; data.is_init = true; - wpaint_prev_create(&((DMGradient_vertStoreBase *)gesture->userdata)->wpp, me->dvert, me->totvert); + wpaint_prev_create(&((WPGradient_vertStoreBase *)gesture->userdata)->wpp, me->dvert, me->totvert); /* on init only, convert face -> vert sel */ if (me->editflag & ME_EDIT_PAINT_FACE_SEL) { @@ -756,8 +755,8 @@ static int paint_weight_gradient_exec(bContext *C, wmOperator *op) data.is_init = true; vert_cache = MEM_mallocN( - sizeof(DMGradient_vertStoreBase) + - (sizeof(DMGradient_vertStore) * me->totvert), + sizeof(WPGradient_vertStoreBase) + + (sizeof(WPGradient_vertStore) * me->totvert), __func__); } @@ -786,16 +785,17 @@ static int paint_weight_gradient_exec(bContext *C, wmOperator *op) ED_view3d_init_mats_rv3d(ob, ar->regiondata); + Mesh *me_eval = mesh_get_eval_final(depsgraph, scene, ob, scene->customdata_mask | CD_MASK_ORIGINDEX); if (data.is_init) { data.vert_visit = BLI_BITMAP_NEW(me->totvert, __func__); - dm->foreachMappedVert(dm, gradientVertInit__mapFunc, &data, DM_FOREACH_NOP); + BKE_mesh_foreach_mapped_vert(me_eval, gradientVertInit__mapFunc, &data, MESH_FOREACH_NOP); MEM_freeN(data.vert_visit); data.vert_visit = NULL; } else { - dm->foreachMappedVert(dm, gradientVertUpdate__mapFunc, &data, DM_FOREACH_NOP); + BKE_mesh_foreach_mapped_vert(me_eval, gradientVertUpdate__mapFunc, &data, MESH_FOREACH_NOP); } DEG_id_tag_update(&ob->id, OB_RECALC_DATA); diff --git a/source/blender/editors/sculpt_paint/sculpt.c b/source/blender/editors/sculpt_paint/sculpt.c index 1c76f20d45c..414b9f2062f 100644 --- a/source/blender/editors/sculpt_paint/sculpt.c +++ b/source/blender/editors/sculpt_paint/sculpt.c @@ -4808,7 +4808,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) { Depsgraph *depsgraph = CTX_data_depsgraph(C); Scene *scene = CTX_data_scene(C); @@ -4829,8 +4829,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(depsgraph, scene, sd, ob, is_smooth, need_mask); - - return 1; } static void sculpt_restore_mesh(Sculpt *sd, Object *ob) @@ -5075,8 +5073,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, @@ -5108,8 +5105,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); @@ -5666,7 +5662,7 @@ void ED_object_sculptmode_enter_ex( /* Make sure derived final from original object does not reference possibly * freed memory. */ - BKE_object_free_derived_mesh_caches(ob); + BKE_object_free_derived_caches(ob); sculpt_init_session(depsgraph, scene, ob); @@ -5737,7 +5733,7 @@ void ED_object_sculptmode_enter_ex( } } - // ED_workspace_object_mode_sync_from_object(G.main->wm.first, workspace, ob); + // ED_workspace_object_mode_sync_from_object(bmain->wm.first, workspace, ob); /* Flush object mode. */ DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE); @@ -5789,14 +5785,14 @@ void ED_object_sculptmode_exit_ex( /* Leave sculptmode */ ob->mode &= ~mode_flag; - // ED_workspace_object_mode_sync_from_object(G.main->wm.first, workspace, ob); + // ED_workspace_object_mode_sync_from_object(G_MAIN->wm.first, workspace, ob); BKE_sculptsession_free(ob); paint_cursor_delete_textures(); /* Never leave derived meshes behind. */ - BKE_object_free_derived_mesh_caches(ob); + BKE_object_free_derived_caches(ob); /* Flush object mode. */ DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE); diff --git a/source/blender/editors/sound/sound_ops.c b/source/blender/editors/sound/sound_ops.c index b7a80a92998..049feea2d8a 100644 --- a/source/blender/editors/sound/sound_ops.c +++ b/source/blender/editors/sound/sound_ops.c @@ -455,10 +455,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; diff --git a/source/blender/editors/space_action/action_buttons.c b/source/blender/editors/space_action/action_buttons.c index a5cc66add87..55ad773f4df 100644 --- a/source/blender/editors/space_action/action_buttons.c +++ b/source/blender/editors/space_action/action_buttons.c @@ -117,7 +117,7 @@ static int action_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) void ACTION_OT_properties(wmOperatorType *ot) { - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->idname = "ACTION_OT_properties"; ot->description = "Toggle the properties region visibility"; diff --git a/source/blender/editors/space_action/action_draw.c b/source/blender/editors/space_action/action_draw.c index 7c8be943a87..35ebb62a7cc 100644 --- a/source/blender/editors/space_action/action_draw.c +++ b/source/blender/editors/space_action/action_draw.c @@ -436,7 +436,7 @@ void timeline_draw_cache(SpaceAction *saction, Object *ob, Scene *scene) continue; gpuPushMatrix(); - gpuTranslate2f(0.0, (float)V2D_SCROLL_HEIGHT + yoffs); + gpuTranslate2f(0.0, (float)V2D_SCROLL_HEIGHT_TEXT + yoffs); gpuScale2f(1.0, cache_draw_height); switch (pid->type) { diff --git a/source/blender/editors/space_action/space_action.c b/source/blender/editors/space_action/space_action.c index e130ea9369c..527e382ec1e 100644 --- a/source/blender/editors/space_action/space_action.c +++ b/source/blender/editors/space_action/space_action.c @@ -116,7 +116,7 @@ static SpaceLink *action_new(const ScrArea *sa, const Scene *scene) BLI_addtail(&saction->regionbase, ar); ar->regiontype = RGN_TYPE_HEADER; - ar->alignment = RGN_ALIGN_BOTTOM; + ar->alignment = RGN_ALIGN_TOP; /* channel list region */ ar = MEM_callocN(sizeof(ARegion), "channel region for action"); @@ -752,7 +752,7 @@ static void action_buttons_area_init(wmWindowManager *wm, ARegion *ar) static void action_buttons_area_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void action_region_listener( diff --git a/source/blender/editors/space_buttons/space_buttons.c b/source/blender/editors/space_buttons/space_buttons.c index be687d365f3..4fe3423e730 100644 --- a/source/blender/editors/space_buttons/space_buttons.c +++ b/source/blender/editors/space_buttons/space_buttons.c @@ -144,7 +144,7 @@ static void buttons_main_region_init(wmWindowManager *wm, ARegion *ar) WM_event_add_keymap_handler(&ar->handlers, keymap); } -static void buttons_main_region_draw_properties(const bContext *C, SpaceButs *sbuts, ARegion *ar) +static void buttons_main_region_layout_properties(const bContext *C, SpaceButs *sbuts, ARegion *ar) { const bool vertical = (sbuts->align == BUT_VERTICAL); @@ -203,12 +203,10 @@ static void buttons_main_region_draw_properties(const bContext *C, SpaceButs *sb break; } - if (contexts[0]) { - ED_region_panels(C, ar, contexts, sbuts->mainb, vertical); - } + ED_region_panels_layout_ex(C, ar, contexts, sbuts->mainb, vertical); } -static void buttons_main_region_draw_tool(const bContext *C, SpaceButs *sbuts, ARegion *ar) +static void buttons_main_region_layout_tool(const bContext *C, SpaceButs *sbuts, ARegion *ar) { const bool vertical = (sbuts->align == BUT_VERTICAL); const char *contexts[3] = {NULL}; @@ -260,30 +258,24 @@ static void buttons_main_region_draw_tool(const bContext *C, SpaceButs *sbuts, A ARRAY_SET_ITEMS(contexts, ".todo"); break; } - if (contexts[0]) { - ED_region_panels(C, ar, contexts, -1, vertical); - } } else if (workspace->tools_space_type == SPACE_IMAGE) { /* TODO */ } - if (contexts[0] == NULL) { - UI_ThemeClearColor(TH_BACK); - glClear(GL_COLOR_BUFFER_BIT); - } + ED_region_panels_layout_ex(C, ar, contexts, -1, vertical); } -static void buttons_main_region_draw(const bContext *C, ARegion *ar) +static void buttons_main_region_layout(const bContext *C, ARegion *ar) { /* draw entirely, view changes should be handled here */ SpaceButs *sbuts = CTX_wm_space_buts(C); if (sbuts->mainb == BCONTEXT_TOOL) { - buttons_main_region_draw_tool(C, sbuts, ar); + buttons_main_region_layout_tool(C, sbuts, ar); } else { - buttons_main_region_draw_properties(C, sbuts, ar); + buttons_main_region_layout_properties(C, sbuts, ar); } sbuts->re_align = 0; @@ -619,7 +611,8 @@ void ED_spacetype_buttons(void) art = MEM_callocN(sizeof(ARegionType), "spacetype buttons region"); art->regionid = RGN_TYPE_WINDOW; art->init = buttons_main_region_init; - art->draw = buttons_main_region_draw; + art->layout = buttons_main_region_layout; + art->draw = ED_region_panels_draw; art->listener = buttons_main_region_listener; art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES; BLI_addhead(&st->regiontypes, art); diff --git a/source/blender/editors/space_clip/clip_buttons.c b/source/blender/editors/space_clip/clip_buttons.c index 469d94fed3a..f2fe06874d7 100644 --- a/source/blender/editors/space_clip/clip_buttons.c +++ b/source/blender/editors/space_clip/clip_buttons.c @@ -387,7 +387,7 @@ void uiTemplateMarker(uiLayout *layout, PointerRNA *ptr, const char *propname, P else tip = TIP_("Marker is enabled at current frame"); - bt = uiDefIconButBitI(block, UI_BTYPE_TOGGLE_N, MARKER_DISABLED, 0, ICON_RESTRICT_VIEW_OFF, 0, 0, UI_UNIT_X, UI_UNIT_Y, + bt = uiDefIconButBitI(block, UI_BTYPE_TOGGLE_N, MARKER_DISABLED, 0, ICON_HIDE_OFF, 0, 0, UI_UNIT_X, UI_UNIT_Y, &cb->marker_flag, 0, 0, 1, 0, tip); UI_but_funcN_set(bt, marker_update_cb, cb, NULL); } diff --git a/source/blender/editors/space_clip/clip_intern.h b/source/blender/editors/space_clip/clip_intern.h index ab8a7add009..e5c4f567d5c 100644 --- a/source/blender/editors/space_clip/clip_intern.h +++ b/source/blender/editors/space_clip/clip_intern.h @@ -145,6 +145,8 @@ void clip_view_center_to_point(SpaceClip *sc, float x, float y); void clip_draw_sfra_efra(struct View2D *v2d, struct Scene *scene); +void clip_on_marker_selection_changed(struct bContext *C); + /* tracking_ops.c */ struct MovieTrackingTrack *tracking_marker_check_slide(struct bContext *C, const struct wmEvent *event, int *area_r, int *action_r, int *corner_r); diff --git a/source/blender/editors/space_clip/clip_toolbar.c b/source/blender/editors/space_clip/clip_toolbar.c index 61bd8df3dbf..3e4d0cd5bb4 100644 --- a/source/blender/editors/space_clip/clip_toolbar.c +++ b/source/blender/editors/space_clip/clip_toolbar.c @@ -106,7 +106,7 @@ static int properties_exec(bContext *C, wmOperator *UNUSED(op)) void CLIP_OT_properties(wmOperatorType *ot) { /* identifiers */ - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->description = "Toggle the properties region visibility"; ot->idname = "CLIP_OT_properties"; @@ -170,7 +170,7 @@ static int tools_exec(bContext *C, wmOperator *UNUSED(op)) void CLIP_OT_tools(wmOperatorType *ot) { /* identifiers */ - ot->name = "Tools"; + ot->name = "Toggle Toolbar"; ot->description = "Toggle clip tools panel"; ot->idname = "CLIP_OT_tools"; diff --git a/source/blender/editors/space_clip/space_clip.c b/source/blender/editors/space_clip/space_clip.c index f022bb7e6f8..b050e991140 100644 --- a/source/blender/editors/space_clip/space_clip.c +++ b/source/blender/editors/space_clip/space_clip.c @@ -1435,7 +1435,7 @@ static void clip_tools_region_init(wmWindowManager *wm, ARegion *ar) static void clip_tools_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } /****************** tool properties region ******************/ @@ -1484,7 +1484,7 @@ static void clip_properties_region_draw(const bContext *C, ARegion *ar) BKE_movieclip_update_scopes(sc->clip, &sc->user, &sc->scopes); - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void clip_properties_region_listener( diff --git a/source/blender/editors/space_file/filelist.c b/source/blender/editors/space_file/filelist.c index 8123bed541c..09e2660a762 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/filesel.c b/source/blender/editors/space_file/filesel.c index 418a9f8c16f..cb014f30d95 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/space_file.c b/source/blender/editors/space_file/space_file.c index 62e7c7923e8..7b045a42595 100644 --- a/source/blender/editors/space_file/space_file.c +++ b/source/blender/editors/space_file/space_file.c @@ -636,7 +636,7 @@ static void file_tools_region_init(wmWindowManager *wm, ARegion *ar) static void file_tools_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void file_tools_region_listener( diff --git a/source/blender/editors/space_graph/graph_buttons.c b/source/blender/editors/space_graph/graph_buttons.c index 4f3de0398a2..2a0d5baa5c3 100644 --- a/source/blender/editors/space_graph/graph_buttons.c +++ b/source/blender/editors/space_graph/graph_buttons.c @@ -801,7 +801,7 @@ static void graph_draw_driver_settings_panel(uiLayout *layout, ID *id, FCurve *f if ((G.f & G_SCRIPT_AUTOEXEC) == 0) { /* TODO: Add button to enable? */ - 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); @@ -1207,7 +1207,7 @@ static int graph_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) void GRAPH_OT_properties(wmOperatorType *ot) { - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->idname = "GRAPH_OT_properties"; ot->description = "Toggle the properties region visibility"; diff --git a/source/blender/editors/space_graph/space_graph.c b/source/blender/editors/space_graph/space_graph.c index 56236ea8f47..d208ead317b 100644 --- a/source/blender/editors/space_graph/space_graph.c +++ b/source/blender/editors/space_graph/space_graph.c @@ -181,14 +181,14 @@ static void graph_free(SpaceLink *sl) /* spacetype; init callback */ -static void graph_init(struct wmWindowManager *UNUSED(wm), ScrArea *sa) +static void graph_init(struct wmWindowManager *wm, ScrArea *sa) { SpaceIpo *sipo = (SpaceIpo *)sa->spacedata.first; /* init dopesheet data if non-existent (i.e. for old files) */ if (sipo->ads == NULL) { sipo->ads = MEM_callocN(sizeof(bDopeSheet), "GraphEdit DopeSheet"); - sipo->ads->source = (ID *)(G.main->scene.first); // FIXME: this is a really nasty hack here for now... + sipo->ads->source = (ID *)WM_window_get_active_scene(wm->winactive); } /* force immediate init of any invalid F-Curve colors */ @@ -422,7 +422,7 @@ static void graph_buttons_region_init(wmWindowManager *wm, ARegion *ar) static void graph_buttons_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void graph_region_listener( diff --git a/source/blender/editors/space_image/image_buttons.c b/source/blender/editors/space_image/image_buttons.c index 8b8aabb2ce0..7236a99ad80 100644 --- a/source/blender/editors/space_image/image_buttons.c +++ b/source/blender/editors/space_image/image_buttons.c @@ -291,23 +291,24 @@ static void ui_imageuser_slot_menu(bContext *UNUSED(C), uiLayout *layout, void * { uiBlock *block = uiLayoutGetBlock(layout); Image *image = image_p; - int slot; + int slot_id; uiDefBut(block, UI_BTYPE_LABEL, 0, IFACE_("Slot"), 0, 0, UI_UNIT_X * 5, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, ""); uiItemS(layout); - slot = IMA_MAX_RENDER_SLOT; - while (slot--) { + slot_id = BLI_listbase_count(&image->renderslots) - 1; + for (RenderSlot *slot = image->renderslots.last; slot; slot = slot->prev) { char str[64]; - if (image->render_slots[slot].name[0] != '\0') { - BLI_strncpy(str, image->render_slots[slot].name, sizeof(str)); + if (slot->name[0] != '\0') { + BLI_strncpy(str, slot->name, sizeof(str)); } else { - BLI_snprintf(str, sizeof(str), IFACE_("Slot %d"), slot + 1); + BLI_snprintf(str, sizeof(str), IFACE_("Slot %d"), slot_id + 1); } uiDefButS(block, UI_BTYPE_BUT_MENU, B_NOP, str, 0, 0, - UI_UNIT_X * 5, UI_UNIT_X, &image->render_slot, (float) slot, 0.0, 0, -1, ""); + UI_UNIT_X * 5, UI_UNIT_X, &image->render_slot, (float) slot_id, 0.0, 0, -1, ""); + slot_id--; } } @@ -708,8 +709,9 @@ static void uiblock_layer_pass_buttons( /* menu buts */ if (render_slot) { char str[64]; - if (image->render_slots[*render_slot].name[0] != '\0') { - BLI_strncpy(str, image->render_slots[*render_slot].name, sizeof(str)); + RenderSlot *slot = BKE_image_get_renderslot(image, *render_slot); + if (slot->name[0] != '\0') { + BLI_strncpy(str, slot->name, sizeof(str)); } else { BLI_snprintf(str, sizeof(str), IFACE_("Slot %d"), *render_slot + 1); @@ -1313,7 +1315,7 @@ static int image_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) void IMAGE_OT_properties(wmOperatorType *ot) { - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->idname = "IMAGE_OT_properties"; ot->description = "Toggle the properties region visibility"; @@ -1337,7 +1339,7 @@ static int image_scopes_toggle_exec(bContext *C, wmOperator *UNUSED(op)) void IMAGE_OT_toolshelf(wmOperatorType *ot) { - ot->name = "Tool Shelf"; + ot->name = "Toggle Toolbar"; ot->idname = "IMAGE_OT_toolshelf"; ot->description = "Toggles tool shelf display"; diff --git a/source/blender/editors/space_image/image_edit.c b/source/blender/editors/space_image/image_edit.c index 0eb6a2400d2..f4ecd2e7d34 100644 --- a/source/blender/editors/space_image/image_edit.c +++ b/source/blender/editors/space_image/image_edit.c @@ -34,6 +34,7 @@ #include "DNA_scene_types.h" #include "BLI_rect.h" +#include "BLI_listbase.h" #include "BKE_colortools.h" #include "BKE_context.h" @@ -302,17 +303,19 @@ bool ED_image_slot_cycle(struct Image *image, int direction) BLI_assert(ELEM(direction, -1, 1)); - for (i = 1; i < IMA_MAX_RENDER_SLOT; i++) { - slot = (cur + ((direction == -1) ? -i : i)) % IMA_MAX_RENDER_SLOT; - if (slot < 0) slot += IMA_MAX_RENDER_SLOT; + int num_slots = BLI_listbase_count(&image->renderslots); + for (i = 1; i < num_slots; i++) { + slot = (cur + ((direction == -1) ? -i : i)) % num_slots; + if (slot < 0) slot += num_slots; - if (image->renders[slot] || slot == image->last_render_slot) { + RenderSlot *render_slot = BKE_image_get_renderslot(image, slot); + if ((render_slot && render_slot->render) || slot == image->last_render_slot) { image->render_slot = slot; break; } } - if (i == IMA_MAX_RENDER_SLOT) { + if (i == num_slots) { image->render_slot = ((cur == 1) ? 0 : 1); } diff --git a/source/blender/editors/space_image/image_intern.h b/source/blender/editors/space_image/image_intern.h index 9167a193f2d..49c2690daaf 100644 --- a/source/blender/editors/space_image/image_intern.h +++ b/source/blender/editors/space_image/image_intern.h @@ -83,6 +83,9 @@ void IMAGE_OT_unpack(struct wmOperatorType *ot); void IMAGE_OT_invert(struct wmOperatorType *ot); void IMAGE_OT_cycle_render_slot(struct wmOperatorType *ot); +void IMAGE_OT_clear_render_slot(struct wmOperatorType *ot); +void IMAGE_OT_add_render_slot(struct wmOperatorType *ot); +void IMAGE_OT_remove_render_slot(struct wmOperatorType *ot); void IMAGE_OT_sample(struct wmOperatorType *ot); void IMAGE_OT_sample_line(struct wmOperatorType *ot); diff --git a/source/blender/editors/space_image/image_ops.c b/source/blender/editors/space_image/image_ops.c index 39544eb55dd..b2116b1a770 100644 --- a/source/blender/editors/space_image/image_ops.c +++ b/source/blender/editors/space_image/image_ops.c @@ -1538,7 +1538,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; @@ -3464,7 +3464,8 @@ static int image_cycle_render_slot_exec(bContext *C, wmOperator *op) WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL); /* no undo push for browsing existing */ - if (ima->renders[ima->render_slot] || ima->render_slot == ima->last_render_slot) + RenderSlot *slot = BKE_image_get_renderslot(ima, ima->render_slot); + if ((slot && slot->render) || ima->render_slot == ima->last_render_slot) return OPERATOR_CANCELLED; return OPERATOR_FINISHED; @@ -3487,6 +3488,97 @@ void IMAGE_OT_cycle_render_slot(wmOperatorType *ot) RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", ""); } +/********************* clear render slot operator *********************/ + +static int image_clear_render_slot_exec(bContext *C, wmOperator *UNUSED(op)) +{ + SpaceImage *sima = CTX_wm_space_image(C); + Image *ima = CTX_data_edit_image(C); + + if (!BKE_image_clear_renderslot(ima, &sima->iuser, ima->render_slot)) { + return OPERATOR_CANCELLED; + } + + WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL); + + return OPERATOR_FINISHED; +} + +void IMAGE_OT_clear_render_slot(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Clear Render Slot"; + ot->idname = "IMAGE_OT_clear_render_slot"; + ot->description = "Clear the currently selected render slot"; + + /* api callbacks */ + ot->exec = image_clear_render_slot_exec; + ot->poll = image_cycle_render_slot_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER; +} + +/********************* add render slot operator *********************/ + +static int image_add_render_slot_exec(bContext *C, wmOperator *UNUSED(op)) +{ + Image *ima = CTX_data_edit_image(C); + + RenderSlot *slot = BKE_image_add_renderslot(ima, NULL); + ima->render_slot = BLI_findindex(&ima->renderslots, slot); + + WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL); + + return OPERATOR_FINISHED; +} + +void IMAGE_OT_add_render_slot(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Add Render Slot"; + ot->idname = "IMAGE_OT_add_render_slot"; + ot->description = "Add a new render slot"; + + /* api callbacks */ + ot->exec = image_add_render_slot_exec; + ot->poll = image_cycle_render_slot_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER; +} + +/********************* remove render slot operator *********************/ + +static int image_remove_render_slot_exec(bContext *C, wmOperator *UNUSED(op)) +{ + SpaceImage *sima = CTX_wm_space_image(C); + Image *ima = CTX_data_edit_image(C); + + if (!BKE_image_remove_renderslot(ima, &sima->iuser, ima->render_slot)) { + return OPERATOR_CANCELLED; + } + + WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL); + + return OPERATOR_FINISHED; +} + +void IMAGE_OT_remove_render_slot(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Remove Render Slot"; + ot->idname = "IMAGE_OT_remove_render_slot"; + ot->description = "Remove the current render slot"; + + /* api callbacks */ + ot->exec = image_remove_render_slot_exec; + ot->poll = image_cycle_render_slot_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER; +} + /********************** change frame operator *********************/ static int change_frame_poll(bContext *C) diff --git a/source/blender/editors/space_image/space_image.c b/source/blender/editors/space_image/space_image.c index c143ebbcd67..e84b596530e 100644 --- a/source/blender/editors/space_image/space_image.c +++ b/source/blender/editors/space_image/space_image.c @@ -272,6 +272,9 @@ static void image_operatortypes(void) WM_operatortype_append(IMAGE_OT_invert); WM_operatortype_append(IMAGE_OT_cycle_render_slot); + WM_operatortype_append(IMAGE_OT_clear_render_slot); + WM_operatortype_append(IMAGE_OT_add_render_slot); + WM_operatortype_append(IMAGE_OT_remove_render_slot); WM_operatortype_append(IMAGE_OT_sample); WM_operatortype_append(IMAGE_OT_sample_line); @@ -358,7 +361,7 @@ static void image_keymap(struct wmKeyConfig *keyconf) RNA_boolean_set(kmi->ptr, "toggle", true); /* fast switch to render slots */ - for (i = 0; i < MIN2(IMA_MAX_RENDER_SLOT, 9); i++) { + for (i = 0; i < 9; i++) { kmi = WM_keymap_add_item(keymap, "WM_OT_context_set_int", ONEKEY + i, KM_PRESS, 0, 0); RNA_string_set(kmi->ptr, "data_path", "space_data.image.render_slots.active_index"); RNA_int_set(kmi->ptr, "value", i); @@ -869,7 +872,7 @@ static void image_buttons_region_init(wmWindowManager *wm, ARegion *ar) static void image_buttons_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void image_buttons_region_listener( @@ -944,7 +947,7 @@ static void image_tools_region_draw(const bContext *C, ARegion *ar) } ED_space_image_release_buffer(sima, ibuf, lock); - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void image_tools_region_listener( @@ -1096,7 +1099,6 @@ void ED_spacetype_image(void) art->init = image_main_region_init; art->draw = image_main_region_draw; art->listener = image_main_region_listener; - BLI_addhead(&st->regiontypes, art); /* regions: listview/buttons */ @@ -1134,5 +1136,9 @@ void ED_spacetype_image(void) BLI_addhead(&st->regiontypes, art); + /* regions: hud */ + art = ED_area_type_hud(st->spaceid); + BLI_addhead(&st->regiontypes, art); + 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 a26e6b0280e..cafb40626ee 100644 --- a/source/blender/editors/space_nla/nla_buttons.c +++ b/source/blender/editors/space_nla/nla_buttons.c @@ -574,7 +574,7 @@ static int nla_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) void NLA_OT_properties(wmOperatorType *ot) { - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->idname = "NLA_OT_properties"; ot->description = "Toggle the properties region visibility"; diff --git a/source/blender/editors/space_nla/nla_edit.c b/source/blender/editors/space_nla/nla_edit.c index 26ac06446c4..23cd504978c 100644 --- a/source/blender/editors/space_nla/nla_edit.c +++ b/source/blender/editors/space_nla/nla_edit.c @@ -1057,7 +1057,7 @@ static int nlaedit_duplicate_exec(bContext *C, wmOperator *op) /* if selected, split the strip at its midpoint */ if (strip->flag & NLASTRIP_FLAG_SELECT) { /* make a copy (assume that this is possible) */ - nstrip = BKE_nlastrip_copy(strip, linked); + nstrip = BKE_nlastrip_copy(ac.bmain, strip, linked); /* in case there's no space in the track above, or we haven't got a reference to it yet, try adding */ if (BKE_nlatrack_add_strip(nlt->next, nstrip) == 0) { @@ -1207,7 +1207,7 @@ void NLA_OT_delete(wmOperatorType *ot) // - variable-length splits? /* split a given Action-Clip strip */ -static void nlaedit_split_strip_actclip(AnimData *adt, NlaTrack *nlt, NlaStrip *strip, float cfra) +static void nlaedit_split_strip_actclip(Main *bmain, AnimData *adt, NlaTrack *nlt, NlaStrip *strip, float cfra) { NlaStrip *nstrip; float splitframe, splitaframe; @@ -1242,7 +1242,7 @@ static void nlaedit_split_strip_actclip(AnimData *adt, NlaTrack *nlt, NlaStrip * /* make a copy (assume that this is possible) and append * it immediately after the current strip */ - nstrip = BKE_nlastrip_copy(strip, true); + nstrip = BKE_nlastrip_copy(bmain, strip, true); BLI_insertlinkafter(&nlt->strips, strip, nstrip); /* set the endpoint of the first strip and the start of the new strip @@ -1303,7 +1303,7 @@ static int nlaedit_split_exec(bContext *C, wmOperator *UNUSED(op)) /* splitting method depends on the type of strip */ switch (strip->type) { case NLASTRIP_TYPE_CLIP: /* action-clip */ - nlaedit_split_strip_actclip(adt, nlt, strip, (float)ac.scene->r.cfra); + nlaedit_split_strip_actclip(ac.bmain, adt, nlt, strip, (float)ac.scene->r.cfra); break; case NLASTRIP_TYPE_META: /* meta-strips need special handling */ diff --git a/source/blender/editors/space_nla/space_nla.c b/source/blender/editors/space_nla/space_nla.c index 318d8bf777b..745cea37ea3 100644 --- a/source/blender/editors/space_nla/space_nla.c +++ b/source/blender/editors/space_nla/space_nla.c @@ -178,14 +178,14 @@ static void nla_free(SpaceLink *sl) /* spacetype; init callback */ -static void nla_init(struct wmWindowManager *UNUSED(wm), ScrArea *sa) +static void nla_init(struct wmWindowManager *wm, ScrArea *sa) { SpaceNla *snla = (SpaceNla *)sa->spacedata.first; /* init dopesheet data if non-existent (i.e. for old files) */ if (snla->ads == NULL) { snla->ads = MEM_callocN(sizeof(bDopeSheet), "NlaEdit DopeSheet"); - snla->ads->source = (ID *)G.main->scene.first; // XXX this is bad, but we need this to be set correct + snla->ads->source = (ID *)WM_window_get_active_scene(wm->winactive); } ED_area_tag_refresh(sa); @@ -360,7 +360,7 @@ static void nla_buttons_region_init(wmWindowManager *wm, ARegion *ar) static void nla_buttons_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void nla_region_listener( diff --git a/source/blender/editors/space_node/drawnode.c b/source/blender/editors/space_node/drawnode.c index db718da12ef..a162a863038 100644 --- a/source/blender/editors/space_node/drawnode.c +++ b/source/blender/editors/space_node/drawnode.c @@ -1080,6 +1080,13 @@ static void node_shader_buts_bevel(uiLayout *layout, bContext *UNUSED(C), Pointe uiItemR(layout, ptr, "samples", 0, NULL, ICON_NONE); } +static void node_shader_buts_ambient_occlusion(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) +{ + uiItemR(layout, ptr, "samples", 0, NULL, ICON_NONE); + uiItemR(layout, ptr, "inside", 0, NULL, ICON_NONE); + uiItemR(layout, ptr, "only_local", 0, NULL, ICON_NONE); +} + /* only once called */ static void node_shader_set_butfunc(bNodeType *ntype) { @@ -1210,6 +1217,9 @@ static void node_shader_set_butfunc(bNodeType *ntype) case SH_NODE_BEVEL: ntype->draw_buttons = node_shader_buts_bevel; break; + case SH_NODE_AMBIENT_OCCLUSION: + ntype->draw_buttons = node_shader_buts_ambient_occlusion; + break; } } diff --git a/source/blender/editors/space_node/node_buttons.c b/source/blender/editors/space_node/node_buttons.c index 0a656ee1deb..38183637750 100644 --- a/source/blender/editors/space_node/node_buttons.c +++ b/source/blender/editors/space_node/node_buttons.c @@ -224,7 +224,7 @@ static int node_properties_poll(bContext *C) void NODE_OT_properties(wmOperatorType *ot) { - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->description = "Toggle the properties region visibility"; ot->idname = "NODE_OT_properties"; diff --git a/source/blender/editors/space_node/node_edit.c b/source/blender/editors/space_node/node_edit.c index 91101d1101e..ff87dcf409a 100644 --- a/source/blender/editors/space_node/node_edit.c +++ b/source/blender/editors/space_node/node_edit.c @@ -656,6 +656,7 @@ void ED_node_set_active(Main *bmain, bNodeTree *ntree, bNode *node) if (wo->nodetree && wo->use_nodes && ntreeHasTree(wo->nodetree, ntree)) GPU_material_free(&wo->gpumaterial); + ED_node_tag_update_nodetree(bmain, ntree, node); WM_main_add_notifier(NC_IMAGE, NULL); } @@ -929,11 +930,13 @@ static int node_resize_modal(bContext *C, wmOperator *op, const wmEvent *event) case LEFTMOUSE: case MIDDLEMOUSE: case RIGHTMOUSE: + if (event->val == KM_RELEASE) { + node_resize_exit(C, op, false); + ED_node_post_apply_transform(C, snode->edittree); - node_resize_exit(C, op, false); - ED_node_post_apply_transform(C, snode->edittree); - - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; + } + break; } return OPERATOR_RUNNING_MODAL; diff --git a/source/blender/editors/space_node/node_group.c b/source/blender/editors/space_node/node_group.c index 5d326a0be38..926fff7a3b6 100644 --- a/source/blender/editors/space_node/node_group.c +++ b/source/blender/editors/space_node/node_group.c @@ -260,7 +260,7 @@ static int node_group_ungroup(Main *bmain, bNodeTree *ntree, bNode *gnode) waction = wgroup->adt->action = BKE_action_copy(bmain, wgroup->adt->action); /* now perform the moving */ - BKE_animdata_separate_by_basepath(&wgroup->id, &ntree->id, &anim_basepaths); + BKE_animdata_separate_by_basepath(bmain, &wgroup->id, &ntree->id, &anim_basepaths); /* paths + their wrappers need to be freed */ for (ld = anim_basepaths.first; ld; ld = ldn) { @@ -397,7 +397,8 @@ void NODE_OT_group_ungroup(wmOperatorType *ot) /* ******************** Separate operator ********************** */ /* returns 1 if its OK */ -static int node_group_separate_selected(bNodeTree *ntree, bNodeTree *ngroup, float offx, float offy, int make_copy) +static int node_group_separate_selected( + Main *bmain, bNodeTree *ntree, bNodeTree *ngroup, float offx, float offy, int make_copy) { bNodeLink *link, *link_next; bNode *node, *node_next, *newnode; @@ -492,7 +493,7 @@ static int node_group_separate_selected(bNodeTree *ntree, bNodeTree *ngroup, flo LinkData *ld, *ldn = NULL; /* now perform the moving */ - BKE_animdata_separate_by_basepath(&ngroup->id, &ntree->id, &anim_basepaths); + BKE_animdata_separate_by_basepath(bmain, &ngroup->id, &ntree->id, &anim_basepaths); /* paths + their wrappers need to be freed */ for (ld = anim_basepaths.first; ld; ld = ldn) { @@ -524,12 +525,13 @@ static const EnumPropertyItem node_group_separate_types[] = { static int node_group_separate_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); SpaceNode *snode = CTX_wm_space_node(C); bNodeTree *ngroup, *nparent; int type = RNA_enum_get(op->ptr, "type"); float offx, offy; - ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C)); + ED_preview_kill_jobs(CTX_wm_manager(C), bmain); /* are we inside of a group? */ ngroup = snode->edittree; @@ -543,13 +545,13 @@ static int node_group_separate_exec(bContext *C, wmOperator *op) switch (type) { case NODE_GS_COPY: - if (!node_group_separate_selected(nparent, ngroup, offx, offy, 1)) { + if (!node_group_separate_selected(bmain, nparent, ngroup, offx, offy, 1)) { BKE_report(op->reports, RPT_WARNING, "Cannot separate nodes"); return OPERATOR_CANCELLED; } break; case NODE_GS_MOVE: - if (!node_group_separate_selected(nparent, ngroup, offx, offy, 0)) { + if (!node_group_separate_selected(bmain, nparent, ngroup, offx, offy, 0)) { BKE_report(op->reports, RPT_WARNING, "Cannot separate nodes"); return OPERATOR_CANCELLED; } @@ -681,6 +683,7 @@ static int node_get_selected_minmax(bNodeTree *ntree, bNode *gnode, float *min, static void node_group_make_insert_selected(const bContext *C, bNodeTree *ntree, bNode *gnode) { + Main *bmain = CTX_data_main(C); bNodeTree *ngroup = (bNodeTree *)gnode->id; bNodeLink *link, *linkn; bNode *node, *nextn; @@ -742,7 +745,7 @@ static void node_group_make_insert_selected(const bContext *C, bNodeTree *ntree, if (ntree->adt) { LinkData *ld, *ldn = NULL; - BKE_animdata_separate_by_basepath(&ntree->id, &ngroup->id, &anim_basepaths); + BKE_animdata_separate_by_basepath(bmain, &ntree->id, &ngroup->id, &anim_basepaths); /* paths + their wrappers need to be freed */ for (ld = anim_basepaths.first; ld; ld = ldn) { diff --git a/source/blender/editors/space_node/space_node.c b/source/blender/editors/space_node/space_node.c index 36886d0ab32..441ab03cb28 100644 --- a/source/blender/editors/space_node/space_node.c +++ b/source/blender/editors/space_node/space_node.c @@ -603,7 +603,7 @@ static void node_buttons_region_init(wmWindowManager *wm, ARegion *ar) static void node_buttons_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } /* add handlers, stuff you only do once or on area/region changes */ @@ -619,7 +619,7 @@ static void node_toolbar_region_init(wmWindowManager *wm, ARegion *ar) static void node_toolbar_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void node_cursor(wmWindow *win, ScrArea *sa, ARegion *ar) diff --git a/source/blender/editors/space_outliner/outliner_collections.c b/source/blender/editors/space_outliner/outliner_collections.c index 909938ad606..a700f8e20e0 100644 --- a/source/blender/editors/space_outliner/outliner_collections.c +++ b/source/blender/editors/space_outliner/outliner_collections.c @@ -320,7 +320,10 @@ static int collection_objects_select_exec(bContext *C, wmOperator *op) } BKE_layer_collection_objects_select(view_layer, layer_collection, deselect); - WM_main_add_notifier(NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_main_add_notifier(NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } diff --git a/source/blender/editors/space_outliner/outliner_draw.c b/source/blender/editors/space_outliner/outliner_draw.c index a514d7f1335..a3f3acf1c32 100644 --- a/source/blender/editors/space_outliner/outliner_draw.c +++ b/source/blender/editors/space_outliner/outliner_draw.c @@ -92,8 +92,9 @@ static void outliner_height(SpaceOops *soops, ListBase *lb, int *h) TreeElement *te = lb->first; while (te) { TreeStoreElem *tselem = TREESTORE(te); - if (TSELEM_OPEN(tselem, soops)) + if (TSELEM_OPEN(tselem, soops)) { outliner_height(soops, &te->subtree, h); + } (*h) += UI_UNIT_Y; te = te->next; } @@ -132,8 +133,9 @@ static void outliner_rna_width(SpaceOops *soops, ListBase *lb, int *w, int start if (startx + 100 > *w) *w = startx + 100; - if (TSELEM_OPEN(tselem, soops)) + if (TSELEM_OPEN(tselem, soops)) { outliner_rna_width(soops, &te->subtree, w, startx + UI_UNIT_X); + } te = te->next; } } @@ -276,6 +278,44 @@ static void restrictbutton_id_user_toggle(bContext *UNUSED(C), void *poin, void } } +static void hidebutton_base_flag_cb(bContext *C, void *poin, void *poin2) +{ + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = poin; + Base *base = poin2; + bool extend = (CTX_wm_window(C)->eventstate->ctrl == 0); + + /* Undo button toggle, let function do it. */ + base->flag ^= BASE_HIDE; + + BKE_base_set_visible(scene, view_layer, base, extend); + + if (!extend && (base->flag & BASE_VISIBLED)) { + /* Auto select solo-ed object. */ + ED_object_base_select(base, BA_SELECT); + view_layer->basact = base; + } + + DEG_id_tag_update(&scene->id, DEG_TAG_BASE_FLAGS_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); +} + +static void hidebutton_layer_collection_flag_cb(bContext *C, void *poin, void *poin2) +{ + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = poin; + LayerCollection *lc = poin2; + bool extend = (CTX_wm_window(C)->eventstate->ctrl == 0); + + /* Undo button toggle, let function do it. */ + lc->runtime_flag ^= LAYER_COLLECTION_HAS_VISIBLE_OBJECTS; + + BKE_layer_collection_set_visible(scene, view_layer, lc, extend); + + DEG_id_tag_update(&scene->id, DEG_TAG_BASE_FLAGS_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); +} + static void namebutton_cb(bContext *C, void *tsep, char *oldname) { Main *bmain = CTX_data_main(C); @@ -432,172 +472,214 @@ static void namebutton_cb(bContext *C, void *tsep, char *oldname) } } -static void outliner_draw_restrictbuts(uiBlock *block, Scene *scene, ARegion *ar, SpaceOops *soops, ListBase *lb) +static void outliner_draw_restrictbuts( + uiBlock *block, Scene *scene, ViewLayer *view_layer, ARegion *ar, SpaceOops *soops, ListBase *lb) { uiBut *bt; - TreeElement *te; - TreeStoreElem *tselem; - Object *ob = NULL; /* get RNA properties (once for speed) */ - PropertyRNA *collection_prop_hide_viewport; - PropertyRNA *collection_prop_hide_select; - PropertyRNA *collection_prop_hide_render; + PropertyRNA *object_prop_hide_viewport, *object_prop_hide_select, *object_prop_hide_render; + PropertyRNA *collection_prop_hide_viewport, *collection_prop_hide_select, *collection_prop_hide_render; + + object_prop_hide_viewport = RNA_struct_type_find_property(&RNA_Object, "hide_viewport"); + object_prop_hide_select = RNA_struct_type_find_property(&RNA_Object, "hide_select"); + object_prop_hide_render = RNA_struct_type_find_property(&RNA_Object, "hide_render"); collection_prop_hide_select = RNA_struct_type_find_property(&RNA_Collection, "hide_select"); collection_prop_hide_viewport = RNA_struct_type_find_property(&RNA_Collection, "hide_viewport"); collection_prop_hide_render = RNA_struct_type_find_property(&RNA_Collection, "hide_render"); - BLI_assert(collection_prop_hide_viewport && + + BLI_assert(object_prop_hide_viewport && + object_prop_hide_select && + object_prop_hide_render && + collection_prop_hide_viewport && collection_prop_hide_select && collection_prop_hide_render); - for (te = lb->first; te; te = te->next) { - tselem = TREESTORE(te); + for (TreeElement *te = lb->first; te; te = te->next) { + TreeStoreElem *tselem = TREESTORE(te); if (te->ys + 2 * UI_UNIT_Y >= ar->v2d.cur.ymin && te->ys <= ar->v2d.cur.ymax) { if (tselem->type == TSE_R_LAYER && (soops->outlinevis == SO_SCENES)) { /* View layer render toggle. */ - ViewLayer *view_layer = te->directdata; - - UI_block_emboss_set(block, UI_EMBOSS_NONE); + ViewLayer *layer = te->directdata; - bt = uiDefIconButBitS(block, UI_BTYPE_ICON_TOGGLE_N, VIEW_LAYER_RENDER, 0, ICON_RESTRICT_RENDER_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &view_layer->flag, 0, 0, 0, 0, TIP_("Use view layer for rendering")); + bt = uiDefIconButBitS( + block, UI_BTYPE_ICON_TOGGLE_N, VIEW_LAYER_RENDER, 0, ICON_RESTRICT_RENDER_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &layer->flag, 0, 0, 0, 0, TIP_("Use view layer for rendering")); UI_but_func_set(bt, restrictbutton_r_lay_cb, tselem->id, NULL); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); + } + else if (tselem->type == 0 && te->idcode == ID_OB) { + Object *ob = (Object *)tselem->id; + Base *base = BKE_view_layer_base_find(view_layer, ob); + + if (base) { + bt = uiDefIconButBitS( + block, UI_BTYPE_ICON_TOGGLE, BASE_HIDE, 0, ICON_HIDE_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_HIDEX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &base->flag, 0, 0, 0, 0, + TIP_("Hide object in viewport (Ctrl to isolate)")); + UI_but_func_set(bt, hidebutton_base_flag_cb, view_layer, base); + UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); + } + + PointerRNA ptr; + RNA_pointer_create((ID *)ob, &RNA_Object, ob, &ptr); + + bt = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_VIEW_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, UI_UNIT_Y, + &ptr, object_prop_hide_viewport, -1, 0, 0, -1, -1, + TIP_("Restrict viewport visibility")); + UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); + + bt = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_SELECT_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, UI_UNIT_Y, + &ptr, object_prop_hide_select, -1, 0, 0, -1, -1, + TIP_("Restrict viewport selection")); + UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); + + bt = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_RENDER_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, UI_UNIT_Y, + &ptr, object_prop_hide_render, -1, 0, 0, -1, -1, + TIP_("Restrict render visibility")); + UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - UI_block_emboss_set(block, UI_EMBOSS); } else if (tselem->type == TSE_MODIFIER) { ModifierData *md = (ModifierData *)te->directdata; - ob = (Object *)tselem->id; + Object *ob = (Object *)tselem->id; - UI_block_emboss_set(block, UI_EMBOSS_NONE); - bt = uiDefIconButBitI(block, UI_BTYPE_ICON_TOGGLE_N, eModifierMode_Realtime, 0, ICON_RESTRICT_VIEW_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &(md->mode), 0, 0, 0, 0, - TIP_("Restrict/Allow visibility in the 3D View")); + bt = uiDefIconButBitI( + block, UI_BTYPE_ICON_TOGGLE_N, eModifierMode_Realtime, 0, ICON_RESTRICT_VIEW_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &(md->mode), 0, 0, 0, 0, + TIP_("Restrict/Allow visibility in the 3D View")); UI_but_func_set(bt, restrictbutton_modifier_cb, scene, ob); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - bt = uiDefIconButBitI(block, UI_BTYPE_ICON_TOGGLE_N, eModifierMode_Render, 0, ICON_RESTRICT_RENDER_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &(md->mode), 0, 0, 0, 0, TIP_("Restrict/Allow renderability")); + bt = uiDefIconButBitI( + block, UI_BTYPE_ICON_TOGGLE_N, eModifierMode_Render, 0, ICON_RESTRICT_RENDER_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &(md->mode), 0, 0, 0, 0, TIP_("Restrict/Allow renderability")); UI_but_func_set(bt, restrictbutton_modifier_cb, scene, ob); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - - UI_block_emboss_set(block, UI_EMBOSS); } else if (tselem->type == TSE_POSE_CHANNEL) { bPoseChannel *pchan = (bPoseChannel *)te->directdata; Bone *bone = pchan->bone; - ob = (Object *)tselem->id; + Object *ob = (Object *)tselem->id; - UI_block_emboss_set(block, UI_EMBOSS_NONE); - bt = uiDefIconButBitI(block, UI_BTYPE_ICON_TOGGLE, BONE_HIDDEN_P, 0, ICON_RESTRICT_VIEW_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &(bone->flag), 0, 0, 0, 0, - TIP_("Restrict/Allow visibility in the 3D View")); + bt = uiDefIconButBitI( + block, UI_BTYPE_ICON_TOGGLE, BONE_HIDDEN_P, 0, ICON_HIDE_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &(bone->flag), 0, 0, 0, 0, + TIP_("Restrict/Allow visibility in the 3D View")); UI_but_func_set(bt, restrictbutton_bone_visibility_cb, ob->data, bone); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - bt = uiDefIconButBitI(block, UI_BTYPE_ICON_TOGGLE, BONE_UNSELECTABLE, 0, ICON_RESTRICT_SELECT_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &(bone->flag), 0, 0, 0, 0, - TIP_("Restrict/Allow selection in the 3D View")); + bt = uiDefIconButBitI( + block, UI_BTYPE_ICON_TOGGLE, BONE_UNSELECTABLE, 0, ICON_RESTRICT_SELECT_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &(bone->flag), 0, 0, 0, 0, + TIP_("Restrict/Allow selection in the 3D View")); UI_but_func_set(bt, restrictbutton_bone_select_cb, ob->data, bone); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - - UI_block_emboss_set(block, UI_EMBOSS); } else if (tselem->type == TSE_EBONE) { EditBone *ebone = (EditBone *)te->directdata; - UI_block_emboss_set(block, UI_EMBOSS_NONE); - bt = uiDefIconButBitI(block, UI_BTYPE_ICON_TOGGLE, BONE_HIDDEN_A, 0, ICON_RESTRICT_VIEW_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &(ebone->flag), 0, 0, 0, 0, - TIP_("Restrict/Allow visibility in the 3D View")); + bt = uiDefIconButBitI( + block, UI_BTYPE_ICON_TOGGLE, BONE_HIDDEN_A, 0, ICON_RESTRICT_VIEW_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &(ebone->flag), 0, 0, 0, 0, + TIP_("Restrict/Allow visibility in the 3D View")); UI_but_func_set(bt, restrictbutton_ebone_visibility_cb, NULL, ebone); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - bt = uiDefIconButBitI(block, UI_BTYPE_ICON_TOGGLE, BONE_UNSELECTABLE, 0, ICON_RESTRICT_SELECT_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &(ebone->flag), 0, 0, 0, 0, - TIP_("Restrict/Allow selection in the 3D View")); + bt = uiDefIconButBitI( + block, UI_BTYPE_ICON_TOGGLE, BONE_UNSELECTABLE, 0, ICON_RESTRICT_SELECT_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &(ebone->flag), 0, 0, 0, 0, + TIP_("Restrict/Allow selection in the 3D View")); UI_but_func_set(bt, restrictbutton_ebone_select_cb, NULL, ebone); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - - UI_block_emboss_set(block, UI_EMBOSS); } else if (tselem->type == TSE_GP_LAYER) { bGPDlayer *gpl = (bGPDlayer *)te->directdata; - UI_block_emboss_set(block, UI_EMBOSS_NONE); - - bt = uiDefIconButBitS(block, UI_BTYPE_ICON_TOGGLE, GP_LAYER_HIDE, 0, ICON_RESTRICT_VIEW_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &gpl->flag, 0, 0, 0, 0, - TIP_("Restrict/Allow visibility in the 3D View")); + bt = uiDefIconButBitS( + block, UI_BTYPE_ICON_TOGGLE, GP_LAYER_HIDE, 0, ICON_HIDE_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &gpl->flag, 0, 0, 0, 0, + TIP_("Restrict/Allow visibility in the 3D View")); UI_but_func_set(bt, restrictbutton_gp_layer_flag_cb, NULL, gpl); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - bt = uiDefIconButBitS(block, UI_BTYPE_ICON_TOGGLE, GP_LAYER_LOCKED, 0, ICON_UNLOCKED, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &gpl->flag, 0, 0, 0, 0, - TIP_("Restrict/Allow editing of strokes and keyframes in this layer")); + bt = uiDefIconButBitS( + block, UI_BTYPE_ICON_TOGGLE, GP_LAYER_LOCKED, 0, ICON_UNLOCKED, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &gpl->flag, 0, 0, 0, 0, + TIP_("Restrict/Allow editing of strokes and keyframes in this layer")); UI_but_func_set(bt, restrictbutton_gp_layer_flag_cb, NULL, gpl); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); /* TODO: visibility in renders */ - - UI_block_emboss_set(block, UI_EMBOSS); } else if (outliner_is_collection_tree_element(te)) { LayerCollection *lc = (tselem->type == TSE_LAYER_COLLECTION) ? te->directdata : NULL; Collection *collection = outliner_collection_from_tree_element(te); - UI_block_emboss_set(block, UI_EMBOSS_NONE); - if ((!lc || !(lc->flag & LAYER_COLLECTION_EXCLUDE)) && !(collection->flag & COLLECTION_IS_MASTER)) { + if (lc && (lc->runtime_flag & LAYER_COLLECTION_HAS_ENABLED_OBJECTS)) { + bt = uiDefIconButBitS( + block, UI_BTYPE_ICON_TOGGLE_N, LAYER_COLLECTION_HAS_VISIBLE_OBJECTS, 0, ICON_HIDE_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_HIDEX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &lc->runtime_flag, 0, 0, 0, 0, + TIP_("Hide collection in viewport (Ctrl to isolate)")); + UI_but_func_set(bt, hidebutton_layer_collection_flag_cb, view_layer, lc); + UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); + } + PointerRNA collection_ptr; RNA_id_pointer_create(&collection->id, &collection_ptr); - bt = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_VIEW_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &collection_ptr, collection_prop_hide_viewport, -1, 0, 0, 0, 0, NULL); + bt = uiDefIconButR_prop( + block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_VIEW_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &collection_ptr, collection_prop_hide_viewport, -1, 0, 0, 0, 0, NULL); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - bt = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_RENDER_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &collection_ptr, collection_prop_hide_render, -1, 0, 0, 0, 0, NULL); + bt = uiDefIconButR_prop( + block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_RENDER_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &collection_ptr, collection_prop_hide_render, -1, 0, 0, 0, 0, NULL); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); - bt = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_SELECT_OFF, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, - UI_UNIT_Y, &collection_ptr, collection_prop_hide_select, -1, 0, 0, 0, 0, NULL); + bt = uiDefIconButR_prop( + block, UI_BTYPE_ICON_TOGGLE, 0, ICON_RESTRICT_SELECT_OFF, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, UI_UNIT_X, + UI_UNIT_Y, &collection_ptr, collection_prop_hide_select, -1, 0, 0, 0, 0, NULL); UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK); } - - UI_block_emboss_set(block, UI_EMBOSS); } } - if (TSELEM_OPEN(tselem, soops)) outliner_draw_restrictbuts(block, scene, ar, soops, &te->subtree); + if (TSELEM_OPEN(tselem, soops)) { + outliner_draw_restrictbuts(block, scene, view_layer, ar, soops, &te->subtree); + } } } static void outliner_draw_userbuts(uiBlock *block, ARegion *ar, SpaceOops *soops, ListBase *lb) { - uiBut *bt; - TreeElement *te; - TreeStoreElem *tselem; - for (te = lb->first; te; te = te->next) { - tselem = TREESTORE(te); + for (TreeElement *te = lb->first; te; te = te->next) { + TreeStoreElem *tselem = TREESTORE(te); if (te->ys + 2 * UI_UNIT_Y >= ar->v2d.cur.ymin && te->ys <= ar->v2d.cur.ymax) { if (tselem->type == 0) { + uiBut *bt; ID *id = tselem->id; const char *tip = NULL; int icon = ICON_NONE; @@ -607,8 +689,6 @@ static void outliner_draw_userbuts(uiBlock *block, ARegion *ar, SpaceOops *soops if (ID_IS_LINKED(id)) but_flag |= UI_BUT_DISABLED; - UI_block_emboss_set(block, UI_EMBOSS_NONE); - if (id->flag & LIB_FAKEUSER) { icon = ICON_FILE_TICK; tip = TIP_("Data-block will be retained using a fake user"); @@ -617,34 +697,37 @@ static void outliner_draw_userbuts(uiBlock *block, ARegion *ar, SpaceOops *soops icon = ICON_X; tip = TIP_("Data-block has no users and will be deleted"); } - bt = uiDefIconButBitS(block, UI_BTYPE_TOGGLE, LIB_FAKEUSER, 1, icon, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, UI_UNIT_Y, - &id->flag, 0, 0, 0, 0, tip); + bt = uiDefIconButBitS( + block, UI_BTYPE_TOGGLE, LIB_FAKEUSER, 1, icon, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), te->ys, UI_UNIT_X, UI_UNIT_Y, + &id->flag, 0, 0, 0, 0, tip); UI_but_func_set(bt, restrictbutton_id_user_toggle, id, NULL); UI_but_flag_enable(bt, but_flag); BLI_str_format_int_grouped(buf, id->us); - bt = uiDefBut(block, UI_BTYPE_BUT, 1, buf, - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, - UI_UNIT_X, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, - TIP_("Number of users of this data-block")); + bt = uiDefBut( + block, UI_BTYPE_BUT, 1, buf, + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_SELECTX), te->ys, + UI_UNIT_X, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, + TIP_("Number of users of this data-block")); UI_but_flag_enable(bt, but_flag); - bt = uiDefButBitS(block, UI_BTYPE_TOGGLE, LIB_FAKEUSER, 1, (id->flag & LIB_FAKEUSER) ? "F" : " ", - (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, UI_UNIT_Y, - &id->flag, 0, 0, 0, 0, - TIP_("Data-block has a 'fake' user which will keep it in the file " - "even if nothing else uses it")); + bt = uiDefButBitS( + block, UI_BTYPE_TOGGLE, LIB_FAKEUSER, 1, (id->flag & LIB_FAKEUSER) ? "F" : " ", + (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_RENDERX), te->ys, UI_UNIT_X, UI_UNIT_Y, + &id->flag, 0, 0, 0, 0, + TIP_("Data-block has a 'fake' user which will keep it in the file " + "even if nothing else uses it")); UI_but_func_set(bt, restrictbutton_id_user_toggle, id, NULL); UI_but_flag_enable(bt, but_flag); - - UI_block_emboss_set(block, UI_EMBOSS); } } - if (TSELEM_OPEN(tselem, soops)) outliner_draw_userbuts(block, ar, soops, &te->subtree); + if (TSELEM_OPEN(tselem, soops)) { + outliner_draw_userbuts(block, ar, soops, &te->subtree); + } } } @@ -676,13 +759,11 @@ static void outliner_draw_rnacols(ARegion *ar, int sizex) static void outliner_draw_rnabuts(uiBlock *block, ARegion *ar, SpaceOops *soops, int sizex, ListBase *lb) { - TreeElement *te; - TreeStoreElem *tselem; PointerRNA *ptr; PropertyRNA *prop; - for (te = lb->first; te; te = te->next) { - tselem = TREESTORE(te); + for (TreeElement *te = lb->first; te; te = te->next) { + TreeStoreElem *tselem = TREESTORE(te); if (te->ys + 2 * UI_UNIT_Y >= ar->v2d.cur.ymin && te->ys <= ar->v2d.cur.ymax) { if (tselem->type == TSE_RNA_PROPERTY) { ptr = &te->rnaptr; @@ -690,17 +771,20 @@ static void outliner_draw_rnabuts(uiBlock *block, ARegion *ar, SpaceOops *soops, if (!TSELEM_OPEN(tselem, soops)) { if (RNA_property_type(prop) == PROP_POINTER) { - uiBut *but = uiDefAutoButR(block, ptr, prop, -1, "", ICON_NONE, sizex, te->ys, - OL_RNA_COL_SIZEX, UI_UNIT_Y - 1); + uiBut *but = uiDefAutoButR( + block, ptr, prop, -1, "", ICON_NONE, sizex, te->ys, + OL_RNA_COL_SIZEX, UI_UNIT_Y - 1); UI_but_flag_enable(but, UI_BUT_DISABLED); } else if (RNA_property_type(prop) == PROP_ENUM) { - uiDefAutoButR(block, ptr, prop, -1, NULL, ICON_NONE, sizex, te->ys, OL_RNA_COL_SIZEX, - UI_UNIT_Y - 1); + uiDefAutoButR( + block, ptr, prop, -1, NULL, ICON_NONE, sizex, te->ys, OL_RNA_COL_SIZEX, + UI_UNIT_Y - 1); } else { - uiDefAutoButR(block, ptr, prop, -1, "", ICON_NONE, sizex, te->ys, OL_RNA_COL_SIZEX, - UI_UNIT_Y - 1); + uiDefAutoButR( + block, ptr, prop, -1, "", ICON_NONE, sizex, te->ys, OL_RNA_COL_SIZEX, + UI_UNIT_Y - 1); } } } @@ -708,15 +792,16 @@ static void outliner_draw_rnabuts(uiBlock *block, ARegion *ar, SpaceOops *soops, ptr = &te->rnaptr; prop = te->directdata; - uiDefAutoButR(block, ptr, prop, te->index, "", ICON_NONE, sizex, te->ys, OL_RNA_COL_SIZEX, - UI_UNIT_Y - 1); + uiDefAutoButR( + block, ptr, prop, te->index, "", ICON_NONE, sizex, te->ys, OL_RNA_COL_SIZEX, + UI_UNIT_Y - 1); } } - if (TSELEM_OPEN(tselem, soops)) outliner_draw_rnabuts(block, ar, soops, sizex, &te->subtree); + if (TSELEM_OPEN(tselem, soops)) { + outliner_draw_rnabuts(block, ar, soops, sizex, &te->subtree); + } } - - UI_block_emboss_set(block, UI_EMBOSS); } static void outliner_buttons(const bContext *C, uiBlock *block, ARegion *ar, TreeElement *te) @@ -740,8 +825,9 @@ static void outliner_buttons(const bContext *C, uiBlock *block, ARegion *ar, Tre spx = te->xs + 1.8f * UI_UNIT_X; dx = ar->v2d.cur.xmax - (spx + 3.2f * UI_UNIT_X); - bt = uiDefBut(block, UI_BTYPE_TEXT, OL_NAMEBUTTON, "", spx, te->ys, dx, UI_UNIT_Y - 1, (void *)te->name, - 1.0, (float)len, 0, 0, ""); + bt = uiDefBut( + block, UI_BTYPE_TEXT, OL_NAMEBUTTON, "", spx, te->ys, dx, UI_UNIT_Y - 1, (void *)te->name, + 1.0, (float)len, 0, 0, ""); UI_but_func_rename_set(bt, namebutton_cb, tselem); /* returns false if button got removed */ @@ -773,9 +859,10 @@ static void tselem_draw_icon_uibut(struct DrawIconArg *arg, int icon) glDisable(GL_BLEND); } else { - uiBut *but = uiDefIconBut(arg->block, UI_BTYPE_LABEL, 0, icon, arg->xb, arg->yb, UI_UNIT_X, UI_UNIT_Y, NULL, - 0.0, 0.0, 1.0, arg->alpha, - (arg->id && ID_IS_LINKED(arg->id)) ? arg->id->lib->name : ""); + uiBut *but = uiDefIconBut( + arg->block, UI_BTYPE_LABEL, 0, icon, arg->xb, arg->yb, UI_UNIT_X, UI_UNIT_Y, NULL, + 0.0, 0.0, 1.0, arg->alpha, + (arg->id && ID_IS_LINKED(arg->id)) ? arg->id->lib->name : ""); if (arg->id) UI_but_drag_set_id(but, arg->id); @@ -816,8 +903,9 @@ static void UNUSED_FUNCTION(tselem_draw_gp_icon_uibut)(struct DrawIconArg *arg, } } -static void tselem_draw_icon(uiBlock *block, int xmax, float x, float y, TreeStoreElem *tselem, TreeElement *te, - float alpha) +static void tselem_draw_icon( + uiBlock *block, int xmax, float x, float y, TreeStoreElem *tselem, TreeElement *te, + float alpha) { struct DrawIconArg arg; float aspect; @@ -1248,17 +1336,15 @@ static void outliner_draw_iconrow( bContext *C, uiBlock *block, Scene *scene, ViewLayer *view_layer, SpaceOops *soops, ListBase *lb, int level, int xmax, int *offsx, int ys, float alpha_fac) { - TreeElement *te; - TreeStoreElem *tselem; eOLDrawState active; const Object *obact = OBACT(view_layer); - for (te = lb->first; te; te = te->next) { + for (TreeElement *te = lb->first; te; te = te->next) { /* exit drawing early */ if ((*offsx) - UI_UNIT_X > xmax) break; - tselem = TREESTORE(te); + TreeStoreElem *tselem = TREESTORE(te); /* object hierarchy always, further constrained on level */ if (level < 1 || (tselem->type == 0 && te->idcode == ID_OB)) { @@ -1437,12 +1523,16 @@ static void outliner_draw_tree_element( int icon_x = startx; // icons a bit higher - if (TSELEM_OPEN(tselem, soops)) - UI_icon_draw_alpha((float)icon_x + 2 * ufac, (float)*starty + 1 * ufac, ICON_DISCLOSURE_TRI_DOWN, - alpha_fac); - else - UI_icon_draw_alpha((float)icon_x + 2 * ufac, (float)*starty + 1 * ufac, ICON_DISCLOSURE_TRI_RIGHT, - alpha_fac); + if (TSELEM_OPEN(tselem, soops)) { + UI_icon_draw_alpha( + (float)icon_x + 2 * ufac, (float)*starty + 1 * ufac, ICON_DISCLOSURE_TRI_DOWN, + alpha_fac); + } + else { + UI_icon_draw_alpha( + (float)icon_x + 2 * ufac, (float)*starty + 1 * ufac, ICON_DISCLOSURE_TRI_RIGHT, + alpha_fac); + } } offsx += UI_UNIT_X; @@ -1457,22 +1547,26 @@ static void outliner_draw_tree_element( if (ELEM(tselem->type, 0, TSE_LAYER_COLLECTION) && ID_IS_LINKED(tselem->id)) { if (tselem->id->tag & LIB_TAG_MISSING) { - UI_icon_draw_alpha((float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_BROKEN, - alpha_fac); + UI_icon_draw_alpha( + (float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_BROKEN, + alpha_fac); } else if (tselem->id->tag & LIB_TAG_INDIRECT) { - UI_icon_draw_alpha((float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_INDIRECT, - alpha_fac); + UI_icon_draw_alpha( + (float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_INDIRECT, + alpha_fac); } else { - UI_icon_draw_alpha((float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_DIRECT, - alpha_fac); + UI_icon_draw_alpha( + (float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_DIRECT, + alpha_fac); } offsx += UI_UNIT_X + 2 * ufac; } else if (ELEM(tselem->type, 0, TSE_LAYER_COLLECTION) && ID_IS_STATIC_OVERRIDE(tselem->id)) { - UI_icon_draw_alpha((float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_OVERRIDE, - alpha_fac); + UI_icon_draw_alpha( + (float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_OVERRIDE, + alpha_fac); offsx += UI_UNIT_X + 2 * ufac; } glDisable(GL_BLEND); @@ -1612,12 +1706,12 @@ static void outliner_draw_tree_element_floating( immUnbindProgram(); } -static void outliner_draw_hierarchy_lines_recursive(unsigned pos, SpaceOops *soops, ListBase *lb, int startx, - const unsigned char col[4], bool draw_grayed_out, - int *starty) +static void outliner_draw_hierarchy_lines_recursive( + unsigned pos, SpaceOops *soops, ListBase *lb, int startx, + const unsigned char col[4], bool draw_grayed_out, + int *starty) { TreeElement *te, *te_vertical_line_last = NULL; - TreeStoreElem *tselem; int y1, y2; if (BLI_listbase_is_empty(lb)) { @@ -1630,7 +1724,7 @@ static void outliner_draw_hierarchy_lines_recursive(unsigned pos, SpaceOops *soo y1 = y2 = *starty; for (te = lb->first; te; te = te->next) { bool draw_childs_grayed_out = draw_grayed_out || (te->drag_data != NULL); - tselem = TREESTORE(te); + TreeStoreElem *tselem = TREESTORE(te); if (draw_childs_grayed_out) { immUniformColor3ubvAlpha(col, grayed_alpha); @@ -1653,8 +1747,9 @@ static void outliner_draw_hierarchy_lines_recursive(unsigned pos, SpaceOops *soo *starty -= UI_UNIT_Y; if (TSELEM_OPEN(tselem, soops)) - outliner_draw_hierarchy_lines_recursive(pos, soops, &te->subtree, startx + UI_UNIT_X, - col, draw_childs_grayed_out, starty); + outliner_draw_hierarchy_lines_recursive( + pos, soops, &te->subtree, startx + UI_UNIT_X, + col, draw_childs_grayed_out, starty); } if (draw_grayed_out) { @@ -1690,14 +1785,11 @@ static void outliner_draw_hierarchy_lines(SpaceOops *soops, ListBase *lb, int st static void outliner_draw_struct_marks(ARegion *ar, SpaceOops *soops, ListBase *lb, int *starty) { - TreeElement *te; - TreeStoreElem *tselem; - - for (te = lb->first; te; te = te->next) { - tselem = TREESTORE(te); + for (TreeElement *te = lb->first; te; te = te->next) { + TreeStoreElem *tselem = TREESTORE(te); /* selection status */ - if (TSELEM_OPEN(tselem, soops)) + if (TSELEM_OPEN(tselem, soops)) { if (tselem->type == TSE_RNA_STRUCT) { Gwn_VertFormat *format = immVertexFormat(); unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT); @@ -1706,6 +1798,7 @@ static void outliner_draw_struct_marks(ARegion *ar, SpaceOops *soops, ListBase * immRecti(pos, 0, *starty + 1, (int)ar->v2d.cur.xmax, *starty + UI_UNIT_Y - 1); immUnbindProgram(); } + } *starty -= UI_UNIT_Y; if (TSELEM_OPEN(tselem, soops)) { @@ -1732,10 +1825,11 @@ static void outliner_draw_highlights_recursive( const float col_selection[4], const float col_highlight[4], const float col_searchmatch[4], int start_x, int *io_start_y) { - const bool is_searching = SEARCHING_OUTLINER(soops) || - (soops->outlinevis == SO_DATA_API && - (soops->filter & SO_FILTER_SEARCH) && - soops->search_string[0] != 0); + const bool is_searching = ( + SEARCHING_OUTLINER(soops) || + (soops->outlinevis == SO_DATA_API && + (soops->filter & SO_FILTER_SEARCH) && + soops->search_string[0] != 0)); for (TreeElement *te = lb->first; te; te = te->next) { const TreeStoreElem *tselem = TREESTORE(te); @@ -1784,8 +1878,9 @@ static void outliner_draw_highlights(ARegion *ar, SpaceOops *soops, int startx, Gwn_VertFormat *format = immVertexFormat(); unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); - outliner_draw_highlights_recursive(pos, ar, soops, &soops->tree, col_selection, col_highlight, col_searchmatch, - startx, starty); + outliner_draw_highlights_recursive( + pos, ar, soops, &soops->tree, col_selection, col_highlight, col_searchmatch, + startx, starty); immUnbindProgram(); glDisable(GL_BLEND); } @@ -1890,7 +1985,10 @@ static void outliner_draw_restrictcols(ARegion *ar) unsigned int pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformThemeColorShadeAlpha(TH_BACK, -15, -200); - immBegin(GWN_PRIM_LINES, 6); + immBegin(GWN_PRIM_LINES, 8); + + immVertex2i(pos, (int)(ar->v2d.cur.xmax - OL_TOG_HIDEX), (int)ar->v2d.cur.ymax); + immVertex2i(pos, (int)(ar->v2d.cur.xmax - OL_TOG_HIDEX), (int)ar->v2d.cur.ymin); immVertex2i(pos, (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), (int)ar->v2d.cur.ymax); immVertex2i(pos, (int)(ar->v2d.cur.xmax - OL_TOG_RESTRICT_VIEWX), (int)ar->v2d.cur.ymin); @@ -1976,10 +2074,16 @@ void draw_outliner(const bContext *C) (bContext *)C, block, scene, view_layer, ar, soops, has_restrict_icons, &te_edit); + /* Default to no emboss for outliner UI. */ + UI_block_emboss_set(block, UI_EMBOSS_NONE); + if (soops->outlinevis == SO_DATA_API) { /* draw rna buttons */ outliner_draw_rnacols(ar, sizex_rna); + + UI_block_emboss_set(block, UI_EMBOSS); outliner_draw_rnabuts(block, ar, soops, sizex_rna, &soops->tree); + UI_block_emboss_set(block, UI_EMBOSS_NONE); } else if ((soops->outlinevis == SO_ID_ORPHANS) && has_restrict_icons) { /* draw user toggle columns */ @@ -1989,7 +2093,8 @@ void draw_outliner(const bContext *C) else if (has_restrict_icons) { /* draw restriction columns */ outliner_draw_restrictcols(ar); - outliner_draw_restrictbuts(block, scene, ar, soops, &soops->tree); + + outliner_draw_restrictbuts(block, scene, view_layer, ar, soops, &soops->tree); } /* draw edit buttons if nessecery */ @@ -1997,6 +2102,8 @@ void draw_outliner(const bContext *C) outliner_buttons(C, block, ar, te_edit); } + UI_block_emboss_set(block, UI_EMBOSS); + UI_block_end(C, block); UI_block_draw(C, block); } diff --git a/source/blender/editors/space_outliner/outliner_edit.c b/source/blender/editors/space_outliner/outliner_edit.c index 2a694e2e2e3..a455f8c076a 100644 --- a/source/blender/editors/space_outliner/outliner_edit.c +++ b/source/blender/editors/space_outliner/outliner_edit.c @@ -63,6 +63,7 @@ #include "BKE_scene.h" #include "BKE_material.h" +#include "DEG_depsgraph.h" #include "DEG_depsgraph_build.h" #include "../blenloader/BLO_readfile.h" @@ -252,6 +253,55 @@ void OUTLINER_OT_item_openclose(wmOperatorType *ot) RNA_def_boolean(ot->srna, "all", 1, "All", "Close or open all items"); } +/* -------------------------------------------------------------------- */ +/** \name Object Mode Enter/Exit + * \{ */ + +static void item_object_mode_enter_exit( + bContext *C, ReportList *reports, Object *ob, + bool enter) +{ + ViewLayer *view_layer = CTX_data_view_layer(C); + Object *obact = OBACT(view_layer); + + if ((ob->type != obact->type) || ID_IS_LINKED(ob->data)) { + return; + } + if (((ob->mode & obact->mode) != 0) == enter) { + return; + } + + if (ob == obact) { + BKE_report(reports, RPT_WARNING, "Active object mode not changed"); + return; + } + + Base *base = BKE_view_layer_base_find(view_layer, ob); + if (base == NULL) { + return; + } + Scene *scene = CTX_data_scene(C); + outliner_object_mode_toggle(C, scene, view_layer, base); +} + +void item_object_mode_enter_cb( + bContext *C, ReportList *reports, Scene *UNUSED(scene), TreeElement *UNUSED(te), + TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) +{ + Object *ob = (Object *)tselem->id; + item_object_mode_enter_exit(C, reports, ob, true); +} + +void item_object_mode_exit_cb( + bContext *C, ReportList *reports, Scene *UNUSED(scene), TreeElement *UNUSED(te), + TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) +{ + Object *ob = (Object *)tselem->id; + item_object_mode_enter_exit(C, reports, ob, false); +} + +/** \} */ + /* Rename --------------------------------------------------- */ static void do_item_rename(ARegion *ar, TreeElement *te, TreeStoreElem *tselem, @@ -901,6 +951,7 @@ static int outliner_toggle_selected_exec(bContext *C, wmOperator *UNUSED(op)) else outliner_set_flag(&soops->tree, TSE_SELECTED, 1); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); ED_region_tag_redraw_no_rebuild(ar); @@ -2169,6 +2220,7 @@ static int scene_drop_invoke(bContext *C, wmOperator *op, const wmEvent *event) DEG_relations_tag_update(bmain); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_main_add_notifier(NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; diff --git a/source/blender/editors/space_outliner/outliner_intern.h b/source/blender/editors/space_outliner/outliner_intern.h index 8ac09648d60..1f8320f73a0 100644 --- a/source/blender/editors/space_outliner/outliner_intern.h +++ b/source/blender/editors/space_outliner/outliner_intern.h @@ -151,11 +151,12 @@ typedef enum { /* size constants */ #define OL_Y_OFFSET 2 +#define OL_TOG_HIDEX (UI_UNIT_X * 4.0f) #define OL_TOG_RESTRICT_SELECTX (UI_UNIT_X * 3.0f) #define OL_TOG_RESTRICT_VIEWX (UI_UNIT_X * 2.0f) #define OL_TOG_RESTRICT_RENDERX UI_UNIT_X -#define OL_TOGW OL_TOG_RESTRICT_SELECTX +#define OL_TOGW OL_TOG_HIDEX #define OL_RNA_COLX (UI_UNIT_X * 15) #define OL_RNA_COL_SIZEX (UI_UNIT_X * 7.5f) @@ -226,6 +227,10 @@ void outliner_item_select( struct SpaceOops *soops, const struct TreeElement *te, const bool extend, const bool toggle); +void outliner_object_mode_toggle( + struct bContext *C, Scene *scene, ViewLayer *view_layer, + Base *base); + /* outliner_edit.c ---------------------------------------------- */ typedef void (*outliner_operation_cb)( struct bContext *C, struct ReportList *, struct Scene *scene, @@ -271,6 +276,13 @@ void id_remap_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, struct TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); +void item_object_mode_enter_cb( + struct bContext *C, struct ReportList *reports, struct Scene *scene, + TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); +void item_object_mode_exit_cb( + struct bContext *C, struct ReportList *reports, struct Scene *scene, + TreeElement *te, struct TreeStoreElem *tsep, struct TreeStoreElem *tselem, void *user_data); + TreeElement *outliner_dropzone_find(const struct SpaceOops *soops, const float fmval[2], const bool children); void outliner_set_coordinates(struct ARegion *ar, struct SpaceOops *soops); diff --git a/source/blender/editors/space_outliner/outliner_ops.c b/source/blender/editors/space_outliner/outliner_ops.c index ecfd12618e5..316caf0e239 100644 --- a/source/blender/editors/space_outliner/outliner_ops.c +++ b/source/blender/editors/space_outliner/outliner_ops.c @@ -560,6 +560,13 @@ void outliner_keymap(wmKeyConfig *keyconf) WM_keymap_verify_item(keymap, "OBJECT_OT_move_to_collection", MKEY, KM_PRESS, 0, 0); WM_keymap_verify_item(keymap, "OBJECT_OT_link_to_collection", MKEY, KM_PRESS, KM_SHIFT, 0); + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_view_clear", HKEY, KM_PRESS, KM_ALT, 0); + RNA_boolean_set(kmi->ptr, "select", false); + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_view_set", HKEY, KM_PRESS, 0, 0); + RNA_boolean_set(kmi->ptr, "unselected", false); + kmi = WM_keymap_add_item(keymap, "OBJECT_OT_hide_view_set", HKEY, KM_PRESS, KM_SHIFT, 0); + RNA_boolean_set(kmi->ptr, "unselected", true); + outliner_item_drag_drop_modal_keymap(keyconf); } diff --git a/source/blender/editors/space_outliner/outliner_select.c b/source/blender/editors/space_outliner/outliner_select.c index 36fd37e1134..38ae0683d4b 100644 --- a/source/blender/editors/space_outliner/outliner_select.c +++ b/source/blender/editors/space_outliner/outliner_select.c @@ -81,6 +81,7 @@ static void do_outliner_activate_obdata(bContext *C, Scene *scene, ViewLayer *vi if (obact == NULL) { ED_object_base_activate(C, base); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); obact = base->object; use_all = true; @@ -104,6 +105,7 @@ static void do_outliner_activate_obdata(bContext *C, Scene *scene, ViewLayer *vi } if (ok) { ED_object_base_select(base, (ob->mode & OB_MODE_EDIT) ? BA_SELECT : BA_DESELECT); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } } @@ -118,6 +120,7 @@ static void do_outliner_activate_pose(bContext *C, ViewLayer *view_layer, Base * if (obact == NULL) { ED_object_base_activate(C, base); Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); obact = base->object; use_all = true; @@ -144,6 +147,7 @@ static void do_outliner_activate_pose(bContext *C, ViewLayer *view_layer, Base * ED_object_base_select(base, (ob->mode & OB_MODE_POSE) ? BA_SELECT : BA_DESELECT); Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } @@ -151,6 +155,20 @@ static void do_outliner_activate_pose(bContext *C, ViewLayer *view_layer, Base * } } +/* For draw callback to run mode switching */ +void outliner_object_mode_toggle( + bContext *C, Scene *scene, ViewLayer *view_layer, + Base *base) +{ + Object *obact = OBACT(view_layer); + if (obact->mode & OB_MODE_EDIT) { + do_outliner_activate_obdata(C, scene, view_layer, base); + } + else if (obact->mode & OB_MODE_POSE) { + do_outliner_activate_pose(C, view_layer, base); + } +} + /* ****************************************************** */ /* Outliner Element Selection/Activation on Click */ @@ -251,22 +269,22 @@ static eOLDrawState tree_element_set_active_object( /* find associated base in current scene */ base = BKE_view_layer_base_find(view_layer, ob); -#ifdef USE_OBJECT_MODE_STRICT - if (base != NULL) { - Object *obact = OBACT(view_layer); - const eObjectMode object_mode = obact ? obact->mode : OB_MODE_OBJECT; - if (base && !BKE_object_is_mode_compat(base->object, object_mode)) { - if (object_mode == OB_MODE_OBJECT) { - struct Main *bmain = CTX_data_main(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - ED_object_mode_generic_exit(bmain, depsgraph, scene, base->object); - } - if (!BKE_object_is_mode_compat(base->object, object_mode)) { - base = NULL; + if (scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) { + if (base != NULL) { + Object *obact = OBACT(view_layer); + const eObjectMode object_mode = obact ? obact->mode : OB_MODE_OBJECT; + if (base && !BKE_object_is_mode_compat(base->object, object_mode)) { + if (object_mode == OB_MODE_OBJECT) { + struct Main *bmain = CTX_data_main(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + ED_object_mode_generic_exit(bmain, depsgraph, scene, base->object); + } + if (!BKE_object_is_mode_compat(base->object, object_mode)) { + base = NULL; + } } } } -#endif if (base) { if (set == OL_SETSEL_EXTEND) { @@ -278,13 +296,11 @@ static eOLDrawState tree_element_set_active_object( } else { /* deleselect all */ -#ifdef USE_OBJECT_MODE_STRICT + /* Only in object mode so we can switch the active object, * keeping all objects in the current 'mode' selected, useful for multi-pose/edit mode. * This keeps the convention that all objects in the current mode are also selected. see T55246. */ - if (ob->mode == OB_MODE_OBJECT) -#endif - { + if ((scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) ? (ob->mode == OB_MODE_OBJECT) : true) { BKE_view_layer_base_deselect_all(view_layer); } ED_object_base_select(base, BA_SELECT); @@ -297,6 +313,7 @@ static eOLDrawState tree_element_set_active_object( if (set != OL_SETSEL_NONE) { ED_object_base_activate(C, base); /* adds notifier */ + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } @@ -976,6 +993,7 @@ static void do_outliner_item_activate_tree_element( FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } else if (OB_DATA_SUPPORT_EDITMODE(te->idcode)) { @@ -1176,6 +1194,7 @@ static int outliner_border_select_exec(bContext *C, wmOperator *op) outliner_item_border_select(scene, &rectf, te, select); } + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); ED_region_tag_redraw(ar); diff --git a/source/blender/editors/space_outliner/outliner_tools.c b/source/blender/editors/space_outliner/outliner_tools.c index 8a01e5a7f2f..32918806765 100644 --- a/source/blender/editors/space_outliner/outliner_tools.c +++ b/source/blender/editors/space_outliner/outliner_tools.c @@ -893,6 +893,7 @@ static void object_delete_hierarchy_cb( #endif } + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); } @@ -910,6 +911,8 @@ enum { OL_OP_TOGSEL, OL_OP_TOGREN, OL_OP_RENAME, + OL_OP_OBJECT_MODE_ENTER, + OL_OP_OBJECT_MODE_EXIT, }; static const EnumPropertyItem prop_object_op_types[] = { @@ -921,6 +924,8 @@ static const EnumPropertyItem prop_object_op_types[] = { {OL_OP_REMAP, "REMAP", 0, "Remap Users", "Make all users of selected data-blocks to use instead a new chosen one"}, {OL_OP_RENAME, "RENAME", 0, "Rename", ""}, + {OL_OP_OBJECT_MODE_ENTER, "OBJECT_MODE_ENTER", 0, "Enter Mode", ""}, + {OL_OP_OBJECT_MODE_EXIT, "OBJECT_MODE_EXIT", 0, "Exit Mode", ""}, {0, NULL, 0, NULL, NULL} }; @@ -947,6 +952,7 @@ static int outliner_object_operation_exec(bContext *C, wmOperator *op) } str = "Select Objects"; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } else if (event == OL_OP_SELECT_HIERARCHY) { @@ -956,11 +962,13 @@ static int outliner_object_operation_exec(bContext *C, wmOperator *op) WM_window_change_active_scene(bmain, C, win, sce); } str = "Select Object Hierarchy"; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } else if (event == OL_OP_DESELECT) { outliner_do_object_operation(C, op->reports, scene, soops, &soops->tree, object_deselect_cb); str = "Deselect Objects"; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } else if (event == OL_OP_DELETE) { @@ -975,6 +983,7 @@ static int outliner_object_operation_exec(bContext *C, wmOperator *op) DEG_relations_tag_update(bmain); str = "Delete Objects"; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); } else if (event == OL_OP_DELETE_HIERARCHY) { @@ -985,6 +994,7 @@ static int outliner_object_operation_exec(bContext *C, wmOperator *op) DEG_relations_tag_update(bmain); str = "Delete Object Hierarchy"; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); } else if (event == OL_OP_REMAP) { @@ -999,6 +1009,14 @@ static int outliner_object_operation_exec(bContext *C, wmOperator *op) outliner_do_object_operation(C, op->reports, scene, soops, &soops->tree, item_rename_cb); str = "Rename Object"; } + else if (event == OL_OP_OBJECT_MODE_ENTER) { + outliner_do_object_operation(C, op->reports, scene, soops, &soops->tree, item_object_mode_enter_cb); + str = "Enter Current Mode"; + } + else if (event == OL_OP_OBJECT_MODE_EXIT) { + outliner_do_object_operation(C, op->reports, scene, soops, &soops->tree, item_object_mode_exit_cb); + str = "Exit Current Mode"; + } else { BLI_assert(0); return OPERATOR_CANCELLED; @@ -1568,8 +1586,8 @@ void OUTLINER_OT_animdata_operation(wmOperatorType *ot) /* **************************************** */ static const EnumPropertyItem prop_constraint_op_types[] = { - {OL_CONSTRAINTOP_ENABLE, "ENABLE", ICON_RESTRICT_VIEW_OFF, "Enable", ""}, - {OL_CONSTRAINTOP_DISABLE, "DISABLE", ICON_RESTRICT_VIEW_ON, "Disable", ""}, + {OL_CONSTRAINTOP_ENABLE, "ENABLE", ICON_HIDE_OFF, "Enable", ""}, + {OL_CONSTRAINTOP_DISABLE, "DISABLE", ICON_HIDE_ON, "Disable", ""}, {OL_CONSTRAINTOP_DELETE, "DELETE", ICON_X, "Delete", ""}, {0, NULL, 0, NULL, NULL} }; diff --git a/source/blender/editors/space_outliner/outliner_tree.c b/source/blender/editors/space_outliner/outliner_tree.c index d155457a208..13b62b766f5 100644 --- a/source/blender/editors/space_outliner/outliner_tree.c +++ b/source/blender/editors/space_outliner/outliner_tree.c @@ -1469,6 +1469,10 @@ static void outliner_add_layer_collection_objects( Base *base = BKE_view_layer_base_find(layer, cob->ob); TreeElement *te_object = outliner_add_element(soops, tree, base->object, ten, 0, 0); te_object->directdata = base; + + if (!(base->flag & BASE_VISIBLED)) { + te_object->flag |= TE_DISABLED; + } } } @@ -1487,7 +1491,9 @@ static void outliner_add_layer_collections_recursive( ten->reinsert_poll = outliner_collections_reorder_poll; const bool exclude = (lc->flag & LAYER_COLLECTION_EXCLUDE) != 0; - if (exclude) { + if (exclude || + ((layer->runtime_flag & VIEW_LAYER_HAS_HIDE) && + !(lc->runtime_flag & LAYER_COLLECTION_HAS_VISIBLE_OBJECTS))) { ten->flag |= TE_DISABLED; } diff --git a/source/blender/editors/space_sequencer/sequencer_edit.c b/source/blender/editors/space_sequencer/sequencer_edit.c index b24817f2af8..a78b3ee79c1 100644 --- a/source/blender/editors/space_sequencer/sequencer_edit.c +++ b/source/blender/editors/space_sequencer/sequencer_edit.c @@ -3874,7 +3874,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); } @@ -3899,7 +3899,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)) { diff --git a/source/blender/editors/space_sequencer/space_sequencer.c b/source/blender/editors/space_sequencer/space_sequencer.c index 75734963a0e..fc47934bc1e 100644 --- a/source/blender/editors/space_sequencer/space_sequencer.c +++ b/source/blender/editors/space_sequencer/space_sequencer.c @@ -708,7 +708,7 @@ static void sequencer_buttons_region_init(wmWindowManager *wm, ARegion *ar) static void sequencer_buttons_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void sequencer_buttons_region_listener( diff --git a/source/blender/editors/space_text/space_text.c b/source/blender/editors/space_text/space_text.c index 5885312e255..e827f4f0149 100644 --- a/source/blender/editors/space_text/space_text.c +++ b/source/blender/editors/space_text/space_text.c @@ -551,7 +551,7 @@ static void text_properties_region_draw(const bContext *C, ARegion *ar) { SpaceText *st = CTX_wm_space_text(C); - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); /* this flag trick is make sure buttons have been added already */ if (st->flags & ST_FIND_ACTIVATE) { diff --git a/source/blender/editors/space_text/text_header.c b/source/blender/editors/space_text/text_header.c index 50a8739c5b4..3d964d07908 100644 --- a/source/blender/editors/space_text/text_header.c +++ b/source/blender/editors/space_text/text_header.c @@ -91,7 +91,7 @@ static int text_properties_exec(bContext *C, wmOperator *UNUSED(op)) void TEXT_OT_properties(wmOperatorType *ot) { /* identifiers */ - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->description = "Toggle the properties region visibility"; ot->idname = "TEXT_OT_properties"; diff --git a/source/blender/editors/space_text/text_ops.c b/source/blender/editors/space_text/text_ops.c index b3815d73c5c..e34edc8908f 100644 --- a/source/blender/editors/space_text/text_ops.c +++ b/source/blender/editors/space_text/text_ops.c @@ -2071,7 +2071,9 @@ void TEXT_OT_delete(wmOperatorType *ot) ot->flag = OPTYPE_UNDO; /* properties */ - RNA_def_enum(ot->srna, "type", delete_type_items, DEL_NEXT_CHAR, "Type", "Which part of the text to delete"); + PropertyRNA *prop; + prop = RNA_def_enum(ot->srna, "type", delete_type_items, DEL_NEXT_CHAR, "Type", "Which part of the text to delete"); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } /******************* toggle overwrite operator **********************/ @@ -2243,13 +2245,15 @@ static int text_scroll_modal(bContext *C, wmOperator *op, const wmEvent *event) case LEFTMOUSE: case RIGHTMOUSE: case MIDDLEMOUSE: - if (ELEM(tsc->zone, SCROLLHANDLE_MIN_OUTSIDE, SCROLLHANDLE_MAX_OUTSIDE)) { - txt_screen_skip(st, ar, st->viewlines * (tsc->zone == SCROLLHANDLE_MIN_OUTSIDE ? 1 : -1)); + if (event->val == KM_RELEASE) { + if (ELEM(tsc->zone, SCROLLHANDLE_MIN_OUTSIDE, SCROLLHANDLE_MAX_OUTSIDE)) { + txt_screen_skip(st, ar, st->viewlines * (tsc->zone == SCROLLHANDLE_MIN_OUTSIDE ? 1 : -1)); - ED_area_tag_redraw(CTX_wm_area(C)); + ED_area_tag_redraw(CTX_wm_area(C)); + } + scroll_exit(C, op); + return OPERATOR_FINISHED; } - scroll_exit(C, op); - return OPERATOR_FINISHED; } return OPERATOR_RUNNING_MODAL; diff --git a/source/blender/editors/space_topbar/space_topbar.c b/source/blender/editors/space_topbar/space_topbar.c index 4342fa87f89..c7ef6591c0d 100644 --- a/source/blender/editors/space_topbar/space_topbar.c +++ b/source/blender/editors/space_topbar/space_topbar.c @@ -57,9 +57,6 @@ #include "WM_types.h" #include "WM_message.h" - -void topbar_panels_register(ARegionType *art); - /* ******************** default callbacks for topbar space ***************** */ static SpaceLink *topbar_new(const ScrArea *UNUSED(area), const Scene *UNUSED(scene)) @@ -277,64 +274,9 @@ void ED_spacetype_topbar(void) art->layout = ED_region_header_layout; art->draw = ED_region_header_draw; - /* For popovers. */ - topbar_panels_register(art); - BLI_addhead(&st->regiontypes, art); recent_files_menu_register(); BKE_spacetype_register(st); } - - -/* -------------------------------------------------------------------- */ -/** \name Redo Panel - * \{ */ - -static int topbar_panel_operator_redo_poll(const bContext *C, PanelType *UNUSED(pt)) -{ - wmOperator *op = WM_operator_last_redo(C); - if (op == NULL) { - return false; - } - - bool success = false; - if (!WM_operator_check_ui_empty(op->type)) { - const OperatorRepeatContextHandle *context_info; - context_info = ED_operator_repeat_prepare_context((bContext *)C, op); - success = WM_operator_poll((bContext *)C, op->type); - ED_operator_repeat_reset_context((bContext *)C, context_info); - } - return success; -} - -static void topbar_panel_operator_redo(const bContext *C, Panel *pa) -{ - wmOperator *op = WM_operator_last_redo(C); - if (op == NULL) { - return; - } - if (!WM_operator_check_ui_enabled(C, op->type->name)) { - uiLayoutSetEnabled(pa->layout, false); - } - uiLayout *col = uiLayoutColumn(pa->layout, false); - uiTemplateOperatorRedoProperties(col, C); -} - -void topbar_panels_register(ARegionType *art) -{ - PanelType *pt; - - pt = MEM_callocN(sizeof(PanelType), __func__); - strcpy(pt->idname, "TOPBAR_PT_redo"); - strcpy(pt->label, N_("Redo")); - strcpy(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA); - pt->draw = topbar_panel_operator_redo; - pt->poll = topbar_panel_operator_redo_poll; - pt->space_type = SPACE_TOPBAR; - pt->region_type = RGN_TYPE_HEADER; - BLI_addtail(&art->paneltypes, pt); -} - -/** \} */ diff --git a/source/blender/editors/space_userpref/space_userpref.c b/source/blender/editors/space_userpref/space_userpref.c index b3f45de518b..1d3c24c518a 100644 --- a/source/blender/editors/space_userpref/space_userpref.c +++ b/source/blender/editors/space_userpref/space_userpref.c @@ -64,7 +64,7 @@ static SpaceLink *userpref_new(const ScrArea *UNUSED(area), const Scene *UNUSED( BLI_addtail(&spref->regionbase, ar); ar->regiontype = RGN_TYPE_HEADER; - ar->alignment = RGN_ALIGN_TOP; + ar->alignment = RGN_ALIGN_BOTTOM; /* main region */ ar = MEM_callocN(sizeof(ARegion), "main region for userpref"); @@ -113,7 +113,7 @@ static void userpref_main_region_init(wmWindowManager *wm, ARegion *ar) static void userpref_main_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void userpref_operatortypes(void) diff --git a/source/blender/editors/space_view3d/space_view3d.c b/source/blender/editors/space_view3d/space_view3d.c index 63d7d98b689..d77b13630e3 100644 --- a/source/blender/editors/space_view3d/space_view3d.c +++ b/source/blender/editors/space_view3d/space_view3d.c @@ -296,8 +296,10 @@ void ED_view3d_shade_update(Main *bmain, View3D *v3d, ScrArea *sa) ARegion *ar; for (ar = sa->regionbase.first; ar; ar = ar->next) { - if (ar->regiondata) + if ((ar->regiontype == RGN_TYPE_WINDOW) && ar->regiondata) { ED_view3d_stop_render_preview(wm, ar); + break; + } } } } @@ -820,7 +822,6 @@ static void view3d_main_region_listener( break; case ND_OB_ACTIVE: case ND_OB_SELECT: - DEG_id_tag_update((ID *)&scene->id, DEG_TAG_SELECT_UPDATE); ATTR_FALLTHROUGH; case ND_FRAME: case ND_TRANSFORM: @@ -875,18 +876,6 @@ static void view3d_main_region_listener( case ND_SELECT: { WM_manipulatormap_tag_refresh(mmap); - - ID *ob_data = wmn->reference; - if (ob_data == NULL) { - BLI_assert(wmn->window); // Use `WM_event_add_notifier` instead of `WM_main_add_notifier` - ViewLayer *view_layer = WM_window_get_active_view_layer(wmn->window); - ob_data = OBEDIT_FROM_VIEW_LAYER(view_layer)->data; - } - if (ob_data) { - BLI_assert(OB_DATA_SUPPORT_ID(GS(ob_data->name))); - /* TODO(sergey): Notifiers shouldn't really be doing DEG tags. */ - DEG_id_tag_update(ob_data, DEG_TAG_SELECT_UPDATE); - } ATTR_FALLTHROUGH; } case ND_DATA: @@ -1232,7 +1221,7 @@ static void view3d_buttons_region_init(wmWindowManager *wm, ARegion *ar) static void view3d_buttons_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, NULL, -1, true); + ED_region_panels(C, ar); } static void view3d_buttons_region_listener( @@ -1361,7 +1350,7 @@ static void view3d_tools_region_init(wmWindowManager *wm, ARegion *ar) static void view3d_tools_region_draw(const bContext *C, ARegion *ar) { - ED_region_panels(C, ar, (const char * []){CTX_data_mode_string(C), NULL}, -1, true); + ED_region_panels_ex(C, ar, (const char * []){CTX_data_mode_string(C), NULL}, -1, true); } /* area (not region) level listener */ @@ -1565,5 +1554,9 @@ void ED_spacetype_view3d(void) art->message_subscribe = view3d_header_region_message_subscribe; BLI_addhead(&st->regiontypes, art); + /* regions: hud */ + art = ED_area_type_hud(st->spaceid); + BLI_addhead(&st->regiontypes, art); + 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 69e8aa07d3f..6ebed88728e 100644 --- a/source/blender/editors/space_view3d/view3d_buttons.c +++ b/source/blender/editors/space_view3d/view3d_buttons.c @@ -69,6 +69,7 @@ #include "RNA_access.h" #include "ED_armature.h" +#include "ED_object.h" #include "ED_mesh.h" #include "ED_screen.h" @@ -1163,6 +1164,11 @@ static void view3d_panel_transform(const bContext *C, Panel *pa) } } +static void hide_collections_menu_draw(const bContext *C, Menu *menu) +{ + ED_hide_collections_menu_draw(C, menu->layout); +} + void view3d_buttons_register(ARegionType *art) { PanelType *pt; @@ -1182,6 +1188,15 @@ void view3d_buttons_register(ARegionType *art) pt->draw = view3d_panel_vgroup; pt->poll = view3d_panel_vgroup_poll; BLI_addtail(&art->paneltypes, pt); + + MenuType *mt; + + mt = MEM_callocN(sizeof(MenuType), "spacetype view3d menu collections"); + strcpy(mt->idname, "VIEW3D_MT_collection"); + strcpy(mt->label, N_("Collection")); + strcpy(mt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA); + mt->draw = hide_collections_menu_draw; + WM_menutype_add(mt); } static int view3d_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) @@ -1197,7 +1212,7 @@ static int view3d_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) void VIEW3D_OT_properties(wmOperatorType *ot) { - ot->name = "Properties"; + ot->name = "Toggle Sidebar"; ot->description = "Toggle the properties region visibility"; ot->idname = "VIEW3D_OT_properties"; diff --git a/source/blender/editors/space_view3d/view3d_edit.c b/source/blender/editors/space_view3d/view3d_edit.c index cdf2106d8bf..bae186097a8 100644 --- a/source/blender/editors/space_view3d/view3d_edit.c +++ b/source/blender/editors/space_view3d/view3d_edit.c @@ -1112,7 +1112,6 @@ static void view3d_ndof_pan_zoom( static void view3d_ndof_orbit( const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar, - /* optional, can be NULL*/ ViewOpsData *vod, const bool apply_dyn_ofs) { View3D *v3d = sa->spacedata.first; @@ -1445,7 +1444,7 @@ static int ndof_orbit_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *ev ED_view3d_distance_set(rv3d, 0.0f); if (has_rotation) { - view3d_ndof_orbit(ndof, vod->sa, vod->ar, NULL, false); + view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod, false); } ED_view3d_distance_set(rv3d, dist_backup); @@ -1812,7 +1811,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); diff --git a/source/blender/editors/space_view3d/view3d_manipulator_camera.c b/source/blender/editors/space_view3d/view3d_manipulator_camera.c index 49fa83e82fc..023e16c070e 100644 --- a/source/blender/editors/space_view3d/view3d_manipulator_camera.c +++ b/source/blender/editors/space_view3d/view3d_manipulator_camera.c @@ -109,7 +109,7 @@ static void WIDGETGROUP_camera_setup(const bContext *C, wmManipulatorGroup *mgro mpr = camgroup->focal_len = WM_manipulator_new_ptr(wt_arrow, mgroup, NULL); mpr->flag |= WM_MANIPULATOR_DRAW_NO_SCALE; RNA_enum_set(mpr->ptr, "draw_style", ED_MANIPULATOR_ARROW_STYLE_CONE); - RNA_enum_set(mpr->ptr, "draw_options", ED_MANIPULATOR_ARROW_STYLE_CONSTRAINED); + RNA_enum_set(mpr->ptr, "transform", ED_MANIPULATOR_ARROW_XFORM_FLAG_CONSTRAINED); UI_GetThemeColor3fv(TH_MANIPULATOR_PRIMARY, mpr->color); UI_GetThemeColor3fv(TH_MANIPULATOR_HI, mpr->color_hi); @@ -117,7 +117,7 @@ static void WIDGETGROUP_camera_setup(const bContext *C, wmManipulatorGroup *mgro mpr = camgroup->ortho_scale = WM_manipulator_new_ptr(wt_arrow, mgroup, NULL); mpr->flag |= WM_MANIPULATOR_DRAW_NO_SCALE; RNA_enum_set(mpr->ptr, "draw_style", ED_MANIPULATOR_ARROW_STYLE_CONE); - RNA_enum_set(mpr->ptr, "draw_options", ED_MANIPULATOR_ARROW_STYLE_CONSTRAINED); + RNA_enum_set(mpr->ptr, "transform", ED_MANIPULATOR_ARROW_XFORM_FLAG_CONSTRAINED); UI_GetThemeColor3fv(TH_MANIPULATOR_PRIMARY, mpr->color); UI_GetThemeColor3fv(TH_MANIPULATOR_HI, mpr->color_hi); diff --git a/source/blender/editors/space_view3d/view3d_manipulator_forcefield.c b/source/blender/editors/space_view3d/view3d_manipulator_forcefield.c index 2a1fdee8e8a..305085be370 100644 --- a/source/blender/editors/space_view3d/view3d_manipulator_forcefield.c +++ b/source/blender/editors/space_view3d/view3d_manipulator_forcefield.c @@ -72,7 +72,7 @@ static void WIDGETGROUP_forcefield_setup(const bContext *UNUSED(C), wmManipulato wwrapper->manipulator = WM_manipulator_new("MANIPULATOR_WT_arrow_3d", mgroup, NULL); wmManipulator *mpr = wwrapper->manipulator; - RNA_enum_set(mpr->ptr, "draw_options", ED_MANIPULATOR_ARROW_STYLE_CONSTRAINED); + RNA_enum_set(mpr->ptr, "transform", ED_MANIPULATOR_ARROW_XFORM_FLAG_CONSTRAINED); ED_manipulator_arrow3d_set_ui_range(mpr, -200.0f, 200.0f); ED_manipulator_arrow3d_set_range_fac(mpr, 6.0f); diff --git a/source/blender/editors/space_view3d/view3d_manipulator_lamp.c b/source/blender/editors/space_view3d/view3d_manipulator_lamp.c index 01c38cfd899..f98a2f336bc 100644 --- a/source/blender/editors/space_view3d/view3d_manipulator_lamp.c +++ b/source/blender/editors/space_view3d/view3d_manipulator_lamp.c @@ -74,7 +74,7 @@ static void WIDGETGROUP_lamp_spot_setup(const bContext *UNUSED(C), wmManipulator wwrapper->manipulator = WM_manipulator_new("MANIPULATOR_WT_arrow_3d", mgroup, NULL); wmManipulator *mpr = wwrapper->manipulator; - RNA_enum_set(mpr->ptr, "draw_options", ED_MANIPULATOR_ARROW_STYLE_INVERTED); + RNA_enum_set(mpr->ptr, "transform", ED_MANIPULATOR_ARROW_XFORM_FLAG_INVERTED); mgroup->customdata = wwrapper; diff --git a/source/blender/editors/space_view3d/view3d_manipulator_navigate.c b/source/blender/editors/space_view3d/view3d_manipulator_navigate.c index c869e23d552..22b7af48de6 100644 --- a/source/blender/editors/space_view3d/view3d_manipulator_navigate.c +++ b/source/blender/editors/space_view3d/view3d_manipulator_navigate.c @@ -51,13 +51,13 @@ * \{ */ /* Offset from screen edge. */ -#define MANIPULATOR_OFFSET_FAC 2.5 +#define MANIPULATOR_OFFSET_FAC 1.5f /* Size of main icon. */ #define MANIPULATOR_SIZE 64 /* Factor for size of smaller button. */ -#define MANIPULATOR_MINI_FAC 0.5 +#define MANIPULATOR_MINI_FAC 0.35f /* How much mini buttons offset from the primary. */ -#define MANIPULATOR_MINI_OFFSET_FAC 0.6666f +#define MANIPULATOR_MINI_OFFSET_FAC 0.42f enum { @@ -297,10 +297,21 @@ static void WIDGETGROUP_navigate_draw_prepare(const bContext *C, wmManipulatorGr navgroup->state.rv3d.is_camera = (rv3d->persp == RV3D_CAMOB); navgroup->state.rv3d.viewlock = rv3d->viewlock; + const bool show_rotate = ( + ((rv3d->viewlock & RV3D_LOCKED) == 0) && + (navgroup->state.rv3d.is_camera == false)); + const bool show_fixed_offset = navgroup->state.rv3d.is_camera; const float icon_size = MANIPULATOR_SIZE; - const float icon_offset = (icon_size / 2.0) * MANIPULATOR_OFFSET_FAC * UI_DPI_FAC; + const float icon_offset = (icon_size * 0.52f) * MANIPULATOR_OFFSET_FAC * UI_DPI_FAC; const float icon_offset_mini = icon_size * MANIPULATOR_MINI_OFFSET_FAC * UI_DPI_FAC; - const float co[2] = {rect_visible.xmax - icon_offset, rect_visible.ymax - icon_offset}; + const float co_rotate[2] = { + rect_visible.xmax - icon_offset, + rect_visible.ymax - icon_offset, + }; + const float co[2] = { + rect_visible.xmax - ((show_rotate || show_fixed_offset) ? (icon_offset * 2.0f) : (icon_offset_mini * 0.75f)), + rect_visible.ymax - icon_offset_mini * 0.75f, + }; wmManipulator *mpr; @@ -309,48 +320,36 @@ static void WIDGETGROUP_navigate_draw_prepare(const bContext *C, wmManipulatorGr WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, true); } - if (((rv3d->viewlock & RV3D_LOCKED) == 0) && (navgroup->state.rv3d.is_camera == false)) { + /* RV3D_LOCKED or Camera: only show supported buttons. */ + if (show_rotate) { mpr = navgroup->mpr_array[MPR_ROTATE]; - mpr->matrix_basis[3][0] = co[0]; - mpr->matrix_basis[3][1] = co[1]; + mpr->matrix_basis[3][0] = co_rotate[0]; + mpr->matrix_basis[3][1] = co_rotate[1]; WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); + } - mpr = navgroup->mpr_array[MPR_MOVE]; - mpr->matrix_basis[3][0] = co[0] + icon_offset_mini; - mpr->matrix_basis[3][1] = co[1] - icon_offset_mini; - WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); + int icon_mini_slot = 0; - mpr = navgroup->mpr_array[MPR_ZOOM]; - mpr->matrix_basis[3][0] = co[0] - icon_offset_mini; - mpr->matrix_basis[3][1] = co[1] - icon_offset_mini; - WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); + mpr = navgroup->mpr_array[MPR_ZOOM]; + mpr->matrix_basis[3][0] = co[0] - (icon_offset_mini * icon_mini_slot++); + mpr->matrix_basis[3][1] = co[1]; + WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); - mpr = navgroup->mpr_array[rv3d->is_persp ? MPR_ORTHO : MPR_PERSP]; - mpr->matrix_basis[3][0] = co[0] + icon_offset_mini; - mpr->matrix_basis[3][1] = co[1] + icon_offset_mini; - WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); + mpr = navgroup->mpr_array[MPR_MOVE]; + mpr->matrix_basis[3][0] = co[0] - (icon_offset_mini * icon_mini_slot++); + mpr->matrix_basis[3][1] = co[1]; + WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); + if ((rv3d->viewlock & RV3D_LOCKED) == 0) { mpr = navgroup->mpr_array[MPR_CAMERA]; - mpr->matrix_basis[3][0] = co[0] - icon_offset_mini; - mpr->matrix_basis[3][1] = co[1] + icon_offset_mini; - WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); - } - else { - /* RV3D_LOCKED or Camera: only show supported buttons. */ - mpr = navgroup->mpr_array[MPR_MOVE]; - mpr->matrix_basis[3][0] = co[0] + icon_offset_mini; - mpr->matrix_basis[3][1] = co[1] + icon_offset_mini; - WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); - - mpr = navgroup->mpr_array[MPR_ZOOM]; - mpr->matrix_basis[3][0] = co[0]; - mpr->matrix_basis[3][1] = co[1] + icon_offset_mini; + mpr->matrix_basis[3][0] = co[0] - (icon_offset_mini * icon_mini_slot++); + mpr->matrix_basis[3][1] = co[1]; WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); - if (navgroup->state.rv3d.is_camera) { - mpr = navgroup->mpr_array[MPR_CAMERA]; - mpr->matrix_basis[3][0] = co[0] - icon_offset_mini; - mpr->matrix_basis[3][1] = co[1] + icon_offset_mini; + if (navgroup->state.rv3d.is_camera == false) { + mpr = navgroup->mpr_array[rv3d->is_persp ? MPR_PERSP : MPR_ORTHO]; + mpr->matrix_basis[3][0] = co[0] - (icon_offset_mini * icon_mini_slot++); + mpr->matrix_basis[3][1] = co[1]; WM_manipulator_set_flag(mpr, WM_MANIPULATOR_HIDDEN, false); } } diff --git a/source/blender/editors/space_view3d/view3d_manipulator_ruler.c b/source/blender/editors/space_view3d/view3d_manipulator_ruler.c index cd918695f60..8178c2f5be9 100644 --- a/source/blender/editors/space_view3d/view3d_manipulator_ruler.c +++ b/source/blender/editors/space_view3d/view3d_manipulator_ruler.c @@ -382,6 +382,7 @@ static bool view3d_ruler_item_mousemove( static bool view3d_ruler_to_gpencil(bContext *C, wmManipulatorGroup *mgroup) { // RulerInfo *ruler_info = mgroup->customdata; + Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); bGPDlayer *gpl; bGPDframe *gpf; @@ -393,7 +394,7 @@ static bool view3d_ruler_to_gpencil(bContext *C, wmManipulatorGroup *mgroup) bool changed = false; if (scene->gpd == NULL) { - scene->gpd = BKE_gpencil_data_addnew("GPencil"); + scene->gpd = BKE_gpencil_data_addnew(bmain, "GPencil"); } gpl = BLI_findstring(&scene->gpd->layers, ruler_name, offsetof(bGPDlayer, info)); diff --git a/source/blender/editors/space_view3d/view3d_ops.c b/source/blender/editors/space_view3d/view3d_ops.c index b3211ed1108..267712b3339 100644 --- a/source/blender/editors/space_view3d/view3d_ops.c +++ b/source/blender/editors/space_view3d/view3d_ops.c @@ -302,7 +302,7 @@ void view3d_keymap(wmKeyConfig *keyconf) kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_view_all", CKEY, KM_PRESS, KM_SHIFT, 0); RNA_boolean_set(kmi->ptr, "center", true); - WM_keymap_add_menu_pie(keymap, "VIEW3D_PIE_view", ACCENTGRAVEKEY, KM_CLICK_DRAG, 0, 0); + WM_keymap_add_menu_pie(keymap, "VIEW3D_MT_view_pie", ACCENTGRAVEKEY, KM_CLICK_DRAG, 0, 0); /* numpad view hotkeys*/ RNA_enum_set(WM_keymap_add_item(keymap, "VIEW3D_OT_viewnumpad", PAD0, KM_PRESS, 0, 0)->ptr, "type", RV3D_VIEW_CAMERA); diff --git a/source/blender/editors/space_view3d/view3d_ruler.c b/source/blender/editors/space_view3d/view3d_ruler.c index c30b72bfb95..e001ed9112b 100644 --- a/source/blender/editors/space_view3d/view3d_ruler.c +++ b/source/blender/editors/space_view3d/view3d_ruler.c @@ -297,6 +297,7 @@ static void ruler_state_set(bContext *C, RulerInfo *ruler_info, int state) #define RULER_ID "RulerData3D" static bool view3d_ruler_to_gpencil(bContext *C, RulerInfo *ruler_info) { + Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); bGPDlayer *gpl; bGPDframe *gpf; @@ -308,7 +309,7 @@ static bool view3d_ruler_to_gpencil(bContext *C, RulerInfo *ruler_info) bool changed = false; if (scene->gpd == NULL) { - scene->gpd = BKE_gpencil_data_addnew("GPencil"); + scene->gpd = BKE_gpencil_data_addnew(bmain, "GPencil"); } gpl = BLI_findstring(&scene->gpd->layers, ruler_name, offsetof(bGPDlayer, info)); diff --git a/source/blender/editors/space_view3d/view3d_select.c b/source/blender/editors/space_view3d/view3d_select.c index f4e39c7a563..b4f3be178aa 100644 --- a/source/blender/editors/space_view3d/view3d_select.c +++ b/source/blender/editors/space_view3d/view3d_select.c @@ -424,10 +424,8 @@ static void do_lasso_select_objects( for (base = vc->view_layer->object_bases.first; base; base = base->next) { if (BASE_SELECTABLE(base)) { /* use this to avoid un-needed lasso lookups */ - if ( -#ifdef USE_OBJECT_MODE_STRICT - (is_pose_mode == false) && -#endif + if (((vc->scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) ? + (is_pose_mode == false) : true) && ED_view3d_project_base(vc->ar, base) == V3D_PROJ_RET_OK) { if (BLI_lasso_is_point_inside(mcords, moves, base->sx, base->sy, IS_CLIPPED)) { @@ -855,6 +853,7 @@ static void view3d_lasso_select( } else { do_lasso_select_objects(vc, mcords, moves, extend, select); + DEG_id_tag_update(&vc->scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc->scene); } } @@ -885,6 +884,7 @@ static void view3d_lasso_select( break; } + DEG_id_tag_update(vc->obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc->obedit->data); } FOREACH_OBJECT_IN_MODE_END; @@ -1009,7 +1009,9 @@ static int object_select_menu_exec(bContext *C, wmOperator *op) /* undo? */ if (changed) { - WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C)); + Scene *scene = CTX_data_scene(C); + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); + WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); return OPERATOR_FINISHED; } else { @@ -1170,7 +1172,7 @@ static int selectbuffer_ret_hits_5(unsigned int *buffer, const int hits15, const /* so check three selection levels and compare */ static int mixed_bones_object_selectbuffer( ViewContext *vc, unsigned int *buffer, const int mval[2], - bool use_cycle, bool enumerate, + bool use_cycle, bool enumerate, eV3DSelectObjectFilter select_filter, bool *r_do_nearest) { rcti rect; @@ -1209,7 +1211,7 @@ static int mixed_bones_object_selectbuffer( view3d_opengl_select_cache_begin(); BLI_rcti_init_pt_radius(&rect, mval, 14); - hits15 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, select_mode); + hits15 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, select_mode, select_filter); if (hits15 == 1) { hits = selectbuffer_ret_hits_15(buffer, hits15); goto finally; @@ -1220,7 +1222,7 @@ static int mixed_bones_object_selectbuffer( offs = 4 * hits15; BLI_rcti_init_pt_radius(&rect, mval, 9); - hits9 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode); + hits9 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode, select_filter); if (hits9 == 1) { hits = selectbuffer_ret_hits_9(buffer, hits15, hits9); goto finally; @@ -1230,7 +1232,7 @@ static int mixed_bones_object_selectbuffer( offs += 4 * hits9; BLI_rcti_init_pt_radius(&rect, mval, 5); - hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode); + hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode, select_filter); if (hits5 == 1) { hits = selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5); goto finally; @@ -1252,8 +1254,7 @@ static int mixed_bones_object_selectbuffer( finally: view3d_opengl_select_cache_end(); -#ifdef USE_OBJECT_MODE_STRICT - { + if (vc->scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) { const bool is_pose_mode = (vc->obact && vc->obact->mode & OB_MODE_POSE); struct { uint data[4]; @@ -1269,7 +1270,6 @@ finally: } hits = j; } -#endif return hits; } @@ -1373,7 +1373,10 @@ Base *ED_view3d_give_base_under_cursor(bContext *C, const int mval[2]) ED_view3d_viewcontext_init(C, &vc); - hits = mixed_bones_object_selectbuffer(&vc, buffer, mval, false, false, &do_nearest); + hits = mixed_bones_object_selectbuffer( + &vc, buffer, mval, + false, false, VIEW3D_SELECT_FILTER_NOP, + &do_nearest); if (hits > 0) { const bool has_bones = selectbuffer_has_bones(buffer, hits); @@ -1466,19 +1469,19 @@ static bool ed_object_select_pick( if (base == startbase) break; } } -#ifdef USE_OBJECT_MODE_STRICT - if (is_obedit == false) { - if (basact && !BKE_object_is_mode_compat(basact->object, object_mode)) { - if (object_mode == OB_MODE_OBJECT) { - struct Main *bmain = CTX_data_main(C); - ED_object_mode_generic_exit(bmain, vc.depsgraph, scene, basact->object); - } - if (!BKE_object_is_mode_compat(basact->object, object_mode)) { - basact = NULL; + if (scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) { + if (is_obedit == false) { + if (basact && !BKE_object_is_mode_compat(basact->object, object_mode)) { + if (object_mode == OB_MODE_OBJECT) { + struct Main *bmain = CTX_data_main(C); + ED_object_mode_generic_exit(bmain, vc.depsgraph, scene, basact->object); + } + if (!BKE_object_is_mode_compat(basact->object, object_mode)) { + basact = NULL; + } } } } -#endif } else { unsigned int buffer[MAXPICKBUF]; @@ -1487,7 +1490,13 @@ static bool ed_object_select_pick( // TIMEIT_START(select_time); /* if objects have posemode set, the bones are in the same selection buffer */ - hits = mixed_bones_object_selectbuffer(&vc, buffer, mval, true, enumerate, &do_nearest); + const eV3DSelectObjectFilter select_filter = ( + (scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) ? + VIEW3D_SELECT_FILTER_OBJECT_MODE_LOCK : VIEW3D_SELECT_FILTER_NOP); + hits = mixed_bones_object_selectbuffer( + &vc, buffer, mval, + true, enumerate, select_filter, + &do_nearest); // TIMEIT_END(select_time); @@ -1503,19 +1512,19 @@ static bool ed_object_select_pick( basact = mouse_select_eval_buffer(&vc, buffer, hits, startbase, has_bones, do_nearest); } -#ifdef USE_OBJECT_MODE_STRICT - if (is_obedit == false) { - if (basact && !BKE_object_is_mode_compat(basact->object, object_mode)) { - if (object_mode == OB_MODE_OBJECT) { - struct Main *bmain = CTX_data_main(C); - ED_object_mode_generic_exit(bmain, vc.depsgraph, scene, basact->object); - } - if (!BKE_object_is_mode_compat(basact->object, object_mode)) { - basact = NULL; + if (scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) { + if (is_obedit == false) { + if (basact && !BKE_object_is_mode_compat(basact->object, object_mode)) { + if (object_mode == OB_MODE_OBJECT) { + struct Main *bmain = CTX_data_main(C); + ED_object_mode_generic_exit(bmain, vc.depsgraph, scene, basact->object); + } + if (!BKE_object_is_mode_compat(basact->object, object_mode)) { + basact = NULL; + } } } } -#endif if (has_bones && basact) { if (basact->object->type == OB_CAMERA) { @@ -1562,6 +1571,7 @@ static bool ed_object_select_pick( retval = true; + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_MOVIECLIP | ND_SELECT, track); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); @@ -1604,19 +1614,19 @@ static bool ed_object_select_pick( } } -#ifdef USE_OBJECT_MODE_STRICT - /* Disallow switching modes, - * special exception for edit-mode - vertex-parent operator. */ - if (is_obedit == false) { - if (oldbasact && basact) { - if ((oldbasact->object->mode != basact->object->mode) && - (oldbasact->object->mode & basact->object->mode) == 0) - { - basact = NULL; + if (scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) { + /* Disallow switching modes, + * special exception for edit-mode - vertex-parent operator. */ + if (is_obedit == false) { + if (oldbasact && basact) { + if ((oldbasact->object->mode != basact->object->mode) && + (oldbasact->object->mode & basact->object->mode) == 0) + { + basact = NULL; + } } } } -#endif /* so, do we have something selected? */ if (basact) { @@ -1658,6 +1668,7 @@ static bool ed_object_select_pick( } } + DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); } @@ -1966,7 +1977,9 @@ static int do_meta_box_select( unsigned int buffer[MAXPICKBUF]; int hits; - hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, VIEW3D_SELECT_ALL); + hits = view3d_opengl_select( + vc, buffer, MAXPICKBUF, rect, + VIEW3D_SELECT_ALL, VIEW3D_SELECT_FILTER_NOP); if (extend == false && select) BKE_mball_deselect_all(mb); @@ -2000,7 +2013,9 @@ static int do_armature_box_select( unsigned int buffer[MAXPICKBUF]; int hits; - hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, VIEW3D_SELECT_ALL); + hits = view3d_opengl_select( + vc, buffer, MAXPICKBUF, rect, + VIEW3D_SELECT_ALL, VIEW3D_SELECT_FILTER_NOP); uint objects_len = 0; Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(vc->view_layer, &objects_len); @@ -2148,7 +2163,12 @@ static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, b /* selection buffer now has bones potentially too, so we add MAXPICKBUF */ vbuffer = MEM_mallocN(4 * (totobj + MAXPICKELEMS) * sizeof(unsigned int), "selection buffer"); - hits = view3d_opengl_select(vc, vbuffer, 4 * (totobj + MAXPICKELEMS), rect, VIEW3D_SELECT_ALL); + const eV3DSelectObjectFilter select_filter = ( + (vc->scene->toolsettings->object_flag & SCE_OBJECT_MODE_LOCK) ? + VIEW3D_SELECT_FILTER_OBJECT_MODE_LOCK : VIEW3D_SELECT_FILTER_NOP); + hits = view3d_opengl_select( + vc, vbuffer, 4 * (totobj + MAXPICKELEMS), rect, + VIEW3D_SELECT_ALL, select_filter); /* * LOGIC NOTES (theeth): * The buffer and ListBase have the same relative order, which makes the selection @@ -2241,6 +2261,7 @@ static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, b MEM_freeN(bases); + DEG_id_tag_update(&vc->scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc->scene); } MEM_freeN(vbuffer); @@ -2276,6 +2297,7 @@ static int view3d_borderselect_exec(bContext *C, wmOperator *op) vc.em = BKE_editmesh_from_object(vc.obedit); ret |= do_mesh_box_select(&vc, &rect, select, extend); if (ret & OPERATOR_FINISHED) { + DEG_id_tag_update(vc.obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data); } break; @@ -2283,24 +2305,28 @@ static int view3d_borderselect_exec(bContext *C, wmOperator *op) case OB_SURF: ret |= do_nurbs_box_select(&vc, &rect, select, extend); if (ret & OPERATOR_FINISHED) { + DEG_id_tag_update(vc.obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data); } break; case OB_MBALL: ret |= do_meta_box_select(&vc, &rect, select, extend); if (ret & OPERATOR_FINISHED) { + DEG_id_tag_update(vc.obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data); } break; case OB_ARMATURE: ret |= do_armature_box_select(&vc, &rect, select, extend); if (ret & OPERATOR_FINISHED) { + DEG_id_tag_update(&vc.obedit->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, vc.obedit); } break; case OB_LATTICE: ret |= do_lattice_box_select(&vc, &rect, select, extend); if (ret & OPERATOR_FINISHED) { + DEG_id_tag_update(vc.obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data); } break; @@ -2403,6 +2429,7 @@ static bool ed_wpaint_vertex_select_pick( } paintvert_flush_flags(obact); + DEG_id_tag_update(obact->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data); return true; } @@ -3004,14 +3031,17 @@ static int view3d_circle_select_exec(bContext *C, wmOperator *op) if (CTX_data_edit_object(C)) { obedit_circle_select(&vc, select, mval, (float)radius); + DEG_id_tag_update(obact->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data); } else if (BKE_paint_select_face_test(obact)) { paint_facesel_circle_select(&vc, select, mval, (float)radius); + DEG_id_tag_update(obact->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data); } else if (BKE_paint_select_vert_test(obact)) { paint_vertsel_circle_select(&vc, select, mval, (float)radius); + DEG_id_tag_update(obact->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data); } else if (obact->mode & OB_MODE_POSE) { @@ -3028,6 +3058,7 @@ static int view3d_circle_select_exec(bContext *C, wmOperator *op) } else { if (object_circle_select(&vc, select, mval, (float)radius)) { + DEG_id_tag_update(&vc.scene->id, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc.scene); } } diff --git a/source/blender/editors/space_view3d/view3d_toolbar.c b/source/blender/editors/space_view3d/view3d_toolbar.c index 8ea33927c4d..acceb40beaa 100644 --- a/source/blender/editors/space_view3d/view3d_toolbar.c +++ b/source/blender/editors/space_view3d/view3d_toolbar.c @@ -190,7 +190,7 @@ static int view3d_toolshelf_toggle_exec(bContext *C, wmOperator *UNUSED(op)) void VIEW3D_OT_toolshelf(wmOperatorType *ot) { - ot->name = "Tool Shelf"; + ot->name = "Toggle Toolbar"; ot->description = "Toggles tool shelf display"; ot->idname = "VIEW3D_OT_toolshelf"; diff --git a/source/blender/editors/space_view3d/view3d_view.c b/source/blender/editors/space_view3d/view3d_view.c index 73b9a67ac56..abb8c688e05 100644 --- a/source/blender/editors/space_view3d/view3d_view.c +++ b/source/blender/editors/space_view3d/view3d_view.c @@ -896,6 +896,13 @@ static bool drw_select_loop_pass(eDRWSelectStage stage, void *user_data) } #endif /* WITH_OPENGL_LEGACY */ +/** Implement #VIEW3D_SELECT_FILTER_OBJECT_MODE_LOCK. */ +static bool drw_select_filter_object_mode_lock(Object *ob, void *user_data) +{ + const Object *obact = user_data; + return BKE_object_is_mode_compat(ob, obact->mode); +} + /** * \warning be sure to account for a negative return value * This is an error, "Too many objects in select buffer" @@ -905,7 +912,7 @@ static bool drw_select_loop_pass(eDRWSelectStage stage, void *user_data) */ int view3d_opengl_select( ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const rcti *input, - eV3DSelectMode select_mode) + eV3DSelectMode select_mode, eV3DSelectObjectFilter select_filter) { struct bThemeState theme_state; Depsgraph *depsgraph = vc->depsgraph; @@ -953,6 +960,25 @@ int view3d_opengl_select( } } + struct { + DRW_ObjectFilterFn fn; + void *user_data; + } object_filter = {NULL, NULL}; + switch (select_filter) { + case VIEW3D_SELECT_FILTER_OBJECT_MODE_LOCK: + { + Object *obact = OBACT(vc->view_layer); + if (obact && obact->mode != OB_MODE_OBJECT) { + object_filter.fn = drw_select_filter_object_mode_lock; + object_filter.user_data = obact; + } + break; + } + case VIEW3D_SELECT_FILTER_NOP: + break; + + } + /* Tools may request depth outside of regular drawing code. */ UI_Theme_Store(&theme_state); UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW); @@ -1014,7 +1040,8 @@ int view3d_opengl_select( DRW_draw_select_loop( depsgraph, ar, v3d, use_obedit_skip, use_nearest, &rect, - drw_select_loop_pass, &drw_select_loop_user_data); + drw_select_loop_pass, &drw_select_loop_user_data, + object_filter.fn, object_filter.user_data); hits = drw_select_loop_user_data.hits; } #endif /* WITH_OPENGL_LEGACY */ diff --git a/source/blender/editors/transform/transform.h b/source/blender/editors/transform/transform.h index c2548fe497f..d72d311e0f6 100644 --- a/source/blender/editors/transform/transform.h +++ b/source/blender/editors/transform/transform.h @@ -65,6 +65,7 @@ struct wmEvent; struct wmTimer; struct ARegion; struct ReportList; +struct RNG; struct EditBone; struct RenderEngineType; struct SnapObjectContext; @@ -536,6 +537,9 @@ typedef struct TransInfo { void *draw_handle_pixel; void *draw_handle_cursor; + /** Currently only used for random curve of proportional editing. */ + struct RNG *rng; + /** Typically for mode settings. */ TransCustomDataContainer custom; } TransInfo; diff --git a/source/blender/editors/transform/transform_conversions.c b/source/blender/editors/transform/transform_conversions.c index 6c608a0b5e4..8462004c549 100644 --- a/source/blender/editors/transform/transform_conversions.c +++ b/source/blender/editors/transform/transform_conversions.c @@ -1255,7 +1255,7 @@ static void createTransArmatureVerts(TransInfo *t) bool mirror = ((arm->flag & ARM_MIRROR_EDIT) != 0); int total_mirrored = 0, i; int oldtot; - BoneInitData *bid; + BoneInitData *bid = NULL; tc->data_len = 0; for (ebo = edbo->first; ebo; ebo = ebo->next) { @@ -2120,7 +2120,6 @@ static void createTransParticleVerts(bContext *C, TransInfo *t) void flushTransParticles(TransInfo *t) { FOREACH_TRANS_DATA_CONTAINER (t, tc) { - Scene *scene = t->scene; ViewLayer *view_layer = t->view_layer; Object *ob = OBACT(view_layer); @@ -8633,6 +8632,10 @@ void createTransData(bContext *C, TransInfo *t) createTransPaintCurveVerts(C, t); countAndCleanTransDataContainer(t); } + /* Mark as initialized if above checks fail. */ + if (t->data_len_all == -1) { + t->data_len_all = 0; + } } else { createTransObject(C, t); diff --git a/source/blender/editors/transform/transform_generics.c b/source/blender/editors/transform/transform_generics.c index 8bef63dba1a..053647cbfea 100644 --- a/source/blender/editors/transform/transform_generics.c +++ b/source/blender/editors/transform/transform_generics.c @@ -58,6 +58,8 @@ #include "BLI_rand.h" #include "BLI_utildefines.h" +#include "PIL_time.h" + #include "BLT_translation.h" #include "RNA_access.h" @@ -74,6 +76,7 @@ #include "BKE_fcurve.h" #include "BKE_lattice.h" #include "BKE_library.h" +#include "BKE_main.h" #include "BKE_nla.h" #include "BKE_context.h" #include "BKE_paint.h" @@ -1695,6 +1698,10 @@ void postTrans(bContext *C, TransInfo *t) MEM_freeN(t->mouse.data); } + if (t->rng != NULL) { + BLI_rng_free(t->rng); + } + freeSnapping(t); } @@ -2163,7 +2170,12 @@ void calculatePropRatio(TransInfo *t) td->factor = sqrtf(2 * dist - dist * dist); break; case PROP_RANDOM: - td->factor = BLI_frand() * dist; + if (t->rng == NULL) { + /* Lazy initialization. */ + uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); + t->rng = BLI_rng_new(rng_seed); + } + td->factor = BLI_rng_get_float(t->rng) * dist; break; case PROP_INVSQUARE: td->factor = dist * (2.0f - dist); diff --git a/source/blender/editors/transform/transform_input.c b/source/blender/editors/transform/transform_input.c index 270ef08be50..5b5c4902377 100644 --- a/source/blender/editors/transform/transform_input.c +++ b/source/blender/editors/transform/transform_input.c @@ -375,8 +375,11 @@ void initMouseInputMode(TransInfo *t, MouseInput *mi, MouseInputMode mode) MEM_freeN(mi_data_prev); } - /* bootstrap mouse input with initial values */ - applyMouseInput(t, mi, mi->imval, t->values); + /* Don't write into the values when non-modal because they are already set from operator redo values. */ + if (t->flag & T_MODAL) { + /* bootstrap mouse input with initial values */ + applyMouseInput(t, mi, mi->imval, t->values); + } } void setInputPostFct(MouseInput *mi, void (*post)(struct TransInfo *t, float values[3])) diff --git a/source/blender/editors/transform/transform_manipulator_3d.c b/source/blender/editors/transform/transform_manipulator_3d.c index b6782470f96..75da0fc2d23 100644 --- a/source/blender/editors/transform/transform_manipulator_3d.c +++ b/source/blender/editors/transform/transform_manipulator_3d.c @@ -107,8 +107,15 @@ #define MAN_SCALE_C (MAN_SCALE_X | MAN_SCALE_Y | MAN_SCALE_Z) /* threshold for testing view aligned manipulator axis */ -#define TW_AXIS_DOT_MIN 0.02f -#define TW_AXIS_DOT_MAX 0.1f +struct { + float min, max; +} g_tw_axis_range[2] = { + /* Regular range */ + {0.02f, 0.1f}, + /* Use a different range because we flip the dot product, + * also the view aligned planes are harder to see so hiding early is preferred. */ + {0.175f, 0.25f}, +}; /* axes as index */ enum { @@ -247,16 +254,18 @@ static bool manipulator_is_axis_visible( const RegionView3D *rv3d, const int twtype, const float idot[3], const int axis_type, const int axis_idx) { - bool is_plane = false; - const uint aidx_norm = manipulator_orientation_axis(axis_idx, &is_plane); - /* don't draw axis perpendicular to the view */ - if (aidx_norm < 3) { - float idot_axis = idot[aidx_norm]; - if (is_plane) { - idot_axis = 1.0f - idot_axis; - } - if (idot_axis < TW_AXIS_DOT_MIN) { - return false; + if ((axis_idx >= MAN_AXIS_RANGE_ROT_START && axis_idx < MAN_AXIS_RANGE_ROT_END) == 0) { + bool is_plane = false; + const uint aidx_norm = manipulator_orientation_axis(axis_idx, &is_plane); + /* don't draw axis perpendicular to the view */ + if (aidx_norm < 3) { + float idot_axis = idot[aidx_norm]; + if (is_plane) { + idot_axis = 1.0f - idot_axis; + } + if (idot_axis < g_tw_axis_range[is_plane].min) { + return false; + } } } @@ -333,22 +342,31 @@ static void manipulator_get_axis_color( const float alpha_hi = 1.0f; float alpha_fac; - bool is_plane = false; - const int axis_idx_norm = manipulator_orientation_axis(axis_idx, &is_plane); - /* get alpha fac based on axis angle, to fade axis out when hiding it because it points towards view */ - if (axis_idx_norm < 3) { - float idot_axis = idot[axis_idx_norm]; - if (is_plane) { - idot_axis = 1.0f - idot_axis; - } - alpha_fac = (idot_axis > TW_AXIS_DOT_MAX) ? - 1.0f : (idot_axis < TW_AXIS_DOT_MIN) ? - 0.0f : ((idot_axis - TW_AXIS_DOT_MIN) / (TW_AXIS_DOT_MAX - TW_AXIS_DOT_MIN)); - } - else { + if (axis_idx >= MAN_AXIS_RANGE_ROT_START && axis_idx < MAN_AXIS_RANGE_ROT_END) { + /* Never fade rotation rings. */ /* trackball rotation axis is a special case, we only draw a slight overlay */ alpha_fac = (axis_idx == MAN_AXIS_ROT_T) ? 0.1f : 1.0f; } + else { + bool is_plane = false; + const int axis_idx_norm = manipulator_orientation_axis(axis_idx, &is_plane); + /* get alpha fac based on axis angle, to fade axis out when hiding it because it points towards view */ + if (axis_idx_norm < 3) { + const float idot_min = g_tw_axis_range[is_plane].min; + const float idot_max = g_tw_axis_range[is_plane].max; + float idot_axis = idot[axis_idx_norm]; + if (is_plane) { + idot_axis = 1.0f - idot_axis; + } + alpha_fac = ( + (idot_axis > idot_max) ? + 1.0f : (idot_axis < idot_min) ? + 0.0f : ((idot_axis - idot_min) / (idot_max - idot_min))); + } + else { + alpha_fac = 1.0f; + } + } switch (axis_idx) { case MAN_AXIS_TRANS_X: @@ -1238,9 +1256,14 @@ static ManipulatorGroup *manipulatorgroup_init(wmManipulatorGroup *mgroup) * Custom handler for manipulator widgets */ static int manipulator_modal( - bContext *C, wmManipulator *widget, const wmEvent *UNUSED(event), + bContext *C, wmManipulator *widget, const wmEvent *event, eWM_ManipulatorTweak UNUSED(tweak_flag)) { + /* Avoid unnecessary updates, partially address: T55458. */ + if (ELEM(event->type, TIMER, INBETWEEN_MOUSEMOVE)) { + return OPERATOR_RUNNING_MODAL; + } + const ScrArea *sa = CTX_wm_area(C); ARegion *ar = CTX_wm_region(C); View3D *v3d = sa->spacedata.first; @@ -1315,6 +1338,14 @@ static void WIDGETGROUP_manipulator_setup(const bContext *C, wmManipulatorGroup case MAN_AXIS_SCALE_X: case MAN_AXIS_SCALE_Y: case MAN_AXIS_SCALE_Z: + if (axis_idx >= MAN_AXIS_RANGE_TRANS_START && axis_idx < MAN_AXIS_RANGE_TRANS_END) { + int draw_options = 0; + if ((man->twtype & (V3D_MANIP_ROTATE | V3D_MANIP_SCALE)) == 0) { + draw_options |= ED_MANIPULATOR_ARROW_DRAW_FLAG_STEM; + } + RNA_enum_set(axis->ptr, "draw_options", draw_options); + } + WM_manipulator_set_line_width(axis, MANIPULATOR_AXIS_LINE_WIDTH); break; case MAN_AXIS_ROT_X: @@ -1348,6 +1379,7 @@ static void WIDGETGROUP_manipulator_setup(const bContext *C, wmManipulatorGroup } else if (axis_idx == MAN_AXIS_ROT_C) { WM_manipulator_set_flag(axis, WM_MANIPULATOR_DRAW_VALUE, true); + WM_manipulator_set_scale(axis, 1.2f); } else { WM_manipulator_set_scale(axis, 0.2f); @@ -1447,6 +1479,13 @@ static void WIDGETGROUP_manipulator_refresh(const bContext *C, wmManipulatorGrou WM_manipulator_set_matrix_rotation_from_z_axis(axis, rv3d->twmat[aidx_norm]); RNA_float_set(axis->ptr, "length", len); + + if (axis_idx >= MAN_AXIS_RANGE_TRANS_START && axis_idx < MAN_AXIS_RANGE_TRANS_END) { + if (man->twtype & V3D_MANIP_ROTATE) { + /* Avoid rotate and translate arrows overlap. */ + start_co[2] += 0.215f; + } + } WM_manipulator_set_matrix_offset_location(axis, start_co); WM_manipulator_set_flag(axis, WM_MANIPULATOR_DRAW_OFFSET_SCALE, true); break; diff --git a/source/blender/editors/transform/transform_ops.c b/source/blender/editors/transform/transform_ops.c index 18d30db7a21..d98e3e3261a 100644 --- a/source/blender/editors/transform/transform_ops.c +++ b/source/blender/editors/transform/transform_ops.c @@ -45,6 +45,7 @@ #include "RNA_enum_types.h" #include "WM_api.h" +#include "WM_message.h" #include "WM_types.h" #include "UI_interface.h" @@ -170,6 +171,9 @@ static int select_orientation_exec(bContext *C, wmOperator *op) WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL); + struct wmMsgBus *mbus = CTX_wm_message_bus(C); + WM_msg_publish_rna_prop(mbus, &scene->id, scene, Scene, transform_orientation); + return OPERATOR_FINISHED; } @@ -537,7 +541,7 @@ void Transform_Properties(struct wmOperatorType *ot, int flags) if (flags & P_PROPORTIONAL) { RNA_def_enum(ot->srna, "proportional", rna_enum_proportional_editing_items, 0, "Proportional Editing", ""); prop = RNA_def_enum(ot->srna, "proportional_edit_falloff", rna_enum_proportional_falloff_items, 0, - "Proportional Editing Falloff", "Falloff type for proportional editing mode"); + "Proportional Falloff", "Falloff type for proportional editing mode"); RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_CURVE); /* Abusing id_curve :/ */ RNA_def_float(ot->srna, "proportional_size", 1, T_PROP_SIZE_MIN, T_PROP_SIZE_MAX, "Proportional Size", "", 0.001f, 100.0f); @@ -563,17 +567,20 @@ void Transform_Properties(struct wmOperatorType *ot, int flags) } if (flags & P_GPENCIL_EDIT) { - RNA_def_boolean(ot->srna, "gpencil_strokes", 0, "Edit Grease Pencil", "Edit selected Grease Pencil strokes"); + prop = RNA_def_boolean(ot->srna, "gpencil_strokes", 0, "Edit Grease Pencil", "Edit selected Grease Pencil strokes"); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } if (flags & P_CURSOR_EDIT) { - RNA_def_boolean(ot->srna, "cursor_transform", 0, "Transform Cursor", ""); + prop = RNA_def_boolean(ot->srna, "cursor_transform", 0, "Transform Cursor", ""); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } if ((flags & P_OPTIONS) && !(flags & P_NO_TEXSPACE)) { - RNA_def_boolean(ot->srna, "texture_space", 0, "Edit Texture Space", "Edit Object data texture space"); + prop = RNA_def_boolean(ot->srna, "texture_space", 0, "Edit Texture Space", "Edit Object data texture space"); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); prop = RNA_def_boolean(ot->srna, "remove_on_cancel", 0, "Remove on Cancel", "Remove elements on cancel"); - RNA_def_property_flag(prop, PROP_HIDDEN); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } if (flags & P_CORRECT_UV) { diff --git a/source/blender/editors/undo/ed_undo.c b/source/blender/editors/undo/ed_undo.c index d2ac346df10..478e004743d 100644 --- a/source/blender/editors/undo/ed_undo.c +++ b/source/blender/editors/undo/ed_undo.c @@ -148,15 +148,10 @@ static int ed_undo_step(bContext *C, int step, const char *undoname) void ED_undo_grouped_push(bContext *C, const char *str) { /* do nothing if previous undo task is the same as this one (or from the same undo group) */ - { - wmWindowManager *wm = CTX_wm_manager(C); - if (wm->undo_stack->steps.last) { - const UndoStep *us = wm->undo_stack->steps.last; - if (STREQ(str, us->name)) { - return; - } - } - + wmWindowManager *wm = CTX_wm_manager(C); + const UndoStep *us = wm->undo_stack->step_active; + if (us && STREQ(str, us->name)) { + BKE_undosys_stack_clear_active(wm->undo_stack); } /* push as usual */ @@ -210,7 +205,7 @@ bool ED_undo_is_valid(const bContext *C, const char *undoname) */ UndoStack *ED_undo_stack_get(void) { - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; return wm->undo_stack; } @@ -307,36 +302,6 @@ void ED_OT_undo_redo(wmOperatorType *ot) /** \} */ -struct OperatorRepeatContextHandle { - ScrArea *restore_area; - ARegion *restore_region; -}; - -/** - * Resets the context to the state \a op was executed in (or at least, was in when registering). - * #ED_operator_repeat_reset_context should be called when done repeating! - */ -const OperatorRepeatContextHandle *ED_operator_repeat_prepare_context(bContext *C, wmOperator *op) -{ - static OperatorRepeatContextHandle context_info; - - context_info.restore_area = CTX_wm_area(C); - context_info.restore_region = CTX_wm_region(C); - - CTX_wm_area_set(C, op->execution_area); - CTX_wm_region_set(C, op->execution_region); - - return &context_info; -} -/** - * Resets context to the old state from before #ED_operator_repeat_prepare_context was called. - */ -void ED_operator_repeat_reset_context(bContext *C, const OperatorRepeatContextHandle *context_info) -{ - CTX_wm_area_set(C, context_info->restore_area); - CTX_wm_region_set(C, context_info->restore_region); -} - /* -------------------------------------------------------------------- */ /** \name Operator Repeat * \{ */ @@ -351,8 +316,13 @@ int ED_undo_operator_repeat(bContext *C, wmOperator *op) wmWindowManager *wm = CTX_wm_manager(C); struct Scene *scene = CTX_data_scene(C); - const OperatorRepeatContextHandle *context_info; - context_info = ED_operator_repeat_prepare_context(C, op); + /* keep in sync with logic in view3d_panel_operator_redo() */ + ARegion *ar_orig = CTX_wm_region(C); + ARegion *ar_win = BKE_area_find_region_active_win(CTX_wm_area(C)); + + if (ar_win) { + CTX_wm_region_set(C, ar_win); + } if ((WM_operator_repeat_check(C, op)) && (WM_operator_poll(C, op->type)) && @@ -398,7 +368,8 @@ int ED_undo_operator_repeat(bContext *C, wmOperator *op) } } - ED_operator_repeat_reset_context(C, context_info); + /* set region back */ + CTX_wm_region_set(C, ar_orig); } else { CLOG_WARN(&LOG, "called with NULL 'op'"); @@ -440,7 +411,7 @@ static const EnumPropertyItem *rna_undo_itemf(bContext *C, int *totitem) item_tmp.identifier = us->name; item_tmp.name = IFACE_(us->name); if (us == wm->undo_stack->step_active) { - item_tmp.icon = ICON_RESTRICT_VIEW_OFF; + item_tmp.icon = ICON_HIDE_OFF; } else { item_tmp.icon = ICON_NONE; diff --git a/source/blender/editors/util/CMakeLists.txt b/source/blender/editors/util/CMakeLists.txt index 24cfde90804..fa21facefc2 100644 --- a/source/blender/editors/util/CMakeLists.txt +++ b/source/blender/editors/util/CMakeLists.txt @@ -87,6 +87,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_util.c b/source/blender/editors/util/ed_util.c index a829f8c1144..549b9b7de77 100644 --- a/source/blender/editors/util/ed_util.c +++ b/source/blender/editors/util/ed_util.c @@ -145,8 +145,8 @@ void ED_editors_exit(bContext *C) return; /* frees all editmode undos */ - if (G.main->wm.first) { - wmWindowManager *wm = G.main->wm.first; + if (G_MAIN->wm.first) { + wmWindowManager *wm = G_MAIN->wm.first; /* normally we don't check for NULL undo stack, do here since it may run in different context. */ if (wm->undo_stack) { BKE_undosys_stack_destroy(wm->undo_stack); diff --git a/source/blender/editors/uvedit/uvedit_ops.c b/source/blender/editors/uvedit/uvedit_ops.c index 45a6ccfe28b..e3d2537c040 100644 --- a/source/blender/editors/uvedit/uvedit_ops.c +++ b/source/blender/editors/uvedit/uvedit_ops.c @@ -1362,7 +1362,7 @@ static int uv_select_more_less(bContext *C, const bool select) else { EDBM_select_less(em, true); } - + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; } @@ -1434,6 +1434,7 @@ static int uv_select_more_less(bContext *C, const bool select) uv_select_flush_from_tag_loop(sima, scene, obedit, select); } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -2058,6 +2059,7 @@ static int uv_select_all_exec(bContext *C, wmOperator *op) for (uint ob_index = 0; ob_index < objects_len; ob_index++) { Object *obedit = objects[ob_index]; + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -2371,7 +2373,7 @@ static int uv_mouse_select_multi( #endif } - DEG_id_tag_update(obedit->data, 0); + DEG_id_tag_update(obedit->data, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_PASS_THROUGH | OPERATOR_FINISHED; @@ -2547,7 +2549,7 @@ static int uv_select_linked_internal(bContext *C, wmOperator *op, const wmEvent for (uint ob_index = 0; ob_index < objects_len; ob_index++) { Object *obedit = objects[ob_index]; - DEG_id_tag_update(obedit->data, 0); + DEG_id_tag_update(obedit->data, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3052,6 +3054,7 @@ static int uv_border_select_exec(bContext *C, wmOperator *op) uv_select_sync_flush(ts, em, select); if (ts->uv_flag & UV_SYNC_SELECTION) { + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } } @@ -3181,6 +3184,7 @@ static int uv_circle_select_exec(bContext *C, wmOperator *op) if (changed) { uv_select_sync_flush(ts, em, select); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } @@ -3314,6 +3318,7 @@ static bool do_lasso_select_mesh_uv(bContext *C, const int mcords[][2], short mo uv_select_sync_flush(scene->toolsettings, em, select); if (ts->uv_flag & UV_SYNC_SELECTION) { + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); } } @@ -3746,6 +3751,7 @@ static int uv_select_pinned_exec(bContext *C, wmOperator *UNUSED(op)) } } + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -3812,6 +3818,8 @@ static int uv_hide_exec(bContext *C, wmOperator *op) if (ts->uv_flag & UV_SYNC_SELECTION) { EDBM_mesh_hide(em, swap); + + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -3880,6 +3888,8 @@ static int uv_hide_exec(bContext *C, wmOperator *op) EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX | SCE_SELECT_EDGE); BM_select_history_validate(em->bm); + + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -3933,6 +3943,7 @@ static int uv_reveal_exec(bContext *C, wmOperator *op) /* call the mesh function if we are in mesh sync sel */ if (ts->uv_flag & UV_SYNC_SELECTION) { EDBM_mesh_reveal(em, select); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; @@ -4022,6 +4033,7 @@ static int uv_reveal_exec(bContext *C, wmOperator *op) /* re-select tagged faces */ BM_mesh_elem_hflag_enable_test(em->bm, BM_FACE, BM_ELEM_SELECT, true, false, BM_ELEM_TAG); + DEG_id_tag_update(obedit->data, DEG_TAG_SELECT_UPDATE); WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data); return OPERATOR_FINISHED; diff --git a/source/blender/freestyle/intern/application/AppCanvas.cpp b/source/blender/freestyle/intern/application/AppCanvas.cpp index f621f45ff77..aca725a0384 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<Vec3r> AppCanvas::scene3DBBox() const +BBox<Vec3r> 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 759f6456759..b4c815f8ad0 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 f41a9b58085..e57d004e503 100644 --- a/source/blender/freestyle/intern/blender_interface/BlenderFileLoader.cpp +++ b/source/blender/freestyle/intern/blender_interface/BlenderFileLoader.cpp @@ -596,7 +596,7 @@ void BlenderFileLoader::insertShapeNode(Object *ob, Mesh *me, int id) MEM_freeN(mlooptri); - // 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/FRS_freestyle.cpp b/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp index 75687edd9f6..b1c5de9d621 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) diff --git a/source/blender/freestyle/intern/geometry/FastGrid.h b/source/blender/freestyle/intern/geometry/FastGrid.h index 355a6e53399..75624bb9d9c 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 fbfa5b331e6..fd7d63bbd28 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 2268f6be1b7..c402f431c27 100644 --- a/source/blender/freestyle/intern/geometry/FitCurve.h +++ b/source/blender/freestyle/intern/geometry/FitCurve.h @@ -90,7 +90,7 @@ public: * 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<Vec2d>& data, std::vector<Vec2d>& oCurve, double error); diff --git a/source/blender/freestyle/intern/geometry/GeomUtils.h b/source/blender/freestyle/intern/geometry/GeomUtils.h index 8f3abf451c9..9e7c629191f 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 371c63318de..61cf70a0aa3 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 22efdcf1d11..4dd345e9b07 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 039ecd7ebf4..98e860862bb 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 T, class Point> -class SweepLine +class SweepLine { public: SweepLine() {} @@ -231,7 +231,7 @@ public: } } - inline void process(Point& p, vector<Segment<T, Point>*>& segments, + inline void process(Point& p, vector<Segment<T, Point>*>& segments, #if 0 binary_rule<Segment<T, Point>,Segment<T, Point> >& binrule = \ binary_rule<Segment<T, Point>, Segment<T, Point> >(), diff --git a/source/blender/freestyle/intern/geometry/VecMat.h b/source/blender/freestyle/intern/geometry/VecMat.h index 3c3d40875d0..e7a44e00b1b 100644 --- a/source/blender/freestyle/intern/geometry/VecMat.h +++ b/source/blender/freestyle/intern/geometry/VecMat.h @@ -150,21 +150,21 @@ public: Vec<T, N> res(v); res += *this; return res; - } + } inline Vec<T, N> operator-(const Vec<T, N>& v) const { Vec<T, N> res(*this); res -= v; return res; - } + } inline Vec<T, N> operator*(const typename Vec<T, N>::value_type r) const { Vec<T, N> res(*this); res *= r; return res; - } + } inline Vec<T, N> operator/(const typename Vec<T, N>::value_type r) const { @@ -172,7 +172,7 @@ public: if (r) res /= r; return res; - } + } // dot product inline value_type operator*(const Vec<T, N>& v) const @@ -181,7 +181,7 @@ public: for (unsigned int i = 0; i < N; i++) sum += (*this)[i] * v[i]; return sum; - } + } template <class U> inline Vec<T, N>& operator=(const Vec<U, N>& v) @@ -255,7 +255,7 @@ public: if (this->_coord[i] == v[i]) continue; } - return false; + return false; } inline bool operator>(const Vec<T, N>& v) const @@ -268,7 +268,7 @@ public: 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 5e585497516..40195361fe0 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 7abd1bc18bc..fdbfd20d764 100644 --- a/source/blender/freestyle/intern/image/GaussianFilter.h +++ b/source/blender/freestyle/intern/image/GaussianFilter.h @@ -120,7 +120,7 @@ protected: }; /* - + ############################################# ############################################# ############################################# @@ -130,7 +130,7 @@ protected: ############################################# ############################################# ############################################# - + */ template<class Map> diff --git a/source/blender/freestyle/intern/python/BPy_Convert.cpp b/source/blender/freestyle/intern/python/BPy_Convert.cpp index 4e1a0a119aa..0ac116b1bd4 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 35c1e58369c..a0e0b578c10 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 0b09a3c2442..23deb63ce36 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_IntegrationType.cpp b/source/blender/freestyle/intern/python/BPy_IntegrationType.cpp index 0db25753caa..548ab529f34 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 8f23800fb7a..d592aed749d 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 240f3f2d6e2..ebd9c6822a9 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 9169adf4d9f..cf4880ad3f7 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_StrokeShader.cpp b/source/blender/freestyle/intern/python/BPy_StrokeShader.cpp index 6b4a1872b61..eee48f19e1b 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 fc43accabf0..87e5e7505ca 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 f2f53159fcf..33c18c3ce80 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 2072faa43ef..8d81e508340 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 9f85e84e297..f4f02a7026f 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<ViewShape*> > *)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 40576c0ec2c..6a0ae7dd704 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 39919b41423..33300ea70b5 100644 --- a/source/blender/freestyle/intern/python/Interface0D/BPy_SVertex.cpp +++ b/source/blender/freestyle/intern/python/Interface0D/BPy_SVertex.cpp @@ -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/Interface1D/BPy_Stroke.cpp b/source/blender/freestyle/intern/python/Interface1D/BPy_Stroke.cpp index 5c816bdfea1..9a39db0ee7e 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 bcae5a2c2a4..9119d8f999e 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/Iterator/BPy_ChainSilhouetteIterator.cpp b/source/blender/freestyle/intern/python/Iterator/BPy_ChainSilhouetteIterator.cpp index 08cfffec860..5a6e838dcc6 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 e91c62c7d24..1f5444d7beb 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<double>(); else { self->uf1D_double = new UnaryFunction1D<double>(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 abef3b2676f..3f0611dba84 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<Nature::EdgeNature>(); else { self->uf1D_edgenature = new UnaryFunction1D<Nature::EdgeNature>(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 13a001c585b..b3b27aabade 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<float>(); else { self->uf1D_float = new UnaryFunction1D<float>(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 4e88020b5c8..0814eafb18e 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<unsigned int>(); else { self->uf1D_unsigned = new UnaryFunction1D<unsigned int>(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 9a864a3f579..f7f4fea02ae 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<Vec2f>(); else { self->uf1D_vec2f = new UnaryFunction1D<Vec2f>(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 60c581ac845..980df2c2268 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<Vec3f>(); else { self->uf1D_vec3f = new UnaryFunction1D<Vec3f>(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 c15d974e771..5eba1573d80 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<ViewShape*> >(); } else { self->uf1D_vectorviewshape = new UnaryFunction1D< std::vector<ViewShape*> >(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 4db28c0db95..7a83a49b9d2 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 16dea6f907e..c1a5b2a6774 100644 --- a/source/blender/freestyle/intern/scene_graph/IndexedFaceSet.h +++ b/source/blender/freestyle/intern/scene_graph/IndexedFaceSet.h @@ -90,7 +90,7 @@ public: * - 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 e7d81113974..a35920a4f4c 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<Vec3r>::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 546458bad48..4ddcadd3542 100644 --- a/source/blender/freestyle/intern/scene_graph/Node.h +++ b/source/blender/freestyle/intern/scene_graph/Node.h @@ -104,7 +104,7 @@ public: protected: -private: +private: BBox<Vec3r> _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 78c34fdef6d..c2f70d514a8 100644 --- a/source/blender/freestyle/intern/scene_graph/NodeCamera.h +++ b/source/blender/freestyle/intern/scene_graph/NodeCamera.h @@ -52,7 +52,7 @@ public: } 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 69c8a2c8f3b..e8e58b0915e 100644 --- a/source/blender/freestyle/intern/scene_graph/NodeGroup.h +++ b/source/blender/freestyle/intern/scene_graph/NodeGroup.h @@ -48,7 +48,7 @@ public: /*! 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 5a54bc09891..9e15f6c1eee 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 c633a6bc7b8..10d6f657872 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 773eb2d3278..4c8017e162d 100644 --- a/source/blender/freestyle/intern/scene_graph/Rep.h +++ b/source/blender/freestyle/intern/scene_graph/Rep.h @@ -97,7 +97,7 @@ public: 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 d101cfd7988..353555b2802 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 48d5cd4803e..87f132b1ff3 100644 --- a/source/blender/freestyle/intern/stroke/AdvancedFunctions0D.h +++ b/source/blender/freestyle/intern/stroke/AdvancedFunctions0D.h @@ -109,7 +109,7 @@ private: 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 @@ private: 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 @@ private: 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 ed527080f36..247217791a5 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 9df690cf5b0..ec698ca5e68 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<double> 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 a9ef49aa802..5ba96f31272 100644 --- a/source/blender/freestyle/intern/stroke/AdvancedStrokeShaders.h +++ b/source/blender/freestyle/intern/stroke/AdvancedStrokeShaders.h @@ -61,7 +61,7 @@ public: 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 cc935a7e311..d3d19beba95 100644 --- a/source/blender/freestyle/intern/stroke/BasicStrokeShaders.h +++ b/source/blender/freestyle/intern/stroke/BasicStrokeShaders.h @@ -405,7 +405,7 @@ public: class BackboneStretcherShader : public StrokeShader { private: - float _amount; + float _amount; public: /*! Builds the shader. @@ -524,7 +524,7 @@ public: * 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 @@ public: 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 5919344b6e0..6d84ff995d2 100644 --- a/source/blender/freestyle/intern/stroke/Canvas.h +++ b/source/blender/freestyle/intern/stroke/Canvas.h @@ -128,7 +128,7 @@ public: 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 4ece24c5ecf..310409f160f 100644 --- a/source/blender/freestyle/intern/stroke/ChainingIterators.h +++ b/source/blender/freestyle/intern/stroke/ChainingIterators.h @@ -80,7 +80,7 @@ public: { _internalIterator = iBrother._internalIterator; _restrictToSelection = iBrother._restrictToSelection; - _restrictToUnvisited = iBrother._restrictToUnvisited; + _restrictToUnvisited = iBrother._restrictToUnvisited; return *this; } @@ -289,7 +289,7 @@ public: */ 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 d8b780e77a0..97710437e47 100644 --- a/source/blender/freestyle/intern/stroke/ContextFunctions.h +++ b/source/blender/freestyle/intern/stroke/ContextFunctions.h @@ -64,7 +64,7 @@ BBox<Vec2i> 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 a8dbce84971..52fd780ee43 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 726b238c74b..04cc2fbfd39 100644 --- a/source/blender/freestyle/intern/stroke/Curve.h +++ b/source/blender/freestyle/intern/stroke/Curve.h @@ -94,7 +94,7 @@ public: // Implementation of Interface0D return _Point3d.z(); } - /*! Returns the 3D point. */ + /*! Returns the 3D point. */ virtual Vec3r getPoint3D() const { return _Point3d; @@ -118,7 +118,7 @@ public: // Implementation of 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 @@ public: } /*! 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 @@ public: } /*! 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 @@ public: } /*! 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 4142117c361..726c80d889c 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<CurvePoint*> public: typedef deque<CurvePoint*> 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<CurvePoint*> @@ -47,7 +47,7 @@ class CurvePoint_nonconst_traits : public Nonconst_traits<CurvePoint*> public: typedef deque<CurvePoint*> vertex_container; typedef vertex_container::iterator vertex_container_iterator; - typedef SVertex vertex_type; + typedef SVertex vertex_type; }; /**********************************/ @@ -325,7 +325,7 @@ protected: } } - virtual void decrement() + virtual void decrement() { if (_Point != 0) { delete _Point; diff --git a/source/blender/freestyle/intern/stroke/CurveIterators.h b/source/blender/freestyle/intern/stroke/CurveIterators.h index d7a79d6e788..cb33221cfd4 100644 --- a/source/blender/freestyle/intern/stroke/CurveIterators.h +++ b/source/blender/freestyle/intern/stroke/CurveIterators.h @@ -35,13 +35,13 @@ namespace Freestyle { namespace CurveInternal { -/*! iterator on a curve. Allows an iterating outside +/*! iterator on a curve. Allows an iterating outside * initial vertices. A CurvePoint is instanciated an returned * when the iterator is dereferenced. */ class CurvePointIterator : public Interface0DIteratorNested -{ +{ public: friend class Freestyle::Curve; diff --git a/source/blender/freestyle/intern/stroke/Operators.cpp b/source/blender/freestyle/intern/stroke/Operators.cpp index dfb50d903f7..151cd29ca07 100644 --- a/source/blender/freestyle/intern/stroke/Operators.cpp +++ b/source/blender/freestyle/intern/stroke/Operators.cpp @@ -704,7 +704,7 @@ static int __recursiveSplit(Chain *_curve, UnaryFunction0D<double>& 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<double>& 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 c7b0e3f8b81..4130f9b370e 100644 --- a/source/blender/freestyle/intern/stroke/Operators.h +++ b/source/blender/freestyle/intern/stroke/Operators.h @@ -94,7 +94,7 @@ public: * \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 c004d73e6fe..83e6a947917 100644 --- a/source/blender/freestyle/intern/stroke/Stroke.h +++ b/source/blender/freestyle/intern/stroke/Stroke.h @@ -564,7 +564,7 @@ public: * \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<class InputVertexIterator> Stroke(InputVertexIterator iBegin, InputVertexIterator iEnd); @@ -600,7 +600,7 @@ public: * 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); @@ -608,7 +608,7 @@ public: */ 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 868f61224de..054182a558a 100644 --- a/source/blender/freestyle/intern/stroke/StrokeRenderer.h +++ b/source/blender/freestyle/intern/stroke/StrokeRenderer.h @@ -112,7 +112,7 @@ protected: 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 028127897ff..81ef46e5b3b 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 02f7177b95c..dd0b945e4d3 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 8b028cdb3da..279730f7934 100644 --- a/source/blender/freestyle/intern/system/Id.h +++ b/source/blender/freestyle/intern/system/Id.h @@ -78,7 +78,7 @@ public: _first = iBrother._first; _second = iBrother._second; return *this; - } + } /*! Returns the first Id number */ id_type getFirst() const diff --git a/source/blender/freestyle/intern/view_map/ArbitraryGridDensityProvider.cpp b/source/blender/freestyle/intern/view_map/ArbitraryGridDensityProvider.cpp index 3243c4d1fb7..79de3ca497d 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 d98a3238a25..ae0d83a3551 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 a97e60d5f60..1eeb6805e7d 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<WEdge*>::iterator we, weend; vector<WEdge*> &wedges = iWShape->getEdgeList(); for (we = wedges.begin(), weend = wedges.end(); we != weend; ++we) { diff --git a/source/blender/freestyle/intern/view_map/Functions0D.cpp b/source/blender/freestyle/intern/view_map/Functions0D.cpp index f47e5ff16d5..15319e54f66 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 d2a5870f27a..f3c8957a804 100644 --- a/source/blender/freestyle/intern/view_map/Functions1D.h +++ b/source/blender/freestyle/intern/view_map/Functions1D.h @@ -101,7 +101,7 @@ public: } /*! 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 9d373107bfa..44bce375a75 100644 --- a/source/blender/freestyle/intern/view_map/Silhouette.h +++ b/source/blender/freestyle/intern/view_map/Silhouette.h @@ -102,7 +102,7 @@ public: // Implementation of Interface0D return _Point3D.z(); } - /*! Returns the 3D point. */ + /*! Returns the 3D point. */ virtual Vec3r getPoint3D() const { return _Point3D; @@ -126,7 +126,7 @@ public: // Implementation of 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 @@ public: // Implementation of 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 @@ private: Id _Id; Vec3r _Point3D; Vec3r _Point2D; - set<Vec3r> _Normals; + set<Vec3r> _Normals; vector<FEdge*> _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 @@ protected: 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 @@ private: const char *_Name; const char *_LibraryPath; BBox<Vec3r> _BBox; - vector<FrsMaterial> _FrsMaterials; + vector<FrsMaterial> _FrsMaterials; float _importance; diff --git a/source/blender/freestyle/intern/view_map/SphericalGrid.h b/source/blender/freestyle/intern/view_map/SphericalGrid.h index 5a94a84705d..2310f5ffe2f 100644 --- a/source/blender/freestyle/intern/view_map/SphericalGrid.h +++ b/source/blender/freestyle/intern/view_map/SphericalGrid.h @@ -173,7 +173,7 @@ public: // 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 4f5b4cba779..34d8ecb3a8d 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<unsigned int, double*>::iterator m = _mapping.begin(), mend = _mapping.end(); m != mend; ++m) { delete[] (*m).second; @@ -170,7 +170,7 @@ unsigned SteerableViewMap::getSVMNumber(unsigned id) map<unsigned int, double *>::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 3a660627776..0327b4a460e 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 52769413e79..01a6edad973 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 8b73c8aac3a..06ab3183027 100644 --- a/source/blender/freestyle/intern/view_map/ViewMap.h +++ b/source/blender/freestyle/intern/view_map/ViewMap.h @@ -218,7 +218,7 @@ public: * 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 @@ public: /**********************************/ /* */ /* */ -/* NonTVertex */ +/* NonTVertex */ /* */ /* */ /**********************************/ @@ -1643,7 +1643,7 @@ void ViewShape::SplitEdge(FEdge *fe, const vector<TVertex*>& 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<TVertex*>::const_iterator vv, vvend; for (vv = iViewVertices.begin(), vvend = iViewVertices.end(); vv != vvend; vv++) { @@ -1685,7 +1685,7 @@ void ViewShape::SplitEdge(FEdge *fe, const vector<TVertex*>& 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 794c782bb73..5b7576ccd3d 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); @@ -2286,7 +2286,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<FEdge*> 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 440ae93c7df..acde3704625 100644 --- a/source/blender/freestyle/intern/view_map/ViewMapBuilder.h +++ b/source/blender/freestyle/intern/view_map/ViewMapBuilder.h @@ -159,7 +159,7 @@ public: /*! 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<Vec3r>& bbox, unsigned int sceneNumFaces); @@ -180,7 +180,7 @@ public: /*! 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<Vec3r>& 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 71ae68c06bc..3e80c004b5f 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 469c2c3b29c..b10de13cef7 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 481133ba984..6829a8c0be2 100644 --- a/source/blender/gpu/CMakeLists.txt +++ b/source/blender/gpu/CMakeLists.txt @@ -23,6 +23,14 @@ # # ***** END GPL LICENSE BLOCK ***** +# WITH_OPENGL limits the visibility of the opengl headers to just gawain and bg_gpu, +# to more easily highlight codepadths in other libraries that need to be refactored, +# bf_gpu is allowed to have opengl regardless of this option. + +if(NOT WITH_OPENGL) + add_definitions(-DWITH_OPENGL) +endif() + set(INC . ../blenkernel diff --git a/source/blender/gpu/GPU_draw.h b/source/blender/gpu/GPU_draw.h index e26d973142b..613a07dc869 100644 --- a/source/blender/gpu/GPU_draw.h +++ b/source/blender/gpu/GPU_draw.h @@ -86,9 +86,6 @@ void GPU_set_gpu_mipmapping(int gpu_mipmap); * - 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); -int GPU_verify_image( - struct Image *ima, struct ImageUser *iuser, - int textarget, bool compare, bool mipmap, bool is_data); void GPU_create_gl_tex( unsigned int *bind, unsigned int *rect, float *frect, int rectw, int recth, int textarget, bool mipmap, bool use_hight_bit_depth, struct Image *ima); diff --git a/source/blender/gpu/GPU_glew.h b/source/blender/gpu/GPU_glew.h index afe1c9763ad..663660ab234 100644 --- a/source/blender/gpu/GPU_glew.h +++ b/source/blender/gpu/GPU_glew.h @@ -32,10 +32,11 @@ #ifndef __GPU_GLEW_H__ #define __GPU_GLEW_H__ -#include "glew-mx.h" - -#ifndef WITH_LEGACY_OPENGL -#include "GPU_legacy_stubs.h" +#if defined(WITH_OPENGL) +# include "glew-mx.h" +# ifndef WITH_LEGACY_OPENGL +# include "GPU_legacy_stubs.h" +# endif #endif #endif /* __GPU_GLEW_H__ */ diff --git a/source/blender/gpu/GPU_texture.h b/source/blender/gpu/GPU_texture.h index 09b351a544a..e53693e7b40 100644 --- a/source/blender/gpu/GPU_texture.h +++ b/source/blender/gpu/GPU_texture.h @@ -161,8 +161,9 @@ GPUTexture *GPU_texture_create_from_vertbuf( GPUTexture *GPU_texture_create_buffer( GPUTextureFormat data_type, const uint buffer); +GPUTexture *GPU_texture_from_bindcode(int textarget, int bindcode); GPUTexture *GPU_texture_from_blender( - struct Image *ima, struct ImageUser *iuser, int textarget, bool is_data, double time, int mipmap); + struct Image *ima, struct ImageUser *iuser, int textarget, bool is_data, double time); GPUTexture *GPU_texture_from_preview(struct PreviewImage *prv, int mipmap); void GPU_texture_update(GPUTexture *tex, const float *pixels); diff --git a/source/blender/gpu/intern/gpu_codegen.c b/source/blender/gpu/intern/gpu_codegen.c index 0dd9d1f0908..436f43d9c1e 100644 --- a/source/blender/gpu/intern/gpu_codegen.c +++ b/source/blender/gpu/intern/gpu_codegen.c @@ -416,15 +416,26 @@ static void codegen_convert_datatype(DynStr *ds, int from, int to, const char *t else if (from == GPU_FLOAT) BLI_dynstr_appendf(ds, "vec3(%s, %s, %s)", name, name, name); } - else { + else if (to == GPU_VEC4) { if (from == GPU_VEC3) BLI_dynstr_appendf(ds, "vec4(%s, 1.0)", name); else if (from == GPU_VEC2) BLI_dynstr_appendf(ds, "vec4(%s.r, %s.r, %s.r, %s.g)", name, name, name, name); else if (from == GPU_FLOAT) BLI_dynstr_appendf(ds, "vec4(%s, %s, %s, 1.0)", name, name, name); - else /* can happen with closure */ - BLI_dynstr_append(ds, name); + } + else if (to == GPU_CLOSURE) { + if (from == GPU_VEC4) + BLI_dynstr_appendf(ds, "closure_emission(%s.rgb)", name); + else if (from == GPU_VEC3) + BLI_dynstr_appendf(ds, "closure_emission(%s.rgb)", name); + else if (from == GPU_VEC2) + BLI_dynstr_appendf(ds, "closure_emission(%s.rrr)", name); + else if (from == GPU_FLOAT) + BLI_dynstr_appendf(ds, "closure_emission(vec3(%s, %s, %s))", name, name, name); + } + else { + BLI_dynstr_append(ds, name); } } @@ -1183,77 +1194,6 @@ void GPU_nodes_extract_dynamic_inputs(GPUShader *shader, ListBase *inputs, ListB GPU_shader_unbind(); } -void GPU_pass_bind(GPUPass *pass, ListBase *inputs, double time, int mipmap) -{ - GPUInput *input; - GPUShader *shader = pass->shader; - - if (!shader) - return; - - GPU_shader_bind(shader); - - /* create the textures */ - for (input = inputs->first; input; input = input->next) { - if (input->ima) - input->tex = GPU_texture_from_blender(input->ima, input->iuser, input->textarget, input->image_isdata, time, mipmap); - else if (input->prv) - input->tex = GPU_texture_from_preview(input->prv, mipmap); - } - - /* bind the textures, in second loop so texture binding during - * create doesn't overwrite already bound textures */ - for (input = inputs->first; input; input = input->next) { - if (input->tex && input->bindtex) { - GPU_texture_bind(input->tex, input->texid); - GPU_shader_uniform_texture(shader, input->shaderloc, input->tex); - } - } -} - -void GPU_pass_update_uniforms(GPUPass *pass, ListBase *inputs) -{ - GPUInput *input; - GPUShader *shader = pass->shader; - - if (!shader) - return; - - /* pass dynamic inputs to opengl, others were removed */ - for (input = inputs->first; input; input = input->next) { - if (!(input->ima || input->tex || input->prv)) { - if (input->dynamictype == GPU_DYNAMIC_MAT_HARD) { - // The hardness is actually a short pointer, so we convert it here - float val = (float)(*(short *)input->dynamicvec); - GPU_shader_uniform_vector(shader, input->shaderloc, 1, 1, &val); - } - else { - GPU_shader_uniform_vector(shader, input->shaderloc, input->type, 1, - input->dynamicvec); - } - } - } -} - -void GPU_pass_unbind(GPUPass *pass, ListBase *inputs) -{ - GPUInput *input; - GPUShader *shader = pass->shader; - - if (!shader) - return; - - for (input = inputs->first; input; input = input->next) { - if (input->tex && input->bindtex) - GPU_texture_unbind(input->tex); - - if (input->ima || input->prv) - input->tex = NULL; - } - - GPU_shader_unbind(); -} - /* Node Link Functions */ static GPUNodeLink *GPU_node_link_create(void) diff --git a/source/blender/gpu/intern/gpu_codegen.h b/source/blender/gpu/intern/gpu_codegen.h index 04bee545a7e..a0f425e39d6 100644 --- a/source/blender/gpu/intern/gpu_codegen.h +++ b/source/blender/gpu/intern/gpu_codegen.h @@ -184,10 +184,6 @@ void GPU_nodes_extract_dynamic_inputs(struct GPUShader *shader, ListBase *inputs void GPU_nodes_get_vertex_attributes(ListBase *nodes, struct GPUVertexAttribs *attribs); void GPU_nodes_prune(ListBase *nodes, struct GPUNodeLink *outlink); -void GPU_pass_bind(GPUPass *pass, ListBase *inputs, double time, int mipmap); -void GPU_pass_update_uniforms(GPUPass *pass, ListBase *inputs); -void GPU_pass_unbind(GPUPass *pass, ListBase *inputs); - void GPU_pass_compile(GPUPass *pass); void GPU_pass_release(GPUPass *pass); void GPU_pass_free_nodes(ListBase *nodes); diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c index 7bfebb702a1..83fd689e3b7 100644 --- a/source/blender/gpu/intern/gpu_draw.c +++ b/source/blender/gpu/intern/gpu_draw.c @@ -127,8 +127,6 @@ static int smaller_power_of_2_limit(int num) /* Current OpenGL state caching for GPU_set_tpage */ static struct GPUTextureState { - Image *ima, *curima; - /* also controls min/mag filtering */ bool domipmap; /* only use when 'domipmap' is set */ @@ -136,10 +134,9 @@ static struct GPUTextureState { /* store this so that new images created while texture painting won't be set to mipmapped */ bool texpaint; - int alphablend; float anisotropic; int gpu_mipmap; -} GTS = {NULL, NULL, 1, 0, 0, -1, 1.0f, 0}; +} GTS = {1, 0, 0, 1.0f, 0}; /* Mipmap settings */ @@ -227,16 +224,14 @@ float GPU_get_anisotropic(void) /* Set OpenGL state for an MTFace */ -static unsigned int *gpu_get_image_bindcode(Image *ima, GLenum textarget) +static GPUTexture **gpu_get_image_gputexture(Image *ima, GLenum textarget) { - unsigned int *bind = 0; - if (textarget == GL_TEXTURE_2D) - bind = &ima->bindcode[TEXTARGET_TEXTURE_2D]; + return &ima->gputexture[TEXTARGET_TEXTURE_2D]; else if (textarget == GL_TEXTURE_CUBE_MAP) - bind = &ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]; + return &ima->gputexture[TEXTARGET_TEXTURE_CUBE_MAP]; - return bind; + return NULL; } typedef struct VerifyThreadData { @@ -289,33 +284,45 @@ static void gpu_verify_high_bit_srgb_buffer(float *srgb_frect, } } -int GPU_verify_image( - Image *ima, ImageUser *iuser, - int textarget, bool compare, bool mipmap, bool is_data) +GPUTexture *GPU_texture_from_blender(Image *ima, + ImageUser *iuser, + int textarget, + bool is_data, + double UNUSED(time)) { - unsigned int *bind = NULL; - int tpx = 0, tpy = 0; - unsigned int *rect = NULL; - float *frect = NULL; - float *srgb_frect = NULL; - /* flag to determine whether deep format is used */ - bool use_high_bit_depth = false, do_color_management = false; + if (ima == NULL) { + return NULL; + } - GTS.ima = ima; + /* Test if we already have a texture. */ + GPUTexture **tex = gpu_get_image_gputexture(ima, textarget); + if (*tex) { + return *tex; + } - if (compare && ima == GTS.curima) { - return (ima != NULL); + /* Check if we have a valid image. If not, we return a dummy + * texture with zero bindcode so we don't keep trying. */ + unsigned int bindcode = 0; + if (ima->ok == 0) { + *tex = GPU_texture_from_bindcode(textarget, bindcode); + return *tex; } - /* check if we have a valid image */ - if (ima == NULL || ima->ok == 0) - return 0; + /* currently, tpage refresh is used by ima sequences */ + if (ima->tpageflag & IMA_TPAGE_REFRESH) { + GPU_free_image(ima); + ima->tpageflag &= ~IMA_TPAGE_REFRESH; + } /* check if we have a valid image buffer */ ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, NULL); + if (ibuf == NULL) { + *tex = GPU_texture_from_bindcode(textarget, bindcode); + return *tex; + } - if (ibuf == NULL) - return 0; + /* flag to determine whether deep format is used */ + bool use_high_bit_depth = false, do_color_management = false; if (ibuf->rect_float) { if (U.use_16bit_textures) { @@ -337,50 +344,33 @@ int GPU_verify_image( } } - /* currently, tpage refresh is used by ima sequences */ - if (ima->tpageflag & IMA_TPAGE_REFRESH) { - GPU_free_image(ima); - ima->tpageflag &= ~IMA_TPAGE_REFRESH; - } + const int rectw = ibuf->x; + const int recth = ibuf->y; + unsigned int *rect = ibuf->rect; + float *frect = NULL; + float *srgb_frect = NULL; - { - /* regular image mode */ - bind = gpu_get_image_bindcode(ima, textarget); - - if (*bind == 0) { - tpx = ibuf->x; - tpy = ibuf->y; - rect = ibuf->rect; - if (use_high_bit_depth) { - if (do_color_management) { - frect = srgb_frect = MEM_mallocN(ibuf->x * ibuf->y * sizeof(*srgb_frect) * 4, "floar_buf_col_cor"); - gpu_verify_high_bit_srgb_buffer(srgb_frect, ibuf); - } - else - frect = ibuf->rect_float; - } + if (use_high_bit_depth) { + if (do_color_management) { + frect = srgb_frect = MEM_mallocN(ibuf->x * ibuf->y * sizeof(*srgb_frect) * 4, "floar_buf_col_cor"); + gpu_verify_high_bit_srgb_buffer(srgb_frect, ibuf); + } + else { + frect = ibuf->rect_float; } } - if (*bind != 0) { - /* enable opengl drawing with textures */ - glBindTexture(textarget, *bind); - BKE_image_release_ibuf(ima, ibuf, NULL); - return *bind; - } - - const int rectw = tpx; - const int recth = tpy; + const bool mipmap = GPU_get_mipmap(); #ifdef WITH_DDS if (ibuf->ftype == IMB_FTYPE_DDS) - GPU_create_gl_tex_compressed(bind, rect, rectw, recth, textarget, mipmap, ima, ibuf); + GPU_create_gl_tex_compressed(&bindcode, rect, rectw, recth, textarget, mipmap, ima, ibuf); else #endif - GPU_create_gl_tex(bind, rect, frect, rectw, recth, textarget, mipmap, use_high_bit_depth, ima); + GPU_create_gl_tex(&bindcode, rect, frect, rectw, recth, textarget, mipmap, use_high_bit_depth, ima); /* mark as non-color data texture */ - if (*bind) { + if (bindcode) { if (is_data) ima->tpageflag |= IMA_GLBIND_IS_DATA; else @@ -393,7 +383,8 @@ int GPU_verify_image( BKE_image_release_ibuf(ima, ibuf, NULL); - return *bind; + *tex = GPU_texture_from_bindcode(textarget, bindcode); + return *tex; } static void **gpu_gen_cube_map(unsigned int *rect, float *frect, int rectw, int recth, bool use_high_bit_depth) @@ -594,6 +585,8 @@ void GPU_create_gl_tex( if (GLEW_EXT_texture_filter_anisotropic) glTexParameterf(textarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic()); + glBindTexture(textarget, 0); + if (ibuf) IMB_freeImBuf(ibuf); } @@ -680,6 +673,8 @@ void GPU_create_gl_tex_compressed( glDeleteTextures(1, (GLuint *)bind); GPU_create_gl_tex(bind, pix, NULL, x, y, textarget, mipmap, 0, ima); } + + glBindTexture(textarget, 0); #endif } @@ -696,17 +691,13 @@ void GPU_paint_set_mipmap(bool mipmap) if (mipmap) { for (Image *ima = G.main->image.first; ima; ima = ima->id.next) { - if (BKE_image_has_bindcode(ima)) { + if (BKE_image_has_opengl_texture(ima)) { if (ima->tpageflag & IMA_MIPMAP_COMPLETE) { - if (ima->bindcode[TEXTARGET_TEXTURE_2D]) { - glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]); + if (ima->gputexture[TEXTARGET_TEXTURE_2D]) { + GPU_texture_bind(ima->gputexture[TEXTARGET_TEXTURE_2D], 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1)); - } - if (ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]) { - glBindTexture(GL_TEXTURE_CUBE_MAP, ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0)); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1)); + GPU_texture_unbind(ima->gputexture[TEXTARGET_TEXTURE_2D]); } } else @@ -719,16 +710,12 @@ void GPU_paint_set_mipmap(bool mipmap) } else { for (Image *ima = G.main->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]); + if (BKE_image_has_opengl_texture(ima)) { + if (ima->gputexture[TEXTARGET_TEXTURE_2D]) { + GPU_texture_bind(ima->gputexture[TEXTARGET_TEXTURE_2D], 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1)); - } - if (ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]) { - glBindTexture(GL_TEXTURE_CUBE_MAP, ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1)); + GPU_texture_unbind(ima->gputexture[TEXTARGET_TEXTURE_2D]); } } else @@ -761,12 +748,13 @@ static bool gpu_check_scaled_image(ImBuf *ibuf, Image *ima, float *frect, int x, if (rectw + x > x_limit) rectw--; if (recth + y > y_limit) recth--; + GPU_texture_bind(ima->gputexture[TEXTARGET_TEXTURE_2D], 0); + /* float rectangles are already continuous in memory so we can use IMB_scaleImBuf */ if (frect) { ImBuf *ibuf_scale = IMB_allocFromBuffer(NULL, frect, w, h); IMB_scaleImBuf(ibuf_scale, rectw, recth); - glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, rectw, recth, GL_RGBA, GL_FLOAT, ibuf_scale->rect_float); @@ -786,7 +774,7 @@ static bool gpu_check_scaled_image(ImBuf *ibuf, Image *ima, float *frect, int x, bilinear_interpolation_color_wrap(ibuf, (unsigned char *)(p + i + j * (rectw)), NULL, u, v); } } - glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]); + glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, rectw, recth, GL_RGBA, GL_UNSIGNED_BYTE, scalerect); @@ -800,6 +788,8 @@ static bool gpu_check_scaled_image(ImBuf *ibuf, Image *ima, float *frect, int x, ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; } + GPU_texture_unbind(ima->gputexture[TEXTARGET_TEXTURE_2D]); + return true; } @@ -811,7 +801,7 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, NULL); if ((!GTS.gpu_mipmap && GPU_get_mipmap()) || - (ima->bindcode[TEXTARGET_TEXTURE_2D] == 0) || + (ima->gputexture[TEXTARGET_TEXTURE_2D] == NULL) || (ibuf == NULL) || (w == 0) || (h == 0)) { @@ -835,7 +825,7 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i return; } - glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]); + GPU_texture_bind(ima->gputexture[TEXTARGET_TEXTURE_2D], 0); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_FLOAT, buffer); MEM_freeN(buffer); @@ -849,6 +839,8 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; } + GPU_texture_unbind(ima->gputexture[TEXTARGET_TEXTURE_2D]); + BKE_image_release_ibuf(ima, ibuf, NULL); return; } @@ -858,7 +850,7 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i return; } - glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]); + GPU_texture_bind(ima->gputexture[TEXTARGET_TEXTURE_2D], 0); glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length); glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels); @@ -882,6 +874,8 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i else { ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; } + + GPU_texture_unbind(ima->gputexture[TEXTARGET_TEXTURE_2D]); } BKE_image_release_ibuf(ima, ibuf, NULL); @@ -1016,11 +1010,6 @@ void GPU_free_image(Image *ima) } for (int i = 0; i < TEXTARGET_COUNT; i++) { - /* free regular image binding */ - if (ima->bindcode[i]) { - glDeleteTextures(1, (GLuint *)&ima->bindcode[i]); - ima->bindcode[i] = 0; - } /* free glsl image binding */ if (ima->gputexture[i]) { GPU_texture_free(ima->gputexture[i]); @@ -1071,7 +1060,7 @@ void GPU_free_images_old(void) 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 * This gives textures a "second chance" to be used before dying. */ - if (BKE_image_has_bindcode(ima)) { + if (BKE_image_has_opengl_texture(ima)) { GPU_free_image(ima); ima->lastused = ctime; } diff --git a/source/blender/gpu/intern/gpu_framebuffer.c b/source/blender/gpu/intern/gpu_framebuffer.c index f86da2eb064..18f8c33c3ca 100644 --- a/source/blender/gpu/intern/gpu_framebuffer.c +++ b/source/blender/gpu/intern/gpu_framebuffer.c @@ -42,7 +42,9 @@ #include "GPU_shader.h" #include "GPU_texture.h" -static ThreadLocal(GLuint) g_currentfb; +#include "intern/gpu_private.h" + +static ThreadLocal(void *) g_currentfb; typedef enum { GPU_FB_DEPTH_ATTACHMENT = 0, @@ -163,6 +165,26 @@ static void gpu_print_framebuffer_error(GLenum status, char err_out[256]) } } +void gpu_framebuffer_module_init(void) +{ + BLI_thread_local_create(g_currentfb); +} + +void gpu_framebuffer_module_exit(void) +{ + BLI_thread_local_delete(g_currentfb); +} + +static uint gpu_framebuffer_current_get(void) +{ + return GET_UINT_FROM_POINTER(BLI_thread_local_get(g_currentfb)); +} + +static void gpu_framebuffer_current_set(uint object) +{ + BLI_thread_local_set(g_currentfb, SET_UINT_IN_POINTER(object)); +} + /* GPUFrameBuffer */ GPUFrameBuffer *GPU_framebuffer_create(void) @@ -188,8 +210,8 @@ void GPU_framebuffer_free(GPUFrameBuffer *fb) /* This restores the framebuffer if it was bound */ glDeleteFramebuffers(1, &fb->object); - if (g_currentfb == fb->object) { - g_currentfb = 0; + if (gpu_framebuffer_current_get() == fb->object) { + gpu_framebuffer_current_set(0); } MEM_freeN(fb); @@ -341,7 +363,7 @@ static void gpu_framebuffer_update_attachments(GPUFrameBuffer *fb) GLenum gl_attachments[GPU_FB_MAX_COLOR_ATTACHMENT]; int numslots = 0; - BLI_assert(g_currentfb == fb->object); + BLI_assert(gpu_framebuffer_current_get() == fb->object); /* Update attachments */ for (GPUAttachmentType type = 0; type < GPU_FB_MAX_ATTACHEMENT; ++type) { @@ -385,10 +407,10 @@ void GPU_framebuffer_bind(GPUFrameBuffer *fb) if (fb->object == 0) gpu_framebuffer_init(fb); - if (g_currentfb != fb->object) + if (gpu_framebuffer_current_get() != fb->object) glBindFramebuffer(GL_FRAMEBUFFER, fb->object); - g_currentfb = fb->object; + gpu_framebuffer_current_set(fb->object); if (fb->dirty_flag != 0) gpu_framebuffer_update_attachments(fb); @@ -409,20 +431,20 @@ void GPU_framebuffer_bind(GPUFrameBuffer *fb) void GPU_framebuffer_restore(void) { - if (g_currentfb != 0) { + if (gpu_framebuffer_current_get() != 0) { glBindFramebuffer(GL_FRAMEBUFFER, 0); - g_currentfb = 0; + gpu_framebuffer_current_set(0); } } bool GPU_framebuffer_bound(GPUFrameBuffer *fb) { - return (fb->object == g_currentfb) && (fb->object != 0); + return (fb->object == gpu_framebuffer_current_get()) && (fb->object != 0); } unsigned int GPU_framebuffer_current_get(void) { - return g_currentfb; + return gpu_framebuffer_current_get(); } bool GPU_framebuffer_check_valid(GPUFrameBuffer *fb, char err_out[256]) @@ -513,7 +535,7 @@ void GPU_framebuffer_blit( { BLI_assert(blit_buffers != 0); - GLuint prev_fb = g_currentfb; + GLuint prev_fb = gpu_framebuffer_current_get(); /* Framebuffers must be up to date. This simplify this function. */ if (fb_read->dirty_flag != 0 || fb_read->object == 0) { @@ -573,7 +595,7 @@ void GPU_framebuffer_blit( } else { glBindFramebuffer(GL_FRAMEBUFFER, prev_fb); - g_currentfb = prev_fb; + gpu_framebuffer_current_set(prev_fb); } } @@ -586,13 +608,13 @@ void GPU_framebuffer_recursive_downsample( void (*callback)(void *userData, int level), void *userData) { /* Framebuffer must be up to date and bound. This simplify this function. */ - if (g_currentfb != fb->object || fb->dirty_flag != 0 || fb->object == 0) { + if (gpu_framebuffer_current_get() != fb->object || fb->dirty_flag != 0 || fb->object == 0) { GPU_framebuffer_bind(fb); } /* HACK: We make the framebuffer appear not bound in order to * not trigger any error in GPU_texture_bind(). */ - GLuint prev_fb = g_currentfb; - g_currentfb = 0; + GLuint prev_fb = gpu_framebuffer_current_get(); + gpu_framebuffer_current_set(0); int i; int current_dim[2] = {fb->width, fb->height}; @@ -640,7 +662,7 @@ void GPU_framebuffer_recursive_downsample( } } - g_currentfb = prev_fb; + gpu_framebuffer_current_set(prev_fb); } /* GPUOffScreen */ diff --git a/source/blender/gpu/intern/gpu_init_exit.c b/source/blender/gpu/intern/gpu_init_exit.c index 92ad9d81b6c..78d4f491b66 100644 --- a/source/blender/gpu/intern/gpu_init_exit.c +++ b/source/blender/gpu/intern/gpu_init_exit.c @@ -60,6 +60,7 @@ void GPU_init(void) GPU_texture_orphans_init(); GPU_material_orphans_init(); gpu_codegen_init(); + gpu_framebuffer_module_init(); if (G.debug & G_DEBUG_GPU) gpu_debug_init(); @@ -89,6 +90,7 @@ void GPU_exit(void) if (G.debug & G_DEBUG_GPU) gpu_debug_exit(); + gpu_framebuffer_module_exit(); gpu_codegen_exit(); gpu_extensions_exit(); /* must come last */ diff --git a/source/blender/gpu/intern/gpu_private.h b/source/blender/gpu/intern/gpu_private.h index 72627e3563e..996ba9c63a1 100644 --- a/source/blender/gpu/intern/gpu_private.h +++ b/source/blender/gpu/intern/gpu_private.h @@ -33,4 +33,8 @@ void gpu_extensions_exit(void); void gpu_debug_init(void); void gpu_debug_exit(void); +/* gpu_framebuffer.c */ +void gpu_framebuffer_module_init(void); +void gpu_framebuffer_module_exit(void); + #endif /* __GPU_PRIVATE_H__ */ diff --git a/source/blender/gpu/intern/gpu_texture.c b/source/blender/gpu/intern/gpu_texture.c index aac75014b3e..ee00a1381f4 100644 --- a/source/blender/gpu/intern/gpu_texture.c +++ b/source/blender/gpu/intern/gpu_texture.c @@ -79,7 +79,6 @@ struct GPUTexture { GLenum target_base; /* same as target, (but no multisample) * use it for unbinding */ GLuint bindcode; /* opengl identifier for texture */ - int fromblender; /* we got the texture from Blender */ GPUTextureFormat format; GPUTextureFormatFlag format_flag; @@ -673,40 +672,22 @@ GPUTexture *GPU_texture_create_buffer(GPUTextureFormat data_type, const GLuint b return tex; } -GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, int textarget, bool is_data, double UNUSED(time), int mipmap) +GPUTexture *GPU_texture_from_bindcode(int textarget, int bindcode) { - int gputt; - /* this binds a texture, so that's why to restore it to 0 */ - GLint bindcode = GPU_verify_image(ima, iuser, textarget, 0, mipmap, is_data); - /* see GPUInput::textarget: it can take two values - GL_TEXTURE_2D and GL_TEXTURE_CUBE_MAP * these values are correct for glDisable, so textarget can be safely used in * GPU_texture_bind/GPU_texture_unbind through tex->target_base */ /* (is any of this obsolete now that we don't glEnable/Disable textures?) */ - if (textarget == GL_TEXTURE_2D) - gputt = TEXTARGET_TEXTURE_2D; - else - gputt = TEXTARGET_TEXTURE_CUBE_MAP; - - if (ima->gputexture[gputt]) { - ima->gputexture[gputt]->bindcode = bindcode; - glBindTexture(textarget, 0); - return ima->gputexture[gputt]; - } - GPUTexture *tex = MEM_callocN(sizeof(GPUTexture), "GPUTexture"); tex->bindcode = bindcode; tex->number = -1; tex->refcount = 1; tex->target = textarget; tex->target_base = textarget; - tex->fromblender = 1; tex->format = -1; tex->components = -1; tex->samples = 0; - ima->gputexture[gputt] = tex; - if (!glIsTexture(tex->bindcode)) { GPU_print_error_debug("Blender Texture Not Loaded"); } @@ -725,10 +706,9 @@ GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, int textarget glGetTexLevelParameteriv(gettarget, 0, GL_TEXTURE_HEIGHT, &h); tex->w = w; tex->h = h; + glBindTexture(textarget, 0); } - glBindTexture(textarget, 0); - return tex; } @@ -1090,7 +1070,7 @@ void GPU_texture_wrap_mode(GPUTexture *tex, bool use_repeat) static void gpu_texture_delete(GPUTexture *tex) { - if (tex->bindcode && !tex->fromblender) + if (tex->bindcode) glDeleteTextures(1, &tex->bindcode); gpu_texture_memory_footprint_remove(tex); diff --git a/source/blender/gpu/shaders/gpu_shader_2D_widget_base_vert.glsl b/source/blender/gpu/shaders/gpu_shader_2D_widget_base_vert.glsl index dcd23413c77..931ea426fbd 100644 --- a/source/blender/gpu/shaders/gpu_shader_2D_widget_base_vert.glsl +++ b/source/blender/gpu/shaders/gpu_shader_2D_widget_base_vert.glsl @@ -47,10 +47,12 @@ const vec2 jit[9] = vec2[9]( /* We can reuse the CORNER_* bits for tria */ #define TRIA_VEC_RANGE BIT_RANGE(6) -const vec2 triavec[37] = vec2[37]( +const vec2 triavec[43] = vec2[43]( + /* ROUNDBOX_TRIA_ARROWS */ - vec2(-0.352077, 0.532607), vec2(-0.352077, -0.549313), vec2( 0.330000, -0.008353), - vec2( 0.352077, 0.532607), vec2( 0.352077, -0.549313), vec2(-0.330000, -0.008353), + vec2(-0.170000, 0.400000), vec2(-0.050000, 0.520000), vec2( 0.250000, 0.000000), vec2( 0.470000, -0.000000), vec2(-0.170000, -0.400000), vec2(-0.050000, -0.520000), + vec2( 0.170000, 0.400000), vec2( 0.050000, 0.520000), vec2(-0.250000, 0.000000), vec2(-0.470000, -0.000000), vec2( 0.170000, -0.400000), vec2( 0.050000, -0.520000), + /* ROUNDBOX_TRIA_SCROLL - circle tria (triangle strip) */ vec2(0.000000, 1.000000), vec2(0.382684, 0.923879), vec2(-0.382683, 0.923880), @@ -61,12 +63,16 @@ const vec2 triavec[37] = vec2[37]( vec2(0.707107, -0.707107), vec2(-0.707107, -0.707107), vec2(0.382684, -0.923879), vec2(-0.382683, -0.923880), vec2(0.000000, -1.000000), + /* ROUNDBOX_TRIA_MENU - menu arrows */ - vec2(-0.33, 0.16), vec2(0.33, 0.16), vec2(0.0, 0.82), - vec2(0.0, -0.82), vec2(-0.33, -0.16), vec2(0.33, -0.16), + vec2(-0.66, 0.08), vec2(-0.56, 0.20), vec2(-0.2, -0.39), + vec2(-0.2, -0.18), vec2(0.26, 0.08), vec2(0.15, 0.20), + + /* ROUNDBOX_TRIA_CHECK - check mark */ - vec2(-0.578579, 0.253369), vec2(-0.392773, 0.412794), vec2(-0.004241, -0.328551), - vec2(-0.003001, 0.034320), vec2(1.055313, 0.864744), vec2(0.866408, 1.026895), + vec2(-0.67000, 0.020000), vec2(-0.500000, 0.190000), vec2(-0.130000, -0.520000), + vec2(-0.130000, -0.170000), vec2(0.720000, 0.430000), vec2(0.530000, 0.590000), + /* ROUNDBOX_TRIA_HOLD_ACTION_ARROW - hold action arrows */ #define OY (-0.2 / 2) #define SC (0.35 * 2) diff --git a/source/blender/gpu/shaders/gpu_shader_material.glsl b/source/blender/gpu/shaders/gpu_shader_material.glsl index 4c77dd038af..3affacf5203 100644 --- a/source/blender/gpu/shaders/gpu_shader_material.glsl +++ b/source/blender/gpu/shaders/gpu_shader_material.glsl @@ -8,38 +8,6 @@ uniform mat3 NormalMatrix; uniform mat4 ModelMatrixInverse; #endif -/* Old glsl mode compat. */ - -#ifndef CLOSURE_DEFAULT - -struct Closure { - vec3 radiance; - float opacity; -}; - -#define CLOSURE_DEFAULT Closure(vec3(0.0), 1.0) - -Closure closure_mix(Closure cl1, Closure cl2, float fac) -{ - Closure cl; - cl.radiance = mix(cl1.radiance, cl2.radiance, fac); - cl.opacity = mix(cl1.opacity, cl2.opacity, fac); - return cl; -} - -Closure closure_add(Closure cl1, Closure cl2) -{ - Closure cl; - cl.radiance = cl1.radiance + cl2.radiance; - cl.opacity = cl1.opacity + cl2.opacity; - return cl; -} - -Closure nodetree_exec(void); /* Prototype */ - -#endif /* CLOSURE_DEFAULT */ - - /* Converters */ float convert_rgba_to_float(vec4 color) @@ -1235,14 +1203,12 @@ void node_bsdf_refraction(vec4 color, float roughness, float ior, vec3 N, out Cl result.ssr_id = REFRACT_CLOSURE_FLAG; } -void node_ambient_occlusion(vec4 color, vec3 vN, out Closure result) +void node_ambient_occlusion(vec4 color, float distance, vec3 normal, out vec4 result_color, out float result_ao) { vec3 bent_normal; vec4 rand = texelFetch(utilTex, ivec3(ivec2(gl_FragCoord.xy) % LUT_SIZE, 2.0), 0); - float final_ao = occlusion_compute(normalize(worldNormal), viewPosition, 1.0, rand, bent_normal); - result = CLOSURE_DEFAULT; - result.ssr_normal = normal_encode(vN, viewCameraVec); - result.radiance = final_ao * color.rgb; + result_ao = occlusion_compute(normalize(normal), viewPosition, 1.0, rand, bent_normal); + result_color = result_ao * color; } #endif /* VOLUMETRICS */ diff --git a/source/blender/imbuf/CMakeLists.txt b/source/blender/imbuf/CMakeLists.txt index e73f227dec8..44ff53cc020 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 ) diff --git a/source/blender/imbuf/IMB_imbuf.h b/source/blender/imbuf/IMB_imbuf.h index 4289f98643d..75f8df99e63 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/intern/IMB_anim.h b/source/blender/imbuf/intern/IMB_anim.h index 6fa31e122cc..804095a0727 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_indexer.h b/source/blender/imbuf/intern/IMB_indexer.h index bac46740f0f..024801cb870 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 faa0b5f7b6e..589955d2ab3 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 f842b69418e..290226acf78 100644 --- a/source/blender/imbuf/intern/anim_movie.c +++ b/source/blender/imbuf/intern/anim_movie.c @@ -325,7 +325,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 +382,7 @@ static int startavi(struct anim *anim) free_anim_avi(anim); return -1; } - + anim->duration = anim->avi->header->TotalFrames; anim->params = NULL; @@ -407,7 +407,7 @@ static ImBuf *avi_fetchibuf(struct anim *anim, int position) ImBuf *ibuf = NULL; int *tmp; int y; - + if (anim == NULL) { return NULL; } @@ -431,7 +431,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 +442,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 +619,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 +630,7 @@ static int startffmpeg(struct anim *anim) else { anim->preseek = 0; } - + anim->img_convert_ctx = sws_getContext( anim->x, anim->y, @@ -640,7 +640,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 +671,7 @@ static int startffmpeg(struct anim *anim) fprintf(stderr, "Warning: Could not set libswscale colorspace details.\n"); } #endif - + return (0); } @@ -691,7 +691,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 +701,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 +738,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 +746,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 +783,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 +820,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 +863,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 +918,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 +934,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 +995,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 +1025,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 +1034,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 +1065,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 +1083,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 +1109,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 +1156,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 +1167,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 +1275,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 +1363,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 +1376,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 e63699ea5ba..edaa57eedf2 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 759f8cc82c2..a36d82be7c7 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 diff --git a/source/blender/imbuf/intern/cineon/CMakeLists.txt b/source/blender/imbuf/intern/cineon/CMakeLists.txt index c96db4e4a3d..0a3c440d9a7 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 1d2ebf88a32..c116d32b2f0 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 bb72f675cb8..614323d0d11 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 7c7c3a7ba45..86c0dd69930 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 8e571483e08..170cf620701 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 <icastano@nvidia.com> -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -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++ ) { diff --git a/source/blender/imbuf/intern/dds/BlockDXT.h b/source/blender/imbuf/intern/dds/BlockDXT.h index 6aae9c9817c..7371d72ea4a 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 <icastano@nvidia.com> -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -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 57603725ce1..8c95695f356 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 6676057d710..51939a6ea4c 100644 --- a/source/blender/imbuf/intern/dds/Color.h +++ b/source/blender/imbuf/intern/dds/Color.h @@ -69,7 +69,7 @@ public: operator unsigned int () const { return u; } - + union { struct { unsigned char b, g, r, a; @@ -85,7 +85,7 @@ public: 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 dd4ae3e518e..2cee4c984dd 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,12 +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 8d5031aa603..7b5291cf976 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 7c11fca3c34..97ce5b90fa0 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 <icastano@nvidia.com> -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -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); } diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.h b/source/blender/imbuf/intern/dds/DirectDrawSurface.h index 44c27a98c1d..b7bcb8303bf 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 <icastano@nvidia.com> -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -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 @@ public: 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/Image.h b/source/blender/imbuf/intern/dds/Image.h index 658f01deaec..bb74a9d5d15 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 e841e696833..e37e09dd661 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 <icastano@nvidia.com> -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -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/dds_api.cpp b/source/blender/imbuf/intern/dds/dds_api.cpp index 67a0b0ffd00..c038407c0a6 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 769d53a44ef..2b6fa573e63 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/filter.c b/source/blender/imbuf/intern/filter.c index 902fc6482da..decbfd6d5b9 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 0f5fd6518fb..2eec5da7bc4 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 90dad70fa61..7c455edd916 100644 --- a/source/blender/imbuf/intern/imbuf.h +++ b/source/blender/imbuf/intern/imbuf.h @@ -34,7 +34,7 @@ #include <stdlib.h> #include <sys/types.h> -#include <stdio.h> +#include <stdio.h> #ifndef WIN32 # include <unistd.h> diff --git a/source/blender/imbuf/intern/indexer.c b/source/blender/imbuf/intern/indexer.c index 2bda07bdbbe..56f90d39850 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 11b1fd7b1c2..61326218d4a 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 @@ fail_rle: 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 @@ fail_rle: 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 @@ fail_rle: 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 @@ fail_rle: 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 @@ fail_rle: fptr += xsize * 4; } } - + } #undef MFILE_CAPACITY_AT_PTR_OK_OR_FAIL fail_uncompressed: @@ -507,7 +507,7 @@ fail_uncompressed: 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 @@ fail_uncompressed: 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 @@ fail_uncompressed: 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); diff --git a/source/blender/imbuf/intern/jp2.c b/source/blender/imbuf/intern/jp2.c index 30a0fdf4e55..753b5276222 100644 --- a/source/blender/imbuf/intern/jp2.c +++ b/source/blender/imbuf/intern/jp2.c @@ -126,7 +126,7 @@ struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, c 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 +134,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 +180,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 +196,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 +211,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 +293,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 +346,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 +416,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 +438,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 +487,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 +534,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 +572,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 +596,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 +616,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 +624,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 +665,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 +676,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 +744,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 +898,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,17 +944,17 @@ 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; } @@ -963,14 +963,14 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) int imb_savejp2(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 +979,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 +1021,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 +1031,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 +1041,13 @@ 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; } diff --git a/source/blender/imbuf/intern/jpeg.c b/source/blender/imbuf/intern/jpeg.c index ef9217fbc8c..2febbb1f861 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 @@ next_stamp_marker: 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/oiio/openimageio_api.cpp b/source/blender/imbuf/intern/oiio/openimageio_api.cpp index b123d508f99..ab8824fdf85 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) diff --git a/source/blender/imbuf/intern/openexr/CMakeLists.txt b/source/blender/imbuf/intern/openexr/CMakeLists.txt index d5cb8e8a3b6..d4e6e9dc670 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 ad04f1fb78d..a52ae75e87b 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 165cc968701..92bbeecfd5d 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 8ac206a97ea..71b7cb2f567 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) { diff --git a/source/blender/imbuf/intern/radiance_hdr.c b/source/blender/imbuf/intern/radiance_hdr.c index 8d822a314f5..be33c16c8ae 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 afa3ffb31f3..0b4490a3beb 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 2fe17ee56c6..a762e3780dc 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 886944f6190..f00745f0052 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 4b528160fb7..43c5a9d3597 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 0949a431293..9d92d146f50 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 831924b780a..a35ca7f0c47 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 7ed725ae163..9cf1b96635b 100644 --- a/source/blender/imbuf/intern/thumbs_blend.c +++ b/source/blender/imbuf/intern/thumbs_blend.c @@ -145,7 +145,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 914fcc4e847..0d650daa1c9 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 @@ cleanup: _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 9dfe926ddff..6a095b2da1f 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 d50cb8c781d..855f6229420 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 8043e01a147..62f8f1395c5 100644 --- a/source/blender/makesdna/DNA_ID.h +++ b/source/blender/makesdna/DNA_ID.h @@ -250,7 +250,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 2266390d348..dac96b6ce5a 100644 --- a/source/blender/makesdna/DNA_action_types.h +++ b/source/blender/makesdna/DNA_action_types.h @@ -73,10 +73,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 */ @@ -97,7 +97,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 --------------------------- */ @@ -108,22 +108,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; @@ -204,19 +204,19 @@ typedef struct bPoseChannelDrawData { /* 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 */ @@ -253,7 +253,7 @@ 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 */ @@ -261,23 +261,23 @@ typedef struct bPoseChannel { float disp_tail_mat[4][4]; /* for display, pose_mat with bone length applied and translated to tail*/ 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; @@ -296,16 +296,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), @@ -383,8 +383,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, @@ -395,7 +395,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). @@ -412,19 +412,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; @@ -514,13 +514,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; @@ -543,7 +543,7 @@ typedef enum eActionGroup_Flag { /* sub channel modifiers off */ AGRP_MODIFIERS_OFF = (1 << 7), - + AGRP_TEMP = (1 << 30), AGRP_MOVED = (1u << 31) } eActionGroup_Flag; @@ -551,7 +551,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), @@ -563,15 +563,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; @@ -597,13 +597,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 Collection *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; @@ -613,7 +613,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 */ @@ -652,22 +652,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; @@ -683,14 +683,14 @@ 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? */ - + int cache_display; /* (eTimeline_Cache_Flag) */ int pad; } SpaceAction; @@ -721,7 +721,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 { @@ -786,10 +786,10 @@ typedef enum eTimeline_Cache_Flag { 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_anim_types.h b/source/blender/makesdna/DNA_anim_types.h index 63dc8920a4b..22067b87ff8 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 */ @@ -471,20 +471,20 @@ 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!) */ /* Value which comes from original DNA ddatablock at a time f-curve was evaluated. */ @@ -492,13 +492,13 @@ typedef struct FCurve { 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[3]; /* 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 */ @@ -519,7 +519,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), @@ -530,7 +530,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; @@ -562,7 +562,7 @@ typedef enum eFCurve_Smoothing { * they are not stored here... see DNA_action_types.h instead */ - + /* ************************************************ */ /* Animation Reuse - i.e. users of Actions */ @@ -581,7 +581,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 @@ -594,7 +594,7 @@ typedef struct AnimMapPair { // such consequences... typedef struct AnimMapper { struct AnimMapper *next, *prev; - + bAction *target; /* target action */ ListBase mappings; /* remapping table (bAnimMapPair) */ } AnimMapper; @@ -700,14 +700,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; @@ -723,12 +723,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; @@ -744,7 +744,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; @@ -753,7 +753,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 @@ -763,18 +763,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; @@ -793,14 +793,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 @@ -813,21 +813,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; @@ -860,7 +860,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 @@ -871,10 +871,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; @@ -968,7 +968,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 9e278c63904..af555fe6d83 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; @@ -211,7 +211,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 44764eb012e..a161fde119e 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 b3c568fab98..7bf89887d8c 100644 --- a/source/blender/makesdna/DNA_camera_types.h +++ b/source/blender/makesdna/DNA_camera_types.h @@ -77,8 +77,8 @@ typedef struct CameraBGImage { 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; @@ -94,7 +94,7 @@ typedef struct Camera { float YF_dofdist; 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 00995bcf290..940872fd08d 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 6f9c407c6c6..8ed38b0b05d 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 6f6ce7d08db..ada4073f51f 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; @@ -340,11 +340,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 */ @@ -369,12 +369,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; @@ -411,10 +411,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; @@ -466,7 +466,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 */ @@ -486,7 +486,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_DEPRECATED = 17 */ CONSTRAINT_TYPE_CLAMPTO = 18, /* clampto constraint */ @@ -501,21 +501,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 */ @@ -534,8 +534,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 */ @@ -578,12 +578,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; @@ -604,7 +604,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) */ @@ -706,7 +706,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), @@ -771,7 +771,7 @@ typedef enum eDistLimit_Modes { LIMITDIST_OUTSIDE = 1, LIMITDIST_ONSURFACE = 2 } eDistLimit_Modes; - + /* python constraint -> flag */ typedef enum ePyConstraint_Flags { PYCON_USETARGETS = (1<<0), @@ -797,14 +797,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_curve_types.h b/source/blender/makesdna/DNA_curve_types.h index f1b0c32e53b..e590780f1ff 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 */ @@ -407,7 +407,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, @@ -424,7 +424,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, diff --git a/source/blender/makesdna/DNA_dynamicpaint_types.h b/source/blender/makesdna/DNA_dynamicpaint_types.h index b341c2841e2..d8caec4da40 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 3455feea1a9..964b330a452 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,40 +102,40 @@ struct Collection; 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 Collection *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_gpencil_types.h b/source/blender/makesdna/DNA_gpencil_types.h index c7ca92ba5cc..e2ee561de7f 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 */ @@ -316,29 +316,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 3b947caf59c..b5208a81510 100644 --- a/source/blender/makesdna/DNA_group_types.h +++ b/source/blender/makesdna/DNA_group_types.h @@ -55,7 +55,7 @@ typedef struct CollectionChild { typedef struct Collection { ID id; - + ListBase gobject; /* CollectionObject */ ListBase children; /* CollectionChild */ diff --git a/source/blender/makesdna/DNA_image_types.h b/source/blender/makesdna/DNA_image_types.h index 3d29c5b3833..26d7f089f8b 100644 --- a/source/blender/makesdna/DNA_image_types.h +++ b/source/blender/makesdna/DNA_image_types.h @@ -80,7 +80,9 @@ typedef struct ImagePackedFile { } ImagePackedFile; typedef struct RenderSlot { + struct RenderSlot *next, *prev; char name[64]; /* 64 = MAX_NAME */ + struct RenderResult *render; } RenderSlot; /* iuser->flag */ @@ -98,17 +100,17 @@ 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; - struct RenderResult *renders[8]; /* IMA_MAX_RENDER_SLOT */ + ListBase renderslots; short render_slot, last_render_slot; int flag; @@ -118,7 +120,6 @@ typedef struct Image { /* texture page */ short tpageflag; short pad2; - unsigned int bindcode[2]; /* only for current image... 2 = TEXTARGET_COUNT */ unsigned int pad3; struct PackedFile *packedfile DNA_DEPRECATED; /* deprecated */ @@ -128,13 +129,13 @@ typedef struct Image { int lastused; short ok; short pad4[3]; - + /* 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; @@ -149,8 +150,6 @@ typedef struct Image { char views_format; ListBase views; /* ImageView */ struct Stereo3dFormat *stereo3d_format; - - RenderSlot render_slots[8]; /* 8 = IMA_MAX_RENDER_SLOT */ } Image; @@ -192,7 +191,6 @@ enum { /* render */ #define IMA_MAX_RENDER_TEXT 512 -#define IMA_MAX_RENDER_SLOT 8 /* gen_flag */ #define IMA_GEN_FLOAT 1 diff --git a/source/blender/makesdna/DNA_ipo_types.h b/source/blender/makesdna/DNA_ipo_types.h index 5ba822616eb..f97935a09a1 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 diff --git a/source/blender/makesdna/DNA_key_types.h b/source/blender/makesdna/DNA_key_types.h index 60ab01c901b..2b097092bc4 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 3a4b07cc791..e1ab56a0206 100644 --- a/source/blender/makesdna/DNA_lamp_types.h +++ b/source/blender/makesdna/DNA_lamp_types.h @@ -47,14 +47,14 @@ 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; float r, g, b, k; float shdwr, shdwg, shdwb, shdwpad; - + float energy, dist, spotsize, spotblend; float att1, att2; /* Quad1 and Quad2 attenuation */ @@ -62,18 +62,18 @@ typedef struct Lamp { struct CurveMapping *curfalloff; short falloff_type; short pad2; - + float clipsta, clipend; float bias, soft, bleedbias, bleedexp; short bufsize, samp, buffers, filtertype; char bufflag, buftype; - + short area_shape; float area_size, area_sizey, area_sizez; - + /* texact is for buttons */ short texact, shadhalostep; - + struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ short pr_texture, use_nodes; char pad6[4]; @@ -99,7 +99,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 diff --git a/source/blender/makesdna/DNA_lattice_types.h b/source/blender/makesdna/DNA_lattice_types.h index 28a401676fc..e329743cce7 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; void *batch_cache; } Lattice; diff --git a/source/blender/makesdna/DNA_layer_types.h b/source/blender/makesdna/DNA_layer_types.h index 66a8c3e236d..6b4dcc39005 100644 --- a/source/blender/makesdna/DNA_layer_types.h +++ b/source/blender/makesdna/DNA_layer_types.h @@ -56,7 +56,8 @@ typedef struct LayerCollection { struct Collection *collection; struct SceneCollection *scene_collection DNA_DEPRECATED; short flag; - short pad[3]; + short runtime_flag; + short pad[2]; ListBase layer_collections; /* synced with collection->children */ } LayerCollection; @@ -64,7 +65,8 @@ typedef struct ViewLayer { struct ViewLayer *next, *prev; char name[64]; /* MAX_NAME */ short flag; - short pad[3]; + short runtime_flag; + short pad[2]; ListBase object_bases; /* ObjectBase */ struct SceneStats *stats; /* default allocated now */ struct Base *basact; @@ -89,14 +91,15 @@ typedef struct ViewLayer { /* Base->flag */ enum { - BASE_SELECTED = (1 << 0), - BASE_VISIBLED = (1 << 1), - BASE_SELECTABLED = (1 << 2), - BASE_FROMDUPLI = (1 << 3), - BASE_DIRTY_ENGINE_SETTINGS = (1 << 4), + BASE_SELECTED = (1 << 0), /* Object is selected. */ + BASE_VISIBLED = (1 << 1), /* Object is visible. */ + BASE_SELECTABLED = (1 << 2), /* Object can be selected. */ + BASE_FROMDUPLI = (1 << 3), /* Object comes from duplicator. */ + /* BASE_DEPRECATED = (1 << 4), */ BASE_FROM_SET = (1 << 5), /* To be set only by the depsgraph */ - BASE_VISIBLE_VIEWPORT = (1 << 6), - BASE_VISIBLE_RENDER = (1 << 7), + BASE_VISIBLE_VIEWPORT = (1 << 6), /* Object is visible in viewport. */ + BASE_VISIBLE_RENDER = (1 << 7), /* Object is visible in final render */ + BASE_HIDE = (1 << 8), /* Object is hidden for editing. */ }; /* LayerCollection->flag */ @@ -108,13 +111,25 @@ enum { LAYER_COLLECTION_EXCLUDE = (1 << 4), }; +/* Layer Collection->runtime_flag */ +enum { + LAYER_COLLECTION_HAS_OBJECTS = (1 << 0), + LAYER_COLLECTION_HAS_VISIBLE_OBJECTS = (1 << 1), + LAYER_COLLECTION_HAS_ENABLED_OBJECTS = (1 << 2), +}; + /* ViewLayer->flag */ enum { VIEW_LAYER_RENDER = (1 << 0), - VIEW_LAYER_ENGINE_DIRTY = (1 << 1), + /* VIEW_LAYER_DEPRECATED = (1 << 1), */ VIEW_LAYER_FREESTYLE = (1 << 2), }; +/* ViewLayer->runtime_flag */ +enum { + VIEW_LAYER_HAS_HIDE = (1 << 0), +}; + /****************************** Deprecated ******************************/ /* Compatibility with collections saved in early 2.8 versions, diff --git a/source/blender/makesdna/DNA_material_types.h b/source/blender/makesdna/DNA_material_types.h index 64c40cc3efa..9401f591b66 100644 --- a/source/blender/makesdna/DNA_material_types.h +++ b/source/blender/makesdna/DNA_material_types.h @@ -54,20 +54,10 @@ typedef struct TexPaintSlot { int pad; } TexPaintSlot; -/* Clay engine */ - -/* MaterialRuntimeClay.flag */ -#define CLAY_OUTDATED 1 - -/* MaterialEngineSettingsClay.type */ -#define CLAY_MATCAP_NONE 0 -#define CLAY_MATCAP_SIMPLE 1 -#define CLAY_MATCAP_COMPLETE 2 - 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 flag, pad1[7]; /* Colors from Blender Internal that we are still using. */ @@ -133,7 +123,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 @@ -155,8 +145,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 diff --git a/source/blender/makesdna/DNA_mesh_types.h b/source/blender/makesdna/DNA_mesh_types.h index 48c39d439dd..247ffa4d865 100644 --- a/source/blender/makesdna/DNA_mesh_types.h +++ b/source/blender/makesdna/DNA_mesh_types.h @@ -103,7 +103,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; @@ -150,7 +150,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]; diff --git a/source/blender/makesdna/DNA_meshdata_types.h b/source/blender/makesdna/DNA_meshdata_types.h index 4014db72adf..551ba945253 100644 --- a/source/blender/makesdna/DNA_meshdata_types.h +++ b/source/blender/makesdna/DNA_meshdata_types.h @@ -421,7 +421,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 fade313e29e..c312d45567f 100644 --- a/source/blender/makesdna/DNA_meta_types.h +++ b/source/blender/makesdna/DNA_meta_types.h @@ -57,33 +57,33 @@ 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 3cf1d9f30f2..891f854c9eb 100644 --- a/source/blender/makesdna/DNA_modifier_types.h +++ b/source/blender/makesdna/DNA_modifier_types.h @@ -184,7 +184,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; @@ -636,7 +636,7 @@ typedef struct ClothModifierData { float hair_grid_max[3]; int hair_grid_res[3]; float hair_grid_cellsize; - + struct ClothSolverResult *solver_result; } ClothModifierData; @@ -984,7 +984,7 @@ typedef struct OceanModifierData { struct Ocean *ocean; struct OceanCache *oceancache; - + int resolution; int spatial_size; @@ -1583,6 +1583,7 @@ enum { enum { MOD_NORMALEDIT_INVERT_VGROUP = (1 << 0), MOD_NORMALEDIT_USE_DIRECTION_PARALLEL = (1 << 1), + MOD_NORMALEDIT_NO_POLYNORS_FIX = (1 << 2), }; /* NormalEditModifierData.mix_mode */ diff --git a/source/blender/makesdna/DNA_nla_types.h b/source/blender/makesdna/DNA_nla_types.h index 16af3bb1be4..c5e14374fb3 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; diff --git a/source/blender/makesdna/DNA_node_types.h b/source/blender/makesdna/DNA_node_types.h index 7d8d1883100..f38ae61421b 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; @@ -290,7 +290,7 @@ typedef struct bNodeInstanceKey { */ typedef struct bNodeInstanceHashEntry { bNodeInstanceKey key; - + /* tags for cleaning the cache */ short tag; short pad; @@ -299,7 +299,7 @@ typedef struct bNodeInstanceHashEntry { typedef struct bNodePreview { bNodeInstanceHashEntry hash_entry; /* must be first */ - + unsigned char *rect; short xsize, ysize; int pad; @@ -308,10 +308,10 @@ typedef struct bNodePreview { typedef struct bNodeLink { struct bNodeLink *next, *prev; - + bNode *fromnode, *tonode; bNodeSocket *fromsock, *tosock; - + int flag; int pad; } bNodeLink; @@ -338,41 +338,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) */ @@ -382,7 +382,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 @@ -391,7 +391,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 */ @@ -401,7 +401,7 @@ typedef struct bNodeTree { void *tbh, *prh, *sdh, *udh; void *duplilock; - + } bNodeTree; /* ntree->type, index */ @@ -631,7 +631,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]; @@ -698,7 +698,7 @@ typedef struct NodeColorBalance { float power[3]; float offset_basis; char _pad[4]; - + /* LGG parameters */ float lift[3]; float gamma[3]; @@ -1043,6 +1043,9 @@ typedef struct NodeSunBeams { #define SHD_SPACE_BLENDER_OBJECT 3 #define SHD_SPACE_BLENDER_WORLD 4 +#define SHD_AO_INSIDE 1 +#define SHD_AO_LOCAL 2 + /* math node clamp */ #define SHD_MATH_CLAMP 1 diff --git a/source/blender/makesdna/DNA_object_fluidsim_types.h b/source/blender/makesdna/DNA_object_fluidsim_types.h index b305235083a..b8927613a59 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; diff --git a/source/blender/makesdna/DNA_object_force_types.h b/source/blender/makesdna/DNA_object_force_types.h index a83517e4eb4..6d38e56f19a 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 */ @@ -123,7 +123,7 @@ typedef struct PartDeflect { typedef struct EffectorWeights { struct Collection *group; /* only use effectors from this group of objects */ - + float weight[14]; /* effector type specific weights */ float global_gravity; short flag, rt[3]; @@ -176,7 +176,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 @@ -201,7 +201,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]; @@ -226,9 +226,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 */ @@ -239,7 +239,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 */ @@ -252,7 +252,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 */ @@ -260,12 +260,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 */ @@ -295,7 +295,7 @@ typedef struct SoftBody { struct Collection *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]; @@ -391,9 +391,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 diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h index f37bccbfe4e..45029e8d412 100644 --- a/source/blender/makesdna/DNA_object_types.h +++ b/source/blender/makesdna/DNA_object_types.h @@ -162,10 +162,10 @@ typedef struct Object_Runtime { 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 */ @@ -180,13 +180,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 */ @@ -201,7 +201,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 */ @@ -218,18 +218,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) */ @@ -277,7 +277,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 PartDeflect *pd; /* particle deflector/attractor/collision data */ struct SoftBody *soft; /* if exists, saved in file */ struct Collection *dup_group; /* object duplicator for group */ @@ -300,7 +300,7 @@ typedef struct Object { ListBase gpulamp; /* runtime, for glsl lamp display only */ ListBase pc_ids; - + struct RigidBodyOb *rigidbody_object; /* settings for Bullet rigid body */ struct RigidBodyCon *rigidbody_constraint; /* settings for Bullet constraint */ @@ -327,13 +327,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; diff --git a/source/blender/makesdna/DNA_particle_types.h b/source/blender/makesdna/DNA_particle_types.h index 8437c93a722..a7f212a0694 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 */ @@ -301,7 +301,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; @@ -387,7 +387,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) */ @@ -422,7 +422,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_rigidbody_types.h b/source/blender/makesdna/DNA_rigidbody_types.h index 42286044970..5a7e7c92380 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 Collection *group; /* Group containing objects to use for Rigid Bodies */ struct Object **objects; /* Array to access group objects by index, only used at runtime */ - + struct Collection *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; diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h index 7d26fc6af3f..6113a7bb0f9 100644 --- a/source/blender/makesdna/DNA_scene_types.h +++ b/source/blender/makesdna/DNA_scene_types.h @@ -184,11 +184,11 @@ typedef struct AudioData { /* Render Layer */ typedef struct SceneRenderLayer { struct SceneRenderLayer *next, *prev; - + char name[64] DNA_DEPRECATED; /* MAX_NAME */ - + struct Material *mat_override DNA_DEPRECATED; /* Converted to ViewLayer override. */ - + unsigned int lay DNA_DEPRECATED; /* Converted to LayerCollection cycles camera visibility override. */ unsigned int lay_zmask DNA_DEPRECATED; /* Converted to LayerCollection cycles holdout override. */ unsigned int lay_exclude DNA_DEPRECATED; @@ -560,7 +560,7 @@ typedef enum ClayFlagSettings { typedef struct RenderData { struct ImageFormatData im_format; - + struct AviCodecData *avicodecdata; struct FFMpegCodecData ffcodecdata; @@ -576,11 +576,11 @@ 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 size; /* size in % */ - + short pad6; /* from buttons: */ @@ -599,7 +599,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. */ @@ -630,34 +630,34 @@ typedef struct RenderData { short frs_sec, pad[7]; - + /* safety, border and display rect */ rctf safety, border; rcti disprect; - + /* information on different layers to be rendered */ ListBase layers DNA_DEPRECATED; /* Converted to Scene->view_layers. */ short actlay DNA_DEPRECATED; /* Converted to Scene->active_layer. */ short pad1; - + /** * 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; - + /* Dither noise intensity */ float dither_intensity; - + /* Bake Render options */ short bake_mode, bake_flag; short bake_filter, bake_samples; @@ -735,14 +735,14 @@ typedef enum eHairType { 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; /* UV Paint */ @@ -805,7 +805,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; @@ -821,7 +821,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 */ @@ -964,10 +964,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; @@ -978,7 +978,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 */ @@ -1001,13 +1001,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; @@ -1023,10 +1023,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, @@ -1073,11 +1073,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; @@ -1213,13 +1213,14 @@ 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; float doublimit; /* remove doubles limit */ - short automerge; + char automerge; + char object_flag; /* Selection Mode for Mesh */ short selectmode; @@ -1245,22 +1246,22 @@ typedef struct ToolSettings { char gpencil_ima_align; /* : Image Editor */ char _pad3[4]; - + /* 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; @@ -1376,19 +1377,11 @@ typedef struct SceneDisplay { float light_direction[3]; /* light direction for shadows/highlight */ float shadow_shift; - int matcap_icon; - int matcap_type; - float matcap_rotation; - float matcap_hue; - float matcap_saturation; - float matcap_value; + /* Settings for Cavity Shader */ float matcap_ssao_distance; float matcap_ssao_attenuation; - float matcap_ssao_factor_cavity; - float matcap_ssao_factor_edge; - float matcap_hair_brightness_randomness; int matcap_ssao_samples; - + int pad; } SceneDisplay; typedef struct SceneEEVEE { @@ -1443,32 +1436,32 @@ typedef struct SceneEEVEE { 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 DNA_DEPRECATED; struct Base *basact DNA_DEPRECATED; /* active base */ void *_pad1; - + View3DCursor cursor; /* 3d cursor location */ - + 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 */ void *pad2; struct DisplaySafeAreas safe_areas; @@ -1488,9 +1481,9 @@ typedef struct 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 GHash *depsgraph_hash; int pad7; @@ -1501,7 +1494,7 @@ typedef struct Scene { /* Units */ struct UnitSettings unit; - + /* Grease Pencil */ struct bGPdata *gpd; @@ -1518,7 +1511,7 @@ typedef struct Scene { ColorManagedViewSettings view_settings; ColorManagedDisplaySettings display_settings; ColorManagedColorspaceSettings sequencer_colorspace_settings; - + /* RigidBody simulation world+settings */ struct RigidBodyWorld *rigidbody_world; @@ -1548,7 +1541,7 @@ typedef struct Scene { #define R_OSA 0x0001 /* #define R_SHADOW 0x0002 */ /* #define R_GAMMA 0x0004 */ -#define R_ORTHO 0x0008 +#define R_ORTHO 0x0008 /* #define R_ENVMAP 0x0010 */ /* #define R_EDGE 0x0020 */ /* #define R_FIELDS 0x0040 */ @@ -1570,7 +1563,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 */ @@ -1708,7 +1701,6 @@ enum { /* sequencer seq_prev_type seq_rend_type */ /* RenderData.engine (scene.c) */ -extern const char *RE_engine_id_BLENDER_CLAY; extern const char *RE_engine_id_BLENDER_EEVEE; extern const char *RE_engine_id_BLENDER_WORKBENCH; extern const char *RE_engine_id_CYCLES; @@ -1784,6 +1776,11 @@ enum { SCE_XFORM_AXIS_ALIGN = (1 << 0), }; +/* ToolSettings.object_flag */ +enum { + SCE_OBJECT_MODE_LOCK = (1 << 0), +}; + /* ToolSettings.snap_flag */ #define SCE_SNAP 1 #define SCE_SNAP_ROTATE 2 @@ -2034,14 +2031,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 91bf1bbddbd..500d198fa74 100644 --- a/source/blender/makesdna/DNA_screen_types.h +++ b/source/blender/makesdna/DNA_screen_types.h @@ -79,7 +79,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[3]; - + struct ARegion *active_region; /* active region that has mouse focus */ struct wmTimer *animtimer; /* if set, screen has timer handler added in window */ @@ -266,7 +266,7 @@ typedef struct ScrArea_Runtime { 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 */ @@ -287,7 +287,7 @@ typedef struct ScrArea { 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 */ /* Non-NULL if this area is global. */ @@ -309,30 +309,36 @@ typedef struct ScrArea { ScrArea_Runtime runtime; } ScrArea; + +typedef struct ARegion_Runtime { + /* Panel category to use between 'layout' and 'draw'. */ + const char *category; +} ARegion_Runtime; + 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 visible; /* region is currently visible on screen */ 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 overlap; /* private, set for indicate drawing overlapped */ short flagfullscreen; /* temporary copy of flag settings for clean fullscreen */ short pad1, pad2; - + struct ARegionType *type; /* callbacks for this region type */ - + ListBase uiblocks; /* uiBlock */ ListBase panels; /* Panel */ ListBase panels_category_active; /* Stack of panel categories */ @@ -347,6 +353,8 @@ typedef struct ARegion { char *headerstr; /* use this string to draw info */ void *regiondata; /* XXX 2.50, need spacedata equivalent? */ + + ARegion_Runtime runtime; } ARegion; /* area->flag */ @@ -455,7 +463,8 @@ enum { RGN_TYPE_UI = 4, RGN_TYPE_TOOLS = 5, RGN_TYPE_TOOL_PROPS = 6, - RGN_TYPE_PREVIEW = 7 + RGN_TYPE_PREVIEW = 7, + RGN_TYPE_HUD = 8, }; /* use for function args */ #define RGN_TYPE_ANY -1 @@ -480,7 +489,9 @@ enum { /* Force delayed reinit of region size data, so that region size is calculated * just big enough to show all its content (if enough space is available). * Note that only ED_region_header supports this right now. */ - RGN_FLAG_DYNAMIC_SIZE = (1 << 2), + RGN_FLAG_DYNAMIC_SIZE = (1 << 2), + /* Region data is NULL'd on read, never written. */ + RGN_FLAG_TEMP_REGIONDATA = (1 << 3), }; /* region do_draw */ diff --git a/source/blender/makesdna/DNA_sequence_types.h b/source/blender/makesdna/DNA_sequence_types.h index b7e118d2053..ef076c98b5f 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 47f73c6ac22..76b609b0c6c 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_space_types.h b/source/blender/makesdna/DNA_space_types.h index 18fd17c006e..4f07a30ed70 100644 --- a/source/blender/makesdna/DNA_space_types.h +++ b/source/blender/makesdna/DNA_space_types.h @@ -620,7 +620,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 8ad987818ae..f7bc3b41e55 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; diff --git a/source/blender/makesdna/DNA_text_types.h b/source/blender/makesdna/DNA_text_types.h index 163dda678d9..78902598fdb 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; } Text; diff --git a/source/blender/makesdna/DNA_texture_types.h b/source/blender/makesdna/DNA_texture_types.h index f5267f20d2c..bc0b3609a09 100644 --- a/source/blender/makesdna/DNA_texture_types.h +++ b/source/blender/makesdna/DNA_texture_types.h @@ -58,7 +58,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]; @@ -68,10 +68,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 colspecfac, mirrfac, alphafac; @@ -127,10 +127,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 */ @@ -138,27 +138,27 @@ 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; 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; @@ -184,7 +184,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 @@ -195,21 +195,21 @@ 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; struct ColorBand *coba; struct PreviewImage *preview; - + char use_nodes; char pad[7]; - + } Tex; /* used for mapping and texture nodes. note: rot is now in radians */ @@ -219,7 +219,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; @@ -337,7 +337,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 @@ -455,7 +455,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 */ diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h index 17f520fdfa9..f4e8d5e0000 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 @@ -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 */ @@ -169,7 +169,7 @@ typedef struct ThemeUI { uiWidgetColors wcol_num, wcol_numslider, wcol_tab; 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) */ @@ -179,10 +179,10 @@ typedef struct ThemeUI { /* fac: 0 - 1 for blend factor, width in pixels */ float menu_shadow_fac; short menu_shadow_width; - + char editor_outline[4]; short pad[1]; - + char iconfile[256]; // FILE_MAXFILE length float icon_alpha; float icon_saturation; @@ -209,7 +209,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 */ @@ -227,19 +227,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; @@ -247,10 +247,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]; @@ -270,58 +270,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]; @@ -329,7 +329,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 */ @@ -337,14 +337,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 */ @@ -369,10 +369,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 { @@ -384,9 +384,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; @@ -411,7 +411,7 @@ typedef struct bTheme { /* 20 sets of bone colors for this theme */ ThemeWireColor tarm[20]; /*ThemeWireColor tobj[20];*/ - + int active_theme_area, pad; } bTheme; @@ -449,7 +449,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; @@ -465,13 +465,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 pad; short wheellinescroll; int uiflag; /* eUserpref_UI_Flag */ @@ -481,7 +481,7 @@ typedef struct UserDef { short app_flag; short language; short userpref, viewzoom; - + int mixbufsize; int audiodevice; int audiorate; @@ -512,7 +512,7 @@ typedef struct UserDef { struct ListBase addons; struct ListBase autoexec_paths; char keyconfigstr[64]; - + short undosteps; short pad1; int undomemory; @@ -541,7 +541,7 @@ typedef struct UserDef { char keyhandles_new; /* handle types for newly added keyframes */ char gpu_select_method; char gpu_select_pick_deph; - char pad4; + char gpu_viewport_antialias; char view_frame_type; /* eZoomFrame_Mode */ int view_frame_keyframes; /* number of keyframes to zoom around current frame */ @@ -549,7 +549,7 @@ typedef struct UserDef { short scrcastfps; /* frame rate for screencast to be played back */ short scrcastwait; /* milliseconds between screencast snapshots */ - + short widget_unit; /* private, defaults to 20 for 72 DPI setting */ short anisotropic_filter; short use_16bit_textures, use_gpu_mipmap; @@ -563,12 +563,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 */ @@ -586,7 +586,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 */ short pie_interaction_type; /* if keeping a pie menu spawn button pressed after this time, it turns into @@ -736,7 +736,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 @@ -759,7 +759,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), @@ -802,6 +802,12 @@ typedef enum eOpenGL_SelectOptions { USER_SELECT_USE_SELECT_RENDERMODE = 2 } eOpenGL_SelectOptions; +/* max anti alias draw method UserDef.gpu_viewport_antialias */ +typedef enum eOpenGL_AntiAliasMethod { + USER_AA_NONE = 0, + USER_AA_FXAA = 1, +} eOpenGL_AntiAliasMethod; + /* text draw options * UserDef.text_render */ typedef enum eText_Draw_Options { @@ -837,7 +843,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_vfont_types.h b/source/blender/makesdna/DNA_vfont_types.h index 7025a5767c4..721a97742b9 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 a0480aa361b..dce78638328 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 */ diff --git a/source/blender/makesdna/DNA_view3d_types.h b/source/blender/makesdna/DNA_view3d_types.h index 9686981d674..b7ad9f7d921 100644 --- a/source/blender/makesdna/DNA_view3d_types.h +++ b/source/blender/makesdna/DNA_view3d_types.h @@ -62,7 +62,7 @@ struct GPUViewport; #endif typedef struct RegionView3D { - + float winmat[4][4]; /* GL_PROJECTION matrix */ float viewmat[4][4]; /* GL_MODELVIEW matrix */ float viewinv[4][4]; /* inverse of viewmat */ @@ -193,24 +193,24 @@ 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; 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; - + short ob_centre_cursor; /* optional bool for 3d cursor to define center */ short scenelock, _pad1; short flag, flag2, pad2; - + float lens, grid; float near, far; float ofs[3] DNA_DEPRECATED; /* XXX deprecated */ @@ -227,7 +227,7 @@ typedef struct View3D { /* transform manipulator info */ char twtype, _pad5, twflag; - + short flag3; /* drawflags, denoting state */ diff --git a/source/blender/makesdna/DNA_windowmanager_types.h b/source/blender/makesdna/DNA_windowmanager_types.h index 6d5d2c380e2..19d4ab10165 100644 --- a/source/blender/makesdna/DNA_windowmanager_types.h +++ b/source/blender/makesdna/DNA_windowmanager_types.h @@ -239,7 +239,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 */ # # @@ -377,11 +377,6 @@ typedef struct wmOperator { struct wmOperator *opm; /* current running macro, not saved */ struct uiLayout *layout; /* runtime for drawing */ short flag, pad[3]; - - /* Screen context the operator was finished in. It gets temporarily - * restored during operator repeat. Only set for registered operators. */ - struct ScrArea *execution_area; - struct ARegion *execution_region; } wmOperator; /* operator type return flags: exec(), invoke() modal(), return values */ diff --git a/source/blender/makesdna/DNA_world_types.h b/source/blender/makesdna/DNA_world_types.h index 84050894faa..38bfb20581b 100644 --- a/source/blender/makesdna/DNA_world_types.h +++ b/source/blender/makesdna/DNA_world_types.h @@ -50,7 +50,7 @@ struct MTex; * gravity, color model etc. It mixes rendering 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) */ char _pad0[4]; short texact, mistype; @@ -64,7 +64,7 @@ typedef struct World { */ float exposure, exp, range; float linfac, logfac; - + /** * Some world modes * bit 0: Do mist @@ -76,10 +76,10 @@ typedef struct World { /* ambient occlusion */ float aodist, aoenergy; - + /* assorted settings */ short flag, pad3[3]; - + struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ short pr_texture, use_nodes, pad; short update_flag; /* XXX temporary flag waiting for depsgraph proper tagging */ @@ -114,7 +114,7 @@ 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) diff --git a/source/blender/makesdna/intern/dna_genfile.c b/source/blender/makesdna/intern/dna_genfile.c index 9c44d60b7c2..257c57e5a9a 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]]); } @@ -364,7 +364,7 @@ static bool init_structDNA( int *data, *verg, gravity_fix = -1; short *sp; char str[8]; - + verg = (int *)str; data = (int *)sdna->data; @@ -385,17 +385,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"); } @@ -407,7 +407,7 @@ static bool init_structDNA( /* Temporary DNA doversion for files that were created with Blender 2.80 * between 280.0 and 280.2. */ const bool doversion_280 = need_doversion_280(sdna, data, data_alloc); - + cp = (char *)data; for (int nr = 0; nr < sdna->nr_names; nr++) { sdna->names[nr] = cp; @@ -449,7 +449,7 @@ static bool init_structDNA( } cp = pad_up_4(cp); - + /* load type names array */ data = (int *)cp; strcpy(str, "TYPE"); @@ -460,7 +460,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"); } @@ -468,14 +468,14 @@ 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) */ - + /* struct Screen was already used by X, 'bScreen' replaces the old IrisGL 'Screen' struct */ if (strcmp("bScreen", cp) == 0) { sdna->types[nr] = cp + 1; @@ -495,13 +495,13 @@ static bool init_structDNA( sdna->types[nr] = "ViewLayerEngineData"; } } - + while (*cp) cp++; cp++; } cp = pad_up_4(cp); - + /* load typelen array */ data = (int *)cp; strcpy(str, "TLEN"); @@ -509,11 +509,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 { @@ -527,12 +527,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"); } @@ -540,17 +540,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--) { @@ -635,7 +635,7 @@ SDNA *DNA_sdna_from_data( sdna->data = data; } sdna->data_alloc = data_alloc; - + if (init_structDNA(sdna, do_endian_swap, data_alloc, &error_message)) { return sdna; @@ -689,11 +689,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]; @@ -710,7 +710,7 @@ static void recurs_test_compflags(const SDNA *sdna, char *compflags, int structn } } } - + } @@ -724,7 +724,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; @@ -732,14 +732,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); @@ -750,7 +750,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]]) { @@ -784,7 +784,7 @@ const char *DNA_struct_get_compareflags(const SDNA *oldsdna, const SDNA *newsdna } } - + } } @@ -801,7 +801,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) { @@ -884,7 +884,7 @@ static void cast_elem( case SDNA_TYPE_UINT64: val = *( (uint64_t *)olddata); break; } - + switch (ctypenr) { case SDNA_TYPE_CHAR: *curdata = val; break; @@ -929,11 +929,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); } @@ -952,7 +952,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--; @@ -966,7 +966,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; @@ -999,9 +999,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; @@ -1017,10 +1017,10 @@ static const char *find_elem( if (sppo) *sppo = old; return olddata; } - + return NULL; } - + olddata += len; } return NULL; @@ -1058,7 +1058,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; @@ -1066,7 +1066,7 @@ static void reconstruct_elem( cp++; countpos++; } if (*cp != '[') countpos = 0; - + /* in old is the old struct */ elemcount = old[1]; old += 2; @@ -1074,9 +1074,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); } @@ -1092,7 +1092,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); @@ -1105,7 +1105,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'; @@ -1169,7 +1169,7 @@ static void reconstruct_struct( spo = oldsdna->structs[oldSDNAnr]; elen = oldsdna->typelens[spo[0]]; memcpy(cur, data, elen); - + return; } @@ -1185,7 +1185,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? */ @@ -1193,26 +1193,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; @@ -1250,18 +1250,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]); @@ -1272,7 +1272,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; @@ -1338,7 +1338,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]]; @@ -1387,11 +1387,11 @@ 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) { return true; } diff --git a/source/blender/makesdna/intern/makesdna.c b/source/blender/makesdna/intern/makesdna.c index b0da028127c..a1bfac66115 100644 --- a/source/blender/makesdna/intern/makesdna.c +++ b/source/blender/makesdna/intern/makesdna.c @@ -226,7 +226,7 @@ static int add_type(const char *str, int len) { int nr; char *cp; - + /* first do validity check */ if (str[0] == 0) { return -1; @@ -236,7 +236,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) { @@ -248,7 +248,7 @@ static int add_type(const char *str, int len) return nr; } } - + /* append new type */ if (nr_types == 0) { cp = typedata; @@ -261,13 +261,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; } @@ -288,7 +288,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] == '*') { @@ -306,7 +306,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. */ @@ -322,7 +322,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) { @@ -332,7 +332,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] != ')') { @@ -349,7 +349,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...) @@ -363,7 +363,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) ) { @@ -390,14 +390,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; @@ -407,13 +407,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; } @@ -430,16 +430,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; } @@ -447,14 +447,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; @@ -470,7 +470,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; @@ -479,7 +479,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; @@ -522,7 +522,7 @@ static int preprocess_include(char *maindata, int len) } cp++; } - + MEM_freeN(temp); return newlen; } @@ -563,7 +563,7 @@ static void *read_file_data(const char *filename, int *r_len) fclose(fp); return NULL; } - + fclose(fp); return data; } @@ -577,7 +577,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); @@ -591,12 +591,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) { @@ -607,7 +607,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) { @@ -626,22 +626,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) { @@ -653,11 +653,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 @@ -676,11 +676,11 @@ static int convert_include(const char *filename) structpoin[1]++; sp += 2; - + md1 += slen; break; } - + name = add_name(md1); slen += additional_slen_offset; @@ -691,7 +691,7 @@ static int convert_include(const char *filename) structpoin[1]++; sp += 2; - + md1 += slen; } md1++; @@ -708,7 +708,7 @@ static int convert_include(const char *filename) count++; md++; } - + MEM_freeN(maindata); return 0; @@ -718,7 +718,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]); @@ -729,7 +729,7 @@ static int arraysize(const char *str) mul *= atoi(cp); } } - + return mul; } @@ -763,7 +763,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]; @@ -771,13 +771,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]; @@ -849,7 +849,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; @@ -861,7 +861,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; @@ -870,7 +870,7 @@ static int calculate_structlens(int firststruct) break; } } - + if (len_native == 0) { unknown++; } @@ -887,30 +887,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]); @@ -918,9 +918,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]; @@ -946,7 +946,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++; @@ -967,7 +967,7 @@ void printStructLengths(void) while (unknown) { /*lastunknown = unknown;*/ /*UNUSED*/ unknown = 0; - + /* check all structs... */ for (a = 0; a < nr_structs; a++) { structpoin = structs[a]; @@ -989,17 +989,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"); @@ -1034,12 +1034,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); @@ -1047,7 +1047,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 */ @@ -1065,13 +1065,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]]); @@ -1087,63 +1087,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 */ @@ -1171,7 +1171,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 */ { @@ -1185,7 +1185,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); @@ -1197,7 +1197,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs MEM_freeN(structs); if (debugSDNA > 0) printf("done.\n"); - + return(0); } @@ -1265,7 +1265,7 @@ int main(int argc, char **argv) } } - + return(return_status); } @@ -1308,14 +1308,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 2582af767be..75d1a328977 100644 --- a/source/blender/makesrna/RNA_access.h +++ b/source/blender/makesrna/RNA_access.h @@ -594,6 +594,7 @@ extern StructRNA RNA_StretchToConstraint; extern StructRNA RNA_StringProperty; extern StructRNA RNA_Struct; extern StructRNA RNA_StucciTexture; +extern StructRNA RNA_StudioLight; extern StructRNA RNA_SubsurfModifier; extern StructRNA RNA_SunLamp; extern StructRNA RNA_SurfaceCurve; diff --git a/source/blender/makesrna/intern/CMakeLists.txt b/source/blender/makesrna/intern/CMakeLists.txt index 134ec2cc170..2288e6c8405 100644 --- a/source/blender/makesrna/intern/CMakeLists.txt +++ b/source/blender/makesrna/intern/CMakeLists.txt @@ -187,10 +187,6 @@ if(WITH_PYTHON) ) endif() -if(WITH_CLAY_ENGINE) - add_definitions(-DWITH_CLAY_ENGINE) -endif() - if(WITH_IMAGE_OPENEXR) add_definitions(-DWITH_OPENEXR) endif() diff --git a/source/blender/makesrna/intern/rna_gpencil.c b/source/blender/makesrna/intern/rna_gpencil.c index 51aed1ff296..cd7081d07a8 100644 --- a/source/blender/makesrna/intern/rna_gpencil.c +++ b/source/blender/makesrna/intern/rna_gpencil.c @@ -1271,7 +1271,7 @@ static void rna_def_gpencil_layer(BlenderRNA *brna) /* Flags */ prop = RNA_def_property(srna, "hide", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", GP_LAYER_HIDE); - RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, 1); + RNA_def_property_ui_icon(prop, ICON_HIDE_OFF, 1); RNA_def_property_ui_text(prop, "Hide", "Set layer Visibility"); RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update"); @@ -1457,7 +1457,7 @@ static void rna_def_gpencil_palettecolor(BlenderRNA *brna) /* Flags */ prop = RNA_def_property(srna, "hide", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", PC_COLOR_HIDE); - RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, 1); + RNA_def_property_ui_icon(prop, ICON_HIDE_OFF, 1); RNA_def_property_ui_text(prop, "Hide", "Set color Visibility"); RNA_def_property_update(prop, NC_GPENCIL | ND_DATA, "rna_GPencil_update"); diff --git a/source/blender/makesrna/intern/rna_group.c b/source/blender/makesrna/intern/rna_group.c index de6c6883977..7266c7578c8 100644 --- a/source/blender/makesrna/intern/rna_group.c +++ b/source/blender/makesrna/intern/rna_group.c @@ -260,21 +260,21 @@ void RNA_def_collections(BlenderRNA *brna) RNA_def_property_boolean_sdna(prop, NULL, "flag", COLLECTION_RESTRICT_SELECT); RNA_def_property_override_flag(prop, PROPOVERRIDE_OVERRIDABLE_STATIC); RNA_def_property_ui_icon(prop, ICON_RESTRICT_SELECT_OFF, 1); - RNA_def_property_ui_text(prop, "Restrict Select", "Disable collection object selection in the 3D viewport"); + RNA_def_property_ui_text(prop, "Restrict Select", "Disable collection for viewport selection"); RNA_def_property_update(prop, NC_SCENE | ND_LAYER_CONTENT, "rna_Collection_flag_update"); prop = RNA_def_property(srna, "hide_viewport", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", COLLECTION_RESTRICT_VIEW); RNA_def_property_override_flag(prop, PROPOVERRIDE_OVERRIDABLE_STATIC); RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, 1); - RNA_def_property_ui_text(prop, "Restrict Viewport", "Hide collection objects in the 3D viewport"); + RNA_def_property_ui_text(prop, "Restrict Viewport", "Disable collection in viewport"); RNA_def_property_update(prop, NC_SCENE | ND_LAYER_CONTENT, "rna_Collection_flag_update"); prop = RNA_def_property(srna, "hide_render", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", COLLECTION_RESTRICT_RENDER); RNA_def_property_override_flag(prop, PROPOVERRIDE_OVERRIDABLE_STATIC); RNA_def_property_ui_icon(prop, ICON_RESTRICT_RENDER_OFF, 1); - RNA_def_property_ui_text(prop, "Restrict Render", "Hide collection objects in renders"); + RNA_def_property_ui_text(prop, "Restrict Render", "Disable collection in renders"); RNA_def_property_update(prop, NC_SCENE | ND_LAYER_CONTENT, "rna_Collection_flag_update"); } diff --git a/source/blender/makesrna/intern/rna_image.c b/source/blender/makesrna/intern/rna_image.c index cf486ee399f..e71bd52593e 100644 --- a/source/blender/makesrna/intern/rna_image.c +++ b/source/blender/makesrna/intern/rna_image.c @@ -67,6 +67,7 @@ static const EnumPropertyItem image_source_items[] = { #include "BKE_global.h" #include "GPU_draw.h" +#include "GPU_texture.h" #include "IMB_imbuf.h" #include "IMB_imbuf_types.h" @@ -298,6 +299,13 @@ static void rna_Image_resolution_set(PointerRNA *ptr, const float *values) BKE_image_release_ibuf(im, ibuf, lock); } +static int rna_Image_bindcode_get(PointerRNA *ptr) +{ + Image *ima = (Image *)ptr->data; + GPUTexture *tex = ima->gputexture[TEXTARGET_TEXTURE_2D]; + return (tex) ? GPU_texture_opengl_bindcode(tex) : 0; +} + static int rna_Image_depth_get(PointerRNA *ptr) { Image *im = (Image *)ptr->data; @@ -454,16 +462,19 @@ static PointerRNA rna_Image_packed_file_get(PointerRNA *ptr) } } -static void rna_Image_render_slots_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) +static void rna_RenderSlot_clear(ID *id, RenderSlot *slot, ImageUser *iuser) { - Image *image = (Image *)ptr->id.data; - rna_iterator_array_begin(iter, (void *)image->render_slots, sizeof(RenderSlot), IMA_MAX_RENDER_SLOT, 0, NULL); + Image *image = (Image *) id; + int index = BLI_findindex(&image->renderslots, slot); + BKE_image_clear_renderslot(image, iuser, index); + + WM_main_add_notifier(NC_IMAGE | ND_DISPLAY, image); } static PointerRNA rna_render_slots_active_get(PointerRNA *ptr) { Image *image = (Image *)ptr->id.data; - RenderSlot *render_slot = &image->render_slots[image->render_slot]; + RenderSlot *render_slot = BKE_image_get_renderslot(image, image->render_slot); return rna_pointer_inherit_refine(ptr, &RNA_RenderSlot, render_slot); } @@ -472,9 +483,9 @@ static void rna_render_slots_active_set(PointerRNA *ptr, PointerRNA value) { Image *image = (Image *)ptr->id.data; if (value.id.data == image) { - RenderSlot *render_slot = (RenderSlot *)value.data; - int index = render_slot - image->render_slots; - image->render_slot = CLAMPIS(index, 0, IMA_MAX_RENDER_SLOT - 1); + RenderSlot *slot = (RenderSlot *)value.data; + int index = BLI_findindex(&image->renderslots, slot); + if (index != -1) image->render_slot = index; } } @@ -487,8 +498,17 @@ static int rna_render_slots_active_index_get(PointerRNA *ptr) static void rna_render_slots_active_index_set(PointerRNA *ptr, int value) { Image *image = (Image *)ptr->id.data; + int num_slots = BLI_listbase_count(&image->renderslots); image->render_slot = value; - CLAMP(image->render_slot, 0, IMA_MAX_RENDER_SLOT - 1); + CLAMP(image->render_slot, 0, num_slots - 1); +} + +static void rna_render_slots_active_index_range(PointerRNA *ptr, int *min, int *max, + int *UNUSED(softmin), int *UNUSED(softmax)) +{ + Image *image = (Image *)ptr->id.data; + *min = 0; + *max = max_ii(0, BLI_listbase_count(&image->renderslots) - 1); } #else @@ -588,7 +608,9 @@ static void rna_def_image_packed_files(BlenderRNA *brna) static void rna_def_render_slot(BlenderRNA *brna) { StructRNA *srna; - PropertyRNA *prop; + PropertyRNA *prop, *parm; + FunctionRNA *func; + srna = RNA_def_struct(brna, "RenderSlot", NULL); RNA_def_struct_ui_text(srna, "Render Slot", "Parameters defining the render slot"); @@ -596,32 +618,45 @@ static void rna_def_render_slot(BlenderRNA *brna) RNA_def_property_string_sdna(prop, NULL, "name"); RNA_def_property_ui_text(prop, "Name", "Render slot name"); RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, NULL); + + func = RNA_def_function(srna, "clear", "rna_RenderSlot_clear"); + RNA_def_function_flag(func, FUNC_USE_SELF_ID); + RNA_def_function_ui_description(func, "Clear the render slot"); + parm = RNA_def_pointer(func, "iuser", "ImageUser", "ImageUser", ""); + RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); } -static void rna_def_render_slots(BlenderRNA *brna) +static void rna_def_render_slots(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; - PropertyRNA *prop; + FunctionRNA *func; + PropertyRNA *prop, *parm; + RNA_def_property_srna(cprop, "RenderSlots"); srna = RNA_def_struct(brna, "RenderSlots", NULL); - RNA_def_struct_sdna(srna, "RenderSlot"); - RNA_def_struct_ui_text(srna, "Render Slots", "Collection of the render slots"); + RNA_def_struct_sdna(srna, "Image"); + RNA_def_struct_ui_text(srna, "Render Layers", "Collection of render layers"); + + prop = RNA_def_property(srna, "active_index", PROP_INT, PROP_UNSIGNED); + RNA_def_property_int_sdna(prop, NULL, "render_slot"); + RNA_def_property_int_funcs(prop, "rna_render_slots_active_index_get", + "rna_render_slots_active_index_set", + "rna_render_slots_active_index_range"); + RNA_def_property_ui_text(prop, "Active", "Active render slot of the image"); + RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, NULL); prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "RenderSlot"); RNA_def_property_pointer_funcs(prop, "rna_render_slots_active_get", "rna_render_slots_active_set", NULL, NULL); - RNA_def_property_flag(prop, PROP_EDITABLE | PROP_NEVER_UNLINK); + RNA_def_property_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Active", "Active render slot of the image"); RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, NULL); - prop = RNA_def_property(srna, "active_index", PROP_INT, PROP_NONE); - RNA_def_property_int_funcs(prop, "rna_render_slots_active_index_get", - "rna_render_slots_active_index_set", - NULL); - RNA_def_property_range(prop, 0, IMA_MAX_RENDER_SLOT); - RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); - RNA_def_property_ui_text(prop, "Active Index", "Index of an active render slot of the image"); - RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, NULL); + func = RNA_def_function(srna, "new", "BKE_image_add_renderslot"); + RNA_def_function_ui_description(func, "Add a render slot to the image"); + parm = RNA_def_string(func, "name", NULL, 0, "Name", "New name for the render slot"); + parm = RNA_def_pointer(func, "result", "RenderSlot", "", "Newly created render layer"); + RNA_def_function_return(func, parm); } static void rna_def_image(BlenderRNA *brna) @@ -796,17 +831,16 @@ static void rna_def_image(BlenderRNA *brna) RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, NULL); prop = RNA_def_property(srna, "bindcode", PROP_INT, PROP_UNSIGNED); - RNA_def_property_int_sdna(prop, NULL, "bindcode"); + RNA_def_property_int_funcs(prop, "rna_Image_bindcode_get", NULL, NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Bindcode", "OpenGL bindcode"); RNA_def_property_update(prop, NC_IMAGE | ND_DISPLAY, NULL); prop = RNA_def_property(srna, "render_slots", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "RenderSlot"); + RNA_def_property_collection_sdna(prop, NULL, "renderslots", NULL); RNA_def_property_ui_text(prop, "Render Slots", "Render slots of the image"); - RNA_def_property_collection_funcs(prop, "rna_Image_render_slots_begin", "rna_iterator_array_next", - "rna_iterator_array_end", "rna_iterator_array_get", NULL, NULL, NULL, NULL); - RNA_def_property_srna(prop, "RenderSlots"); + rna_def_render_slots(brna, prop); /* * Image.has_data and Image.depth are temporary, @@ -889,7 +923,6 @@ static void rna_def_image(BlenderRNA *brna) void RNA_def_image(BlenderRNA *brna) { rna_def_render_slot(brna); - rna_def_render_slots(brna); rna_def_image(brna); rna_def_imageuser(brna); rna_def_image_packed_files(brna); diff --git a/source/blender/makesrna/intern/rna_image_api.c b/source/blender/makesrna/intern/rna_image_api.c index 39164430140..d839995d15e 100644 --- a/source/blender/makesrna/intern/rna_image_api.c +++ b/source/blender/makesrna/intern/rna_image_api.c @@ -220,29 +220,30 @@ static void rna_Image_scale(Image *image, ReportList *reports, int width, int he static int rna_Image_gl_load(Image *image, ReportList *reports, int frame, int filter, int mag) { - ImBuf *ibuf; - unsigned int *bind = &image->bindcode[TEXTARGET_TEXTURE_2D]; + GPUTexture *tex = image->gputexture[TEXTARGET_TEXTURE_2D]; int error = GL_NO_ERROR; - ImageUser iuser = {NULL}; - void *lock; - if (*bind) + if (tex) return error; + + ImageUser iuser = {NULL}; iuser.framenr = frame; iuser.ok = true; - ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock); + void *lock; + ImBuf *ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock); /* clean glError buffer */ while (glGetError() != GL_NO_ERROR) {} 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; } - GPU_create_gl_tex(bind, ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y, GL_TEXTURE_2D, + unsigned int bindcode = 0; + GPU_create_gl_tex(&bindcode, ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y, GL_TEXTURE_2D, (filter != GL_NEAREST && filter != GL_LINEAR), false, image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLint)filter); @@ -253,23 +254,24 @@ static int rna_Image_gl_load(Image *image, ReportList *reports, int frame, int f error = glGetError(); if (error) { - glDeleteTextures(1, (GLuint *)bind); - image->bindcode[TEXTARGET_TEXTURE_2D] = 0; + glDeleteTextures(1, (GLuint *)&bindcode); + } + else { + image->gputexture[TEXTARGET_TEXTURE_2D] = GPU_texture_from_bindcode(GL_TEXTURE_2D, bindcode); } - BKE_image_release_ibuf(image, ibuf, NULL); + BKE_image_release_ibuf(image, ibuf, lock); return error; } static int rna_Image_gl_touch(Image *image, ReportList *reports, int frame, int filter, int mag) { - unsigned int *bind = &image->bindcode[TEXTARGET_TEXTURE_2D]; int error = GL_NO_ERROR; BKE_image_tag_time(image); - if (*bind == 0) + if (image->gputexture[TEXTARGET_TEXTURE_2D] == NULL) error = rna_Image_gl_load(image, reports, frame, filter, mag); return error; diff --git a/source/blender/makesrna/intern/rna_key.c b/source/blender/makesrna/intern/rna_key.c index 11fb5f7f94b..05efe350a2f 100644 --- a/source/blender/makesrna/intern/rna_key.c +++ b/source/blender/makesrna/intern/rna_key.c @@ -722,7 +722,7 @@ static void rna_def_keyblock(BlenderRNA *brna) prop = RNA_def_property(srna, "mute", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", KEYBLOCK_MUTE); RNA_def_property_ui_text(prop, "Mute", "Mute this shape key"); - RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, 1); + RNA_def_property_ui_icon(prop, ICON_HIDE_OFF, 1); RNA_def_property_update(prop, 0, "rna_Key_update_data"); prop = RNA_def_property(srna, "slider_min", PROP_FLOAT, PROP_NONE); diff --git a/source/blender/makesrna/intern/rna_main_api.c b/source/blender/makesrna/intern/rna_main_api.c index 331bf4a580d..6ff3849e295 100644 --- a/source/blender/makesrna/intern/rna_main_api.c +++ b/source/blender/makesrna/intern/rna_main_api.c @@ -1642,7 +1642,7 @@ void RNA_def_main_gpencil(BlenderRNA *brna, PropertyRNA *cprop) RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); func = RNA_def_function(srna, "new", "BKE_gpencil_data_addnew"); - RNA_def_function_flag(func, FUNC_NO_SELF); + RNA_def_function_flag(func, FUNC_NO_SELF | FUNC_USE_MAIN); parm = RNA_def_string(func, "name", "GreasePencil", 0, "", "New name for the data-block"); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); /* return type */ diff --git a/source/blender/makesrna/intern/rna_modifier.c b/source/blender/makesrna/intern/rna_modifier.c index 568b5b81ade..c29e40cba56 100644 --- a/source/blender/makesrna/intern/rna_modifier.c +++ b/source/blender/makesrna/intern/rna_modifier.c @@ -45,7 +45,6 @@ #include "BKE_animsys.h" #include "BKE_data_transfer.h" -#include "BKE_DerivedMesh.h" #include "BKE_dynamicpaint.h" #include "BKE_effect.h" #include "BKE_mesh_mapping.h" @@ -288,6 +287,7 @@ const EnumPropertyItem rna_enum_axis_flag_xyz_items[] = { #include "BKE_cachefile.h" #include "BKE_context.h" #include "BKE_library.h" +#include "BKE_mesh_runtime.h" #include "BKE_modifier.h" #include "BKE_object.h" #include "BKE_particle.h" @@ -905,6 +905,9 @@ static const EnumPropertyItem *rna_DataTransferModifier_layers_select_src_itemf( return rna_enum_dt_layers_select_src_items; } + Depsgraph *depsgraph= CTX_data_depsgraph(C); + Scene *scene = CTX_data_scene(C); + /* No active here! */ RNA_enum_items_add_value(&item, &totitem, rna_enum_dt_layers_select_src_items, DT_LAYERS_ALL_SRC); @@ -938,22 +941,18 @@ static const EnumPropertyItem *rna_DataTransferModifier_layers_select_src_itemf( Object *ob_src = dtmd->ob_source; if (ob_src) { - DerivedMesh *dm_src; - CustomData *ldata; + Mesh *me_eval; int num_data, i; - dm_src = object_get_derived_final(ob_src, false); - if (dm_src != NULL) { - ldata = dm_src->getLoopDataLayout(dm_src); - num_data = CustomData_number_of_layers(ldata, CD_MLOOPUV); + me_eval = mesh_get_eval_final(depsgraph, scene, ob_src, CD_MASK_BAREMESH | CD_MLOOPUV); + num_data = CustomData_number_of_layers(&me_eval->ldata, CD_MLOOPUV); - RNA_enum_item_add_separator(&item, &totitem); + RNA_enum_item_add_separator(&item, &totitem); - for (i = 0; i < num_data; i++) { - tmp_item.value = i; - tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(ldata, CD_MLOOPUV, i); - RNA_enum_item_add(&item, &totitem, &tmp_item); - } + for (i = 0; i < num_data; i++) { + tmp_item.value = i; + tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(&me_eval->ldata, CD_MLOOPUV, i); + RNA_enum_item_add(&item, &totitem, &tmp_item); } } } @@ -961,22 +960,18 @@ static const EnumPropertyItem *rna_DataTransferModifier_layers_select_src_itemf( Object *ob_src = dtmd->ob_source; if (ob_src) { - DerivedMesh *dm_src; - CustomData *ldata; + Mesh *me_eval; int num_data, i; - dm_src = object_get_derived_final(ob_src, false); - if (dm_src != NULL) { - ldata = dm_src->getLoopDataLayout(dm_src); - num_data = CustomData_number_of_layers(ldata, CD_MLOOPCOL); + me_eval = mesh_get_eval_final(depsgraph, scene, ob_src, CD_MASK_BAREMESH | CD_MLOOPCOL); + num_data = CustomData_number_of_layers(&me_eval->ldata, CD_MLOOPCOL); - RNA_enum_item_add_separator(&item, &totitem); + RNA_enum_item_add_separator(&item, &totitem); - for (i = 0; i < num_data; i++) { - tmp_item.value = i; - tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(ldata, CD_MLOOPCOL, i); - RNA_enum_item_add(&item, &totitem, &tmp_item); - } + for (i = 0; i < num_data; i++) { + tmp_item.value = i; + tmp_item.identifier = tmp_item.name = CustomData_get_layer_name(&me_eval->ldata, CD_MLOOPCOL, i); + RNA_enum_item_add(&item, &totitem, &tmp_item); } } } @@ -4876,6 +4871,14 @@ static void rna_def_modifier_normaledit(BlenderRNA *brna) RNA_def_property_subtype(prop, PROP_ANGLE); RNA_def_property_update(prop, 0, "rna_Modifier_update"); + prop = RNA_def_property(srna, "no_polynors_fix", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_NORMALEDIT_NO_POLYNORS_FIX); + RNA_def_property_boolean_default(prop, false); + RNA_def_property_ui_text(prop, "Lock Polygon Normals", + "Do not flip polygons when their normals are not consistent " + "with their newly computed custom vertex normals"); + RNA_def_property_update(prop, 0, "rna_Modifier_update"); + prop = RNA_def_property(srna, "vertex_group", PROP_STRING, PROP_NONE); RNA_def_property_string_sdna(prop, NULL, "defgrp_name"); RNA_def_property_ui_text(prop, "Vertex Group", "Vertex group name for selecting/weighting the affected areas"); diff --git a/source/blender/makesrna/intern/rna_nodetree.c b/source/blender/makesrna/intern/rna_nodetree.c index 3790dffec3b..56065df45bb 100644 --- a/source/blender/makesrna/intern/rna_nodetree.c +++ b/source/blender/makesrna/intern/rna_nodetree.c @@ -4398,6 +4398,27 @@ static void def_sh_bevel(StructRNA *srna) RNA_def_property_update(prop, 0, "rna_Node_update"); } +static void def_sh_ambient_occlusion(StructRNA *srna) +{ + PropertyRNA *prop; + + prop = RNA_def_property(srna, "samples", PROP_INT, PROP_UNSIGNED); + RNA_def_property_int_sdna(prop, NULL, "custom1"); + RNA_def_property_range(prop, 1, 128); + RNA_def_property_ui_text(prop, "Samples", "Number of rays to trace per shader evaluation"); + RNA_def_property_update(prop, 0, "rna_Node_update"); + + prop = RNA_def_property(srna, "inside", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_sdna(prop, NULL, "custom2", SHD_AO_INSIDE); + RNA_def_property_ui_text(prop, "Inside", "Trace rays towards the inside of the object"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update"); + + prop = RNA_def_property(srna, "only_local", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_sdna(prop, NULL, "custom2", SHD_AO_LOCAL); + RNA_def_property_ui_text(prop, "Only Local", "Only consider the object itself when computing AO"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update"); +} + static void def_sh_subsurface(StructRNA *srna) { static const EnumPropertyItem prop_subsurface_falloff_items[] = { diff --git a/source/blender/makesrna/intern/rna_object.c b/source/blender/makesrna/intern/rna_object.c index 28e13790d5c..73a2b293c22 100644 --- a/source/blender/makesrna/intern/rna_object.c +++ b/source/blender/makesrna/intern/rna_object.c @@ -46,6 +46,7 @@ #include "BKE_paint.h" #include "BKE_editlattice.h" #include "BKE_editmesh.h" +#include "BKE_layer.h" #include "BKE_object_deform.h" #include "BKE_object_facemap.h" @@ -219,9 +220,12 @@ static void rna_Object_matrix_world_update(Main *bmain, Scene *scene, PointerRNA rna_Object_internal_update(bmain, scene, ptr); } -static void rna_Object_hide_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) +static void rna_Object_hide_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *ptr) { - DEG_id_type_tag(bmain, ID_OB); + Object *ob = ptr->id.data; + BKE_main_collection_sync(bmain); + DEG_relations_tag_update(bmain); + WM_main_add_notifier(NC_OBJECT | ND_DRAW, &ob->id); } static void rna_Object_matrix_local_get(PointerRNA *ptr, float values[16]) @@ -278,7 +282,7 @@ static void rna_Object_active_shape_update(bContext *C, PointerRNA *ptr) /* exit/enter editmode to get new shape */ switch (ob->type) { case OB_MESH: - EDBM_mesh_load(ob); + EDBM_mesh_load(bmain, ob); EDBM_mesh_make(ob, scene->toolsettings->selectmode, true); DEG_id_tag_update(ob->data, 0); @@ -894,12 +898,27 @@ static int rna_Object_rotation_4d_editable(PointerRNA *ptr, int index) return PROP_EDITABLE; } +static int rna_MaterialSlot_material_editable(PointerRNA *ptr, const char **UNUSED(r_info)) +{ + Object *ob = (Object *)ptr->id.data; + const int index = (Material **)ptr->data - ob->mat; + bool is_editable; + + if ((ob->matbits == NULL) || ob->matbits[index]) { + is_editable = !ID_IS_LINKED(ob); + } + else { + is_editable = ob->data ? !ID_IS_LINKED(ob->data) : false; + } + + return is_editable ? PROP_EDITABLE : 0; +} static PointerRNA rna_MaterialSlot_material_get(PointerRNA *ptr) { Object *ob = (Object *)ptr->id.data; Material *ma; - int index = (Material **)ptr->data - ob->mat; + const int index = (Material **)ptr->data - ob->mat; ma = give_current_material(ob, index + 1); return rna_pointer_inherit_refine(ptr, &RNA_Material, ma); @@ -1566,6 +1585,7 @@ static void rna_def_material_slot(BlenderRNA *brna) prop = RNA_def_property(srna, "material", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "Material"); RNA_def_property_flag(prop, PROP_EDITABLE); + RNA_def_property_editable_func(prop, "rna_MaterialSlot_material_editable"); RNA_def_property_override_flag(prop, PROPOVERRIDE_OVERRIDABLE_STATIC); RNA_def_property_pointer_funcs(prop, "rna_MaterialSlot_material_get", "rna_MaterialSlot_material_set", NULL, NULL); RNA_def_property_ui_text(prop, "Material", "Material data-block used by this material slot"); @@ -1985,6 +2005,7 @@ static void rna_def_object(BlenderRNA *brna) RNA_def_property_pointer_funcs(prop, "rna_Object_active_material_get", "rna_Object_active_material_set", NULL, NULL); RNA_def_property_flag(prop, PROP_EDITABLE); + RNA_def_property_override_flag(prop, PROPOVERRIDE_OVERRIDABLE_STATIC); RNA_def_property_editable_func(prop, "rna_Object_active_material_editable"); RNA_def_property_ui_text(prop, "Active Material", "Active material being displayed"); RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, "rna_MaterialSlot_update"); @@ -2276,6 +2297,18 @@ static void rna_def_object(BlenderRNA *brna) RNA_def_property_ui_text(prop, "Rigid Body Constraint", "Constraint constraining rigid bodies"); /* restrict */ + prop = RNA_def_property(srna, "hide_viewport", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_sdna(prop, NULL, "restrictflag", OB_RESTRICT_VIEW); + RNA_def_property_ui_text(prop, "Restrict View", "Restrict visibility in the viewport"); + RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, 1); + RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, "rna_Object_hide_update"); + + prop = RNA_def_property(srna, "hide_select", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_sdna(prop, NULL, "restrictflag", OB_RESTRICT_SELECT); + RNA_def_property_ui_text(prop, "Restrict Select", "Restrict selection in the viewport"); + RNA_def_property_ui_icon(prop, ICON_RESTRICT_SELECT_OFF, 1); + RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL); + prop = RNA_def_property(srna, "hide_render", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "restrictflag", OB_RESTRICT_RENDER); RNA_def_property_ui_text(prop, "Restrict Render", "Restrict renderability"); diff --git a/source/blender/makesrna/intern/rna_object_api.c b/source/blender/makesrna/intern/rna_object_api.c index fb27af7c464..f86a3d8236a 100644 --- a/source/blender/makesrna/intern/rna_object_api.c +++ b/source/blender/makesrna/intern/rna_object_api.c @@ -211,9 +211,10 @@ static Mesh *rna_Object_to_mesh( static PointerRNA rna_Object_shape_key_add(Object *ob, bContext *C, ReportList *reports, const char *name, int from_mix) { + Main *bmain = CTX_data_main(C); KeyBlock *kb = NULL; - if ((kb = BKE_object_shapekey_insert(ob, name, from_mix))) { + if ((kb = BKE_object_shapekey_insert(bmain, ob, name, from_mix))) { PointerRNA keyptr; RNA_pointer_create((ID *)ob->data, &RNA_ShapeKey, kb, &keyptr); diff --git a/source/blender/makesrna/intern/rna_scene.c b/source/blender/makesrna/intern/rna_scene.c index ae1b60c7d27..e89898863be 100644 --- a/source/blender/makesrna/intern/rna_scene.c +++ b/source/blender/makesrna/intern/rna_scene.c @@ -2536,6 +2536,11 @@ static void rna_def_tool_settings(BlenderRNA *brna) RNA_def_property_enum_items(prop, uv_sculpt_relaxation_items); RNA_def_property_ui_text(prop, "Relaxation Method", "Algorithm used for UV relaxation"); + prop = RNA_def_property(srna, "lock_object_mode", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_sdna(prop, NULL, "object_flag", SCE_OBJECT_MODE_LOCK); + RNA_def_property_ui_text(prop, "Lock Object Modes", "Restrict select to the current mode"); + RNA_def_property_update(prop, NC_SCENE | ND_TOOLSETTINGS, NULL); + /* Transform */ prop = RNA_def_property(srna, "proportional_edit", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "proportional"); @@ -5090,12 +5095,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); @@ -5117,6 +5124,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); @@ -5142,6 +5150,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_ui_text(prop, "Save Buffers", "Save tiles for all RenderLayers and SceneNodes to files in the temp directory " "(saves memory, required for Full Sample)"); @@ -5156,12 +5165,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); @@ -5176,6 +5187,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)"); @@ -5688,36 +5700,6 @@ static void rna_def_scene_display(BlenderRNA *brna) StructRNA *srna; PropertyRNA *prop; -#ifdef WITH_CLAY_ENGINE - static const EnumPropertyItem clay_matcap_items[] = { - {1, "01", ICON_MATCAP_01, "", ""}, - {2, "02", ICON_MATCAP_02, "", ""}, - {3, "03", ICON_MATCAP_03, "", ""}, - {4, "04", ICON_MATCAP_04, "", ""}, - {5, "05", ICON_MATCAP_05, "", ""}, - {6, "06", ICON_MATCAP_06, "", ""}, - {7, "07", ICON_MATCAP_07, "", ""}, - {8, "08", ICON_MATCAP_08, "", ""}, - {9, "09", ICON_MATCAP_09, "", ""}, - {10, "10", ICON_MATCAP_10, "", ""}, - {11, "11", ICON_MATCAP_11, "", ""}, - {12, "12", ICON_MATCAP_12, "", ""}, - {13, "13", ICON_MATCAP_13, "", ""}, - {14, "14", ICON_MATCAP_14, "", ""}, - {15, "15", ICON_MATCAP_15, "", ""}, - {16, "16", ICON_MATCAP_16, "", ""}, - {17, "17", ICON_MATCAP_17, "", ""}, - {19, "18", ICON_MATCAP_18, "", ""}, - {19, "19", ICON_MATCAP_19, "", ""}, - {20, "20", ICON_MATCAP_20, "", ""}, - {21, "21", ICON_MATCAP_21, "", ""}, - {22, "22", ICON_MATCAP_22, "", ""}, - {23, "23", ICON_MATCAP_23, "", ""}, - {24, "24", ICON_MATCAP_24, "", ""}, - {0, NULL, 0, NULL, NULL} - }; -#endif - static float default_light_direction[3] = {-M_SQRT1_3, -M_SQRT1_3, M_SQRT1_3}; srna = RNA_def_struct(brna, "SceneDisplay", NULL); @@ -5741,43 +5723,6 @@ static void rna_def_scene_display(BlenderRNA *brna) RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_set_update"); -#ifdef WITH_CLAY_ENGINE - /* Matcap. */ - prop = RNA_def_property(srna, "matcap_icon", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_items(prop, clay_matcap_items); - RNA_def_property_enum_default(prop, 1); - RNA_def_property_ui_text(prop, "Matcap", "Image to use for Material Capture by this material"); - - prop = RNA_def_property(srna, "matcap_rotation", PROP_FLOAT, PROP_FACTOR); - RNA_def_property_float_default(prop, 0.0f); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_ui_text(prop, "Matcap Rotation", "Orientation of the matcap on the model"); - - prop = RNA_def_property(srna, "matcap_hue", PROP_FLOAT, PROP_FACTOR); - RNA_def_property_float_default(prop, 0.5f); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_ui_text(prop, "Matcap Hue Shift", "Hue correction of the matcap"); - - prop = RNA_def_property(srna, "matcap_saturation", PROP_FLOAT, PROP_FACTOR); - RNA_def_property_float_default(prop, 0.5f); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_ui_text(prop, "Matcap Saturation", "Saturation correction of the matcap"); - - prop = RNA_def_property(srna, "matcap_value", PROP_FLOAT, PROP_FACTOR); - RNA_def_property_float_default(prop, 0.5f); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_ui_text(prop, "Matcap Value", "Value correction of the matcap"); - - prop = RNA_def_property(srna, "matcap_ssao_factor_cavity", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Cavity Strength", "Strength of the Cavity effect"); - RNA_def_property_range(prop, 0.0f, 250.0f); - - prop = RNA_def_property(srna, "matcap_ssao_factor_edge", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Edge Strength", "Strength of the Edge effect"); - RNA_def_property_range(prop, 0.0f, 250.0f); - prop = RNA_def_property(srna, "matcap_ssao_distance", PROP_FLOAT, PROP_NONE); RNA_def_property_float_default(prop, 0.2f); RNA_def_property_ui_text(prop, "Distance", "Distance of object that contribute to the Cavity/Edge effect"); @@ -5794,12 +5739,6 @@ static void rna_def_scene_display(BlenderRNA *brna) RNA_def_property_int_default(prop, 16); RNA_def_property_ui_text(prop, "Samples", "Number of samples"); RNA_def_property_range(prop, 1, 500); - - prop = RNA_def_property(srna, "matcap_hair_brightness_randomness", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_default(prop, 0.0f); - RNA_def_property_ui_text(prop, "Hair Brightness Randomness", "Brightness randomness for hair"); - RNA_def_property_range(prop, 0.0f, 1.0f); -#endif } static void rna_def_scene_eevee(BlenderRNA *brna) diff --git a/source/blender/makesrna/intern/rna_sculpt_paint.c b/source/blender/makesrna/intern/rna_sculpt_paint.c index be52a3ffca7..b89b2185a38 100644 --- a/source/blender/makesrna/intern/rna_sculpt_paint.c +++ b/source/blender/makesrna/intern/rna_sculpt_paint.c @@ -40,8 +40,9 @@ #include "DNA_screen_types.h" #include "DNA_space_types.h" -#include "BKE_paint.h" +#include "BKE_main.h" #include "BKE_material.h" +#include "BKE_paint.h" #include "ED_image.h" @@ -104,9 +105,9 @@ const EnumPropertyItem rna_enum_symmetrize_direction_items[] = { #include "BKE_context.h" #include "BKE_DerivedMesh.h" -#include "BKE_pointcache.h" #include "BKE_particle.h" #include "BKE_pbvh.h" +#include "BKE_pointcache.h" #include "BKE_object.h" #include "DEG_depsgraph.h" diff --git a/source/blender/makesrna/intern/rna_sequencer.c b/source/blender/makesrna/intern/rna_sequencer.c index fb6953904b3..0dbec5b5355 100644 --- a/source/blender/makesrna/intern/rna_sequencer.c +++ b/source/blender/makesrna/intern/rna_sequencer.c @@ -1504,7 +1504,7 @@ static void rna_def_sequence(BlenderRNA *brna) prop = RNA_def_property(srna, "mute", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_MUTE); - RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, true); + RNA_def_property_ui_icon(prop, ICON_HIDE_OFF, true); RNA_def_property_ui_text(prop, "Mute", "Disable strip so that it cannot be viewed in the output"); RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_mute_update"); @@ -2581,7 +2581,7 @@ static void rna_def_modifier(BlenderRNA *brna) prop = RNA_def_property(srna, "mute", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQUENCE_MODIFIER_MUTE); RNA_def_property_ui_text(prop, "Mute", "Mute this modifier"); - RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, 1); + RNA_def_property_ui_icon(prop, ICON_HIDE_OFF, 1); RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceModifier_update"); prop = RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE); diff --git a/source/blender/makesrna/intern/rna_space.c b/source/blender/makesrna/intern/rna_space.c index 8de651f822d..34d393c7b62 100644 --- a/source/blender/makesrna/intern/rna_space.c +++ b/source/blender/makesrna/intern/rna_space.c @@ -249,6 +249,9 @@ const EnumPropertyItem rna_enum_file_sort_items[] = { #include "DNA_screen_types.h" #include "DNA_userdef_types.h" +#include "BLI_path_util.h" +#include "BLI_string.h" + #include "BKE_animsys.h" #include "BKE_brush.h" #include "BKE_colortools.h" @@ -671,7 +674,7 @@ static PointerRNA rna_View3DShading_selected_studio_light_get(PointerRNA *ptr) { View3D *v3d = (View3D *)ptr->data; StudioLight *sl; - if (v3d->shading.light == V3D_LIGHTING_MATCAP) { + if (v3d->drawtype == OB_SOLID && v3d->shading.light == V3D_LIGHTING_MATCAP) { sl = BKE_studiolight_find(v3d->shading.matcap, STUDIOLIGHT_FLAG_ALL); } else { @@ -719,8 +722,8 @@ static const EnumPropertyItem *rna_View3DShading_light_itemf( static int rna_View3DShading_studio_light_get(PointerRNA *ptr) { View3D *v3d = (View3D *)ptr->data; - char* dna_storage = v3d->shading.studio_light; - + char *dna_storage = v3d->shading.studio_light; + int flag = STUDIOLIGHT_ORIENTATIONS_SOLID; if (v3d->drawtype == OB_SOLID && v3d->shading.light == V3D_LIGHTING_MATCAP) { flag = STUDIOLIGHT_ORIENTATION_VIEWNORMAL; @@ -737,8 +740,8 @@ static int rna_View3DShading_studio_light_get(PointerRNA *ptr) static void rna_View3DShading_studio_light_set(PointerRNA *ptr, int value) { View3D *v3d = (View3D *)ptr->data; - char* dna_storage = v3d->shading.studio_light; - + char *dna_storage = v3d->shading.studio_light; + int flag = STUDIOLIGHT_ORIENTATIONS_SOLID; if (v3d->drawtype == OB_SOLID && v3d->shading.light == V3D_LIGHTING_MATCAP) { flag = STUDIOLIGHT_ORIENTATION_VIEWNORMAL; @@ -763,7 +766,7 @@ static const EnumPropertyItem *rna_View3DShading_studio_light_itemf( const int flags = (STUDIOLIGHT_EXTERNAL_FILE | STUDIOLIGHT_ORIENTATION_VIEWNORMAL); LISTBASE_FOREACH(StudioLight *, sl, BKE_studiolight_listbase()) { - int icon_id = sl->irradiance_icon_id; + int icon_id = (v3d->shading.flag & V3D_SHADING_MATCAP_FLIP_X) ? sl->icon_id_matcap_flipped: sl->icon_id_matcap; if ((sl->flag & flags) == flags) { EnumPropertyItem tmp = {sl->index, sl->name, icon_id, sl->name, ""}; RNA_enum_item_add(&item, &totitem, &tmp); @@ -772,10 +775,10 @@ static const EnumPropertyItem *rna_View3DShading_studio_light_itemf( } else { LISTBASE_FOREACH(StudioLight *, sl, BKE_studiolight_listbase()) { - int icon_id = sl->irradiance_icon_id; + int icon_id = sl->icon_id_irradiance; bool show_studiolight = false; - if ((sl->flag & STUDIOLIGHT_INTERNAL)) { + if (sl->flag & STUDIOLIGHT_INTERNAL) { /* always show internal lights */ show_studiolight = true; } @@ -788,7 +791,7 @@ static const EnumPropertyItem *rna_View3DShading_studio_light_itemf( case OB_MATERIAL: show_studiolight = (sl->flag & STUDIOLIGHT_ORIENTATION_WORLD) > 0; - icon_id = sl->radiance_icon_id; + icon_id = sl->icon_id_radiance; break; } } @@ -1662,6 +1665,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); @@ -2423,10 +2436,10 @@ static void rna_def_space_view3d_shading(BlenderRNA *brna) RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL); - prop = RNA_def_property(srna, "studiolight_background", PROP_FLOAT, PROP_FACTOR); + prop = RNA_def_property(srna, "studiolight_background_alpha", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "shading.studiolight_background"); RNA_def_property_float_default(prop, 0.0); - RNA_def_property_ui_text(prop, "Show Background", "Show the studiolight in the background"); + RNA_def_property_ui_text(prop, "Background", "Show the studiolight in the background"); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_range(prop, 0.00f, 1.0f, 1, 3); RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); @@ -4137,7 +4150,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_ui.c b/source/blender/makesrna/intern/rna_ui.c index ebee502515f..70aa4709d8c 100644 --- a/source/blender/makesrna/intern/rna_ui.c +++ b/source/blender/makesrna/intern/rna_ui.c @@ -166,6 +166,24 @@ static void panel_draw_header(const bContext *C, Panel *pnl) RNA_parameter_list_free(&list); } +static void panel_draw_header_preset(const bContext *C, Panel *pnl) +{ + extern FunctionRNA rna_Panel_draw_header_preset_func; + + PointerRNA ptr; + ParameterList list; + FunctionRNA *func; + + RNA_pointer_create(&CTX_wm_screen(C)->id, pnl->type->ext.srna, pnl, &ptr); + func = &rna_Panel_draw_header_preset_func; + + RNA_parameter_list_create(&list, &ptr, func); + RNA_parameter_set_lookup(&list, "context", &C); + pnl->type->ext.call((bContext *)C, &ptr, func, &list); + + RNA_parameter_list_free(&list); +} + static void rna_Panel_unregister(Main *UNUSED(bmain), StructRNA *type) { ARegionType *art; @@ -199,7 +217,7 @@ static StructRNA *rna_Panel_register( PanelType *pt, *parent = NULL, dummypt = {NULL}; Panel dummypanel = {NULL}; PointerRNA dummyptr; - int have_function[3]; + int have_function[4]; /* setup dummy panel & panel type to store static properties in */ dummypanel.type = &dummypt; @@ -267,6 +285,7 @@ static StructRNA *rna_Panel_register( pt->poll = (have_function[0]) ? panel_poll : NULL; pt->draw = (have_function[1]) ? panel_draw : NULL; pt->draw_header = (have_function[2]) ? panel_draw_header : NULL; + pt->draw_header_preset = (have_function[3]) ? panel_draw_header_preset : NULL; /* XXX use "no header" flag for some ordering of panels until we have real panel ordering */ if (pt->flag & PNL_NO_HEADER) { @@ -944,6 +963,16 @@ static void rna_UILayout_property_split_set(PointerRNA *ptr, int value) uiLayoutSetPropSep(ptr->data, value); } +static int rna_UILayout_property_decorate_get(PointerRNA *ptr) +{ + return uiLayoutGetPropDecorate(ptr->data); +} + +static void rna_UILayout_property_decorate_set(PointerRNA *ptr, int value) +{ + uiLayoutSetPropDecorate(ptr->data, value); +} + #else /* RNA_RUNTIME */ static void rna_def_ui_layout(BlenderRNA *brna) @@ -1011,6 +1040,9 @@ static void rna_def_ui_layout(BlenderRNA *brna) prop = RNA_def_property(srna, "use_property_split", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs(prop, "rna_UILayout_property_split_get", "rna_UILayout_property_split_set"); + + prop = RNA_def_property(srna, "use_property_decorate", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_funcs(prop, "rna_UILayout_property_decorate_get", "rna_UILayout_property_decorate_set"); } static void rna_def_panel(BlenderRNA *brna) @@ -1058,6 +1090,12 @@ static void rna_def_panel(BlenderRNA *brna) parm = RNA_def_pointer(func, "context", "Context", "", ""); RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED); + func = RNA_def_function(srna, "draw_header_preset", NULL); + RNA_def_function_ui_description(func, "Draw UI elements for presets in the panel's header"); + RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL); + parm = RNA_def_pointer(func, "context", "Context", "", ""); + RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED); + prop = RNA_def_property(srna, "layout", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "UILayout"); RNA_def_property_ui_text(prop, "Layout", "Defines the structure of the panel in the UI"); diff --git a/source/blender/makesrna/intern/rna_ui_api.c b/source/blender/makesrna/intern/rna_ui_api.c index 3940f13c64a..9377ef8a925 100644 --- a/source/blender/makesrna/intern/rna_ui_api.c +++ b/source/blender/makesrna/intern/rna_ui_api.c @@ -869,6 +869,12 @@ void RNA_api_ui_layout(StructRNA *srna) api_ui_item_rna_common(func); RNA_def_boolean(func, "expand", false, "", "Expand button to show more detail"); + func = RNA_def_function(srna, "template_icon", "uiTemplateIcon"); + RNA_def_function_ui_description(func, "Display a large icon"); + parm = RNA_def_int(func, "icon_value", 0, 0, INT_MAX, "Icon to display", "", 0, INT_MAX); + RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); + RNA_def_float(func, "scale", 1.0f, 1.0f, 100.0f, "Scale", "Scale the icon size (by the button size)", 1.0f, 100.0f); + func = RNA_def_function(srna, "template_icon_view", "uiTemplateIconView"); RNA_def_function_ui_description(func, "Enum. Large widget showing Icon previews"); api_ui_item_rna_common(func); diff --git a/source/blender/makesrna/intern/rna_userdef.c b/source/blender/makesrna/intern/rna_userdef.c index 0d05d03e3a9..2dbdb1bbb1c 100644 --- a/source/blender/makesrna/intern/rna_userdef.c +++ b/source/blender/makesrna/intern/rna_userdef.c @@ -78,11 +78,6 @@ const EnumPropertyItem rna_enum_navigation_mode_items[] = { {0, NULL, 0, NULL, NULL} }; -static const EnumPropertyItem rna_enum_studio_light_icons_id_items[] = { - {0, "DEFAULT", 0, "Default", ""}, - {0, NULL, 0, NULL, NULL} -}; - #if defined(WITH_INTERNATIONAL) || !defined(RNA_RUNTIME) static const EnumPropertyItem rna_enum_language_default_items[] = { @@ -704,38 +699,6 @@ static int rna_UserDef_studiolight_index_get(PointerRNA *ptr) return sl->index; } -/* StudioLight.icon_id */ -static int rna_UserDef_studiolight_icon_id_get(PointerRNA *ptr) -{ - StudioLight *sl = (StudioLight *)ptr->data; - if (sl->flag & (STUDIOLIGHT_ORIENTATION_VIEWNORMAL | STUDIOLIGHT_ORIENTATION_CAMERA)) { - return 1; - } - return 0; -} - -static const EnumPropertyItem *rna_UserDef_studiolight_icon_id_itemf( - bContext *UNUSED(C), PointerRNA *ptr, - PropertyRNA *UNUSED(prop), bool *r_free) -{ - EnumPropertyItem *item = NULL; - int totitem = 0; - StudioLight *sl = (StudioLight *)ptr->data; - - if ((sl->flag & (STUDIOLIGHT_ORIENTATION_VIEWNORMAL | STUDIOLIGHT_ORIENTATION_CAMERA)) == 0) { - EnumPropertyItem tmp = {0, sl->name, sl->radiance_icon_id, sl->name, ""}; - RNA_enum_item_add(&item, &totitem, &tmp); - } - - { - EnumPropertyItem tmp = {1, sl->name, sl->irradiance_icon_id, sl->name, ""}; - RNA_enum_item_add(&item, &totitem, &tmp); - } - RNA_enum_item_end(&item, &totitem); - *r_free = true; - return item; -} - /* StudioLight.is_user_defined */ static int rna_UserDef_studiolight_is_user_defined_get(PointerRNA *ptr) { @@ -743,21 +706,6 @@ static int rna_UserDef_studiolight_is_user_defined_get(PointerRNA *ptr) return (sl->flag & STUDIOLIGHT_USER_DEFINED) > 0; } -/* StudioLight.show_expanded */ -static int rna_UserDef_studiolight_show_expanded_get(PointerRNA *ptr) -{ - StudioLight *sl = (StudioLight *)ptr->data; - return (sl->flag & STUDIOLIGHT_UI_EXPANDED) > 0; -} - -static void rna_UserDef_studiolight_show_expanded_set(PointerRNA *ptr, const bool value) -{ - StudioLight *sl = (StudioLight *)ptr->data; - sl->flag ^= STUDIOLIGHT_UI_EXPANDED; - sl->flag |= value ? STUDIOLIGHT_UI_EXPANDED : 0; -} - - /* StudioLight.orientation */ static int rna_UserDef_studiolight_orientation_get(PointerRNA *ptr) @@ -1748,7 +1696,7 @@ static void rna_def_userdef_theme_space_view3d(BlenderRNA *brna) prop = RNA_def_property(srna, "wire_edit", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); - RNA_def_property_ui_text(prop, "Wire Edit", ""); + RNA_def_property_ui_text(prop, "Wire Edit", "Color for wireframe when in edit mode, but edge selection is active"); RNA_def_property_update(prop, 0, "rna_userdef_update"); @@ -3306,21 +3254,11 @@ static void rna_def_userdef_studiolight(BlenderRNA *brna) RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "User Defined", ""); - prop = RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_funcs(prop, "rna_UserDef_studiolight_show_expanded_get", "rna_UserDef_studiolight_show_expanded_set"); - RNA_def_property_ui_text(prop, "Show Expanded", ""); - prop = RNA_def_property(srna, "orientation", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_studio_light_orientation_items); RNA_def_property_enum_funcs(prop, "rna_UserDef_studiolight_orientation_get", "rna_UserDef_studiolight_orientation_set", NULL); RNA_def_property_ui_text(prop, "Orientation", ""); - prop = RNA_def_property(srna, "icon_id", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_funcs(prop, "rna_UserDef_studiolight_icon_id_get", NULL, "rna_UserDef_studiolight_icon_id_itemf"); - RNA_def_property_enum_items(prop, rna_enum_studio_light_icons_id_items); - RNA_def_property_clear_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Preview", "Preview of the studiolight"); - prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_property_string_funcs(prop, "rna_UserDef_studiolight_name_get", "rna_UserDef_studiolight_name_length", NULL); RNA_def_property_ui_text(prop, "Name", ""); @@ -4129,6 +4067,12 @@ static void rna_def_userdef_system(BlenderRNA *brna) {0, NULL, 0, NULL, NULL} }; + static const EnumPropertyItem gpu_antialias_method_items[] = { + {USER_AA_NONE, "OFF", 0, "Off", "Disable Anti Alias in viewport"}, + {USER_AA_FXAA, "FXAA", 0, "FXAA", "Use FXAA, a fast screenspace Anti Alias method"}, + {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"); @@ -4387,6 +4331,13 @@ static void rna_def_userdef_system(BlenderRNA *brna) "Draw tool/property regions over the main region, when using Triple Buffer"); RNA_def_property_update(prop, 0, "rna_userdef_dpi_update"); + prop = RNA_def_property(srna, "max_anti_alias_method", PROP_ENUM, PROP_NONE); + RNA_def_property_enum_sdna(prop, NULL, "gpu_viewport_antialias"); + RNA_def_property_enum_items(prop, gpu_antialias_method_items); + RNA_def_property_ui_text(prop, "Viewport Anti-aliasing", + "Method to draw the Anti-Aliasing in the viewport"); + RNA_def_property_update(prop, 0, "rna_userdef_update"); + #ifdef WITH_OPENSUBDIV prop = RNA_def_property(srna, "opensubdiv_compute_type", PROP_ENUM, PROP_NONE); RNA_def_property_flag(prop, PROP_ENUM_NO_CONTEXT); diff --git a/source/blender/modifiers/CMakeLists.txt b/source/blender/modifiers/CMakeLists.txt index 0a619ecf9c7..045a5d31fcb 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 8f99bc2bf39..40d568537a0 100644 --- a/source/blender/modifiers/intern/MOD_armature.c +++ b/source/blender/modifiers/intern/MOD_armature.c @@ -60,7 +60,7 @@ static void initData(ModifierData *md) { ArmatureModifierData *amd = (ArmatureModifierData *) md; - + amd->deformflag = ARM_DEF_VGROUP; } @@ -120,7 +120,7 @@ static void deformVerts( ArmatureModifierData *amd = (ArmatureModifierData *) md; modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */ - + armature_deform_verts(amd->object, ctx->object, mesh, 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 7a20eb005f3..6902b811c26 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 "DNA_mesh_types.h" #include "DNA_scene_types.h" diff --git a/source/blender/modifiers/intern/MOD_boolean.c b/source/blender/modifiers/intern/MOD_boolean.c index f2c0baedc01..f7b16431c48 100644 --- a/source/blender/modifiers/intern/MOD_boolean.c +++ b/source/blender/modifiers/intern/MOD_boolean.c @@ -170,13 +170,14 @@ static int bm_face_isect_pair(BMFace *f, void *UNUSED(user_data)) static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mesh *mesh) { BooleanModifierData *bmd = (BooleanModifierData *) md; - Mesh *result; + Mesh *result = mesh; Mesh *mesh_other; bool mesh_other_free; - if (!bmd->object) - return mesh; + if (!bmd->object) { + return result; + } Object *ob_eval = DEG_get_evaluated_object(ctx->depsgraph, bmd->object); mesh_other = BKE_modifier_get_evaluated_mesh_from_evaluated_object(ob_eval, &mesh_other_free); @@ -309,6 +310,7 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes use_dissolve, use_island_connect, false, + false, bmd->operation, bmd->double_threshold); @@ -344,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 eb32c77ca1e..9b491d4333f 100644 --- a/source/blender/modifiers/intern/MOD_build.c +++ b/source/blender/modifiers/intern/MOD_build.c @@ -116,7 +116,7 @@ static Mesh *applyModifier( MPoly *mpoly, *mp; MLoop *ml, *mloop; uintptr_t hash_num, hash_num_alt; - + if (bmd->flag & MOD_BUILD_FLAG_RANDOMIZE) { BLI_array_randomize(faceMap, sizeof(*faceMap), numPoly_src, bmd->seed); @@ -254,7 +254,7 @@ static Mesh *applyModifier( mpoly_dst = result->mpoly; ml_dst = result->mloop; - + /* copy the faces across, remapping indices */ k = 0; for (i = 0; i < numFaces_dst; i++) { @@ -279,7 +279,7 @@ static Mesh *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 5b6ad9b8f29..4441af57c93 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; @@ -125,7 +125,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 33d608aa868..19afe30acae 100644 --- a/source/blender/modifiers/intern/MOD_cloth.c +++ b/source/blender/modifiers/intern/MOD_cloth.c @@ -56,18 +56,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( { Mesh *mesh_src; ClothModifierData *clmd = (ClothModifierData *) md; - + /* check for alloc failing */ if (!clmd->sim_parms || !clmd->coll_parms) { initData(md); @@ -166,7 +166,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; @@ -189,13 +189,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); @@ -203,13 +203,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 71022f8a4ab..7f02bbf0453 100644 --- a/source/blender/modifiers/intern/MOD_collision.c +++ b/source/blender/modifiers/intern/MOD_collision.c @@ -55,10 +55,10 @@ #include "DEG_depsgraph_query.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; @@ -74,7 +74,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); @@ -111,7 +111,7 @@ static void deformVerts( Mesh *mesh_src; MVert *tempVert = NULL; Object *ob = ctx->object; - + if (mesh == NULL) { mesh_src = get_mesh(ob, NULL, NULL, NULL, false, false); } @@ -131,21 +131,21 @@ static void deformVerts( printf("CollisionModifier deformVerts: Should not happen!\n"); return; } - + if (mesh_src) { float current_time = 0; unsigned int mvert_num = 0; BKE_mesh_apply_vert_coords(mesh_src, vertexCos); BKE_mesh_calc_normals(mesh_src); - + current_time = DEG_get_ctime(ctx->depsgraph); - + if (G.debug_value > 0) printf("current_time %f, collmd->time_xnew %f\n", current_time, collmd->time_xnew); - + mvert_num = mesh_src->totvert; - + if (current_time > collmd->time_xnew) { unsigned int i; @@ -161,7 +161,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 @@ -218,9 +218,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( @@ -243,7 +243,7 @@ static void deformVerts( else if (mvert_num != collmd->mvert_num) { freeData((ModifierData *)collmd); } - + } else if (current_time < collmd->time_xnew) { freeData((ModifierData *)collmd); @@ -254,7 +254,7 @@ static void deformVerts( } } } - + if (mesh_src != mesh) { BKE_id_free(NULL, mesh_src); } diff --git a/source/blender/modifiers/intern/MOD_dynamicpaint.c b/source/blender/modifiers/intern/MOD_dynamicpaint.c index c7386f947ce..5ca367e342a 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; diff --git a/source/blender/modifiers/intern/MOD_edgesplit.c b/source/blender/modifiers/intern/MOD_edgesplit.c index e8ffddbde4e..e1806dc8283 100644 --- a/source/blender/modifiers/intern/MOD_edgesplit.c +++ b/source/blender/modifiers/intern/MOD_edgesplit.c @@ -107,8 +107,7 @@ static Mesh *doEdgeSplit(Mesh *mesh, EdgeSplitModifierData *emd, const ModifierE /* BM_mesh_validate(bm); */ /* for troubleshooting */ - result = BKE_id_new_nomain(ID_ME, mesh->id.name); - BM_mesh_bm_to_me(bm, result, &((struct BMeshToMeshParams){0})); + result = BKE_bmesh_to_mesh_nomain(bm, &((struct BMeshToMeshParams){0})); BM_mesh_free(bm); result->runtime.cd_dirty_vert |= CD_MASK_NORMAL; diff --git a/source/blender/modifiers/intern/MOD_explode.c b/source/blender/modifiers/intern/MOD_explode.c index 6688236a558..cbb15665bef 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); @@ -844,7 +844,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]; @@ -935,12 +935,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 e13594e46d9..ffa74be0b33 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)) { @@ -91,11 +91,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; } diff --git a/source/blender/modifiers/intern/MOD_fluidsim_util.c b/source/blender/modifiers/intern/MOD_fluidsim_util.c index 4bcc14236a0..cea9e69526c 100644 --- a/source/blender/modifiers/intern/MOD_fluidsim_util.c +++ b/source/blender/modifiers/intern/MOD_fluidsim_util.c @@ -72,10 +72,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; @@ -89,12 +89,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 @@ -130,18 +130,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; } @@ -163,7 +163,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; } @@ -434,7 +434,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 */ @@ -530,7 +530,7 @@ DerivedMesh *fluidsimModifier_do( FluidsimSettings *fss = NULL; framenr = (int)DEG_get_ctime(depsgraph); - + /* only handle fluidsim domains */ if (fluidmd && fluidmd->fss && (fluidmd->fss->type != OB_FLUIDSIM_DOMAIN)) return dm; @@ -549,12 +549,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_hook.c b/source/blender/modifiers/intern/MOD_hook.c index 05fb6bb43bc..76df31823a7 100644 --- a/source/blender/modifiers/intern/MOD_hook.c +++ b/source/blender/modifiers/intern/MOD_hook.c @@ -53,7 +53,7 @@ #include "MOD_util.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { HookModifierData *hmd = (HookModifierData *) md; @@ -259,7 +259,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); diff --git a/source/blender/modifiers/intern/MOD_mask.c b/source/blender/modifiers/intern/MOD_mask.c index 887e8f86200..fd833a2a322 100644 --- a/source/blender/modifiers/intern/MOD_mask.c +++ b/source/blender/modifiers/intern/MOD_mask.c @@ -115,17 +115,17 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes } /* 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 = mesh->totvert; maxEdges = mesh->totedge; maxPolys = mesh->totpoly; - - /* 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)) || @@ -133,7 +133,7 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes { return mesh; } - + /* 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; @@ -142,18 +142,18 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes 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 mesh; } - - /* 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)) { @@ -169,8 +169,8 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes * 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 */ @@ -178,7 +178,7 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes 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) { @@ -190,16 +190,16 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes } } } - + 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); } @@ -210,10 +210,10 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes if (defgrp_index == -1) { return mesh; } - + /* 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; @@ -239,12 +239,12 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes /* 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))) @@ -258,14 +258,14 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes 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)); @@ -274,13 +274,13 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes 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 = BKE_mesh_new_nomain_from_template(mesh, numVerts, numEdges, 0, numLoops, numPolys); - + mpoly_dst = result->mpoly; mloop_dst = result->mloop; medge_dst = result->medge; @@ -293,21 +293,21 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes 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; CustomData_copy_data(&mesh->vdata, &result->vdata, 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]; @@ -316,7 +316,7 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes 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)); @@ -327,7 +327,7 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes 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]; - + CustomData_copy_data(&mesh->pdata, &result->pdata, i_src, i_dst, 1); CustomData_copy_data(&mesh->ldata, &result->ldata, i_ml_src, i_ml_dst, mp_src->totloop); @@ -344,7 +344,7 @@ static Mesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx, Mes /* why is this needed? - campbell */ /* recalculate normals */ result->runtime.cd_dirty_vert |= CD_MASK_NORMAL; - + /* 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 4fe8942a194..b50672e4160 100644 --- a/source/blender/modifiers/intern/MOD_meshdeform.c +++ b/source/blender/modifiers/intern/MOD_meshdeform.c @@ -98,7 +98,7 @@ static void copyData(const ModifierData *md, ModifierData *target) } static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md) -{ +{ MeshDeformModifierData *mmd = (MeshDeformModifierData *)md; CustomDataMask dataMask = 0; @@ -305,7 +305,7 @@ static void meshdeformModifier_do( * We'll support this case once granular dependency graph is landed. */ cagemesh = BKE_modifier_get_evaluated_mesh_from_evaluated_object(mmd->object, &free_cagemesh); - + if (cagemesh == NULL) { modifier_setError(md, "Cannot get mesh from cage object"); return; @@ -444,7 +444,7 @@ void modifier_mdef_compact_influences(ModifierData *md) weights = mmd->bindweights; if (!weights) return; - + totvert = mmd->totvert; totcagevert = mmd->totcagevert; @@ -490,7 +490,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 892092f844b..4b16f165a12 100644 --- a/source/blender/modifiers/intern/MOD_mirror.c +++ b/source/blender/modifiers/intern/MOD_mirror.c @@ -189,7 +189,7 @@ static Mesh *doMirrorOnAxis( vtmap_b++; } } - + /* handle shape keys */ totshape = CustomData_number_of_layers(&result->vdata, CD_SHAPEKEY); for (a = 0; a < totshape; a++) { @@ -198,14 +198,14 @@ static Mesh *doMirrorOnAxis( mul_m4_v3(mtx, cos[i]); } } - + /* adjust mirrored edge vertex indices */ me = result->medge + 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 = result->mpoly + maxPolys; ml = result->mloop; @@ -229,7 +229,7 @@ static Mesh *doMirrorOnAxis( ml2[j].e = ml2[j + 1].e; } ml2[mp->totloop - 1].e = e; - + mp->loopstart += maxLoops; } @@ -267,7 +267,7 @@ static Mesh *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 */ diff --git a/source/blender/modifiers/intern/MOD_multires.c b/source/blender/modifiers/intern/MOD_multires.c index c263c2e3f5d..a23511ff87a 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 || !(ctx->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_normal_edit.c b/source/blender/modifiers/intern/MOD_normal_edit.c index 08dbcf81256..935d99e4a21 100644 --- a/source/blender/modifiers/intern/MOD_normal_edit.c +++ b/source/blender/modifiers/intern/MOD_normal_edit.c @@ -201,6 +201,7 @@ static void normalEditModifier_do_radial( MVert *mvert, const int num_verts, MEdge *medge, const int num_edges, MLoop *mloop, const int num_loops, MPoly *mpoly, const int num_polys) { + const bool do_polynors_fix = (enmd->flag & MOD_NORMALEDIT_NO_POLYNORS_FIX) == 0; int i; float (*cos)[3] = MEM_malloc_arrayN((size_t)num_verts, sizeof(*cos), __func__); @@ -278,7 +279,7 @@ static void normalEditModifier_do_radial( mix_limit, mix_mode, num_verts, mloop, loopnors, nos, num_loops); } - if (polygons_check_flip(mloop, nos, &mesh->ldata, mpoly, polynors, num_polys)) { + if (do_polynors_fix && polygons_check_flip(mloop, nos, &mesh->ldata, mpoly, polynors, num_polys)) { /* XXX TODO is this still needed? */ // mesh->dirty |= DM_DIRTY_TESS_CDLAYERS; /* We need to recompute vertex normals! */ @@ -301,6 +302,7 @@ static void normalEditModifier_do_directional( MVert *mvert, const int num_verts, MEdge *medge, const int num_edges, MLoop *mloop, const int num_loops, MPoly *mpoly, const int num_polys) { + const bool do_polynors_fix = (enmd->flag & MOD_NORMALEDIT_NO_POLYNORS_FIX) == 0; const bool use_parallel_normals = (enmd->flag & MOD_NORMALEDIT_USE_DIRECTION_PARALLEL) != 0; float (*nos)[3] = MEM_malloc_arrayN((size_t)num_loops, sizeof(*nos), __func__); @@ -357,7 +359,7 @@ static void normalEditModifier_do_directional( mix_limit, mix_mode, num_verts, mloop, loopnors, nos, num_loops); } - if (polygons_check_flip(mloop, nos, &mesh->ldata, mpoly, polynors, num_polys)) { + if (do_polynors_fix && polygons_check_flip(mloop, nos, &mesh->ldata, mpoly, polynors, num_polys)) { mesh->runtime.cd_dirty_vert |= CD_MASK_NORMAL; } diff --git a/source/blender/modifiers/intern/MOD_particlesystem.c b/source/blender/modifiers/intern/MOD_particlesystem.c index 72bdcc779ea..cbdeeebaa04 100644 --- a/source/blender/modifiers/intern/MOD_particlesystem.c +++ b/source/blender/modifiers/intern/MOD_particlesystem.c @@ -51,7 +51,7 @@ #include "MOD_util.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { ParticleSystemModifierData *psmd = (ParticleSystemModifierData *) md; psmd->psys = NULL; @@ -115,7 +115,7 @@ static void deformVerts( psys = psmd->psys; else return; - + if (!psys_check_enabled(ctx->object, psys, (ctx->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 df607c04164..edf59f6b6b2 100644 --- a/source/blender/modifiers/intern/MOD_remesh.c +++ b/source/blender/modifiers/intern/MOD_remesh.c @@ -99,7 +99,7 @@ static void *dualcon_alloc_output(int totvert, int totquad) { return NULL; } - + output->mesh = BKE_mesh_new_nomain(totvert, 0, 0, 4 * totquad, totquad); return output; } @@ -108,9 +108,9 @@ static void dualcon_add_vert(void *output_v, const float co[3]) { DualConOutput *output = output_v; Mesh *mesh = output->mesh; - + assert(output->curvert < mesh->totvert); - + copy_v3_v3(mesh->mvert[output->curvert].co, co); output->curvert++; } @@ -122,17 +122,17 @@ static void dualcon_add_quad(void *output_v, const int vert_indices[4]) MLoop *mloop; MPoly *cur_poly; int i; - + assert(output->curface < mesh->totpoly); mloop = mesh->mloop; cur_poly = &mesh->mpoly[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++; } @@ -166,7 +166,7 @@ static Mesh *applyModifier( mode = DUALCON_SHARP_FEATURES; break; } - + output = dualcon(&input, dualcon_alloc_output, dualcon_add_vert, @@ -183,7 +183,7 @@ static Mesh *applyModifier( if (rmd->flag & MOD_REMESH_SMOOTH_SHADING) { MPoly *mpoly = result->mpoly; int i, totpoly = result->totpoly; - + /* 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 32b0894e946..96335707082 100644 --- a/source/blender/modifiers/intern/MOD_screw.c +++ b/source/blender/modifiers/intern/MOD_screw.c @@ -90,7 +90,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 Mesh *applyModifier( Mesh *result; ScrewModifierData *ltmd = (ScrewModifierData *) md; const bool use_render_params = (ctx->flag & MOD_APPLY_RENDER) != 0; - + int *origindex; int mpoly_index = 0; unsigned int step; @@ -228,18 +228,18 @@ static Mesh *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 Mesh *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,9 +375,9 @@ static Mesh *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 = BKE_mesh_new_nomain_from_template(mesh, (int)maxVerts, (int)maxEdges, 0, (int)maxPolys * 4, (int)maxPolys); - + /* copy verts from mesh */ mvert_orig = mesh->mvert; medge_orig = mesh->medge; @@ -421,10 +421,10 @@ static Mesh *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 Mesh *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 Mesh *applyModifier( } } /* done with edge connectivity based normal flipping */ - + /* Add Faces */ for (step = 1; step < step_tot; step++) { const unsigned int varray_stride = totvert * step; @@ -855,7 +855,7 @@ static Mesh *applyModifier( 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 Mesh *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 Mesh *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 Mesh *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))); @@ -1049,7 +1049,7 @@ static Mesh *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 29f5815c733..da31de911e4 100644 --- a/source/blender/modifiers/intern/MOD_shrinkwrap.c +++ b/source/blender/modifiers/intern/MOD_shrinkwrap.c @@ -153,7 +153,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 26fd16ef167..323994e6738 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) || @@ -938,14 +938,14 @@ static Mesh *subdivide_base(Mesh *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; @@ -953,7 +953,7 @@ static Mesh *subdivide_base(Mesh *orig) if (vgroups) MEM_freeN(vgroups); - + /* Link up to final vertex */ outedge->v1 = u; outedge->v2 = e->v2; @@ -977,7 +977,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); @@ -1064,7 +1064,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); } @@ -1094,14 +1094,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); @@ -1162,7 +1162,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; @@ -1260,7 +1260,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); @@ -1308,7 +1308,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); @@ -1514,7 +1514,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) { @@ -1530,11 +1530,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]; @@ -1554,19 +1554,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); @@ -1579,14 +1579,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); @@ -1631,7 +1631,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]; @@ -1647,7 +1647,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]]; @@ -1730,15 +1730,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); @@ -1766,7 +1766,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); @@ -1911,7 +1911,7 @@ static Mesh *final_skin(SkinModifierData *smd, Mesh *mesh) 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 44b013c2bb5..4c10df71f92 100644 --- a/source/blender/modifiers/intern/MOD_smoke.c +++ b/source/blender/modifiers/intern/MOD_smoke.c @@ -58,10 +58,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; @@ -73,14 +73,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); } diff --git a/source/blender/modifiers/intern/MOD_smooth.c b/source/blender/modifiers/intern/MOD_smooth.c index a8a1692b158..e44ead73ced 100644 --- a/source/blender/modifiers/intern/MOD_smooth.c +++ b/source/blender/modifiers/intern/MOD_smooth.c @@ -167,7 +167,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) @@ -188,7 +188,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_surface.c b/source/blender/modifiers/intern/MOD_surface.c index 46fd3198699..d6e78c6f19b 100644 --- a/source/blender/modifiers/intern/MOD_surface.c +++ b/source/blender/modifiers/intern/MOD_surface.c @@ -54,10 +54,10 @@ #include "MEM_guardedalloc.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { SurfaceModifierData *surmd = (SurfaceModifierData *) md; - + surmd->bvhtree = NULL; } @@ -77,7 +77,7 @@ static void freeData(ModifierData *md) } MEM_SAFE_FREE(surmd->x); - + MEM_SAFE_FREE(surmd->v); } } @@ -95,7 +95,7 @@ static void deformVerts( { SurfaceModifierData *surmd = (SurfaceModifierData *) md; const int cfra = (int)DEG_get_ctime(ctx->depsgraph); - + if (surmd->mesh) { BKE_id_free(NULL, surmd->mesh); } @@ -112,7 +112,7 @@ static void deformVerts( false); } else surmd->mesh = get_mesh(ctx->object, NULL, NULL, NULL, false, false); - + if (!ctx->object->pd) { printf("SurfaceModifier deformVerts: Should not happen!\n"); return; @@ -126,7 +126,7 @@ static void deformVerts( BKE_mesh_apply_vert_coords(surmd->mesh, vertexCos); BKE_mesh_calc_normals(surmd->mesh); - + numverts = surmd->mesh->totvert; if (numverts != surmd->numverts || @@ -160,7 +160,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 d4f035915d0..c72cf41737e 100644 --- a/source/blender/modifiers/intern/MOD_util.c +++ b/source/blender/modifiers/intern/MOD_util.c @@ -276,7 +276,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 394255ddb18..9a06d397be6 100644 --- a/source/blender/modifiers/intern/MOD_uvproject.c +++ b/source/blender/modifiers/intern/MOD_uvproject.c @@ -216,7 +216,7 @@ static Mesh *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) diff --git a/source/blender/modifiers/intern/MOD_weightvgproximity.c b/source/blender/modifiers/intern/MOD_weightvgproximity.c index 070d4ad80e6..1a69ae13120 100644 --- a/source/blender/modifiers/intern/MOD_weightvgproximity.c +++ b/source/blender/modifiers/intern/MOD_weightvgproximity.c @@ -230,7 +230,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/NOD_static_types.h b/source/blender/nodes/NOD_static_types.h index 437093a9cb3..ec4e88768de 100644 --- a/source/blender/nodes/NOD_static_types.h +++ b/source/blender/nodes/NOD_static_types.h @@ -71,7 +71,7 @@ DefNode( ShaderNode, SH_NODE_LAYER_WEIGHT, 0, "LA DefNode( ShaderNode, SH_NODE_MIX_SHADER, 0, "MIX_SHADER", MixShader, "Mix Shader", "" ) DefNode( ShaderNode, SH_NODE_ADD_SHADER, 0, "ADD_SHADER", AddShader, "Add Shader", "" ) DefNode( ShaderNode, SH_NODE_ATTRIBUTE, def_sh_attribute, "ATTRIBUTE", Attribute, "Attribute", "" ) -DefNode( ShaderNode, SH_NODE_AMBIENT_OCCLUSION, 0, "AMBIENT_OCCLUSION", AmbientOcclusion, "Ambient Occlusion", "" ) +DefNode( ShaderNode, SH_NODE_AMBIENT_OCCLUSION, def_sh_ambient_occlusion,"AMBIENT_OCCLUSION", AmbientOcclusion, "Ambient Occlusion", "" ) DefNode( ShaderNode, SH_NODE_BACKGROUND, 0, "BACKGROUND", Background, "Background", "" ) DefNode( ShaderNode, SH_NODE_HOLDOUT, 0, "HOLDOUT", Holdout, "Holdout", "" ) DefNode( ShaderNode, SH_NODE_BSDF_ANISOTROPIC, def_anisotropic, "BSDF_ANISOTROPIC", BsdfAnisotropic, "Anisotropic BSDF", "" ) 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 f835822469c..eae35b4cd22 100644 --- a/source/blender/nodes/shader/nodes/node_shader_ambient_occlusion.c +++ b/source/blender/nodes/shader/nodes/node_shader_ambient_occlusion.c @@ -31,17 +31,29 @@ 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_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_SHADER, 0, N_("AO")}, + { SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 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, "" } }; static int node_shader_gpu_ambient_occlusion(GPUMaterial *mat, bNode *node, bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out) { - return GPU_stack_link(mat, node, "node_ambient_occlusion", in, out, GPU_builtin(GPU_VIEW_NORMAL)); + if (!in[2].link) + GPU_link(mat, "world_normals_get", &in[2].link); + + return GPU_stack_link(mat, node, "node_ambient_occlusion", in, out); +} + +static void node_shader_init_ambient_occlusion(bNodeTree *UNUSED(ntree), bNode *node) +{ + node->custom1 = 8; /* samples */ + node->custom2 = SHD_AO_LOCAL; } /* node type definition */ @@ -49,10 +61,10 @@ void register_node_type_sh_ambient_occlusion(void) { static bNodeType ntype; - sh_node_type_base(&ntype, SH_NODE_AMBIENT_OCCLUSION, "Ambient Occlusion", NODE_CLASS_SHADER, 0); + sh_node_type_base(&ntype, SH_NODE_AMBIENT_OCCLUSION, "Ambient Occlusion", NODE_CLASS_INPUT, 0); node_type_compatibility(&ntype, NODE_NEW_SHADING); node_type_socket_templates(&ntype, sh_node_ambient_occlusion_in, sh_node_ambient_occlusion_out); - node_type_init(&ntype, NULL); + node_type_init(&ntype, node_shader_init_ambient_occlusion); node_type_storage(&ntype, "", NULL, NULL); node_type_gpu(&ntype, node_shader_gpu_ambient_occlusion); diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h index b4c36a7c516..da1b031f1c0 100644 --- a/source/blender/python/BPY_extern.h +++ b/source/blender/python/BPY_extern.h @@ -87,7 +87,8 @@ void BPY_modules_load_user(struct bContext *C); void BPY_app_handlers_reset(const short do_all); void BPY_driver_reset(void); -float BPY_driver_exec(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver, const float evaltime); +float BPY_driver_exec(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver, + struct ChannelDriver *driver_orig, const float evaltime); void BPY_DECREF(void *pyob_ptr); /* Py_DECREF() */ void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr); diff --git a/source/blender/python/bmesh/bmesh_py_types.c b/source/blender/python/bmesh/bmesh_py_types.c index c6a67a1b2dd..d32b8696c9c 100644 --- a/source/blender/python/bmesh/bmesh_py_types.c +++ b/source/blender/python/bmesh/bmesh_py_types.c @@ -36,6 +36,7 @@ #include "BKE_customdata.h" #include "BKE_DerivedMesh.h" +#include "BKE_global.h" #include "DEG_depsgraph.h" @@ -903,6 +904,7 @@ static PyObject *bpy_bmesh_to_mesh(BPy_BMesh *self, PyObject *args) bm = self->bm; BM_mesh_bm_to_me( + G.main, /* XXX UGLY! */ bm, me, (&(struct BMeshToMeshParams){ .calc_object_remap = true, @@ -1401,7 +1403,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 e2241ade7f0..15548714113 100644 --- a/source/blender/python/bmesh/bmesh_py_types_customdata.c +++ b/source/blender/python/bmesh/bmesh_py_types_customdata.c @@ -1127,7 +1127,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; } @@ -1139,7 +1139,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 54b33e7b6b6..bc96ce606a9 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" @@ -465,7 +466,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 { diff --git a/source/blender/python/bmesh/bmesh_py_utils.c b/source/blender/python/bmesh/bmesh_py_utils.c index 224c8295a9b..ca34de219b8 100644 --- a/source/blender/python/bmesh/bmesh_py_utils.c +++ b/source/blender/python/bmesh/bmesh_py_utils.c @@ -33,6 +33,7 @@ #include <Python.h> #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/intern/bpy_driver.c b/source/blender/python/intern/bpy_driver.c index 215a64a4449..b8c71d4e054 100644 --- a/source/blender/python/intern/bpy_driver.c +++ b/source/blender/python/intern/bpy_driver.c @@ -48,13 +48,25 @@ #include "bpy_driver.h" +#include "BPY_extern.h" + extern void BPY_update_rna_module(void); #define USE_RNA_AS_PYOBJECT +#define USE_BYTECODE_WHITELIST + +#ifdef USE_BYTECODE_WHITELIST +# include <opcode.h> +#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 +91,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 +110,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 +220,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 +250,130 @@ static void pydriver_error(ChannelDriver *driver) PyErr_Clear(); } +#ifdef USE_BYTECODE_WHITELIST + +#define OK_OP(op) [op] = 1 + +const char secure_opcodes[255] = { + OK_OP(0), + 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 char *codestr; + Py_ssize_t code_len; + + PyBytes_AsStringAndSize(py_code->co_code, (char **)&codestr, &code_len); + +#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1) + + for (Py_ssize_t i = 0; i < code_len; i += CODESIZE(codestr[i])) { + const int 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. * @@ -196,8 +385,12 @@ static void pydriver_error(ChannelDriver *driver) * (new)note: checking if python is running is not threadsafe [#28114] * now release the GIL on python operator execution instead, using * PyEval_SaveThread() / PyEval_RestoreThread() so we don't lock up blender. + * + * For copy-on-write we always cache expressions and write errors in the + * original driver, otherwise these would get freed while editing. Due to + * the GIL this is thread-safe. */ -float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, const float evaltime) +float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, ChannelDriver *driver_orig, const float evaltime) { PyObject *driver_vars = NULL; PyObject *retval = NULL; @@ -213,10 +406,11 @@ float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, c int i; /* get the py expression to be evaluated */ - expr = driver->expression; + expr = driver_orig->expression; 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 +420,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(); */ @@ -249,47 +446,50 @@ float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, c /* update global namespace */ bpy_pydriver_namespace_update_frame(evaltime); - if (driver->flag & DRIVER_FLAG_USE_SELF) { + if (driver_orig->flag & DRIVER_FLAG_USE_SELF) { bpy_pydriver_namespace_update_self(anim_rna); } else { bpy_pydriver_namespace_clear_self(); } - if (driver->expr_comp == NULL) - driver->flag |= DRIVER_FLAG_RECOMPILE; + if (driver_orig->expr_comp == NULL) + driver_orig->flag |= DRIVER_FLAG_RECOMPILE; /* compile the expression first if it hasn't been compiled or needs to be rebuilt */ - if (driver->flag & DRIVER_FLAG_RECOMPILE) { - Py_XDECREF(driver->expr_comp); - driver->expr_comp = PyTuple_New(2); + if (driver_orig->flag & DRIVER_FLAG_RECOMPILE) { + Py_XDECREF(driver_orig->expr_comp); + driver_orig->expr_comp = PyTuple_New(2); expr_code = Py_CompileString(expr, "<bpy driver>", Py_eval_input); - PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 0, expr_code); + PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 0, expr_code); - driver->flag &= ~DRIVER_FLAG_RECOMPILE; - driver->flag |= DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */ + driver_orig->flag &= ~DRIVER_FLAG_RECOMPILE; + driver_orig->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); + expr_code = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 0); } - if (driver->flag & DRIVER_FLAG_RENAMEVAR) { + if (driver_orig->flag & DRIVER_FLAG_RENAMEVAR) { /* may not be set */ - expr_vars = PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1); + expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1); Py_XDECREF(expr_vars); - expr_vars = PyTuple_New(BLI_listbase_count(&driver->variables)); - PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 1, expr_vars); + expr_vars = PyTuple_New(BLI_listbase_count(&driver_orig->variables)); + PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 1, expr_vars); - for (dvar = driver->variables.first, i = 0; dvar; dvar = dvar->next) { + for (dvar = driver_orig->variables.first, i = 0; dvar; dvar = dvar->next) { PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_FromString(dvar->name)); } - driver->flag &= ~DRIVER_FLAG_RENAMEVAR; + driver_orig->flag &= ~DRIVER_FLAG_RENAMEVAR; } else { - expr_vars = PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1); + expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1); } /* add target values to a dict that will be used as '__locals__' dict */ @@ -350,6 +550,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_orig->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_driver.h b/source/blender/python/intern/bpy_driver.h index 017a6fe89c5..971cbdf901f 100644 --- a/source/blender/python/intern/bpy_driver.h +++ b/source/blender/python/intern/bpy_driver.h @@ -27,14 +27,7 @@ #ifndef __BPY_DRIVER_H__ #define __BPY_DRIVER_H__ -struct ChannelDriver; -struct PathResolvedRNA; - int bpy_pydriver_create_dict(void); extern PyObject *bpy_pydriver_Dict; -/* externals */ -float BPY_driver_exec(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver, const float evaltime); -void BPY_driver_reset(void); - #endif /* __BPY_DRIVER_H__ */ diff --git a/source/blender/python/intern/bpy_interface.c b/source/blender/python/intern/bpy_interface.c index 5f51f2ac152..0d7b0c92a90 100644 --- a/source/blender/python/intern/bpy_interface.c +++ b/source/blender/python/intern/bpy_interface.c @@ -726,7 +726,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_rna_callback.c b/source/blender/python/intern/bpy_rna_callback.c index 45d556d68e9..7adb1d40fcc 100644 --- a/source/blender/python/intern/bpy_rna_callback.c +++ b/source/blender/python/intern/bpy_rna_callback.c @@ -101,7 +101,10 @@ PyObject *pyrna_callback_add(BPy_StructRNA *self, PyObject *args) if (RNA_struct_is_a(self->ptr.type, &RNA_Region)) { if (cb_event_str) { - if (pyrna_enum_value_from_id(region_draw_mode_items, cb_event_str, &cb_event, "bpy_struct.callback_add()") == -1) { + if (pyrna_enum_value_from_id( + region_draw_mode_items, cb_event_str, + &cb_event, "bpy_struct.callback_add()") == -1) + { return NULL; } } @@ -210,10 +213,16 @@ PyObject *pyrna_callback_classmethod_add(PyObject *UNUSED(self), PyObject *args) return NULL; } - if (pyrna_enum_value_from_id(region_draw_mode_items, cb_event_str, &cb_event, "bpy_struct.callback_add()") == -1) { + if (pyrna_enum_value_from_id( + region_draw_mode_items, cb_event_str, + &cb_event, "bpy_struct.callback_add()") == -1) + { return NULL; } - else if (pyrna_enum_value_from_id(rna_enum_region_type_items, cb_regiontype_str, &cb_regiontype, "bpy_struct.callback_add()") == -1) { + else if (pyrna_enum_value_from_id( + rna_enum_region_type_items, cb_regiontype_str, + &cb_regiontype, "bpy_struct.callback_add()") == -1) + { return NULL; } else { @@ -225,7 +234,10 @@ PyObject *pyrna_callback_classmethod_add(PyObject *UNUSED(self), PyObject *args) else { SpaceType *st = BKE_spacetype_from_id(spaceid); ARegionType *art = BKE_regiontype_from_id(st, cb_regiontype); - + if (art == NULL) { + PyErr_Format(PyExc_TypeError, "region type '%.200s' not in space", cb_regiontype_str); + return NULL; + } handle = ED_region_draw_cb_activate(art, cb_region_draw, (void *)args, cb_event); Py_INCREF(args); } @@ -276,7 +288,10 @@ PyObject *pyrna_callback_classmethod_remove(PyObject *UNUSED(self), PyObject *ar customdata = ED_region_draw_cb_customdata(handle); Py_DECREF((PyObject *)customdata); - if (pyrna_enum_value_from_id(rna_enum_region_type_items, cb_regiontype_str, &cb_regiontype, "bpy_struct.callback_remove()") == -1) { + if (pyrna_enum_value_from_id( + rna_enum_region_type_items, cb_regiontype_str, + &cb_regiontype, "bpy_struct.callback_remove()") == -1) + { return NULL; } else { @@ -288,7 +303,10 @@ PyObject *pyrna_callback_classmethod_remove(PyObject *UNUSED(self), PyObject *ar else { SpaceType *st = BKE_spacetype_from_id(spaceid); ARegionType *art = BKE_regiontype_from_id(st, cb_regiontype); - + if (art == NULL) { + PyErr_Format(PyExc_TypeError, "region type '%.200s' not in space", cb_regiontype_str); + return NULL; + } ED_region_draw_cb_exit(art, handle); } } diff --git a/source/blender/render/extern/include/RE_pipeline.h b/source/blender/render/extern/include/RE_pipeline.h index 55638471883..bde3c1c8cb3 100644 --- a/source/blender/render/extern/include/RE_pipeline.h +++ b/source/blender/render/extern/include/RE_pipeline.h @@ -221,6 +221,7 @@ void RE_ReleaseResultImageViews(struct Render *re, struct RenderResult *rr); void RE_AcquireResultImage(struct Render *re, struct RenderResult *rr, const int view_id); void RE_ReleaseResultImage(struct Render *re); void RE_SwapResult(struct Render *re, struct RenderResult **rr); +void RE_ClearResult(struct Render *re); struct RenderStats *RE_GetStats(struct Render *re); void RE_ResultGet32(struct Render *re, unsigned int *rect); @@ -311,8 +312,10 @@ void RE_draw_lock_cb (struct Render *re, void *handle, void (*f)(void *handle, void RE_test_break_cb (struct Render *re, void *handle, int (*f)(void *handle)); void RE_current_scene_update_cb(struct Render *re, void *handle, void (*f)(void *handle, struct Scene *scene)); +/* TODO replace by a simple set and get draw manager. */ void RE_gl_context_create(Render *re); void RE_gl_context_destroy(Render *re); +void RE_gl_context_set(Render *re, void *gl_context); void *RE_gl_context_get(Render *re); void *RE_gwn_context_get(Render *re); diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h index 34535fba1e0..134fa56f01c 100644 --- a/source/blender/render/intern/include/render_types.h +++ b/source/blender/render/intern/include/render_types.h @@ -161,6 +161,7 @@ struct Render { /* TODO replace by a whole draw manager. */ void *gl_context; void *gwn_context; + bool gl_context_ownership; }; /* **************** defines ********************* */ diff --git a/source/blender/render/intern/source/external_engine.c b/source/blender/render/intern/source/external_engine.c index 6e4336f80ea..7a9be04d8f6 100644 --- a/source/blender/render/intern/source/external_engine.c +++ b/source/blender/render/intern/source/external_engine.c @@ -797,8 +797,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, view_layer, name, type); } diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c index 54fb4251a3b..14ef7a3cb94 100644 --- a/source/blender/render/intern/source/pipeline.c +++ b/source/blender/render/intern/source/pipeline.c @@ -193,7 +193,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); @@ -330,6 +331,14 @@ RenderResult *RE_AcquireResultWrite(Render *re) return NULL; } +void RE_ClearResult(Render *re) +{ + if (re) { + render_result_free(re->result); + re->result = NULL; + } +} + void RE_SwapResult(Render *re, RenderResult **rr) { /* for keeping render buffers */ @@ -1021,10 +1030,13 @@ void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle)) /* ********* GL Context ******** */ +/* Create the gl context of the Render. + * It will be free by the render itself. */ void RE_gl_context_create(Render *re) { /* Needs to be created in the main ogl thread. */ re->gl_context = WM_opengl_context_create(); + re->gl_context_ownership = true; } void RE_gl_context_destroy(Render *re) @@ -1036,11 +1048,22 @@ void RE_gl_context_destroy(Render *re) re->gwn_context = NULL; } if (re->gl_context) { - WM_opengl_context_dispose(re->gl_context); + if (re->gl_context_ownership) { + WM_opengl_context_dispose(re->gl_context); + } re->gl_context = NULL; } } +/* Manually set the gl context of the Render. + * It won't be free by the render itself. */ +void RE_gl_context_set(Render *re, void *gl_context) +{ + BLI_assert(gl_context); /* Cannot set NULL */ + re->gl_context = gl_context; + re->gl_context_ownership = false; +} + void *RE_gl_context_get(Render *re) { return re->gl_context; @@ -1225,19 +1248,6 @@ static int composite_needs_render(Scene *sce, int this_scene) return 0; } -static bool rlayer_node_uses_alpha(bNodeTree *ntree, bNode *node) -{ - bNodeSocket *sock; - - for (sock = node->outputs.first; sock; sock = sock->next) { - /* Weak! but how to make it better? */ - if (STREQ(sock->name, "Alpha") && nodeCountSocketLinks(ntree, sock) > 0) - return true; - } - - return false; -} - bool RE_allow_render_generic_object(Object *ob) { /* override not showing object when duplis are used with particles */ @@ -1250,188 +1260,6 @@ bool RE_allow_render_generic_object(Object *ob) return true; } -/* Issue here is that it's possible that object which is used by boolean, - * array or shrinkwrap modifiers weren't displayed in the viewport before - * rendering. This leads to situations when apply() of this modifiers - * could not get ob->derivedFinal and modifiers are not being applied. - * - * This was worked around by direct call of get_derived_final() from those - * modifiers, but such approach leads to write conflicts with threaded - * update. - * - * Here we make sure derivedFinal will be calculated by update_for_newframe - * function later in the pipeline and all the modifiers are applied - * properly without hacks from their side. - * - sergey - - */ -#define DEPSGRAPH_WORKAROUND_HACK - -#ifdef DEPSGRAPH_WORKAROUND_HACK -static void tag_dependend_object_for_render(Scene *scene, Object *object); - -static void tag_dependend_group_for_render(Scene *scene, Collection *collection) -{ - if (collection->id.tag & LIB_TAG_DOIT) { - return; - } - collection->id.tag |= LIB_TAG_DOIT; - - for (CollectionObject *cob = collection->gobject.first; cob != NULL; cob = cob->next) { - Object *object = cob->ob; - tag_dependend_object_for_render(scene, object); - } -} - -static void tag_dependend_object_for_render(Scene *scene, Object *object) -{ - if (object->type == OB_MESH) { - if (RE_allow_render_generic_object(object)) { - ModifierData *md; - VirtualModifierData virtualModifierData; - - if (object->particlesystem.first) { - DEG_id_tag_update(&object->id, OB_RECALC_DATA); - } - - for (md = modifiers_getVirtualModifierList(object, &virtualModifierData); - md; - md = md->next) - { - if (!modifier_isEnabled(scene, md, eModifierMode_Render)) { - continue; - } - - if (md->type == eModifierType_Boolean) { - BooleanModifierData *bmd = (BooleanModifierData *)md; - if (bmd->object && bmd->object->type == OB_MESH) { - DEG_id_tag_update(&bmd->object->id, OB_RECALC_DATA); - } - } - else if (md->type == eModifierType_Array) { - ArrayModifierData *amd = (ArrayModifierData *)md; - if (amd->start_cap && amd->start_cap->type == OB_MESH) { - DEG_id_tag_update(&amd->start_cap->id, OB_RECALC_DATA); - } - if (amd->end_cap && amd->end_cap->type == OB_MESH) { - DEG_id_tag_update(&amd->end_cap->id, OB_RECALC_DATA); - } - } - else if (md->type == eModifierType_Shrinkwrap) { - ShrinkwrapModifierData *smd = (ShrinkwrapModifierData *)md; - if (smd->target && smd->target->type == OB_MESH) { - DEG_id_tag_update(&smd->target->id, OB_RECALC_DATA); - } - } - else if (md->type == eModifierType_ParticleSystem) { - ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md; - ParticleSystem *psys = psmd->psys; - ParticleSettings *part = psys->part; - switch (part->ren_as) { - case PART_DRAW_OB: - if (part->dup_ob != NULL) { - DEG_id_tag_update(&part->dup_ob->id, OB_RECALC_DATA); - } - break; - case PART_DRAW_GR: - if (part->dup_group != NULL) { - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, ob) - { - DEG_id_tag_update(&ob->id, OB_RECALC_DATA); - } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; - } - break; - } - } - } - } - } - if (object->dup_group != NULL) { - tag_dependend_group_for_render(scene, object->dup_group); - } -} - -static void tag_dependend_objects_for_render(Main *bmain, Scene *scene) -{ - BKE_main_id_tag_idcode(bmain, ID_GR, LIB_TAG_DOIT, false); - FOREACH_OBJECT_RENDERABLE_BEGIN(scene, object) - { - tag_dependend_object_for_render(scene, object); - } - FOREACH_OBJECT_RENDERABLE_END; -} -#endif - -static void tag_scenes_for_render(Render *re) -{ - bNode *node; - Scene *sce; - - for (sce = re->main->scene.first; sce; sce = sce->id.next) { - sce->id.tag &= ~LIB_TAG_DOIT; -#ifdef DEPSGRAPH_WORKAROUND_HACK - tag_dependend_objects_for_render(re->main, sce); -#endif - } - -#ifdef WITH_FREESTYLE - if (re->freestyle_bmain) { - for (sce = re->freestyle_bmain->scene.first; sce; sce = sce->id.next) { - sce->id.tag &= ~LIB_TAG_DOIT; -#ifdef DEPSGRAPH_WORKAROUND_HACK - tag_dependend_objects_for_render(re->freestyle_bmain, sce); -#endif - } - } -#endif - - if (RE_GetCamera(re) && composite_needs_render(re->scene, 1)) { - re->scene->id.tag |= LIB_TAG_DOIT; -#ifdef DEPSGRAPH_WORKAROUND_HACK - tag_dependend_objects_for_render(re->main, re->scene); -#endif - } - - if (re->scene->nodetree == NULL) return; - - /* check for render-layers nodes using other scenes, we tag them LIB_TAG_DOIT */ - for (node = re->scene->nodetree->nodes.first; node; node = node->next) { - node->flag &= ~NODE_TEST; - if (node->type == CMP_NODE_R_LAYERS && (node->flag & NODE_MUTED) == 0) { - if (node->id) { - if (!MAIN_VERSION_ATLEAST(re->main, 265, 5)) { - if (rlayer_node_uses_alpha(re->scene->nodetree, node)) { - Scene *scene = (Scene *)node->id; - - if (scene->r.alphamode != R_ALPHAPREMUL) { - BKE_reportf(re->reports, RPT_WARNING, "Setting scene %s alpha mode to Premul", scene->id.name + 2); - - /* also print, so feedback is immediate */ - printf("2.66 versioning fix: setting scene %s alpha mode to Premul\n", scene->id.name + 2); - - scene->r.alphamode = R_ALPHAPREMUL; - } - } - } - - if (node->id != (ID *)re->scene) { - if ((node->id->tag & LIB_TAG_DOIT) == 0) { - Scene *scene = (Scene *) node->id; - if (render_scene_has_layers_to_render(scene, NULL)) { - node->flag |= NODE_TEST; - node->id->tag |= LIB_TAG_DOIT; -#ifdef DEPSGRAPH_WORKAROUND_HACK - tag_dependend_objects_for_render(re->main, scene); -#endif - } - } - } - } - } - } - -} - static void ntree_render_scenes(Render *re) { bNode *node; @@ -1441,12 +1269,6 @@ static void ntree_render_scenes(Render *re) if (re->scene->nodetree == NULL) return; - tag_scenes_for_render(re); - -#ifdef DEPSGRAPH_WORKAROUND_GROUP_HACK - tag_collections_for_render(re); -#endif - /* now foreach render-result node tagged we do a full render */ /* results are stored in a way compisitor will find it */ for (node = re->scene->nodetree->nodes.first; node; node = node->next) { @@ -1564,9 +1386,6 @@ static void do_render_composite(Render *re) bNodeTree *ntree = re->scene->nodetree; int update_newframe = 0; - /* INIT seeding, compositor can use random texture */ - BLI_srandom(re->r.cfra); - if (composite_needs_render(re->scene, 1)) { /* save memory... free all cached images */ ntreeFreeCache(ntree); @@ -1643,11 +1462,6 @@ static void do_render_composite(Render *re) free_all_freestyle_renders(); #endif -#ifdef DEPSGRAPH_WORKAROUND_GROUP_HACK - /* Restore their visibility based on the viewport visibility flags. */ - tag_collections_for_render(re); -#endif - /* weak... the display callback wants an active renderlayer pointer... */ if (re->result != NULL) { re->result->renlay = render_get_active_layer(re, re->result); @@ -1831,7 +1645,7 @@ static void do_render_all_options(Render *re) /* ensure no images are in memory from previous animated sequences */ BKE_image_all_free_anim_ibufs(re->main, re->r.cfra); - BKE_sequencer_all_free_anim_ibufs(re->r.cfra); + BKE_sequencer_all_free_anim_ibufs(re->main, re->r.cfra); if (RE_engine_render(re, 1)) { /* in this case external render overrides all */ @@ -2101,7 +1915,7 @@ static void update_physics_cache(Render *re, Scene *scene, ViewLayer *view_layer PTCacheBaker baker; memset(&baker, 0, sizeof(baker)); - baker.main = re->main; + baker.bmain = re->main; baker.scene = scene; baker.view_layer = view_layer; baker.depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true); @@ -2167,14 +1981,6 @@ static int render_initialize_from_main(Render *re, RenderData *rd, Main *bmain, return 1; } - /* check all scenes involved */ - tag_scenes_for_render(re); - -#ifdef DEPSGRAPH_WORKAROUND_GROUP_HACK - /* Update collection collections visibility. */ - tag_collections_for_render(re); -#endif - /* * Disabled completely for now, * can be later set as render profile option @@ -2352,7 +2158,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); @@ -2407,7 +2213,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); @@ -2520,7 +2326,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(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); BLI_timecode_string_from_time_simple(name, sizeof(name), re->i.lastframetime - render_time); printf(" (Saving: %s)\n", name); @@ -2839,6 +2646,9 @@ void RE_PreviewRender(Render *re, Main *bmain, Scene *sce) RE_SetCamera(re, camera); do_render_3d(re); + + /* Destroy the opengl context in the correct thread. */ + RE_gl_context_destroy(re); } /* note; repeated win/disprect calc... solve that nicer, also in compo */ diff --git a/source/blender/render/intern/source/render_result.c b/source/blender/render/intern/source/render_result.c index e0cacdf4b8f..c259a60cda0 100644 --- a/source/blender/render/intern/source/render_result.c +++ b/source/blender/render/intern/source/render_result.c @@ -1227,7 +1227,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/windowmanager/WM_api.h b/source/blender/windowmanager/WM_api.h index 267aa448dc3..a2142b2d569 100644 --- a/source/blender/windowmanager/WM_api.h +++ b/source/blender/windowmanager/WM_api.h @@ -520,6 +520,7 @@ enum { WM_JOB_TYPE_DPAINT_BAKE, WM_JOB_TYPE_ALEMBIC, WM_JOB_TYPE_SHADER_COMPILATION, + WM_JOB_TYPE_STUDIOLIGHT, /* add as needed, screencast, seq proxy build * if having hard coded values is a problem */ }; diff --git a/source/blender/windowmanager/intern/wm.c b/source/blender/windowmanager/intern/wm.c index 6a42bf26a97..7eeea0f64ee 100644 --- a/source/blender/windowmanager/intern/wm.c +++ b/source/blender/windowmanager/intern/wm.c @@ -165,9 +165,6 @@ void wm_operator_register(bContext *C, wmOperator *op) wmWindowManager *wm = CTX_wm_manager(C); int tot = 0; - op->execution_area = CTX_wm_area(C); - op->execution_region = CTX_wm_region(C); - BLI_addtail(&wm->operators, op); /* only count registered operators */ diff --git a/source/blender/windowmanager/intern/wm_cursors.c b/source/blender/windowmanager/intern/wm_cursors.c index f13dac9cb4c..eaeaac45f89 100644 --- a/source/blender/windowmanager/intern/wm_cursors.c +++ b/source/blender/windowmanager/intern/wm_cursors.c @@ -194,7 +194,7 @@ void WM_cursor_modal_restore(wmWindow *win) void WM_cursor_wait(bool val) { if (!G.background) { - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; wmWindow *win = wm ? wm->windows.first : NULL; for (; win; win = win->next) { diff --git a/source/blender/windowmanager/intern/wm_event_system.c b/source/blender/windowmanager/intern/wm_event_system.c index ffef33d344a..e700a17b1ca 100644 --- a/source/blender/windowmanager/intern/wm_event_system.c +++ b/source/blender/windowmanager/intern/wm_event_system.c @@ -210,7 +210,7 @@ void WM_event_add_notifier(const bContext *C, unsigned int type, void *reference void WM_main_add_notifier(unsigned int type, void *reference) { - Main *bmain = G.main; + Main *bmain = G_MAIN; wmWindowManager *wm = bmain->wm.first; wmNotifier *note; @@ -235,7 +235,7 @@ void WM_main_add_notifier(unsigned int type, void *reference) */ void WM_main_remove_notifier_reference(const void *reference) { - Main *bmain = G.main; + Main *bmain = G_MAIN; wmWindowManager *wm = bmain->wm.first; if (wm) { @@ -263,7 +263,7 @@ void WM_main_remove_notifier_reference(const void *reference) void WM_main_remap_editor_id_reference(ID *old_id, ID *new_id) { - Main *bmain = G.main; + Main *bmain = G_MAIN; bScreen *sc; for (sc = bmain->screen.first; sc; sc = sc->id.next) { @@ -714,7 +714,7 @@ void WM_event_print(const wmEvent *event) */ void WM_report_banner_show(void) { - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; ReportList *wm_reports = &wm->reports; ReportTimerInfo *rti; @@ -749,7 +749,7 @@ static void wm_add_reports(ReportList *reports) { /* if the caller owns them, handle this */ if (reports->list.first && (reports->flag & RPT_OP_HOLD) == 0) { - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; /* add reports to the global list, otherwise they are not seen */ BLI_movelisttolist(&wm->reports.list, &reports->list); @@ -843,6 +843,7 @@ static bool wm_operator_register_check(wmWindowManager *wm, wmOperatorType *ot) static void wm_operator_finished(bContext *C, wmOperator *op, const bool repeat, const bool store) { wmWindowManager *wm = CTX_wm_manager(C); + enum { NOP, SET, CLEAR, } hud_status = NOP; op->customdata = NULL; @@ -854,10 +855,19 @@ static void wm_operator_finished(bContext *C, wmOperator *op, const bool repeat, * called from operators that already do an undo push. usually * this will happen for python operators that call C operators */ if (wm->op_undo_depth == 0) { - if (op->type->flag & OPTYPE_UNDO) + if (op->type->flag & OPTYPE_UNDO) { ED_undo_push_op(C, op); - else if (op->type->flag & OPTYPE_UNDO_GROUPED) + if (repeat == 0) { + hud_status = CLEAR; + } + } + else if (op->type->flag & OPTYPE_UNDO_GROUPED) { ED_undo_grouped_push_op(C, op); + if (repeat == 0) { + hud_status = CLEAR; + } + } + } if (repeat == 0) { @@ -873,11 +883,29 @@ static void wm_operator_finished(bContext *C, wmOperator *op, const bool repeat, wm_operator_register(C, op); WM_operator_region_active_win_set(C); + + /* Show the redo panel. */ + hud_status = SET; } else { WM_operator_free(op); } } + + if (hud_status != NOP) { + if (hud_status == SET) { + ScrArea *sa = CTX_wm_area(C); + if (sa) { + ED_area_type_hud_ensure(C, sa); + } + } + else if (hud_status == CLEAR) { + ED_area_type_hud_clear(wm, NULL); + } + else { + BLI_assert(0); + } + } } /* if repeat is true, it doesn't register again, nor does it free */ @@ -979,14 +1007,7 @@ int WM_operator_call_notest(bContext *C, wmOperator *op) */ int WM_operator_repeat(bContext *C, wmOperator *op) { - const OperatorRepeatContextHandle *context_info; - int retval; - - context_info = ED_operator_repeat_prepare_context(C, op); - retval = wm_operator_exec(C, op, true, true); - ED_operator_repeat_reset_context(C, context_info); - - return retval; + return wm_operator_exec(C, op, true, true); } /** * \return true if #WM_operator_repeat can run @@ -2358,8 +2379,7 @@ static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers if (event->type == MOUSEMOVE && !wm_manipulatormap_modal_get(mmap)) { int part; mpr = wm_manipulatormap_highlight_find(mmap, C, event, &part); - wm_manipulatormap_highlight_set(mmap, C, mpr, part); - if (mpr != NULL) { + if (wm_manipulatormap_highlight_set(mmap, C, mpr, part) && mpr != NULL) { WM_tooltip_timer_init(C, CTX_wm_window(C), region, WM_manipulatormap_tooltip_init); } } @@ -2527,24 +2547,34 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers) return action; if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) { - if (event->check_drag) { - wmWindow *win = CTX_wm_window(C); - if ((abs(event->x - win->eventstate->prevclickx)) >= U.tweak_threshold || - (abs(event->y - win->eventstate->prevclicky)) >= U.tweak_threshold) - { - short val = event->val; - short type = event->type; - event->val = KM_CLICK_DRAG; - event->type = win->eventstate->type; - CLOG_INFO(WM_LOG_HANDLERS, 1, "handling PRESS_DRAG"); + /* Test for CLICK_DRAG events. */ + if (wm_action_not_handled(action)) { + if (event->check_drag) { + wmWindow *win = CTX_wm_window(C); + if ((abs(event->x - win->eventstate->prevclickx)) >= U.tweak_threshold || + (abs(event->y - win->eventstate->prevclicky)) >= U.tweak_threshold) + { + short val = event->val; + short type = event->type; + event->val = KM_CLICK_DRAG; + event->type = win->eventstate->type; - action |= wm_handlers_do_intern(C, event, handlers); + CLOG_INFO(WM_LOG_HANDLERS, 1, "handling PRESS_DRAG"); - event->val = val; - event->type = type; + action |= wm_handlers_do_intern(C, event, handlers); - win->eventstate->check_click = 0; + event->val = val; + event->type = type; + + win->eventstate->check_click = 0; + win->eventstate->check_drag = 0; + } + } + } + else { + wmWindow *win = CTX_wm_window(C); + if (win) { win->eventstate->check_drag = 0; } } @@ -2552,7 +2582,7 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers) else if (ISMOUSE_BUTTON(event->type) || ISKEYBOARD(event->type)) { /* All events that don't set wmEvent.prevtype must be ignored. */ - /* test for CLICK events */ + /* Test for CLICK events. */ if (wm_action_not_handled(action)) { wmWindow *win = CTX_wm_window(C); @@ -2604,9 +2634,9 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers) } else { wmWindow *win = CTX_wm_window(C); - - if (win) + if (win) { win->eventstate->check_click = 0; + } } } diff --git a/source/blender/windowmanager/intern/wm_files.c b/source/blender/windowmanager/intern/wm_files.c index 3aaec875627..be805fa7b1f 100644 --- a/source/blender/windowmanager/intern/wm_files.c +++ b/source/blender/windowmanager/intern/wm_files.c @@ -153,8 +153,8 @@ static void wm_window_match_init(bContext *C, ListBase *wmlist) wmWindowManager *wm; wmWindow *win, *active_win; - *wmlist = G.main->wm; - BLI_listbase_clear(&G.main->wm); + *wmlist = G_MAIN->wm; + BLI_listbase_clear(&G_MAIN->wm); active_win = CTX_wm_window(C); @@ -227,7 +227,7 @@ static void wm_window_match_keep_current_wm( for (wmWindow *win = wm->windows.first; win; win = win->next) { WorkSpace *workspace; - BKE_workspace_layout_find_global(G.main, screen, &workspace); + BKE_workspace_layout_find_global(bmain, screen, &workspace); BKE_workspace_active_set(win->workspace_hook, workspace); win->scene = CTX_data_scene(C); @@ -440,12 +440,12 @@ void WM_file_autoexec_init(const char *filepath) } } -void wm_file_read_report(bContext *C) +void wm_file_read_report(bContext *C, Main *bmain) { ReportList *reports = NULL; Scene *sce; - for (sce = G.main->scene.first; sce; sce = sce->id.next) { + for (sce = bmain->scene.first; sce; sce = sce->id.next) { if (sce->r.engine[0] && BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL) { @@ -483,7 +483,9 @@ static void wm_file_read_post(bContext *C, const bool is_startup_file, const boo CTX_wm_window_set(C, wm->windows.first); ED_editors_init(C); - DEG_on_visible_update(CTX_data_main(C), true); + + Main *bmain = CTX_data_main(C); + DEG_on_visible_update(bmain, true); #ifdef WITH_PYTHON if (is_startup_file) { @@ -513,8 +515,8 @@ static void wm_file_read_post(bContext *C, const bool is_startup_file, const boo WM_operatortype_last_properties_clear_all(); /* important to do before NULL'ing the context */ - BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_VERSION_UPDATE); - BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST); + BLI_callback_exec(bmain, NULL, BLI_CB_EVT_VERSION_UPDATE); + BLI_callback_exec(bmain, NULL, BLI_CB_EVT_LOAD_POST); #if 1 WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL); @@ -525,7 +527,7 @@ static void wm_file_read_post(bContext *C, const bool is_startup_file, const boo /* report any errors. * currently disabled if addons aren't yet loaded */ if (addons_loaded) { - wm_file_read_report(C); + wm_file_read_report(C, bmain); } if (!G.background) { @@ -535,7 +537,7 @@ static void wm_file_read_post(bContext *C, const bool is_startup_file, const boo else { BKE_undosys_stack_clear(wm->undo_stack); } - BKE_undosys_stack_init_from_main(wm->undo_stack, CTX_data_main(C)); + BKE_undosys_stack_init_from_main(wm->undo_stack, bmain); BKE_undosys_stack_init_from_context(wm->undo_stack, C); } @@ -677,7 +679,7 @@ int wm_homefile_read( bool use_factory_settings, bool use_empty_data, bool use_userdef, const char *filepath_startup_override, const char *app_template_override) { - Main *bmain = G.main; /* Context does not always have valid main pointer here... */ + Main *bmain = G_MAIN; /* Context does not always have valid main pointer here... */ ListBase wmbase; bool success = false; @@ -1098,8 +1100,8 @@ 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"); - if (BLO_write_file(G.main, path, fileflags, NULL, NULL)) { + 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; } @@ -1234,7 +1236,7 @@ void wm_autosave_location(char *filepath) const char *savedir; #endif - if (G.main && G.relbase_valid) { + if (G_MAIN && G.relbase_valid) { const char *basename = BLI_path_basename(BKE_main_blendfile_path_from_global()); int len = strlen(basename) - 6; BLI_snprintf(path, sizeof(path), "%.*s.blend", len, basename); @@ -1384,7 +1386,7 @@ void wm_open_init_use_scripts(wmOperator *op, bool use_prefs) void WM_file_tag_modified(void) { - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; if (wm->file_saved) { wm->file_saved = 0; /* notifier that data changed, for save-over warning or header */ @@ -1401,6 +1403,7 @@ void WM_file_tag_modified(void) */ static int wm_homefile_write_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); wmWindowManager *wm = CTX_wm_manager(C); wmWindow *win = CTX_wm_window(C); char filepath[FILE_MAX]; @@ -1413,7 +1416,7 @@ static int wm_homefile_write_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; } - BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE); + BLI_callback_exec(bmain, NULL, BLI_CB_EVT_SAVE_PRE); /* check current window and close it if temp */ if (win && WM_window_is_temp_screen(win)) @@ -1431,7 +1434,7 @@ static int wm_homefile_write_exec(bContext *C, wmOperator *op) /* force save as regular blend file */ fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_HISTORY); - if (BLO_write_file(CTX_data_main(C), filepath, fileflags | G_FILE_USERPREFS, op->reports, NULL) == 0) { + if (BLO_write_file(bmain, filepath, fileflags | G_FILE_USERPREFS, op->reports, NULL) == 0) { printf("fail\n"); return OPERATOR_CANCELLED; } @@ -1440,7 +1443,7 @@ static int wm_homefile_write_exec(bContext *C, wmOperator *op) G.save_over = 0; - BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_POST); + BLI_callback_exec(bmain, NULL, BLI_CB_EVT_SAVE_POST); return OPERATOR_FINISHED; } @@ -2163,9 +2166,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; } diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c index c5a57147dd6..a14cbed6381 100644 --- a/source/blender/windowmanager/intern/wm_init_exit.c +++ b/source/blender/windowmanager/intern/wm_init_exit.c @@ -296,7 +296,7 @@ void WM_init(bContext *C, int argc, const char **argv) /* allow a path of "", this is what happens when making a new file */ #if 0 if (BKE_main_blendfile_path_from_global()[0] == '\0') - BLI_make_file_string("/", G.main->name, BKE_appdir_folder_default(), "untitled.blend"); + BLI_make_file_string("/", G_MAIN->name, BKE_appdir_folder_default(), "untitled.blend"); #endif BLI_strncpy(G.lib, BKE_main_blendfile_path_from_global(), sizeof(G.lib)); @@ -314,6 +314,7 @@ void WM_init(bContext *C, int argc, const char **argv) /* that prevents loading both the kept session, and the file on the command line */ } else { + Main *bmain = CTX_data_main(C); /* note, logic here is from wm_file_read_post, * call functions that depend on Python being initialized. */ @@ -324,10 +325,10 @@ void WM_init(bContext *C, int argc, const char **argv) * note that recovering the last session does its own callbacks. */ CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first); - BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_VERSION_UPDATE); - BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST); + BLI_callback_exec(bmain, NULL, BLI_CB_EVT_VERSION_UPDATE); + BLI_callback_exec(bmain, NULL, BLI_CB_EVT_LOAD_POST); - wm_file_read_report(C); + wm_file_read_report(C, bmain); if (!G.background) { CTX_wm_window_set(C, NULL); @@ -516,7 +517,6 @@ void WM_exit_ext(bContext *C, const bool do_python) GPU_pass_cache_free(); DRW_opengl_context_destroy(); } - BKE_studiolight_free(); #ifdef WITH_INTERNATIONAL BLF_free_unifont(); diff --git a/source/blender/windowmanager/intern/wm_keymap.c b/source/blender/windowmanager/intern/wm_keymap.c index 67493454e8f..bcb4fffea87 100644 --- a/source/blender/windowmanager/intern/wm_keymap.c +++ b/source/blender/windowmanager/intern/wm_keymap.c @@ -828,7 +828,7 @@ wmKeyMap *WM_modalkeymap_add(wmKeyConfig *keyconf, const char *idname, const Enu if (!items) { /* init modal items from default config */ - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; if (wm->defaultconf) { wmKeyMap *defaultkm = WM_keymap_list_find(&wm->defaultconf->keymaps, km->idname, 0, 0); @@ -992,11 +992,7 @@ int WM_keymap_item_raw_to_string( alt == KM_ANY && oskey == KM_ANY) { - /* make it implicit in case of compact result expected. */ - if (!compact) { - ADD_SEP; - p += BLI_strcpy_rlen(p, IFACE_("Any")); - } + /* Don't show anything for any mapping. */ } else { if (shift) { diff --git a/source/blender/windowmanager/intern/wm_operator_props.c b/source/blender/windowmanager/intern/wm_operator_props.c index 8e2f41c49e0..fa7ff85c874 100644 --- a/source/blender/windowmanager/intern/wm_operator_props.c +++ b/source/blender/windowmanager/intern/wm_operator_props.c @@ -130,7 +130,9 @@ void WM_operator_properties_filesel( static void wm_operator_properties_select_action_ex(wmOperatorType *ot, int default_action, const EnumPropertyItem *select_actions) { - RNA_def_enum(ot->srna, "action", select_actions, default_action, "Action", "Selection action to execute"); + PropertyRNA *prop; + prop = RNA_def_enum(ot->srna, "action", select_actions, default_action, "Action", "Selection action to execute"); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } void WM_operator_properties_select_action(wmOperatorType *ot, int default_action) diff --git a/source/blender/windowmanager/intern/wm_playanim.c b/source/blender/windowmanager/intern/wm_playanim.c index d93d51df105..30b1d6237c4 100644 --- a/source/blender/windowmanager/intern/wm_playanim.c +++ b/source/blender/windowmanager/intern/wm_playanim.c @@ -66,6 +66,7 @@ #include "GPU_matrix.h" #include "GPU_immediate.h" #include "GPU_immediate_util.h" +#include "GPU_batch.h" #include "DNA_scene_types.h" #include "ED_datafiles.h" /* for fonts */ @@ -179,6 +180,7 @@ typedef enum eWS_Qual { static struct WindowStateGlobal { GHOST_SystemHandle ghost_system; void *ghost_window; + Gwn_Context *gwn_context; /* events */ eWS_Qual qual; @@ -195,7 +197,8 @@ static void playanim_window_get_size(int *r_width, int *r_height) static void playanim_gl_matrix(void) { /* unified matrix, note it affects offset for drawing */ - gpuOrtho2D(0.0f, 1.0f, 0.0f, 1.0f); + /* note! cannot use gpuOrtho2D here because shader ignores. */ + gpuOrtho(0.0f, 1.0f, 0.0f, 1.0f, -1.0, 1.0f); } /* implementation */ @@ -1262,6 +1265,7 @@ static char *wm_main_playanim_intern(int argc, const char **argv) //GHOST_ActivateWindowDrawingContext(g_WS.ghost_window); /* initialize OpenGL immediate mode */ + g_WS.gwn_context = GWN_context_create(); immInit(); /* initialize the font */ @@ -1538,6 +1542,12 @@ static char *wm_main_playanim_intern(int argc, const char **argv) immDestroy(); + if (g_WS.gwn_context) { + GWN_context_active_set(g_WS.gwn_context); + GWN_context_discard(g_WS.gwn_context); + g_WS.gwn_context = NULL; + } + BLF_exit(); GHOST_DisposeWindow(g_WS.ghost_system, g_WS.ghost_window); diff --git a/source/blender/windowmanager/intern/wm_tooltip.c b/source/blender/windowmanager/intern/wm_tooltip.c index 6096317b582..94a44a97afd 100644 --- a/source/blender/windowmanager/intern/wm_tooltip.c +++ b/source/blender/windowmanager/intern/wm_tooltip.c @@ -41,6 +41,8 @@ void WM_tooltip_timer_init( bContext *C, wmWindow *win, ARegion *ar, wmTooltipInitFn init) { + WM_tooltip_timer_clear(C, win); + bScreen *screen = WM_window_get_active_screen(win); wmWindowManager *wm = CTX_wm_manager(C); if (screen->tool_tip == NULL) { diff --git a/source/blender/windowmanager/intern/wm_window.c b/source/blender/windowmanager/intern/wm_window.c index e1528551c12..076514cd73f 100644 --- a/source/blender/windowmanager/intern/wm_window.c +++ b/source/blender/windowmanager/intern/wm_window.c @@ -232,7 +232,7 @@ void wm_window_free(bContext *C, wmWindowManager *wm, wmWindow *win) wm_ghostwindow_destroy(wm, win); - BKE_workspace_instance_hook_free(G.main, win->workspace_hook); + BKE_workspace_instance_hook_free(G_MAIN, win->workspace_hook); MEM_freeN(win->stereo3d_format); MEM_freeN(win); @@ -553,7 +553,7 @@ void wm_window_title(wmWindowManager *wm, wmWindow *win) char str[sizeof(((Main *)NULL)->name) + 24]; BLI_snprintf(str, sizeof(str), "Blender%s [%s%s]", wm->file_saved ? "" : "*", BKE_main_blendfile_path_from_global(), - G.main->recovered ? " (Recovered)" : ""); + G_MAIN->recovered ? " (Recovered)" : ""); GHOST_SetTitle(win->ghostwin, str); } else @@ -1236,7 +1236,7 @@ void wm_window_reset_drawable(void) { BLI_assert(BLI_thread_is_main()); BLI_assert(GPU_framebuffer_current_get() == 0); - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; if (wm == NULL) return; @@ -2318,13 +2318,14 @@ void *WM_opengl_context_create(void) * So we should call this function only on the main thread. */ BLI_assert(BLI_thread_is_main()); - BLI_assert(GPU_framebuffer_current_get() == 0); + // BLI_assert(GPU_framebuffer_current_get() == 0); return GHOST_CreateOpenGLContext(g_system); } void WM_opengl_context_dispose(void *context) { - BLI_assert(GPU_framebuffer_current_get() == 0); + // BLI_assert(BLI_thread_is_main()); + // BLI_assert(GPU_framebuffer_current_get() == 0); GHOST_DisposeOpenGLContext(g_system, (GHOST_ContextHandle)context); } diff --git a/source/blender/windowmanager/manipulators/intern/wm_manipulator.c b/source/blender/windowmanager/manipulators/intern/wm_manipulator.c index 5634a1a3ee7..d6eb110dca0 100644 --- a/source/blender/windowmanager/manipulators/intern/wm_manipulator.c +++ b/source/blender/windowmanager/manipulators/intern/wm_manipulator.c @@ -92,7 +92,7 @@ static wmManipulator *wm_manipulator_create( IDPropertyTemplate val = {0}; mpr->properties = IDP_New(IDP_GROUP, &val, "wmManipulatorProperties"); } - RNA_pointer_create(G.main->wm.first, wt->srna, mpr->properties, mpr->ptr); + RNA_pointer_create(G_MAIN->wm.first, wt->srna, mpr->properties, mpr->ptr); WM_manipulator_properties_sanitize(mpr->ptr, 0); diff --git a/source/blender/windowmanager/manipulators/intern/wm_manipulator_map.c b/source/blender/windowmanager/manipulators/intern/wm_manipulator_map.c index ab8c797df69..7b06382b029 100644 --- a/source/blender/windowmanager/manipulators/intern/wm_manipulator_map.c +++ b/source/blender/windowmanager/manipulators/intern/wm_manipulator_map.c @@ -542,9 +542,8 @@ static wmManipulator *manipulator_find_intersected_3d( int hotspot_radii[] = { 3 * U.pixelsize, -#if 0 /* We may want to enable when selection doesn't run on mousemove! */ - 7 * U.pixelsize, -#endif + /* This runs on mouse move, careful doing too many tests! */ + 10 * U.pixelsize, }; *r_part = 0; @@ -846,7 +845,7 @@ bool WM_manipulatormap_cursor_set(const wmManipulatorMap *mmap, wmWindow *win) return false; } -void wm_manipulatormap_highlight_set( +bool wm_manipulatormap_highlight_set( wmManipulatorMap *mmap, const bContext *C, wmManipulator *mpr, int part) { if ((mpr != mmap->mmap_context.highlight) || @@ -881,7 +880,11 @@ void wm_manipulatormap_highlight_set( ARegion *ar = CTX_wm_region(C); ED_region_tag_redraw(ar); } + + return true; } + + return false; } wmManipulator *wm_manipulatormap_highlight_get(wmManipulatorMap *mmap) diff --git a/source/blender/windowmanager/manipulators/wm_manipulator_wmapi.h b/source/blender/windowmanager/manipulators/wm_manipulator_wmapi.h index 87cf711a60b..7b294b9320f 100644 --- a/source/blender/windowmanager/manipulators/wm_manipulator_wmapi.h +++ b/source/blender/windowmanager/manipulators/wm_manipulator_wmapi.h @@ -77,7 +77,7 @@ void wm_manipulatormap_handler_context(bContext *C, struct wmEventHandler *handl struct wmManipulator *wm_manipulatormap_highlight_find( struct wmManipulatorMap *mmap, bContext *C, const struct wmEvent *event, int *r_part); -void wm_manipulatormap_highlight_set( +bool wm_manipulatormap_highlight_set( struct wmManipulatorMap *mmap, const bContext *C, struct wmManipulator *mpr, int part); struct wmManipulator *wm_manipulatormap_highlight_get(struct wmManipulatorMap *mmap); diff --git a/source/blender/windowmanager/wm_files.h b/source/blender/windowmanager/wm_files.h index 4e87202ef5f..5b6022658db 100644 --- a/source/blender/windowmanager/wm_files.h +++ b/source/blender/windowmanager/wm_files.h @@ -31,6 +31,7 @@ #ifndef __WM_FILES_H__ #define __WM_FILES_H__ +struct Main; struct wmOperatorType; /* wm_files.c */ @@ -39,7 +40,7 @@ int wm_homefile_read( struct bContext *C, struct ReportList *reports, bool use_factory_settings, bool use_empty_data, bool use_userdef, const char *filepath_startup_override, const char *app_template_override); -void wm_file_read_report(bContext *C); +void wm_file_read_report(bContext *C, struct Main *bmain); void WM_OT_save_homefile(struct wmOperatorType *ot); void WM_OT_userpref_autoexec_path_add(struct wmOperatorType *ot); |