T99807: Add support for exporting to USDZ #104556

Closed
Sonny Campbell wants to merge 8 commits from SonnyCampbell_Unity/blender:unity/T99807-usdz-refactor into main

When changing the target branch, be careful to rebase the branch in your fork to match. See documentation.
Member

Historical patch review here: https://archive.blender.org/developer/D15623

This change will add the default .usdz export capability. There is a separate UsdUtilsCreateNewARKitUsdzPackage capability for exporting usdz for iOS devices that will be implemented in a follow up patch as it will require some more small UI changes.

The importer already supports usdz so no change is required other than updating the text in menu to match the updated exporter text.

On export, we must first create a .usd/a/c file and then covert it to .usdz. We are required to do a weird change of directory because of a quirk with the USD conversion to usdz. If an absolute filepath is passed into the UsdUtilsCreateNewUsdzPackage function, the usd files inside the usdz archive will have the same directory structure, i.e. if I try to create a file at C:\code\BlenderProjects\file.usdz, when I create the usdz file inside it will have the structure \code\BlenderProjects\file.usdc.

This is counteracted by setting the current working directory to the temporary session directory where I create both the usdc and usdz files, and just passing the file name to UsdUtilsCreateNewUsdzPackage without any filepath. Once the usdz file is created I copy it out to the intended directory.

Historical patch review here: https://archive.blender.org/developer/D15623 This change will add the default .usdz export capability. There is a separate UsdUtilsCreateNewARKitUsdzPackage capability for exporting usdz for iOS devices that will be implemented in a follow up patch as it will require some more small UI changes. The importer already supports usdz so no change is required other than updating the text in menu to match the updated exporter text. On export, we must first create a .usd/a/c file and then covert it to .usdz. We are required to do a weird change of directory because of a quirk with the USD conversion to usdz. If an absolute filepath is passed into the UsdUtilsCreateNewUsdzPackage function, the usd files inside the usdz archive will have the same directory structure, i.e. if I try to create a file at C:\code\BlenderProjects\file.usdz, when I create the usdz file inside it will have the structure \code\BlenderProjects\file.usdc. This is counteracted by setting the current working directory to the temporary session directory where I create both the usdc and usdz files, and just passing the file name to UsdUtilsCreateNewUsdzPackage without any filepath. Once the usdz file is created I copy it out to the intended directory.
Sonny Campbell added 2 commits 2023-02-10 09:26:36 +01:00
02a45eeeeb Added unit testing to cover usdz export.
Removed `is_usdz_export` flag to now check if `usdz_filepath` is set instead.
Renamed `unarchived_filepath` to clearly distiguish from `usdz_filepath`. Added comments to clarify the difference.
Created a method on `ExportJobData` to return the final export filepath.
Added comment summary to `perform_usdz_conversion` describing functionality.
Sonny Campbell requested review from Sybren A. Stüvel 2023-02-10 09:26:46 +01:00
Sonny Campbell requested review from Michael Kowalski 2023-02-10 09:26:56 +01:00
Sonny Campbell added 806 commits 2023-02-10 09:36:56 +01:00
d7598c8081 Metal: Fix crash when compiling compositor shaders.
Although viewport compositor isn't supported yet on Apple deviced the
shaderlibs are compiled. The compositor shaders uses mat3 constructor
with a single vec3 and 6 floats. This constructor wasn't defined in
metal so it failed the compilation.

This patch adds the override to mat3.
34fa369b48 Eevee: Mark Properties on Samples Panel Animatable.
Eevee:
Mark `Scene->Sampling->Render/Viewport` samples animatable.
Mark Viewport Denoising also animatable

Reviewed By: jbakker

Differential Revision: https://developer.blender.org/D16827
76a68649c1 Animation: Graph Editor Ease operator
Added a new operator that aligns selected keys on an exponential curve

Revied by Reviewed by: Sybren A. Stüvel
Differential Revision: https://developer.blender.org/D9479
Ref: D9479
200a114e15 Fix T87548: Propagate Pose, Next Keyframe
Change the logic for propagating poses such that it checks keyframes
on all selected bones to determine the frame on which a pose
should be propagated to.
It then adds keyframes if they don't exist on whatever
frame the pose should be propagated to.

Reviewd by: Sybren A. Stüvel
Differential Revision: https://developer.blender.org/D16654
Ref: D16654
963600ddc0 CMake: when compiler is too old, report found version
To aid in debugging the case where your compiler is too old for Blender,
actually log which version CMake found.

Before, CMake would output:
```
CMake Error at CMakeLists.txt:121 (message):
  The minimum supported version of GCC is 11.0.0
```

With the patch, it logs:
```
CMake Error at CMakeLists.txt:121 (message):
  The minimum supported version of GCC is 11.0.0, found 10.4.0
```

This has been implemented for GCC and Clang. MSVC has been explicitly
excluded, as the version numbers used for this comparison are internal
versions and not directly usable/recognisable.

Reviewed By: LazyDodo, brecht

Differential Revision: https://developer.blender.org/D16849
58b6c91d36 Cleanup: Remove unused runtime field from the MovieClip
It is a part of old-standing TODO, and code which accesses
the value was commented out for many years.

Remove the field to help with an upcoming const-correctness
improvements.
fdc918c32c Cleanup: Better const-correctness in MovieClip
Mainly make MovieClipUser constant.
2ffd08e952 Geometry Nodes: deterministic anonymous attribute lifetimes
Previously, the lifetimes of anonymous attributes were determined by
reference counts which were non-deterministic when multiple threads
are used. Now the lifetimes of anonymous attributes are handled
more explicitly and deterministically. This is a prerequisite for any kind
of caching, because caching the output of nodes that do things
non-deterministically and have "invisible inputs" (reference counts)
doesn't really work.

For more details for how deterministic lifetimes are achieved, see D16858.

No functional changes are expected. Small performance changes are expected
as well (within few percent, anything larger regressions should be reported as
bugs).

Differential Revision: https://developer.blender.org/D16858
a318f3b8d6 install_deps: Add py binding for OCIO, OIIO, OpenVDB and USD.
This was quite a fight, some resulting notes:
* We cannot use anymore Boost packages because of a weird bug breaking
  Blender debug builds and ivolving Boost, TBB and USD (see also
  rB019b930d6b9c).
* OCIO, OIIO, OpenVDB and USD build options where updated to match these
  from cmake libs building.
** Most notably, USD now has imaging, OIIO, OpenVDB and GL support.

Ref. T99618.
862d08bb97 Fix: use-after-free when threadlocal is destructed after static variable
This issue was introduced in rB78f28b55d39288926634d0cc.

The fix is to use a `std::shared_ptr` to ensure that the `Global` will live
long enough until all `Local` objects are destructed.
25e28f518c install_deps: Add package handling for fribidi, harfbuzz, shaderc and vulkan ICD loader.
All these are available on recent distros, don't think it's worth adding
support to build them for the time being.

Ref. T99618.
a5d4c63e86 GPencil: remove multiframe copy/paste restriction
Multiframe copy paste operations were prohibited by a block of code.
While this is understandable as it prevents confusing actions, there is a good use case to allow multiframe copy pasting.

This patch does:
- remove restricting block of code
- adds outer loops for frames both in copy and paste actions.

In copy action it will create an array of selected strokes from all selected frames
In paste action it will create new from previous copy action merged to a single frame. It will paste to all selected frames and create new frame if autokey is on and time cursor is not on any of the keyframes.

The main usecase is for creating motion smears as in examples attached. The user still need to do some actions in order to achieve desired look, such as stroke ordering and deleting excessive strokes.

{F14069747}

{F14069743}

Reviewed By: antoniov, mendio

Differential Revision: https://developer.blender.org/D16805
d1810d11f4 Fix T103303: Dbl-click in the Graph Editor wont select all keyframes
This was the case when an Annotation is also present as in the report.

Since {rB92d7f9ac56e0}, Dopesheet is aware of greaspencil/annotations
(displays its channels/keyframes, can rename their data, layers, fcurve
groupings etc.). However, the Graph Editor does not display these /
should not be aware of them.

Above commit already had issues that were addressed in the following
commits (mostly adding the new `ANIMFILTER_FCURVESONLY` to places that
dont handle greasepencil/annotations)
- {rBfdf34666f00f}
- {rB45f483681fef}
- {rBa26038ff3851}

Now in T103303 it was reported that doublicking a channel would not
select all fcurve`s keyframes anymore and this wasnt actually an issue
with that particular operator, but instead with another operator that is
also mapped to doubleclicking: the channel renaming (I assume the
keyconflict here is actually wanted behavior).
Channel renaming would not return `OPERATOR_PASS_THROUGH` here anymore
in the case nothing cannot be renamed, so we would not actually reach
the 2nd operator at all (the one selecting all keyframes).
Deeper reason for this is that the renaming operator would actually
"see" a channel that could be renamed (in the case of the report: an
annotation layer), but then cannot proceed, because the "real"
underlying data where the doubleclick happens is an fcurve...

So now exclude non-greasepencil channels in filtering as well where
appropriate by also adding `ANIMFILTER_FCURVESONLY` to the filter there.

Fixes T103303.

Maniphest Tasks: T103303

Differential Revision: https://developer.blender.org/D16871
74c4977aea Pose Library: allow extrapolating the pose
While blending, press E to enable extrapolation / overshoot of the pose.
It will make it possible to blend in more than 100% of the pose asset.
This has the potential to completely break the rig, but it can be useful
to exaggerate poses when used with caution.
8a65e33d41 Pose Library: properly set hard min/max for blend factor
Since rBcommit 74c4977a the pose library blending operator can extrapolate.
This is now also reflected in the hard min/max value of the blend factor
RNA property. The soft min/max are still -1/1 to indicate normal use.
59ce7bf5a9 Nodes: better default name for custom node tree datablocks
Use NodeTree.bl_label instead of "NodeTree" for more descriptive name.

Implemented by Iliya Katueshenock.

Differential Revision: https://developer.blender.org/D16856
0fb12a9c2e GPencil: Fix size difference between radial control and Brush size
Due an internal scale of the brush size done by grease pencil
draw tool (this scale factor cannot be removed), the size of the
radial control is not equal to the actual stroke thickness and
this makes the radial size displayed useless.

This patch adds a new property that allows to pass the
path of the tool path and this value is used to apply
the correct scale to the radial size.

Reviewed By: mendio, frogstomp, pepeland, brecht

Differential Revision: https://developer.blender.org/D16866
7d712dcd0b Gpencil: Add offset(Location, Rotation, Scale) by Layer, Stroke and Material to Offset modifier
This patch adds two new panels in which users can control
offset (position, rotation, scale) by layer and by stroke number.

Use cases:
- if you want to create array of Suzannes and place them one behind 
another, in 2d mode, Z depth will be wrong. 
In 3d mode there will be Z fighting. With combination of stroke 
and layer offset we can fight this issue without touching original drawing.
- even easier way to create 2.5d environments.. 
simply draw on layers and then displace them in one panel 
instead fiddling with every layer individually

Possible improvements:
- add offset by material slot
- add step parameter, to allow displacing groups of N strokes.

{F13129598}

Reviewed By: mendio, antoniov

Differential Revision: https://developer.blender.org/D15106
084b52bcd8 Cycles: take into account IES texture node strength input for light tree
To better estimate light contribution. Note that estimating the texture
from the IES file is still missing.

Contributed by Alaska.

Differential Revision: https://developer.blender.org/D16901
0796210c8d BVH: implement an optimized self-overlap traversal.
Previously cloth self-collision and other code that wants self-overlap
data was using an ordinary BVH overlap utility function. This works,
but is suboptimal because it fails to take advantage of the fact that
it is comparing two identical trees.

The standard traversal for self-collision essentially devolves into
enumerating all elements of the tree, and then matching them to the
tree starting at the root. However, the tree itself naturally partitions
the space, so overlapping elements are likely to be mostly placed nearby
in the tree structure as well.

Instead, self-overlap can be computed by recursively computing ordinary
overlap between siblings within each subtree. This only considers each
pair of leaves once, and provides significantly better locality.
It also avoids outputting every overlap pair twice in different order.

Differential Revision: https://developer.blender.org/D16915
4fb0eb3a6e Minor fixes after introducing special BVH traversal for self-collision.
- Add parentheses to suppress an assertion on some compilers.

- It turns out cloth self-collision math is not precisely symmetric,
  so sort the triangle index pair to restore behavior exactly identical
  to the version before the new traversal.

Follow up to rB0796210c8df32
bc5337a05a Fix T103507: Distant lights partially contribute to wrong lightgroup
The the BSDF-sampling half of MIS next-event estimation for distant lights was
using the background lightgroup instead of the lamp's lightgroup.
8d0c98740a Cleanup: remove unused OffsetGpencilModifierData.object
Added as part of D15106 but was not used anywhere.
280502e630 Fix T103469: improve uv cylinder projection and uv sphere projection
Multiple improvements to UV Cylinder and UV Sphere projection including:

 * New option "Pinch" or "Fan" to improve unwrap of faces at the poles.
 * Support for "Polar ZY" option on "View On Equator" and "Align To Object"
 * Better handling of inputs with round-off error.
 * Improved handling of faces touching the unit square border.
 * Improved handling of very wide quads spanning the right hand border.
 * Improved accuracy near to (0, 0).
 * Code cleanup and simplification.

Differential Revision: https://developer.blender.org/D16869
b6c74b4c6f Fix T82081: Remove workaround for OCIO Unicode issue on Windows
This workaround is no longer needed and prevents our OCIO configuration
from being loaded if Blender is unpacked under a Unicode path.

Differential Revision: https://developer.blender.org/D16818
fc9c39e320 Fix T103242: Missing update on undo/redo for some image properties.
Issue comes from the fact that some of the image updates are handled
outside of depsgraph context (through the signal system), and therefore
completely ignored by the undo/redo code.

Now that undo/redo tries to update as little data as possible, it needs
to be aware of these changes.

As a temporary workaround, until image update is fully handled through depsgraph,
consider that IDs tagged with `ID_RECALC_SOURCE` should get their caches
cleared on undo/redo, and tag some RNA property updates of
Image/ColorSpace as such.

Reviewed By: sergey

Maniphest Tasks: T103242

Differential Revision: https://developer.blender.org/D16927
42b88c0088 Functions: simplify multi-function parameters
The use of `std::variant` allows combining the four vectors
into one which more closely matches the intend and avoids
a workaround used before.

Note that this uses `std::get_if` instead of `std::get` because
`std::get` is only available since macOS 10.14.
1229b96652 Fix empty asset index files after bug in asset loading
Initial error caused by 1efc94bb2f and fixed in 6a7917162c. However
the empty index files (empty as in, they contain the version number but
no assets) will have to be fixed somehow, since otherwise assets don't
show up at all for people who saved asset files in a broken version.

Delete empty index files if the modification timestamp indicates a time
when the bug was present (plus a day before and after, to address
possible time zone differences). This will basically make Blender skip
the optimization for .blend files without assets for one load, but even
then the index should still produce faster results than a completely
non-index read.

This can be removed after a while, it's just a (much needed) fix for
people who were using alpha/beta builds.

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

Reviewed by: Jeroen Bakker
8556741183 Editors: Slider, add possibility to disable ctrl-for-increments
The slider component can now be told to not use CTRL for toggling stepped
10% increments. This is useful when the operator that uses the slider needs
that modifier key for its own purposes.
bd36c712b9 Pose Library: while blending, use CTRL for flipping the pose
Using negative blend factors for blending in flipped poses was undesirable.
Instead, the pose blending operator now uses CTRL to flip the pose.

Negative blend values are still allowed, and cause the pose asset to be
subtracted from the current pose. It can quickly break the rig, but for
small adjustments it can be useful.
3337838b49 Fix: retrieved writable attribute but did not write to it
This caused a warning because `attribute.finish` was not called.
006e905957 Tests: support running benchmark when Blender prints unrelated text
I noticed that sometimes the geometry nodes benchmark would not work
if there were some left-over debug prints in the code. The reason it did
not work was because the prints were mixed with the test output print.
I also tried using explicit flusing and `atexit` for printing the test output,
but that didn't solve it. Just printing additional newlines to better separate
the test output from other printed output helped though.
d49b850399 Tests: run geometry nodes benchmarks multiple times to reduce noise
Ideally, we would also get variance information out of the test, but that
seems a bit more complex to implement. For now just run the test a couple
of times and average the timings.

The test now runs between 5 and 100 times, depending on how long it
to run the test once.
ae7163007d Allocator: improve protection against false sharing
On Apple Silicon, the cache line size is 128 bytes.
825f01b7b5 Animation: Remove While Held Pose propagate option
The "While Held" option from the Pose Propagate Operator
doesn't do anything meaningful.
After talking with the Animation Module it was decided to remove it.

In code it was called `POSE_PROPAGATE_SMART_HOLDS`

Reviewed by: Sybren A. Stüvel
Differential Revision: https://developer.blender.org/D16771
Ref: D16771
5eab813fc0 Fix T102746: Jumping to next/previous (key)frame doesn't take subframes into account
Previously when on frame 2.5 and trying to jump to a
keyframe that was on frame 2, it would instead jump past it.

Now it properly respects the subframes for that.

Reviewed by: Sybren A. Stüvel
Differential Revision: https://developer.blender.org/D16651
Ref: D16651
cc78fd4e93 Realtime Compositor: Allow limited compositing region
This patch allows the realtime compositor to be limited to a specific
compositing region that is a subset of the full render region. In the
context of the viewport compositor, when the viewport is in camera view
and has a completely opaque passepartout, the compositing region will be
limited to the visible camera region.

On the user-level, this gives the user the ability to make the result of
the compositor invariant of the aspect ratio, shift, and zoom of the
viewport, making the result in the viewport identical to the final
render compositor assuming size relative operations.

It should be noted that compositing region is the *visible* camera
region, that is, the result of the intersection of the camera region and
the render region. So the user should be careful not to shift or zoom
the view such that the camera border extends outside of the viewport to
have the aforementioned benefits. While we could implement logic to fill
the areas outside of the render region with zeros in some cases, there
are many other ambiguous cases where such a solution wouldn't work,
including the problematic case where the user zooms in very close,
making the camera region much bigger than that of the render region.

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

Reviewed By: Clement Foucault
0bf8b98437 Realtime Compositor: Move out of experimental
This patch moves the realtime compositor out of experimental. See
T99210.

The first milestone is finished with regards to implementing most
essential nodes for single pass compositing. It is also now documented
in the manual and no major issues are known.

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

Reviewed By: Clement Foucault
d05909a70c Fix T102766: Refactor liboverride diffing, by un-threading restoration step.
The reported backtrace in T102766 strongly points at some
concurrency issues within exisitng liboverride diffing code that
restores forbidden changes to reference linked data values.

This commit instead add tags to mark liboverrides/properties that need
to be restored, and do so in a separate new step of diffing, from the
main thread only.
e0d70e6a9d Nodes: avoid processing same node group multiple times to find textures
This removes a lot of overhead when there are node groups that are
reused a lot and only need to be processed once.
a3a60e9647 Nodes: Resolve performance bottleneck with mix node updates
Improve animation playback performance in EEVEE for materials using Mix
nodes. Socket availability was being set and reset on every evaluation
of Mix nodes, during animation playback, this was causing the graph to
be marked dirty, and the whole graph being re-evaluated on every frame,
causing performance issues during playback.

Additionally, do a bit of cleanup, traversing the node sockets with
the next link to improve clarity and reduce errors. Also refactoring
`nodeSetSocketAvailability` to early out and increase clarity on no-op.

Differential Revision: https://developer.blender.org/D16929
87fd798ae3 Nodes: Remove runtime socket location from struct
Socket locations are set while drawing the node tree in the editor.
They can always be recalculated this way based on the node position and
other factors. Storing them in the socket is misleading. Plus, ideally
sockets would be quite small to store, this helps us move in that
direction.

Now the socket locations are stored as runtime data of the node editor,
making use of the new node topology cache's `index_in_tree` function
to make a SoA layout possible.

Differential Revision: https://developer.blender.org/D15874
2752a88478 Object: Support converting curves object to mesh
Previously you had to use a workaround with the Object info node to get
evaluated data from the new curves object to an original editable mesh.
This commit makes it so that a curves object can be converted directly
to a mesh object if it has evaluated curves or an evaluated mesh.

Differential Revision: https://developer.blender.org/D16930
3b37538975 Fix T103663: Set material node can fail for single material
Caused by f1c0249f34, which filled the wrong value.
I have noticed several problems:
- Using a full array as single result.
- Checking single material index for 0. If we have a list of all slots,
  then we must check this in the list.
- The result was filled false. Simple fix.
- Fixed problem with incorrect recording by mask indices, not polygons.
    - Added domain specifics to names to avoid confusion.

Differential Revision: https://developer.blender.org/D16926
5cc793912e Fix T103671: memory leak in material preview render
Introduced with the fix for T103101.
a3ac91da27 Cloth: share self and object collision BVH trees when possible.
Both cloth object collision and self collision use a BVH tree
representing the current cloth shape. The only difference between
them is the epsilon threshold value.

If these values are the same, it is possible to use the same tree
for both uses, thus easily reducing the overhead in the case when
both collision modes are used by the same cloth object.

Differential Revision: https://developer.blender.org/D16914
e1df731c91 Cloth: precompute barycentric coordinates for collision points.
Profiling shows that this computation consumes a noticeable amount
of time, so it is worth moving it to an earlier part of the code
that is executed less frequently and is multithreaded.

Differential Revision: https://developer.blender.org/D16933
8a16523bf1 BLI: Refactor matrix types & functions to use templates
This patch implements the matrix types (i.e:float4x4) by making heavy
usage of templating. All matrix functions are now outside of the vector
classes (inside the blender::math namespace) and are not vector size
dependent for the most part.

###Motivations
The goal/motivations of this rewrite are the same as the Vector C++ API (D13791):
- Template everything for making it work with any types and avoid code duplication.
- Use functional style instead of Object Oriented function call to allow a simple compatibility layer with GLSL syntax (see T103026 for more details).
- Allow most convenient constructor syntax and accessors (array subscript `matrix[c][r]`, or component alias `matrix.y.z`).
- Make it cover all features the current C API supports for adoption.
- Keep compilation time and debug performance somehow acceptable.

###Consideration:
- The new `MatView` class can be generated by `my_float.view<NumCol, NumRow, StartCol, StartRow>()` (with the last 2 being optionnal). This one allows modifying parts of the source matrix in place. It isn't pretty and duplicates a lot of code, but it is needed mainly to replace `normalize_m4`. At least I think it is a good starting point that can refined further.
- An exhaustive list of missing `BLI_math_matrix.h` functions from the new API can be found here P3373.
- This adds new Rotation types in order to have a clean API. This will be extended when we port the full Rotation API. The types are made so that they don't allow implicit down-casting to their vector representation.
- Some functions make direct use of the Eigen library, bypassing the Eigen C API defined in `intern/eigen`. Its use is contained inside `math_matrix.cc`. There is conflicting opinion wether we should use it more so I contained its usage to almost the tasks as in the C API for now.

Reviewed By: sergey, JacquesLucke, HooglyBoogly, Severin, brecht
Differential Revision: https://developer.blender.org/D16625
302cb349c7 Cleanup: quiet compiler warning
For some reason this resulted in a unused-variable warning (on gcc).
Think we had such false positives before when `constexpr` was used.
67e1b52568 BLI: Matrix: Fix compilation errors and wrong alignment
Auto alignment was reversed and 0 alignment is producing warning.
940fd87e77 Fix T103615: OSL image box mapping has flipped textures
This breaks backwards compatibility some in that 3 sides will be mapped
differently now, but difficult to avoid and can be considered a bugfix.

Similar to rBdd8016f7081f.

Maniphest Tasks: T103615

Differential Revision: https://developer.blender.org/D16910
11ecde6a5a Cleanup: BLI: Remove BLI_ENABLE_IF((is_math_float_type)) from vector API
This was limiting the use of the templates with other non internal types
like Ceres types, xithout defining thing like that:
`template<> inline constexpr bool is_math_float_type<mpq_class> = true;`
56216e2a62 Cleanup: BLI: Rename vector compare() to is_equal() for consistency
Also rename parameters and give default value of 0 to epsilon.
This way ommiting epsilon means expecting perfect equality.
da2dccca61 BLI: Add [[nodiscard]] to math vector lib
This avoid silently ignoring the returned value.
8f44c37f5c Cleanup: Rename BLI_math_vec_types* files to BLI_math_vector_types
This is for the sake of consistency and clarity.
73594f4c9c Cleanup: BLI: Rename vec_base to VecBase
For consistency with our codestyle and matrix class.

# Conflicts:
#	source/blender/blenlib/BLI_math_matrix_types.hh
ba9f0d5a15 BLI: Math: Vector: Improve API documentation
Add precision about non-trivial functions.
5fa694ffe1 Cleanup: BLI: Remove BLI_ENABLE_IF((is_math_float_type)) from vector API
This was limiting the use of the templates with other non internal types.
125b283589 GPU: Add Math libraries to GPU shaders code
This implement most of the functions provided by the BLI math library.
This is part of the effort to unify GLSL and C++ syntax. Ref T103026.

This also adds some infrastructure to make it possible to run GLSL shader unit
test.

Some code already present in other libs is being copied to the new libs.
This patch does not make use of the new libs outside of the tests.

Note that the test is still crashing when using metal.
1bbf1ed03c Functions: improve devirtualization in multi-function builder
This refactors how devirtualization is done in general and how
multi-functions use it.

* The old `Devirtualizer` class has been removed in favor of a simpler
  solution. It is also more general in the sense that it is not coupled
  with `IndexMask` and `VArray`. Instead there is a function that has
  inputs which control how different types are devirtualized. The
  new implementation is currently less general with regard to the number
  of parameters it supports. This can be changed in the future, but
  does not seem necessary now and would make the code less obvious.
* Devirtualizers for different types are now defined in their respective
  headers.
* The multi-function builder works with the `GVArray` stored in `MFParams`
  directly now, instead of first converting it to a `VArray<T>`. This reduces
  some constant overhead, which makes the multi-function slightly
  faster. This is only noticable when very few elements are processed though.

No functional changes or performance regressions are expected.
b3146200a8 Functions: refactor multi-function builder API
* New `build_mf` namespace for the multi-function builders.
* The type name of the created multi-functions is now "private",
  i.e. the caller has to use `auto`. This has the benefit that the
  implementation can change more freely without affecting
  the caller.
* `CustomMF` does not use `std::function` internally anymore.
  This reduces some overhead during code generation and at
  run-time.
* `CustomMF` now supports single-mutable parameters.
577442a26f Functions: build multi-function signature in-place
This avoids a move of the signature after building it. Tthe value had
to be moved out of `MFSignatureBuilder` in the `build` method.

This also makes the naming a bit less confusing where sometimes
both the `MFSignature` and `MFSignatureBuilder` were referred
to as "signature".
a5b27f9858 Functions: simplify multi-function signature type
* `depends_on_context` was not used for a long time already.
* `param_data_indices` is not used since rB42b88c008861b6.
* The remaining data is moved to a single `Vector` to avoid
  having to do two allocations when the size signature becomes
  larger than fits into the inline buffer.
eedcf1876a Functions: introduce multi-function namespace
This moves all multi-function related code in the `functions` module
into a new `multi_function` namespace. This is similar to how there
is a `lazy_function` namespace.

The main benefit of this is that many types names that were prefixed
with `MF` (for "multi function") can be simplified.

There is also a common shorthand for the `multi_function` namespace: `mf`.
This is also similar to lazy-functions where the shortened namespace
is called `lf`.
a2ea32a600 Cleanup: inline signatures into multi-function constructors
This reduces the amount of code. Also the signature should be thought
of as being setup in the constructor, so it's good if the code is there as well.
c4d4db39dc Functions: enable more gcc optimizations for multi-functions
This mainly helps GCC catch up with Clang in terms of field evaluation
performance in some cases. In some cases this patch can speedup
field evaluation 2-3x (e.g. when there are many float math nodes).
See D16942 for a more detailed benchmark.
2895c67086 Fix T103408: Cycles deadlock during GPU viewport rendering
This was caused by rB0d73d5c1a2, which releases the scene mutex during kernel
loading. However, the reset mutex was still held, which can cause a deadlock
if another thread tries to reset the session, since it will acquire the
released scene mutex and then wait for the reset mutex.

Turns out there's no point in keeping the reset mutex locked after the delayed
reset section, so now we just release it earlier, which resolves the deadlock.
e22247a965 Fix: crash when opening file with visible node editor
Caused by rB87fd798ae383a344d51dcbd9f66d5834595bdc5a.
d4c085c17d Metal: Resolve failing assertions relating to memory sizing and texture swizzle.
Required texture bytesize calculation for compacted data types was incorrectly calculated, resulting in an erroneous format conversion taking place instead of direct data upload.
Metal dummy buffer size also temporarily increased to address problematic cases where the bound buffer was too small for missing UBOs.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D16904
5f9a48ed59 Functions: improve compiler optimizability of multi-function evaluation
This simplifies the code enough so that msvc is able to unroll and
vectorize some multi-functions like simple addition.

The performance improvements are almost as good as the GCC
improvements shown in D16942 (for add and multiply at least).
b1d2ea3e1b Metal: Add gl_PrimitiveID support.
Resolves failing Mesh Snap utilities line add-on.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D16905
ed8f3dc9c7 Fix T103399: correctly apply SRGB framebuffer and shader conversion mode in Metal.
First binding of a framebuffer lead to an incorrect SRGB conversion state being applied, as attachments, where presence of SRGB is determined, were processed after the SRGB check rather than before.
This DIFF also cleans up SRGB naming conventions and caching of fallback non-srgb texture view, for use when SRGB mode is disabled.

Authored by Apple: Michael Parkin-White

Ref T103399
Ref T96261

Reviewed By: fclem

Maniphest Tasks: T103399, T96261

Differential Revision: https://developer.blender.org/D16907
d3f626b535 Fix T103658: Resolve Metal partial texture update overwriting whole image when staging textures are used.
Staging texture update copied over the entire texture, rather than just the region of the texture which had been updated. Also added early-exit for cases where the net texture update extent was zero, as this was causing validation failures.

Authored by Apple: Michael Parkin-White

Ref T103658
Ref T96261

Reviewed By: fclem

Maniphest Tasks: T103658, T96261

Differential Revision: https://developer.blender.org/D16924
891b973029 Functions: optimize multi-function evaluation in materialized mode
This allows auto-vectorization to happen when the a multi-function is
evaluated in "materialized" mode, i.e. it is processed in chunks where
all input and outputs values are stored in contiguous arrays.

It also unifies the handling input, mutable and output parameters a bit.
Now they all can use tempory buffers in the same way.
73a2c79c07 Functions: free memory of unused sockets earlier
During geometry nodes evaluation some sockets can be determined
to be unused, for example based on the condition input in a switch node.
Once a socket is determined to be unused, that information has to be
propagated backwards through the tree to free any memory that may
have been reserved for those sockets already. This is happening before
this commit already, but in a less ideal way.

Determining that sockets are unused early is good because it helps with
memory reuse and avoids copy-on-write copies caused by shared data.
Now, nodes that are scheduled because an output became unused have
priority over nodes scheduled for other reasons.
d11f3267cd Fix T103210: Don't Always Clear Glyphs With Zoom
Do not clear all the font's glyph caches with single-step zoom
operators if the area does not change font size when doing so.

See D16785 for more details.

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

Reviewed by Campbell Barton
e7a554e551 Fix T94698: Cycles: Volume-scattered light is always counted as diffuse
At the first bounce, the diffuse/glossy/transmission weights are stored so that
contributions along the path can be split into the d/g/t indirect passes.

However, volume bounces always set the weight even at indirect bounces, so
even paths that had their first bounce on a purely glossy object would suddenly
start counting towards the diffuse indirect pass after a secondary volume bounce.
95696d09bc Fix T88849: Motion blur in cycles leaves bright edge on trailing end of blur
The code that computes and inverts the shutter CDF had some issues that caused
the result to be asymmetric, this tweaks it to be more robust and produce
symmetric outputs for symmetric inputs.
d8e01150d6 Fix T94752: Cycles renders stereoscopic panoramas incorrectly
The bug is caused by rBb66b3f547c43e841a7d5da0ecb2c911628339f56.
From what I can see, that fix was intended to enable manual lens shift for
panorama cameras, but it appears that it also unintentionally applies
interocular shift.

This fix disables the multiview shift for panorama cameras, that way manual lens
shift still works but we get the 2.x behavior for stereoscopic renders back.

Differential Revision: https://developer.blender.org/D16950
59ce3b8f6b Cleanup: doxygen comment use
Avoid '\note' outside of doxygen comments.
f3df7b4fbd Fix T103075: Crash when using Limit textures.
Crash only occured when textures was stored in a gray scale GPU
texture and was scaled down to fit inside the given limitation.

In this case the original number of pixels were packed into the
GPU buffer, not taken into account the scaled down image. This
resulted in a buffer overflow.
b5390a4aee Fix assert on blend file load when seek fails
Only assert seek worked as expected when it doesn't return an error.
b3f664f8fb GPencil: Fix unreported Vertex Color missing in Outline Draw
When drawing using the option `Outline` the result stroke
was not using the Vertex Color option and always was converted
using material.

Now the vertex color option is used.
385bd0c4e9 Fix T103685: Animation on objects that are disabled is ignored
Happens, for example, when the object has animation, and disabled for
render, and animation render is performed.

The regression has been uncovered by f12f7800c2 which made it so
the dependency graph relies on runtime visibility tracking and
updates (without updating relations).

The optimization from a while ago in the ff60dd8b18 got in a way
of the visibilit updates because it removed relation between two
no-op nodes which belong to different IDs, which make the visibility
tracking impossible.

This change makes it so only relations which belong to the same
component are removed. This matches the expectations of the visibility
tracking (which, actually, also needed to happen at the moment of the
initial optimization commit). Technically, this change could introduce
some performance regression, but with the current design design of the
graph it is not really avoidable.

The idea to gain the best performance is to separate relations which
actually define the execution flow, and which are only needed to
define things like visibility dependencies.
8d2f4ddb2f Fix T103423: boolean crash on macOS Apple silicon
Thanks to Howard Trickey for finding the cause.
ec2046c38d Fix T103531: Hold split not working correctly
Incorrect offset was calculated when strip was implicitly retimed (movie
FPS does not match scene FPS). This is because strip playback rate was
not used for offset calculation at all.

Since hold offset is specifying numbers of frames to skip, but at frame
rate of the source, this could result in gap when splitting the strip.
If that occurs, gap is compensated by moving handle to frame where strip
is split.
3b476d020a Cleanup: Move particle.c to C++
In order to simplify a mesh data structure refactor. See T103343
71ca339fe0 GPU: Fix math lib compilation and tests on AMD drivers
- Matrix normalize overloads needs to have the vector normalize redefined.
- double underscore (anywhere in symbol name) are reserved.
- Some operation yield different result due to float imprecision. Increasing
  epsilon threshold for the failing tests.
7bf75231e8 Nodes: Improve wording of node operator descriptions
- Avoid calling node interface items "sockets"
- Use "active" instead of "current" to be more correct
- Avoid using the same word in description and name
- A couple grammar fixes
317a5f61f0 Cycles: Fix recently introduced off-by-one error in an assert
This was added in rB95696d09bc07, but I got the index wrong.
c41601becd Fix T89037: Cycles: Backfacing node can be wrong for lights with negative scale
When rendering in the viewport (or probably on instanced objects, but I didn't
test that), emissive objects whose scale is negative give the wrong value on the
"backfacing" input when multiple sampling is enabled.

The underlying problem was a corner case in how normal transformation is handled,
which is generally a bit messy.

From what I can tell, the pattern appears to be:
- If you first transform vertices to world space and then compute the normal from
  them (as triangle light samping, MNEE and light tree do), you need to flip
  whenever the transform has negative scale regardless of whether the transform
  has been applied
- If you compute the normal in object space and then transform it to world space
  (as the regular shader_setup_from_ray path does), you only need to flip if the
  transform was already applied and was negative
- If you get the normal from a local intersection result (as bevel and SSS do),
  you only need to flip if the transform was already applied and was negative
- If you get the normal from vertex normals, you don't need to do anything since
  the host-side code does the flip for you (arguably it'd be more consistent to
  do this in the kernel as well, but meh, not worth the potential slowdown)

So, this patch fixes the logic in the triangle emission code.

Also, turns out that the MNEE code had the same problem and was also having
problems in the viewport on negative-scale objects, this is also fixed now.

Differential Revision: https://developer.blender.org/D16952
63b9a57f8b Cleanup: use descriptive names for transform snapping functions
activeSnap --> transform_snap_is_active
activeSnap_SnappingIndividual --> transform_snap_project_individual_is_active
activeSnap_SnappingAsGroup --> transform_snap_mixed_is_active
applySnappingIndividual --> transform_snap_project_individual_apply
applySnappingAsGroup --> transform_snap_mixed_apply

Also rearrange functions to be close to where they are used.

And use static when possible.
13450c2d22 Cleanup: Clang format
Mostly bad white space from a bad find & replace in my own cleanup commit.
05ddc7daa2 Nodes: Avoid small allocations for internal links
Since internal links are only runtime data, we have the flexibility to
allocating every link individually. Instead we can store links directly
in the node runtime vector. This allows avoiding many small allocations
when copying and changing node trees.

In the future we could use a smaller type like a pair of sockets
instead of `bNodeLink` to save memory.

Differential Revision: https://developer.blender.org/D16960
1af62cb3bf Mesh: Move positions to a generic attribute
**Changes**
As described in T93602, this patch removes all use of the `MVert`
struct, replacing it with a generic named attribute with the name
`"position"`, consistent with other geometry types.

Variable names have been changed from `verts` to `positions`, to align
with the attribute name and the more generic design (positions are not
vertices, they are just an attribute stored on the point domain).

This change is made possible by previous commits that moved all other
data out of `MVert` to runtime data or other generic attributes. What
remains is mostly a simple type change. Though, the type still shows up
859 times, so the patch is quite large.

One compromise is that now `CD_MASK_BAREMESH` now contains
`CD_PROP_FLOAT3`. With the general move towards generic attributes
over custom data types, we are removing use of these type masks anyway.

**Benefits**
The most obvious benefit is reduced memory usage and the benefits
that brings in memory-bound situations. `float3` is only 3 bytes, in
comparison to `MVert` which was 4. When there are millions of vertices
this starts to matter more.

The other benefits come from using a more generic type. Instead of
writing algorithms specifically for `MVert`, code can just use arrays
of vectors. This will allow eliminating many temporary arrays or
wrappers used to extract positions.

Many possible improvements aren't implemented in this patch, though
I did switch simplify or remove the process of creating temporary
position arrays in a few places.

The design clarity that "positions are just another attribute" brings
allows removing explicit copying of vertices in some procedural
operations-- they are just processed like most other attributes.

**Performance**
This touches so many areas that it's hard to benchmark exhaustively,
but I observed some areas as examples.
* The mesh line node with 4 million count was 1.5x (8ms to 12ms) faster.
* The Spring splash screen went from ~4.3 to ~4.5 fps.
* The subdivision surface modifier/node was slightly faster
RNA access through Python may be slightly slower, since now we need
a name lookup instead of just a custom data type lookup for each index.

**Future Improvements**
* Remove uses of "vert_coords" functions:
  * `BKE_mesh_vert_coords_alloc`
  * `BKE_mesh_vert_coords_get`
  * `BKE_mesh_vert_coords_apply{_with_mat4}`
* Remove more hidden copying of positions
* General simplification now possible in many areas
* Convert more code to C++ to use `float3` instead of `float[3]`
  * Currently `reinterpret_cast` is used for those C-API functions

Differential Revision: https://developer.blender.org/D15982
fdcbad37be Fix window creation with Hi-DPI exiting under Wayland
Wayland requires the windows surface size is divisible by the surface
scale. This wasn't guaranteed when creating new temporary windows.

This meant opening the preferences could exit Blender with an error
with Hi-DPI configurations.
485ab42075 BLF: Improved CJK Font Preview Differentiation
Use font's OS/2 table code page range bits to help differentiate
between Korean, Japanese, Simplified & Traditional Chinese fonts.

See D16484 for details.

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

Reviewed by Brecht Van Lommel
6ef8db35e7 Cleanup: clarify naming for deformed vertex positions & normals
Edit-mesh duplicator logic used a struct member vert_coords which read
as an alternative (and inconsistent) naming to vert_positions.

Rename to `vert_positions_deform` as the purpose of this value is to
assign when modifiers deform an edit-mesh.
Add `_deform` suffix to normals as well.
6c774feba2 Mesh: Move UV layers to generic attributes
Currently the `MLoopUV` struct stores UV coordinates and flags related
to editing UV maps in the UV editor. This patch changes the coordinates
to use the generic 2D vector type, and moves the flags into three
separate boolean attributes. This follows the design in T95965, with
the ultimate intention of simplifying code and improving performance.

Importantly, the change allows exporters and renderers to use UVs
"touched" by geometry nodes, which only creates generic attributes.
It also allows geometry nodes to create "proper" UV maps from scratch,
though only with the Store Named Attribute node for now.

The new design considers any 2D vector attribute on the corner domain
to be a UV map. In the future, they might be distinguished from regular
2D vectors with attribute metadata, which may be helpful because they
are often interpolated differently.

Most of the code changes deal with passing around UV BMesh custom data
offsets and tracking the boolean "sublayers". The boolean layers are
use the following prefixes for attribute names: vert selection: `.vs.`,
edge selection: `.es.`, pinning: `.pn.`. Currently these are short to
avoid using up the maximum length of attribute names. To accommodate
for these 4 extra characters, the name length limit is enlarged to 68
bytes, while the maximum user settable name length is still 64 bytes.

Unfortunately Python/RNA API access to the UV flag data becomes slower.
Accessing the boolean layers directly is be better for performance in
general.

Like the other mesh SoA refactors, backward and forward compatibility
aren't affected, and won't be changed until 4.0. We pay for that by
making mesh reading and writing more expensive with conversions.

Resolves T85962

Differential Revision: https://developer.blender.org/D14365
aaaa75f906 Fix: Failing test after combination of Mesh refactors
The mesh positions are now a span, but the convex hull didn't copy
the custom data layout to the new mesh since it assumed it didn't
need to. Moving UV maps to a generic attribute triggers this difference
in the test results.

It doesn't really make sense for the convex hull node to copy the
source mesh custom data layout at all anyway, but do it anyway
to avoid having to change the tests right now.
dad9f45561 Cleanup: move run-time members of SurfaceModifierData into a struct
Using run-time members in the surface modifier complicated code-review
and caused an unnecessary renaming in `dna_rename_defs.h`.

Also rename:
- `x` -> `vert_positions_prev`.
- `v` -> `vert_velocities`.
- `cfra` -> `cfra_prev`.
ed66321996 GHOST/Wayland: simplify logic for disconnecting monitors under Wayland
The T103586 fix effectively ran the wl_surface_listener.leave callback
to as WLROOTS based compositors doesn't run them. Remove the workaround
since it's an error in WLROOTS to be fixed upstream.

Temporarily using the wrong window scale when disconnecting a monitor
on configurations that use different DPI per monitor is a minor enough
issue that I don't think it makes sense to workaround in GHOST.
b7f5e4b1b6 Fix building on MSVC
Empty struct introduced in dad9f45561.
6f38ce5a40 Fix T103679: Add missing operators in object context menu for point cloud and curves
Set origin and convert operator now accepts point cloud and new curve
object. But these operators were not added in context menu.
Support for set origin and convert operator was added in
rBadb4dd911b91, rB933d56d9e98d and rB2752a88478a8

Reviewed by: HooglyBoogly

Differential Revision: https://developer.blender.org/D16939
c6b4bd407e Cleanup: deduplicate conditions in transform code
The `t->spacetype` check is already done in `setSnappingCallback`.
387fc9b40b MacOS: Silence OpenGL deprecation warnings.
OpenGL is deprecated by Apple and triggers a warning when used. The goal
is that OpenGL is replaced by Metal backend, but we are not there yet.

To improve tracability of new warnings we hide deprecation warnings
when the GHOST_ContextCGL.h file is included.

NOTE: This change silences other deprecation warnings as well.
597aecc016 MacOS: Update Min Requirement to 10.15.
A few weeks ago we enabled the Metal back-end for the viewport.
Due to metal, master is only able to build on MacOS 10.15 and above.
The previous minimum requirement is MacOS 10.13.

It was already planned to bump to a higher version for Blender 3.6. After
a short discussion via bf-committers it was decided that it is fine to bump it for
3.5 release.

This patch cleans up the CMake files and update the minimum requirement.

With this patch the next deprecations will be listsed.
- `NSOpenGLView`, `NSOpenGLContext` is deprecated. (replaced by metal)
- `NSStringPboardType` is replaced by `NSPasteboardTypeString`
- `NSTIFFPboardType` is replaced by `NSPasteboardTypeTIFF`
- `NSFilenamesPboardType` should be replaved by multiple pasteboard items with `NSPasteboardTypeFileURL` instead.
- `NSUserNotification` should be replaced with UserNotifications.frameworks API

Deprecations will be handled in separate tasks and commits. OpenGL won't be
fixed at this moment, as it will be phased out in the future. NSStringPboardType, NSTiffPboardType & NSFilenamesPboardType
 will be provided in a single patch. NSUserNotification will also be provided in
its own patch.

Reviewed By: brecht, sergey

Differential Revision: https://developer.blender.org/D16953
fddb76e9af Fix: new Grease Pencil layer not selected when added from the viewport
When adding a new layer from the viewport, the newly created layer
is set as active, which is visible in the properties panel,
but the selection in the dopesheet was not updated accordingly,
due to a missing notifier which is added in this patch.
250eda36b8 GPencil: Build modifier add "natural drawing" time
This patch uses the recorded drawing speed to rebuild the strokes. This results in a way more
natural feel of the animation.

Here's a short summary of existing data used:

- gps->points->time: This is a timestamp in seconds of when the point was created
  since the creation of the stroke. It's quite often 0 (I added a sanitization routine).
- gpf->inittime: This is a timestamp in seconds when a stroke was drawn measured
  since some unknown point in time. I only ever use the difference between two strokes,
  so the absolute value is not relevant.

Reviewed By: frogstomp, antoniov, mendio

Differential Revision: https://developer.blender.org/D16759
35e54b52e6 Assets: "All" asset library
Adds a new built-in asset library that contains all other asset
libraries visible in the asset library selector menu. This also means
all their asset catalogs will be displayed as a single merged tree. The
asset catalogs are not editable, since this would require support for
writing multiple catalog definition files, which isn't there yet.

Often it's not relevant where an asset comes from. Users just want to be
able to get an asset quickly, comparable to how people use a search
engine to browse images or the web itself, instead of first going to a
dedicated platform. They don't want to bother with first choosing where
they want the result to come from.
This especially is needed for the Asset Shelf (T102879) that is being
developed for the brush assets project (T101895). With this, users will
have access to all their brushes efficiently from the 3D view, without
much browsing.

Did an informal review of the asset system bits with Sybren.
66af16571d Refactor: Use new "All" asset library to extend node menus with assets
Updates the add and search menu of the node editor to use the new "All"
asset library introduced in the previous commit. This simplifies code by
removing redundant logic to merge contents of multiple asset libraries.
09a5443f20 GPencil: Fix unreported wrong fill vertex color in Outline
The Fill vertex color was assigned to the wrong stroke. It needs to be
set in the perimeter stroke, not in the original one.
3a98dc6812 Fix crash when dragging video into VSE timeline
Caused by NULL dereference in strip overlap handling (expand to fit),
because `time_dependent_strips` strip collection is not created.

Check if strip collection is provided in `query_right_side_strips()`.
df5ebd348b Fix T103556: Cycles viewport unexpected pixel changes when hovering over UI
With the GPU API the sampler can not be set after texture binding, which caused
a delay of the actual change. Now do both in a single call for correctness and
performance.
9b8c2f91f6 Cleanup: Compile `filesel.c` in C++
This is a mere "get this to compile in C++", didn't do changes like
using `MEM_cnew()` instead of `MEM_calloc()`.

Needed for the blender-project-basics branch, so I don't have to write C
wrappers for a single call from this file.
db688b62f9 Fix T103764: Grease Pencil modes other than Draw use a wrong radial
It was introduced in commit https://developer.blender.org/rB0fb12a9c2ebc

The problem was that the tool uses the same values for all modes,
but the new calculation must be only for Draw mode.

Now the mode is checked.
8a3a1a0c14 Fix T103781: assert when connecting viewer node on mesh without faces
`Span.data()` does not have to be `nullptr` when the size is zero.
This happens e.g. when slicing a span to a size of zero.
d397ecae32 Geometry Nodes: Add a selection input to the store named attribute node
This patch is a response to T101313.

Adds a selection to the Store Named Attribute node.

If the attribute does not exist unselected parts
are filled with zero values. Otherwise, only the
selected parts are filled.

Differential Revision: https://developer.blender.org/D16237
5bc71f22a2 Snap Gizmo: remove unused "snap_elements"
This property was intended to keep the snap elements synchronized with the scene.

But another solution exists.

And this property is not even working correctly.
30c90f0ad0 Cleanup: Replace "UV's" with "UVs"
An apostrophe should not be used because it is not a mark of plural,
even for initialisms. This involves mostly comments, but a few UI
messages are affected as well.

Differential Revision: https://developer.blender.org/D16749
dd9e1eded0 Mesh: Move sharp edge flag to generic attribute
Move the `ME_SHARP` flag for mesh edges to a generic boolean
attribute. This will help allow changing mesh edges to just a pair
of integers, giving performance improvements. In the future it could
also give benefits for normal calculation, which could more easily
check if all or no edges are marked sharp, which is helpful considering
the plans in T93551.

The attribute is generally only allocated when it's necessary. When
leaving edit mode, it will only be created if an edge is marked sharp.
The data can be edited with geometry nodes just like a regular edge
domain boolean attribute.

The attribute is named `sharp_edge`, aiming to reflect the similar
`select_edge` naming and to allow a future `sharp_face` name in
a separate commit.

Ref T95966

Differential Revision: https://developer.blender.org/D16921
50d6af1e0e Fix invalid string comparison
Error from recent addition: 250eda36b8.
Compare the enum value instead.
bd9602036a Fix pose-slide failing with array custom properties
Pose slide would attempt to use non-array functions to get/set RNA
array properties. Asserting in debug mode.
9f283bee7e BLI_string_ref: avoid passing null to strncmp (quiet ASAN warning)
The existing logic to avoid passing null only worked when both
strings were null.
32812c2cc2 Cleanup: Remove redundant mesh data mask handling
Byte colors are generic attributes and are therefore included in
CD_MASK_PROP_ALL. Also clarify the use of vertex groups.
They always have to be propagated since they're displayed in
the spreadsheet, etc.
86464cfcef Fix error converting UV's to MLoopUV
Logic to skip UV layers that are part of the MLoopUV treated all
loop-layers as UV's, causing duplicate and invalid names to be added
to be added to 'uv_sublayers_to_skip', this asserted in debug mode
when saving the `ellie_animation.blend` demo blend file.
d8d20e0e59 UI: include 'drag-' prefix in the short-cut text for menu items
This was already done for double-click events but not drag events.
f88e788569 Pose Slide: set the value of "release_confirm" from the event when unset
Needed to fix T103267, so the properties for the menu item and the
drag action will match & show the shortcut in the menu.
68c6fc6d38 Fix T103267: No shortcuts shown in the Pose Assets context menu
Support displaying shortcuts for uiListDyn.custom_drag_* &
custom_activate_* operators.
d3e8d63a8c Fix error in StringRef equality
Regression in [0] wasn't correct as it's important for empty strings
to be equal to nullptr.

[0]: 9f283bee7e
cff2807aff Fix T103719: missing shortcuts info for some tool-settings
Tool settings can be accessed from both `tool_settings` &
`scene.tool_settings`.

As of [0] `scene.tool_settings` was used instead of `tool_settings`
causing the snap shortcut not to display.

Resolve by supporting variations of data-paths so both are detected.

[0]: 9a76dd2454
8f7bb812c4 Gitea: Add Issue and Pull Request templates
It is a part of the Phabricator to Gitea migration.

The issue template is based on the bug submission instructions which
are shown in the Phabricator's bug submission form. Some further tweaks
are likely needed, but the current version of the template simplifies
re-iteration while working on the migration.

The pull request template is needed to override the template in the
.github folder which is otherwise picked up by Gitea.
5d07b0e6da Cleanup: delegate to string_view equality for StringRef
This also fixes an issue introduced in rBd3e8d63a8c455d0,
where the function relied on the `StringRef` being null-terminated.
a6b6f5db10 Fix issue with recent refactor in liboverride diffing.
New code from rBd05909a70c36 last week did not take into account
liboverride templates and `NOOP` operations. So we cannot assume that
there is no valid override property for these which need to be restored.

While we may get rid of templates at some point now, for now they are
still exposed in PY API, and have some basic unittests, so keep them
working as best as possible.

Issue reported on IRC by Martijn Versteegh (@Baardaap), thanks!
3b761901b6 Fix T103783: crash when canceling vertex crease having vertex groups
`transdata_restore_basic` uses `copy_v3_v3` to restore a pointer that is 1D.
4d1f12212b Transform: deduplicate code
Edge Bevel Weight and Edge Crease operations have the same code.

Only the name displayed in the header changes.
88e9826529 Sculpt: Fix T102889: Sculpt trim tool extrudes in perspective
Added an extrude mode enum to the trim operators to
control extrusion: "project" and "fixed."  "Fixed" just
extrudes along a fixed normal and is the new default.
ff86573d72 Fix T102313: Enabling shadow catcher in viewport render shows self-shadowing
The problem here is that whether an object is a shadow catcher or not affects the
visibility flags, but changes to the shadow catcher property did not trigger a
visibility flag update.
442b08aac0 Snap Gizmo: support the WM_GIZMO_HIDDEN flag
Support snap cursor removal in poll callback, this makes it possible to
delay cursor removal if the gizmo is hidden.
2b4bf586ad Fix T102920: Cycles doesn't support multiple outputs on muted nodes
Cycles converts internal links to converter nodes which don't do anything and
later on get collapsed by the graph optimization. However, the previous code
assumed that one Blender input socket maps to one Cycles input socket.

When a node is muted, there might be internal links from one input to multiple
outputs. In Cycles, this meant that one Blender input socket now mapped to
multiple input sockets on all the converter nodes, so only the last one survived.

THe fix is simple, just make the mapping a MultiMap.
0349a6e6e0 Fix disappearing snap indication in Measure tool
Snap cursor disappeared while dragging.

Regression in 2b32a2c3b
b9177014b6 3D Texturing: Replace pointers with indexes in pbvh_uv_islands
Replace the pointers in the MeshEdge with indexes, removing MeshPrimitive and MeshVertex.

Code cleanup proposed by the geometry nodes to make the data structures more reusable by
other areas of Blender as well. Old implementation was to focused to the texture painting.

Initial the idea was to do the same with the data structures in UVIslands, but there some
concerns were raised that requires a different design than expected from a clean-up patch.

Concerns raised about converting UVIslands:
* Maps between UVPrimitive, UVEdge and UVVertex will be stored inside the UVIsland.
   During UVIsland extraction detected islands can be merged. When they are merged all
   Indexes should be updated.
* It is not possible to pre-allocate all buffers as they grow, what will lead to more re-allocations. The current
   implementation uses a VectorList to ensure that re-allocations don't require the data to be
   moved to the newly allocated memory. We could store some information about last used
   sizes in runtime data to reduce the re-allocation overhead.
* Solution would require index based access inside a VectorList, which might increase the
   complexity.
* UVIslands during 3d texturing is used as intermediate data, the final data is stored as PackedPixelRows.
   We could proceed converting UVIslands as well, but that would lower the performance noticeably.
   3D texturing has performance requirements, so when doing so we should make sure that
   it matches that as well.

Reviewed By: HooglyBoogly

Maniphest Tasks: T101740

Differential Revision: https://developer.blender.org/D16752
3590e263e0 macOS: Remove user notifications.
User notifications in Blender were always annoying and therefore by default turned off.
- When tweaking compositor/material tree a notification was shown.
- When rendering an animation for each frame a notification was shown.

The reason for this was that it was automatically shown when a background job was
finished and Blender wasn't the top most application.

In stead of migrating user notification to UserNotification.framework it was decided
to remove it for now. If in the future notifications should be added back we should
start with a design to figure out where notifications makes sense.

Reviewed By: sergey, brecht

Maniphest Tasks: T103757

Differential Revision: https://developer.blender.org/D16955
eeff49a3b1 macOS: Replace PboardTypes with PasteboardTypes.
Related to {T103758}.

- NSStringPboardType is replaced by NSPasteboardTypeString
- NSTIFFPboardType is replaced by NSPasteboardTypeTIFF
09a26f26e8 Cleanup: missing-declarations warnings
Also remove duplicate doc-string.
ea1c31a244 Fix T103074: flipped vertex group meaning in Multi-Modifier Armature.
For some reason the Armature modifier in the Multi-Modifier mode
interpreted the vertex group in a way essentially opposite to the
regular mode. Moreover, this depended not on the Multi-Modifier
checkbox, but on whether the mode was actually active.

This fixes the flip and adds versioning code to patch old files.
One difficulty is that whether the Multi-Modifier flag is valid
can be different between the viewport and render. The versioning
code assumes any modifier enabled in either to be active.

This change is not forward compatible, so min version is also bumped.

Differential Revision: https://developer.blender.org/D16787
ed178f5ff5 Fix: Potential divide by 0 using GRAPH_OT_ease
In case there is only 1 key on the FCurve,
the operator can run into a situation where it divides by 0.
It now skips the curve in that case

Reviewed by: Sybren A. Stüvel
Differential Revision: https://developer.blender.org/D16982
Ref: D16982
c5f9bf95cd Cleanup: Remove unused function pose_propagate_fcurve
Remove the unused function `pose_propagate_fcurve`
It was missed in D16771

Reviewed By: Jacques Lucke
Differential Revision: https://developer.blender.org/D16937
Ref: D16937
16fc928068 Fix: uninitialized UVs when painting in sculpt mode
Because of a mistake in commit 6c774feba2 the uv vbo was not
initialized in the pbvh.
589d1be147 Cleanup: rename variables to distinguish between target and source
From --> To

**Struct Members:**
|snapTarget|snap_source
|snapPoint|snap_target
|snapTargetGrid|snap_target_grid
|calcSnap|snap_target_fn
|targetSnap|snap_source_fn
|applySnap|snap_mode_apply_fn
|distance|snap_mode_distance_fn
|source_select|source_operation
|target_select|target_operation

**Functions:**
|snap_calc_view3d_fn|snap_target_view3d_fn
|snap_calc_uv_fn|snap_target_uv_fn
|snap_calc_node_fn|snap_target_node_fn
|snap_calc_sequencer_fn|snap_target_sequencer_fn
|TargetSnapMedian|snap_source_median_fn
|TargetSnapCenter|snap_source_center_fn
|TargetSnapClosest|snap_source_closest_fn
|TargetSnapActive|snap_source_active_fn

**Enums:**
|TARGET_INIT|SNAP_SOURCE_FOUND
|TARGET_GRID_INIT|SNAP_TARGET_GRID_FOUND
|POINT_INIT|SNAP_TARGET_FOUND
|MULTI_POINTS|SNAP_MULTI_POINTS

**Types:**
|eSnapSourceSelect|eSnapSourceOP
|eSnapTargetSelect|eSnapTargetOP

Also rename Select to Operation.

Reviewed By: campbellbarton

Differential Revision: https://developer.blender.org/D16967
063caae72e GPencil: Fix unreported error in Build modifier
In patch D16759 cleanup a  else was removed by error which
 deals with situations where current gpf was copied, 
so that previous gpf may have MORE strokes than current gpf.

Reviewed By: antoniov

Differential Revision: https://developer.blender.org/D16986
b2746876f2 EEVEE: Avoid glitchy displacement on curve geometry
This is caused by the partial derivatives not being precise enough to
take the tube shape into account. For now we just disable displacement
bump for this type of geometry to match cycles.

Fixes T101175 Eevee displacement behavior changed
b599820418 OBJ: add split by objects/groups import options (T103839)
The new C++ OBJ importer was missing "split by objects" / "split by
groups" import settings of the older Python importer.
Implements T103839.

Added test coverage for all 4 possible combinations of these two
options.
bbe7183cd3 GHOST/Wayland: fix threaded event handling
The previous fix from T100855 [0] no longer works on my system
(3.4.1 release also fails for GNOME/KDE/WLROOTS compositors).

Resolve by removing the loop from the wait-on-file handle check.
Also reduce locking/unlocking calls.

[0]: 37b256e26f
0c2a3054ba Fix high CPU use when idle under Wayland
Recently the event handling thread for Wayland sometimes used 100% of a
CPU core while idle.

Resolve by waiting for changes to the Wayland file-handle when
there are no events to read.
c158dd560e WM: reduce CPU use while idle in ED_view3d_datamask
When idle, each 3D view made two calls CTX_data_mode_enum(C) from the
WM_main loop. While not causing problems it complicated troubleshooting
high CPU use while idle in other areas.

Access the object via the view layer, giving approx 40x speedup.
2fb829a2de Fix T103837: crash opening a specific file
Caused by {rBd397ecae325}.

Above commit added a new socket, so
`version_geometry_nodes_primitive_uv_maps` was getting the wrong sockect
with `->next`.

Now get the right one with yet another `->next` (might not be ideal, but
searching the right socket with other methods might be overhead?)

Maniphest Tasks: T103837

Differential Revision: https://developer.blender.org/D16994
d4e638baac User Interface: Re-organization of Geometry Nodes Add Node Menu
The menus are growing too large. This patches move some categories under
sub-menus, and shuffle some entries around.

We already had sub-categories split by separators. This change now
goes a step further and embrace 3-level menus.

Inspired by the "Simpler Add Menu" add-on by Quackers (waiting to hear
back to know Quackers real name).

Inspired by the "Simpler Add Menu" add-on by Alfonso Martinez II.

Differential Revision: https://developer.blender.org/D16993
046d1a414b Fix: Curves select all operator name
The operator is used for edit mode and sculpt mode, so it
shouldn't have the sculpt prefix.
4961e5f91d Geometry Nodes: Rename Interpolate Domain and Field at Index nodes
- `Interpolate Domain` -> `Evaluate on Domain`
- `Field at Index` -> `Evaluate at Index`

These names, discussed in recent geometry nodes submodule meetings,
describe actions rather than nouns, which is generally how nodes are
supposed to be named. The names are consistent, which is helpful
because they're similar conceptually. They also don't require knowledge
of the field concept, which we generally try to keep out of the UI in
favor of more beginner-friendly concepts.

We hope to add the ability to search for nodes with multiple
names for 3.5, so the old names can still have search items.
ef68a37e5d Custom Properties: Add boolean type
A proper boolean custom property type is commonly requested. This
commit simply adds a new `IDP_BOOLEAN` type that can be used for
boolean and boolean array custom properties. This can also be used
for exposing boolean node sockets in the geometry nodes modifier.

I've just extended the places existing IDProperty types are used, and
tested with the custom property edit operator and the python console.
Adding another IDProperty type is a straightforward extension of the
existing design.

Differential Revision: https://developer.blender.org/D12815
cb92ff7b2d Geometry Nodes: Only set soft range for modifier properties
Similar to the corresponding properties on node sockets, only adjust
the soft range. Because group nodes only have soft limits, groups
should generally be able to accept these inputs anyway. The benefit
of only using a soft range is that it allows choosing a more user-
friendly default range while keeping flexibility.
2c910cb70a Modifiers: Only allow geometry nodes for curves and point cloud
Effectively this disables two volume modifiers for the new curves
object and the point cloud object types. The aim is to simplify the
process of using these object types to prove out a node-group-based
workflow integrated with the asset browser. We're making the assumption
that these two modifiers were used very rarely on the new curves type
since that wasn't its purpose, so this breaks backwards compatibility.
a5c3f5b0bc Fix T103818: Freeze frames in movie strips when timecodes are used
Timecodes were generated from read packets, but applied to decoded
frames. This works as long as delay between packet read and decoded
frame is less than GOP size or if packet does not produce multiple
frames. In this case it did not work.

Use `pkt_pos`, `pkt_dts` and `pts` from `AVFrame` instead of `AVPacket`.
This way delay can be eliminated and timecode files are more reliable.
0a21a554d5 Fix T103304: Incorrect handling of edge crease in subdivision node
The crease custom data layer was added to a mutable version of the mesh,
but that wasn't used in the rest of the operation. Also the layer wasn't
retrieved properly with write access from the custom data API (fixed
separately as part of D14140). Also clean up a bit by retrieving
attributes from the mesh directly and by tweaking naming a bit.
e35053d369 Fix T103850: Convex hull node crash with empty geometry components
Avoid using components that can contain null pointer.
Getting attibute should avoid trying to do it for a null mesh.
This fix bypasses working with components.

Differential Revision: https://developer.blender.org/D16997
326e1eeb56 UV: cleanup
Cleanup ahead of D16992

Changes in `seam_connected_recursive`:

- Remove redundant `anchor` parameter.
- Improve const correctness

No functional changes.
4160da187c Fix T103670: correct seam calculation when finding unique uvs
Fixes bugs where UV islands with `mark seam` would tear at boundaries.

Modify seam_connected to search both it's edges instead of only one,
as this could fail if the edge was a seam or did not fan to the other loop.

Also fixes bug in `seam_connected_recursive`:
- `loop->prev == needle` changed to `loop == needle`

Maniphest Tasks: T103787
Reviewed By: Campbell Barton
Differential Revision: https://developer.blender.org/D16992
Test File: F14145477, F14137755, T79304
3a3d9488a1 Refactor: Const correct Custom Data API, prepare for CoW
Currently you can retrieve a mutable array from a const CustomData.
That makes code unsafe since the compiler can't check for correctness
itself. Fix that by introducing a separate function to retrieve mutable
arrays from CustomData. The new functions have the `_for_write`
suffix that make the code's intention clearer.

Because it makes retrieving write access an explicit step, this change
also makes proper copy-on-write possible for attributes.

Notes:
- The previous "duplicate referenced layer" functions are redundant
  with retrieving layers with write access
- The custom data functions that give a specific index only have
  `for_write` to simplify the API

Differential Revision: https://developer.blender.org/D14140
aea26830dc Cleanup: use std::get instead of std::get_if
`std::get` could not be used due to restrictions on macos.
However, the minimum requirement has been lifted in
{rB597aecc01644f0063fa4545dabadc5f73387e3d3}.
8625495b1c Functions: improve handling of unused multi-function outputs
Previously, `ParamsBuilder` lazily allocated an array for an
output when it was unused, but the called multi-function
wanted to access it. Now, whether the multi-function supports
an output to be unused is part of the signature. This way, the
allocation can happen earlier when the parameters are build.
The benefit is that this makes all methods of `MFParams`
thread-safe again, removing the need for a mutex.
50980981e3 Cleanup: remove MF prefix from some classes in multi-function namespace
This was missing in rBeedcf1876a6651c38d8f4daa2e65d1fb81f77c5d.
72cc68e299 Functions: only allocate resource scope when it is actually used
In most cases it is currently not used, so always having it there
causes unnecessary overhead. In my test file that causes
a 2 % performance improvement.
ff15edc6ab Cleanup: unify method parameters for virtual arrays
This makes `GVArrayImpl` and `VArrayImpl` more similar.
Only passing the pointer instead of the span also increases
efficiency a little bit. The downside is that a few asserts had
to be removed as well. However, in practice the same asserts
are in place at a higher level as well (in `VArrayCommon`).
1a79bdfbf1 BLI: inline index mask slice methods
Those are simple enough to be inlined.
fc9c818531 Fix missing view layer sync in recent change to ED_view3d_datamask
Call BKE_view_layer_synced_ensure before getting the active object [0]
caused an assertion for tests in debug mode.

[0]: c158dd560e
82bd020a30 CMake: suppress GCC warnings stringop-overread & stringop-overflow
As noted in comments, there are a lot of false positives which can't
be conveniently suppressed. Many of these warnings were caused by
`float x, y, z` being passed as `float[3]` using a pointer to `x`.
8c7df5fa72 Fix invalid arguments to memcpy in IMB_rectfill_area_replace
Passing the pointer to the array doesn't make sense in this case.
8b5d5cbf06 BLI: Math: Add sign() function
This implement the sign function as simple as possible while giving the
the same result as `signum`.
87bb14ab5f Fix T103256 Viewport: Regression: Clipping Region is not working
This was caused by a change in UBO name that wasn't propagated through
all usage, leading to missing UBO bind.
e1aef2e87e Cleanup: suppress '-Warray-bounds' warnings
Changes to overlay_shader.cc workaround a bug in GCC-12.2
(likely a duplicate of [0]). As the workaround involved removing
a local variable which most functions already didn't assign,
remove it for all functions.

An alternative is to add (otherwise redundant) parenthesis, e.g.
`&(e_data.sh_data[sh_cfg])`, but this would need to be noted in
code-comments, so opt for removing the intermediate variable.

[0]: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106247
6d07b459f2 Cleanup: compare to GPU_SHADER_CFG_CLIPPED when checking configurations
Don't assume a non-zero eGPUShaderConfig is clipped, as this would cause
unexpected behavior if other configurations are added.
945d108ab8 GPU: Fix uninitialized variable which created asan warning / errors
This wasn't really a problem since these are set on first bind or creation.
The test `if (enabled_srgb && srgb_) {` was depending on that variable that
in certain case, might not have been initialized (because of lazy init).
28db19433e GPU: Math: Add floatBitsToOrderedInt and orderedIntBitsToFloat
These allow the usage of `atomicMin` and `atomicMax` function with float
values as there is no overload for these types in GLSL.

This also allows signed 0 preservation.
b038662887 Fix T103559: Check for no-face object for particle baking
Meshes spawning particles from faces with with UV's/Vertex-colors but no
faces would crash de-referencing a NULL pointer.

Resolve by adding a check for this case and an assertion if CD_MFACE is
NULL when the mesh has polygons.

Ref D16947
33c30af742 Cleanup: comments in struct declarations
Use a consistent style for declaring the names of struct members
in their declarations. Note that this convention was already used in
many places but not everywhere.

Remove spaces around the text (matching commented arguments) with
the advantage that the the spell checking utility skips these terms.
Making it possible to extract & validate these comments automatically.

Also use struct names for `bAnimChannelType` & `bConstraintTypeInfo`
which were using brief descriptions.
6a7ecec6e1 Cleanup: avoid returning large structs from functions
Return BezTriple as a const pointer from utility functions
instead of by a value since it's a large struct.
5cbc8ce3b1 Fix ASAN error when Wayland fell back to X11
An alternative fix to [0] which caused an error with ASAN
(freeing an GHOST_ISystem instead of a GHOST_System).
Reported by @Baardaap in chat, I'm unable to reproduce the issue.

Instead of calling the destructor directly, add a private method that
deletes data before raising an exception.

[0]: fd36221930
ff814ec5f6 Metal: Fix read from uninitialized memory.
Implementation didn't count the string terminator when allocating
memory to store `msl_patch_default`. The string terminator could
be overwritted by other memory adding some undefined behavior.
9a1f0443cb Fix Unreported: GPencil Separating strokes creates negative times
Separating strokes using "selected points" didn't take into account 
that points->time can be 0 and thus created points with negative 
values in points->time, which should be an impossibility. 
This patch fixes this in BKE_gpencil_stroke_delete_tagged_points.

Also, it makes the build modifier's new drawspeed immune 
to (erroneous) negative time values, should they arise in other situations.

Reviewed By: antoniov


Differential Revision: https://developer.blender.org/D17006
5320372c34 User Inteface: Missing separator in Geometry Nodes > Add Node > Geometry menu
This separator was missing in the original change in the menus (d4e638baac).
154d3e95f8 Fix: don't set default value for unused socket in geometry nodes
Setting the default value resulted in an incorrect tooltip.

Differential Revision: https://developer.blender.org/D16957
debd912bef Fix T103906: Crash when canceling transform operation with the mirror options set
Caused by rB3b761901b6d6.

Some mirror transdata values were not being initialized.
a84a8a528d Cycles: remove SSE3 and AVX kernel optimization levels
While keeping SSE2, SSE4.1 and AVX2. This does not affect hardware support, it
only slightly reduces performance for some older CPUs.

To reduce maintenance cost and improve compile times.

Differential Revision: https://developer.blender.org/D16978
b82f7814c4 Fix: Draw: Incorrect culling in the new Draw Manager
ViewCullingData::corners (vec4) was casted to a BoundingBox (vec3),  so the frustum corners were uploaded in the wrong format to the GPU.

Now the ViewCullingData::corners are used directly without casting, since the BoundBox API is not really needed.

Reviewed By: fclem

Differential Revision: https://developer.blender.org/D17008
c55767b32e Fix T103632: Single point trim samples curve end point incorrectly
Trim erronously samples the next to last control point when it should
sample the last control point on the curve. This only happens when
reducing the curve to a single point. These changes should correct
the behavior.

Differential Revision: https://developer.blender.org/D17003
e0e6afb766 Geometry Nodes: Parallelize mesh and curve edit hint transformation
Previously transforming and translating meshes (used by the object info
and transform geometry nodes) was single threaded. Now use the same
code path as other geometry types which already includes multithreading.

I observed a 5x performance improvement for a 4 million vert mesh on a
Ryzen 7950x.
39c6953462 UI: Fix alignment of custom properties edit & remove buttons
This fixes the UI alignment issues that were introduced by {D12815} with the addition of the boolean custom properties.

Reviewed By: HooglyBoogly

Differential Revision: https://developer.blender.org/D17012
6d12d43a05 Mesh: Skip conversion from legacy data if reading new format
Under some circumstances (loading autosaves), we end up reading from
files that were saved with the new mesh format (after T95965). When
that happens we should skip the conversion from the old format to
avoid data-loss. This will also give forward compatibility when we
stop saving in the old format completely in 4.0.

Here I mostly just check if the attributes in the new format already
exist. Along with checking for the null status of `Mesh::mvert`, that
should cover the majority of cases.

Fixes T103878

Differential Revision: https://developer.blender.org/D17011
7026096099 Nodes: Use dynamic declarations for group nodes
Since a year and a half ago we've been switching to a new way to
represent what sockets a node should have called "declarations"
that's easier to use, clearer, and more flexible for upcoming
features like dynamic socket counts or generic type sockets.

All builtin nodes with a static set of sockets have switched, but one
missing area has been group nodes and group input/output nodes. These
nodes have **dynamic** declarations which change based on their
properties or the group they're inside of. This patch addresses that,
in preparation for using the same dynamic declaration feature for
simulation nodes.

Generally there shouldn't be user-visible differences, but one benefit
is that user-created socket descriptions are now visible directly in
the node editor for group nodes and group input/output nodes.

The commit contains a few changes:
- Add a node type callback for building dynamic declarations with
  different arguments
- Add an `Extend` socket declaration for the "virtual" sockets used
  for connecting new links
- A similar `Custom` socket declaration is used for addon-defined socket
- Simplify the node update loop to use the declaration to build update
  sockets
- Replace the "group update" functions with the declaration building
- Move the node group input/output link creation to link drag operator
- Make the field status part of group node declarations
  (not for group input/output nodes though)
- Some fixes for declarations to make them update and build properly

Differential Revision: https://developer.blender.org/D16850
6769acbbba BLI_math: simplify matrix multiply logic
Improve safety and correctness of matrix multiplication by using
temporary storage if one of the inputs is also the output.

No functional changes.

Differential Revision: https://developer.blender.org/D16876
Reviewed By: Campbell Barton, Sergey Sharybin
647a7da17d Curves: Avoid adding curve type attribute when setting default
The default curve type when there is no "curve_type" attribute is
Catmull ROM. In order to avoid allocating an entire array of values
just to set this default type, remove the attribute instead. This will
be less important when we can store attributes as single values.

Also fix a curve utility API comment.
7241ab6ede Revert "Fix: don't set default value for unused socket in geometry nodes"
This reverts commit 154d3e95f8.

This caused crashes in the mouse house and flower shop benchmark files.
A proper solution will be investigated soon.
9789835db8 Docs: improve ID property doc-strings
Add some clarifications and reference enum types from DNA.
962c3cf6b1 Cleanup: remove unused IDProperty members
Remove:

- IDPropertyTemplate.matrix_or_vector
  Matrix & vector types have been deprecated, this wasn't used.

- IDProperty.saved
  This was added preemptively but never used, replace with a pad so as
  not to hint at a feature that doesn't exist.
8082b96a75 Tracking: fix inverted pie menu items for pattern match of track
The two items had their effects inverted.

Reviewed By: sebastian_k

Differential Revision: https://developer.blender.org/D16438
2c6ed49c03 Cleanup: Rename confusing region variable
`scaleare` reads like "scale area", but should read "scale region".
b510508513 Geometry Nodes: optimize Sample Index node with constant index
Previously, the node would always evaluate the input field on the
entire geometry domain. This is good when most indices will be
accessed afterwards. However, it is quite a bad when only a single
index is used. Now the field is only evaluated for that one index.
f8328ec172 Fix: Draw: Freeze Culling
Bind the frozen culling data as well.

Reviewed By: fclem

Differential Revision: https://developer.blender.org/D17010
e144af1f7c GPencil: Provide Option for Fill in Material Popover
The Grease Pencil Material Popover currently has a color picker 
for the Stroke of a Material using Solid style, but not one for
 a Fill using Solid style. 

With the default Grease Pencil Materials, the current 
popover only shows the Stroke color for the grey "Solid Fill" 
material (which doesn't have its Stroke enabled) instead of 
the more useful Fill color.

This patch shows a Stroke color picker when the Material 
has Stroke enabled and the style is Solid. 
This is the same for the Fill.

Reviewed By: antoniov, mendio

Differential Revision: https://developer.blender.org/D17004
7df5d7c7a7 Cleanup: Curves selection boolean to float comparison
The conversion from float to boolean is now handled by
the attribute API.
f8b11528b2 USD export: ensure edit mode changes are exported
Code authored by Charles Wardlaw.

Reviewed by Bastien, Sybren and makowalski.

Differential Revision: https://developer.blender.org/D15916
50105b2952 Fix T103911: Editing boolean custom property UI data resets value
The old value wasn't retrieved for boolean array properties.
d411de96f7 Fix T103936: Regression: Track To constraint broken
Caused by 6769acbbba.

Some of the matrix variants are rather obscure from the
semantic: they don't really fully initialize the output:
as in, they only write to an upper-left 3x3 block.

A quick solution to fix the very commonly used constraint.
It feels that it is possible to minimize about of copy
operations.
873794b196 Fix T103937: Applying modifier resets shape keys
The order of arguments to memcpy was reversed, which is sadly possible
because the constness `KeyBlock` of keyblock doesn't propagate to
pointers it contains.
400f022989 Geometry Nodes: Add warning to set material node with no faces
The node can't do anything in this case, which isn't always obvious.

Resolves T103133
543bf28fb1 Refactor: renamed I -> wi, omega_in -> wo in Cycles
wi is the viewing direction, and wo is the illumination direction. Under this notation, BSDF sampling always samples from wi and outputs wo, which is consistent with most of the papers and mitsuba. This order is reversed compared with PBRT, although PBRT also traces from the camera.
34326fec02 Fix: sample index node outputs default value
Error in rBb5105085139227a713f154446ff6a3255cb8be99.
1d253b6652 Fix T103945: incorrect anonymous attribute references
The case where the same field group input is evaluated on
more than one geometry inputs was not handled correctly.
d76a0e98ba Fix: Avoid node reevaluations for selection and parenting
Since 90ea1b7643, node trees have been reevaluated
after many selection operations because nodes are sorted based on
the selection status and an update tag was added for that. However,
for years the node order was allowed to be different between the
original and evaluated copy of node trees.

Though it is a bit sketchy to have that difference in the evaluated
node tree, reevaluations for just selection are very bad, so use a
"smaller" update tag and add a comment for justification.

Differential Revision: https://developer.blender.org/D17023
85ea74ad77 Cleanup: Remove unnecessary curves RNA verification disabling
There is no SDNA data for `position_data` anymore after
e9f82d3dc7.
17768b3df1 BLI: Math: Fix perspective matrix function
The port missed this one component that should have been left to 0.0.
dcb37959d4 Fix roation snap failing with zero angle
Due to precision issues, the cosine value calculated with
`dot_v3v3(start, end)` can be outside the -1, 1 range causing `acosf`
to return `nan(ind)`.

Use `angle_signed_on_axis_v3v3_v3` instead. It returns more accurate
values, deduplicates code, and avoids these `nan` issues.
301119619c Curves: Remove attribute retrieval, deduplicate evaluation logic
Avoid calling `interpolate_to_evaluate` while evaluating normals,
which has to look up attributes by name for every curve. Also avoid
duplicating the curve type switch in a few functions. I didn't observe
a performance difference, but theoretically this could reduce
overhead for many small curves.
d45ad0acd3 Geometry Nodes: Show supported geometry types tooltip without computing
Socket declarations exist all the time and it would be useful to use
them for tooltips at all times, not just when there is a computed log.

Differential Revision: https://developer.blender.org/D16846
9179362e7b Geometry Nodes: Prefer evaluate at index value input in search
Give the "Value" input a higher search weight than the "Index"
input, since it's more likely that users will want to connect to
that. Based on feedback from Simon Thommes.
44dd3308a5 DNA: move Collection members into their own Runtime struct
Also add static assert that COLLECTION_COLOR_TOT has the correct number
of items in the enum.
1c470dbd72 Cleanup: replace BLI_findptr with BKE_collection_has_object
Also swap the order of checks in collection_object_add to perform
the comparison before calling collection_find_child_recursive.
9e5e2aa775 Cleanup: rename Mesh/Curve/MetaBall loc/size/texflag
Struct members loc/size were misleading as they read as if the object
data stored object level transform channels. Rename these to match RNA
with a `texspace_*` prefix to make it clear these struct members only
apply to texture-space transform.

Also rename ME_AUTOSPACE & ME_AUTOSPACE_EVALUATED to
ME_TEXSPACE_FLAG_AUTO & ME_TEXSPACE_FLAG_AUTO_EVALUATED.
ca3e19f4c5 Fixes for 'make check_pep8' target
- Skip files in dirs starting with '.' (`.git` was being searched).
- Update --disable list for pylint.
c1d360f7fb Fix urls in LTS script.
The urls were missing /release/, leading to 404 links on the LTS download page.
2c2178549b Curves: add OffsetIndices abstraction
This changes how we access the points that correspond to each curve in a `CurvesGeometry`.
Previously, `CurvesGeometry::points_for_curve(int curve_index) -> IndexRange`
was called for every curve in many loops. Now one has to call
`CurvesGeometry::points_by_curve() -> OffsetIndices` before the
loop and use the returned value inside the loop.

While this is a little bit more verbose in general, it has some benefits:
* Better standardization of how "offset indices" are used. The new data
  structure can be used independent of curves.
* Allows for better data oriented design. Generally, we want to retrieve
  all the arrays we need for a loop first and then do the processing.
  Accessing the old `CurvesGeometry::points_for_curve(...)` did not follow
  that design because it hid the underlying offset array.
* Makes it easier to pass the offsets to a function without having to
  pass the entire `CurvesGeometry`.
* Can improve performance in theory due to one less memory access
  because `this` does not have to be dereferenced every time.
  This likely doesn't have a noticable impact in practice.

Differential Revision: https://developer.blender.org/D17025
973db6b5c1 Gitea: make bug report template more compact
And split text before and after description field to reduce long distance
between title and description.
cf50a3eabc Cleanup: remove is_same method for virtual arrays
This abstraction is rarely used. It could be replaced by some more
general "query" API in the future. For now it's easier to just compare
pointers in the Set Position node where this was used.

This is possible now, because mesh positions are stored as flat `float3`
arrays (previously, they were stored as `MVert` with some other data
interleaved).
21b3689fb9 DRW: GPU Wrappers: Add swap to storage buffers, empty framebuffer and fixes
Also add an assert to mip_view to avoid incorrect usage.
493e3230b4 DRW: Fix display print
Wrong uniform for viewport size.
efe51f0220 DRW: View: Allow for GPU side specification of view bounds
This allows an engine to perform GPU side view specification and let the
draw manager extract the culling informations (bounds).

To this end, the matrices ubo gets exposed to be able to write to it.

`compute_procedural_bounds()` need to be explicitely called before any
main pass using the culling result.
9c54f2655d DRW: Add double buffering of objects matrices, bounds, and infos
This allows easy delta calculation and access to last known position of
deleted objects.
9e5ada315f DRW: Protect `common_math_lib.glsl` from duplicated declaration
This avoid most issues when including this header along with some of the
newer `gpu_shader_math_*_lib.glsl`.
534214e65c DRW: Make intersect lib not dependent on common_view_lib.glsl
This declares view intersection functions only if the view lib if
required.
6f206f713e BLI: Math: Fix matrix tests failling
Regression introduced in rB17768b3df19a
e4e91bf830 Fix crash when listing assets repeatedly in node search menus
When doing partial reloads of asset libraries (only reload assets from
the current file, e.g. after undo re-allocated ID pointers), we'd end up
with assets that don't have their asset data read correctly. It would
execute a branch that didn't set the asset library object necessary to
create and store asset representations.

Steps to reproduce were:
* Open .blend file with geometry node assets in there
* In a geometry node editor, press Shift+A to open the add menu
* Cancel
* Move a node
* Undo
* Press Shift+A again
d3aaa7d523 Fix: Build issue with VS2019
fix by @JacquesLucke I just sprinkled it to all places
it needed to be.
6c4e3a9e51 Curves: Deduplicate and parallelize point to curve map creation
There is a utility method on `CurvesGeometry` to build a map of the
curve for each point. Use that in two more places and make sure its
implementation is multithreaded, which gives a slight speedup
in a simple test file.
163d4aa094 Fix T103707: Use beauty fill for the UV select overlap operator
The original code used `BLI_polyfill_calc` which can create degenerate
triangles during triangulation per T103913. This causes the subsequent
overlap test to produce incorrect results in certain cases. Change to
using a "beauty" fill instead.

Differential Revision: https://developer.blender.org/D17015
c2120b8c4f CMake: suppress missing-variable-declarations warnings with Clang
Code generated by wayland-scanner contained missing declarations.
8b7d2d8eb2 CMake: use BULLET_LIBRARIES for both extern_bullet and system libraries
There was no need to differentiate between these and it made
the CMake files more verbose.
66dee44088 CMake: quiet references to undeclared variable warnings
These warnings can reveal errors in logic, so quiet them by checking
if the features are enabled before using variables or by assigning
empty strings in some cases.

- Check CMAKE_THREAD_LIBS_INIT is set before use as CMake docs
  note that this may be left unset if it's not needed.
- Remove BOOST/OPENVDB/VULKAN references when disable.
- Define INC_SYS even when empty.
- Remove PNG_INC from freetype (not defined anywhere).
bc502f3b19 CMake: add WITH_LIBS_PRECOMPILED option (UNIX only)
This makes it convenient to build blender without referencing
pre-compiled libraries which don't always work on newer Linux systems.

Previously I had to rename ../lib while creating the CMakeCache.txt
to ensure my systems libraries would be used.

This change ensures LIBDIR is undefined when WITH_LIBS_PRECOMPILED is
disabled, so any accidental use warns with CMake's `--warn-unused-vars`
argument is given.
66595e29e2 Cleanup: remove/comment unused code, simplify casts
Remove simple counters where they aren't used, comment in some cases.
Also add missing include.
cac6b6f388 BGL_Wrap: disable calls on non-opengl backends.
Goal of this patch is to stop the invocation of OpenGL calls via the bgl module
on a none OpenGL GPU backend, report this as a python deprecation warning
and report this to the user.

## Deprecation warning to developers

```
>>> import bgl
>>> bgl.glUseProgram(0)
<blender_console>:1: DeprecationWarning: 'bgl.glUseProgram' is deprecated and will be removed in Blender 3.7. Report or update your script to use 'gpu' module.
```

## Deprecation message to users

The message to the user is shown as part of the Info Space and as a message box.
{F14159203 width=100%}
{F14158674 width=100%}

During implementation we tried several ideas:

# Use python warning as errors: This isn't fine grained enough and can show incorrect information to the user.
# Throw deprecation as error and use sys.excepthook to report the user message.
   This required a custom exception class to identify the bgl deprecation and a CPython handler function to
   be set during python initialization. Although this is the most flexible there was a disconnect between the
   exception class, exception function and the excepthook registration.
# A variant how we handle autoexec failures. A flag is stored in Global and when set the user message is reported.
   Not that flexible, but code is more connected to the boolean stored in the Global struct.

Although using Global struct isn't nice I chose this solution due to its traceability. It is clear to developers
reading the code how the mechanism works by using search all functionality of your IDE.

Reviewed By: MichaelPW, campbellbarton

Maniphest Tasks: T103863

Differential Revision: https://developer.blender.org/D16996
93d84e87b2 Fix T103400: Transfer Mesh Data Layout broken for color attributes
This was the case when using the operator outside of the modifiers panel.

Caused by {rBeae36be372a6}.

In above commit, `DT_layer_items` shared both `DT_TYPE_MPROPCOL_LOOP` |
`DT_TYPE_MLOOPCOL_LOOP` in a single EnumPropertyItem value "Colors".
This is a bit unusual, but probably allowed.
As a consequence, checks for specific datatypes would fail when selecting
such EnumPropertyItem:
- `DT_DATATYPE_IS_MULTILAYERS` (uses `ELEM` to check distinct entries --
would return false)
- `BKE_object_data_transfer_dttype_to_srcdst_index` (would return
`DT_MULTILAYER_INDEX_INVALID`)

These places have now been corrected to take these "special" values into
account.

Another issue was that multiple EnumPropertyItems with the same value
could be created in dt_add_vcol_layers() if attributes of the same
domain, but different color types are in play (could lead to crashes)
and that has also been corrected.

Also: above commit did not give the choice of transfering color
attributes from the vertex domain (only face corner attributes could be
chosen), this has now been added. DT_layer_vert_items (used from the
modifier) already had this included so this was only an issue when using
the operator outside of the modifiers panel.

Since we now feature two domains, the single "VCOL" in the enum has been
split into "COLOR_VERTEX" and "COLOR_CORNER". This will break existing
scripts calling bpy.ops.object.datalayout_transfer and will be marked as
a breaking change in the release notes.

NOTE: there is another bug here when attributes of the same domain, but
different color types are in play and you want to transfer just a single
specific layer (but that is for a separate commit)

Maniphest Tasks: T103400

Differential Revision: https://developer.blender.org/D16935
2907227db2 Fix T103880: Crash with Line Art Grease-Pencil modifier
The line art modifier added a wmNotifier in it's
GpencilModifierTypeInfo.generateStrokes callback which isn't thread-safe
when called from the depsgraph. This was from the original inclusion
of the feature [0] however a more recent optimization to notifier
lookups [1] made the crash occur more frequently.

Remove the notifier as modifiers should not be adding WM level events
and it works without it.

[0]: 3e87d8a431
[1]: 0aaff9a07d
a3c38667f0 Fix T103881: Unlink operation crash in Blender File view
Similar to rBe97443478e32 and rBe772087ed664, exit early when
texture, collection and world ID has no parent to unlink from.

Reviewed by: Severin, lichtwerk

Differential Revision: https://developer.blender.org/D17017
203bacbe4a Fix T103809: Using Preview Range Breaks Normalized FCurve Display
When using the "normalized" display of FCurves in the
Graph Editor, and also turning on the preview range,
the normalized display would break.

The preview frame range was assumed to be bezt indices,
which is only true when every frame has a key.

Reviewed by: Colin Basnett
Differential Revision: https://developer.blender.org/D16987
Ref: D16987
7f81d18ffe Metal: Fix crash when using `batch_for_shader`.
`batch_for_shader` is an utility function that creates the correct
vertex buffer based on the given shader. In the shader interface
the `attr_types_` contains the GPUType for each location in the
vertex buffer.

When using Metal, the `attr_types_` was never updated, resulting
in using incorrect or non-existing data types. This patch fixes
this by updating the `attr_types_` when building the shader
interface.

Reviewed By: fclem

Differential Revision: https://developer.blender.org/D17042
90c6674f28 Fix T102615: crash on USD export for scenes with point clouds or hair
Code authored by Michael B Johnson (drwave).

Reviewed by Sybren and makowalski.

This patch addresses a crash that occurs when exporting a
scene to a USD file, when that scene includes a point cloud
object or hair.

Added OB_POINTCLOUD and OB_CURVES enums and a default case
statement in the switch statement in
USDHierarchyIterator::create_data_writer, to avoid dereferencing
a NULL pointer.

Differential Revision: https://developer.blender.org/D16776
25ce705617 Merge by Distance: split code into more specialized functions
Split the algorithms that find duplicates.

This improves readability and helps us find areas for optimization.

It may also facilitate the implementation of generic utilities.

No functional changes.

Differential Revision: https://developer.blender.org/D16918
2a41e0822a Fix T103911: Custom property edit gets wrong existing default
The array length was wrong for all types after 0e89d24318, and
a typo meant that the boolean defaults were assigned to the int defaults.
08b3426df9 Cycles: Occupancy tuning for new higher end M2 machines
This patch adds occupancy tuning for the newly announced high-end M2 machines, giving 10-15% render speedup over a pre-tuned build.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D17037
e270a198a5 Cycles: Markup to disable specialisation of kernel data fields (Metal)
This patch adds markup to specify that certain kernel data constants should not be specialised. Currently it is used for `tabulated_sobol_sequence_size` and `sobol_index_mask` which change frequently based on the aa sample count, trash the shader cache, and have little bearing on performance.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D16968
9066f2e043 Cycles: Add support for OSL texture intrinsic on the GPU
This makes it possible to use `texture` and `texture3d` in custom
OSL shaders with a constant image file name as argument on the
GPU, where previously texturing was only possible through Cycles
nodes.
For constant file name arguments, OSL calls
`OSL::RendererServices::get_texture_handle()` with the file name
string to convert it into an opaque handle for use on the GPU.
That is now used to load the respective image file using the Cycles
image manager and generate a SVM handle that can be used on
the GPU. Some care is necessary as the renderer services class is
shared across multiple Cycles instances, whereas the Cycles image
manager is local to each.

Maniphest Tasks: T101222

Differential Revision: https://developer.blender.org/D17032
fa67b84c34 NLA: Udating Blend-in and Blend-out values to clamp on NLA strip Transform
Previously, transforming a clip (scaling, repeat, etc) wouldn't re-calculate the blend-in and blend-out values, leading to over / undershoot, and a visual clip artifact

Old:

{F14045003}

This patch adds re-calculation logic (new `BKE_nlastrip_recalculate_blend()`  method) to the blend-in/out on transformations to clamp values, and avoid over/under shoot.

The `BKE_nlastrip_recalculate_blend()`  encapsulates the existing logic for both the `rna_NlaStrip_blend_in_set()` and `rna_NlaStrip_blend_out_set()` methods into a single BKE method that we an execute as needed. The fact that blend-in is first decreased, is strictly on the order of calculation. My suspicion is that //if// the blend-in / blend-our values were working as intended, the RNA set methods would update in order, and we'd experience the same thing. In short, the choice here was to linearly combine the logic, without making any assumptions of my own.

while talking things over with @sybren  and @RiggingDojo, they are fine with how this currently works, but there a desire to update how the two values interact with each (ratio scale, etc) in the future.

New:
{F14045024}

{F14045025}

Reviewed By: sybren

Maniphest Tasks: T101369

Differential Revision: https://developer.blender.org/D16720
f71bfe4655 Fix anisotropic Beckmann regression test failing on Metal
The lookup table method on CPU and the numerical root finding method on
GPU give quite different results. This commit deletes the Beckmann lookup
table and uses numerical root finding on all devices. For the numerical
root finding, a combined bisection-Newton method with precision control
is used.

Differential Revision: https://developer.blender.org/D17050
38a45e46bc Cleanup: Use OffsetIndices class in more cases
The same logic from D17025 is used in other places in the curve code.
This patch uses the class for the evaluated point offsets and the Bezier
control point offsets. This helps to standardize the behavior and make
it easier to read.

Previously the Bezier control point offsets used a slightly different standard
where the first point was the first offset, just so they could have the same
size as the number of points. However two nodes used a helper function
to use the same `OffsetIndices` system, so switch to that there too.
That requires removing the subtraction by one to find the actual offset.

Also add const when accessing data arrays from curves, for consistency.

Differential Revision: https://developer.blender.org/D17038
4cfa4f7551 Geometry Nodes: Parallelize flip faces node
I observed a 2x performance improvement for a large mesh.
e12498e44e Cleanup: Avoid reallocations when evaluating curve in trim node
Use the same method as the resample node to use a single vector for
each thread. This avoids an allocation for each attribute of each curve.
dfd63bf1e4 Curves: Avoid reallocations when evaluating NURBS curves
I didn't detect a noticeable performance difference in a basic test,
but this is better in principle anyway.
9233b609eb Cleanup: Use utility function for copying curve domain data
Standardizing the process of creating a new CurvesGeometry with
different curve sizes based on an existing curves is helpful, since
there are a few methods to simplify the process that aren't obvious
at first, like filling the offsets with sizes directly and accumulating
them to become sizes.

Also, in the trim curves node, avoid creating the curve types attribute
all the time. Use the special API functions for the types which do
some optimizations automatically. Also use a more consistent
method to copy the curve domain data, and correct some comments.
8d63293c46 Curves: Avoid building evaluated point offsets for poly curves
When all the curves are poly curves, skip the work of building a
separate array of offsets for the evaluated points (which are the
same as the control points). This saves 1-4ms on every reevaluation
in test files with many curves.
7db00d4ef7 Cleanup: Rename curves utility function
"Fill" usually refers to setting a single value. This copies the
sizes from curves offsets to a separate array.
baf69b064b Geometry Nodes: Avoid creating cyclic attribute when redundant
The default when there is no cyclic attribute is that none of the curves
are cyclic. In the mesh to curve node, avoid creating the attribute with
just false to save time and memory usage. Also avoid looking up the
attribute twice in the trim node.
190d66b51e Cleanup: Remove unused attribute API function
While we do need higher level utilities for copying attributes
between geometries, this currently isn't used and it's not clear
that it will be the right abstraction in the end.
2ab72f6db8 Fix T103964: Assert on mouse hover of empty node editor
The reverse iteration added in e091291b5b didn't handle
the case where there are no nodes properly. Thanks to Iliya Katueshenock
for investigating this.
79053a6ff7 Cleanup: Move several modifiers files to C++
For continued refactoring of the Mesh data structure. See T103343.
203ab983ce Geometry Nodes: Rename node and socket for "Group ID" convention
Based on discussion about T102962, rename the "Face Set Boundaries" node
to "Face Group Boundaries" and the Accumulate Field node's "Group Index"
socket to "Group ID". This convention of "__ Group" and "Group ID" will
be used more in other nodes in the future.

This commit doesn't affect forwards or backwards compatibility.
241d87e9f4 Curves: Add RNA access to evaluated normals per control point
Add an RNA API function that gives an array of the normals for every control point.
The normals depend on the `normal_mode` attribute, which can currently be
minumum twist or Z-up, though more options are planned. Normals are currently
evaluated on the evaluated points and then sampled back to the control points.
Because that can be expensive, a normal mode that only does a first evaluation
on control points may be important

The function is intended to be used by Cycles, so it doesn't have to implement
the calculation of normals itself. They can be interpolated between control points
and normalized.

For best performance, the function should only be called once, since it does the
full calculation for every control point every time it is called.

Differential Revision: https://developer.blender.org/D17024
05bdef7ce6 Fix T103094: Cycles ignores small suns in Nishita sky
The background evaluation samples the sky discretely, so if the sun is
too small, it can be missed in the evaluation. To solve this, the sun is
ignored during the background evaluation and its contribution is
computed separately.
9889918fd4 Sculpt: New API for keeping track of topology islands
Mesh islands (shells) are now calculated on an as-needed
basis and cached inside of a temp attribute,
`sculpt_topology_island_key`.  This attribute is updated
as needed when geometry changes (e.g. the trim brush)
or when mesh visibility changes.

This replaces the old behavior where the "topology" automasking
mode would walk the entire mesh on every stroke.
8b5c2d9ef1 Sculpt: Restrict expand to active mesh islands for geodesic and topology
Fixes bug where other islands sometimes get their masks cleared (or
filled) in strange circumstances.  Still need to figure out the
correct behavior for spherical falloff.
4fa6ce0973 Sculpt: Expand NORMALS and TOPOLOGY_DIAGNAL falloff now check islands
Prevents disconnect parts of the mesh from having their masks
filled.
da21e035d3 Sculpt: Fix T103923: Expand face sets now taking visibility into account
The code was never ported from the old system of encoding visibility
as negative face set values.
ebb519652c Object: add functionality to access the object as an index for operators
Add:
- ED_object_in_mode_to_index
- ED_object_in_mode_from_index

Useful for operators that act on a non-active object in multi-edit mode,
so the index can be stored for the operators exec function to read back
the value when redoing an action. Needed to resolve T102680.
a0706d6cf0 Fix T102680: UV Pick shortest Path wrong for multi-object editing
Path selection support from [0] didn't account for multiple objects in
edit-mode. Now picking the UV also picks the object to operate on.

[0]: ea5fe7abc1
d0010d48c7 Cleanup: add ED_uvedit_get_aspect_y utility function
This avoids having to perform the aspect division inline.
92734d868b PyDoc: resolve bpy.types & bpy.ops expanding sub-modules inline
The bpy.types page was unreasonably long (over 17k lines).
Resolve by setting the `maxdepth` for this and the `bpy.ops` page too.

This problem showed up in v3.4 release and may be caused by changes
to Sphinx's default behavior as there doesn't seem to be any change
that would cause this in the generated docs.
6672b5373f Fix T103971: uv packing wasn't ignoring uv islands on hidden faces
Fixes the packing operators that use ED_uvedit_pack_islands_multi

Also fixes UV Select Similar with hidden UV islands.

Packing operators using GEO_uv_parametrizer should remain unchanged.

Add a check to BM_elem_flag_test(efa, BM_ELEM_HIDDEN).
Note that BM_mesh_calc_face_groups doesn't easily support XOR of flags,
requiring logic to be moved to a preprocess step on BM_ELEM_TAG.

Regression in rBe3075f3cf7ce.

Differential Revision: https://developer.blender.org/D17055
06c836c911 WM: rename safe areas preset add operator
The name SAFE_AREAS_OT_preset_add lead to "Safe Areas" having it's own
section in the operator API docs. Name CAMERA_OT_safe_areas_preset_add
instead. Keep "safe_areas" as the preset directory for users with
existing presets.
bbc35fef25 Cleanup: Remove remaining subdiv/subsurf files to C++
For continued refactoring of the Mesh data structure. See T103343.
721bd5e6cf Fix invalid swapBuffer calls & outdated window decorations on Wayland
Swap-buffers was being deferred (to prevent it being called
from the event handling thread) however when it was called the
OpenGL context might not be active (especially with multiple windows).

Moving the cursor between windows made eglSwapBuffers report:
EGL Error (0x300D): EGL_BAD_SURFACE.

Resolve this by removing swapBuffer calls and instead add a
GHOST_kEventWindowUpdateDecor event intended for redrawing
client-side-decoration.

Besides the warning, this results an error with LIBDECOR window frames
not redrawing when a window became inactive.
884e14ac93 3D Texturing: Adding print_debug for visually inspecting the generated geometry.
During 3D texturing the uv islands are extended in order to fix seam bleeding
for manifold parts of the input mesh. This patch adds a `print_debug` method
on UVIsland that generates a python script. This script can be copy-past
into the Python Console to show the generated geometry.

This script can be extended to show the extracted border and use face colors
for showing internal decisions.
244522d6cb 3D Texturing: Remove actual invocation of print_debug.
Was a mistake as only the function should have landed in master.
85908e9edf Geometry Nodes: new Interpolate Curves node
This adds a new `Interpolate Curves` node. It allows generating new curves
between a set of existing guide curves. This is essential for procedural hair.

Usage:
- One has to provide a set of guide curves and a set of root positions for
  the generated curves. New curves are created starting from these root
  positions. The N closest guide curves are used for the interpolation.
- An additional up vector can be provided for every guide curve and
  root position. This is typically a surface normal or nothing. This allows
  generating child curves that are properly oriented based on the
  surface orientation.
- Sometimes a point should only be interpolated using a subset of the
  guides. This can be achieved using the `Guide Group ID` and
  `Point Group ID` inputs. The curve generated at a specific point will
  only take the guides with the same id into account. This allows e.g.
  for hair parting.
- The `Max Neighbors` input limits how many guide curves are taken
  into account for every interpolated curve.

Differential Revision: https://developer.blender.org/D16642
127eb2e328 Fix: wrong identifier int for interpolate curves node
This does not break existing files, because the idname is the ground truth.
5218391701 Fix assertion in UV path select
Existing path selection & new path picking included without UV's.
Now limit objects to those with UV's.

Also remove use of CTX_wm_view3d(C) in the UV editor it would be NULL,
but it doesn't makes sense to use the 3D viewport for UV operations
even if it was available.
31a505d1a5 Functions: add debug utility for lazy function graphs
This makes it easier to print information about a socket. Just the
socket name is sometimes not enough information to know where
it is in the graph.
b6278c5a96 Fix: crash when subdividing curves
This was an error in rB38a45e46bc910c68ae3.
c006ba83e0 Fix: execution graph for geometry nodes contained cycles leading to crash
The `fix_link_cycles` function added in rB2ffd08e95249df2a068dd did not
handle the case correctly when there are multiple cycles going through
the same socket.
c8a10c43b1 Geometry Nodes: show number of curve points in socket inspection tooltip
This was not done originally, because one had to iterate over all curves
to get the number of points which had some overhead. Now the number
of points is stored all the time anyway.
c07fdad03d Cleanup: Move multires files to C++
For continued refactoring of the Mesh data structure. See T103343.
d650162ecd Curves: Add initial undo system
This adds an `UndoType` for the `Curves` object, for edit mode.
For now, this will only store the `CurvesGeometry` at every step.
Other properties such as the `selection_domain` or the `surface` object
will have to be dealt with in subsequent commits.

Differential Revision: https://developer.blender.org/D16979
70ca15670d Curves: Edit mode selection operators
This adds the following operators to edit mode:
 - `select_all`
 - `select_random`
 - `select_end`

Differential Revision: https://developer.blender.org/D17047
f31f7e3ef0 Cleanup: Remove unused light_sample_is_light() function.
This also fixes compile warnings on MSVC.
60ea01aa30 Cleanup: Move four sculpt/paint files to C++
For continued refactoring of the Mesh data structure. See T103343.
37dfce550f Fix Cycles CUDA compiler warning with if constexpr
This is a C++17 feature, compiler should be able to figure this out
without the hint.
244c87dd68 Geometry Nodes: avoid geometry copy if nothing is selected in Set Position node
This improves performance in cases where the Set Position node is "turned off"
by passing `false` into the selection input.

It's possible that the node still takes some time in this case currently, because
it is destructing the input fields which may reference geometries that need
to be destructed as well. We could potentially change this node (and others)
so that the field inputs are only requested when the selection is not a
constant `false`.
453724894e Fix T103704: Particle hair doesn't fall back to active UV
Caused by 05952aa94d, which removed the use of the
active tessface UV pointer on meshes but didn't replace it properly with
the equivalend custom data API function.
a82c12ae32 Add collection properties to MeshUVLoopLayer to access UV and the associated bool attributes (Python API).
This adds 4 collection properties to MeshUVLoopLayer to eventually replace the (MeshUVLoop) .data property.
The added properties are:

.uv
.vertex_selection
.edge_selection
.pin

The direct access to the separate arrays is much more efficient than the access via MeshUVLoop.

Differential Revision: https://developer.blender.org/D16998
2ea47e0def Geometry Nodes: Use checkbox for exposed boolean sockets
This uses the changes from ef68a37e5d to create IDProperties
for exposed boolean sockets with a boolean type instead of an integer
with a [0,1] range. Existing properties and values are converted
automatically.

For forward compatibility, the properties are switched to the integer
type for saving. Otherwise older versions crash immediately when opening
a newer file. The "Use Attribute" IDProperties aren't changed here,
since that wouldn't have a visible benefit.

Differential Revision: https://developer.blender.org/D12816
68625431d5 Geometry Nodes: Adjust modifier UI to put field toggles on the right
This also fixes the layout of boolean properties with the field toggle
visible. This was discussed in the most recent geometry nodes submodule
meeting.
25864d3dfc Cleanup: Use ampersand instead of "and" for labels
UI guideline is use '&' for labels, use "and" for descriptions.
6aa29549e8 Fix T103887: Line Art Vertex Weight Transfer to target group broken
Caused by {rB841df831e89d} and {rB3558bb8eae75}.

These commits moved flags from `eLineArtGPencilModifierFlags` to
`eLineartMainFlags`, but later on in code, these were still evaluated
from the modifiers `flags` (instead of `calculation_flags`).
This resulted in a false condition (`match_output` was assumed true but
it wasnt), leading to a wrong codepath taken.

This is now corrected (`calculation_flags` need to be passed around for
this as well).

Maniphest Tasks: T103887

Differential Revision: https://developer.blender.org/D17062
cbd15d387f GHOST/Wayland: don't send activate/deactivate on pointer enter/leave
This isn't correct as window activation is handled separately
from the cursor entering/leaving a window.

This would call de-activate when the cursor moved outside the window
even though the window remained focused.

Rely on focus changes which already handle activate/deactivate events.
0b17d171d7 Cleanup: Move three modifier related files to C++
For continued refactoring of the Mesh data structure. See T103343.
50387964b6 Curves: Add initial transform support
This adds basic support for the transform operators for curves.

Differential Revision: https://developer.blender.org/D17063
f2bb044fdb Cleanup: Move six mesh-related files to C++
For continued refactoring of the Mesh data structure. See T103343.
3f1886d0b7 Functions: align chunk sizes in multi-function evaluation
This can improve performance in some circumstances when there are
vectorized and/or unrolled loops. I especially noticed that this helps
a lot while working on D16970 (got a 10-20% speedup there by avoiding
running into the non-vectorized fallback loop too often).
00ac2ddca2 Fix T103722: Stuck modifiers for wheel events over unfocused windows
Regression in [0] caused mouse wheel events over windows without focus
to use the modifier state at the point the window was de-activated.

Now un-focused windows have all events release, when focused again
modifier press events are set again.

[0]: 8bc76bf4b9
537db96fb7 GHOST/NDOF: don't send button events when there is no active window
NDOF events without an active window were ignored and printed
warnings in the console.
b544199c56 Fix T102532: bevel spikes with loop slide.
There's a compromise of a code parameter called BEVEL_GOOD_ANGLE,
and bugs T44961, T86768, T95335, and this one, are all about problems
with various values of that parameter. If an angle of an adjacent
non-beveled edge is too close to that of the beveled edge, then you
get spikes. The BEVEL_GOOD_ANGLE says that if you are within that
angle difference, then no bevel happens. If the value is too small
then one gets spikes for certain models people build; if the value
is too large, then other people are annoyed that no bevel happens.
Hopefully this compromise in this commit is the final one I will do
before switching to Bevel v2, where none of this should be an issue.
3a2899cc31 Fix T103942 ASAN crash in math_boolean function.
The code in questions comes from Shewchuk's triangle code, which
hasn't been updated to fix the out-of-buffer access problem
that ASAN finds in the delaunay unit test. The problem is benign:
the code would exit the loop before using the value fetched from
beyond the end of the buffer, but to make ASAN happy, I put in
a couple extra tests to not fetch values that aren't going to be used.
e2006f15a9 Fix T103618: GN Transform modifies source VDB grid
The call to BKE_volume_grid_openvdb_for_write() was accidentally removed
in D15806. This adds it to BKE_volume_grid_transform_matrix_set() to
avoid that it happens again when that function is used.

Differential Revision: D16949
4bef5f3df7 Cleanup: move some undo related files to C++
For continued testing in D14139. Also see T103343.
64dbfe714b Fix T99963: Fallback actions are used in RCS on left click
The right mouse-select action no longer changes the dragging behavior
of the left mouse button.
f5c081dafc Fix T104033: UV edges not selecting when selecting faces
Regression in [0] replaced edge with vertex selection.

[0]: 6c774feba2
e0c8fa4ab9 DRW: Fix Texture.ensure() function always recreating the texture
This was caused by recent change of the `size()` method which now return
1 for missing dimensions.
6043ed9e62 Build: checkout assets directory automatically
This changes `make update` to download the assets repository automatically
if it does not exist already. If it does exist, it is updated. Precompiled libraries
have the same behavior. This is required for T103620.

`pipeline_config.yaml` is updated as well for the builtbot.

Differential Revision: https://developer.blender.org/D17090
b44a8f6749 Fix: Draw: Negative scaled objects cause wrong resource indexing
In the new Draw Manager, when the same DrawGroup has both front and back facing instances, the front facing instances don't offset their indices accordingly.

Differential Revision: https://developer.blender.org/D17069
48b82a6ea3 Fix Metal GPU backend shader compile errors in certain language environments
This patch fixes an issue where Blender 3.5 alpha with the Metal GPU backend enabled on Japanese macOS fails to compile shaders and crashes on startup.

In a Japanese environment, `defaultCStringEncoding` is the legacy MacJapanese encoding, and it erroneously converts backslashes (0x5c) to Yen symbols (¥).
Therefore, Metal shader compile fails with the following log and Blender crashes.
```
2022-12-29 13:50:10.200 Blender[13404:246707] Compile Error - Metal Shader Library (Stage: 0), error Error Domain=MTLLibraryErrorDomain Code=3 "program_source:225:74: error: non-ASCII characters are not allowed outside of literals and identifiers
    template<typename T, access A = access::sample> struct STRUCT_NAME { ¥
                                                                         ^
program_source:226:14: error: no template named 'TEX_TYPE'
      thread TEX_TYPE<T, A> *texture; ¥
             ^
program_source:226:39: error: non-ASCII characters are not allowed outside of literals and identifiers
      thread TEX_TYPE<T, A> *texture; ¥
                                      ^
program_source:227:29: error: non-ASCII characters are not allowed outside of literals and identifiers
      thread sampler *samp; ¥
                            ^
...
```
We can use `stringWithUTF8String` instead.

Reviewed By: fclem, MichaelPW

Differential Revision: https://developer.blender.org/D16881
cd2926fb05 Fix T103412: Resolve selection outline rendering with Metal backend on AMD.
AMD GPUs do not appear to produce consistent results with other GPUs when using textureGather in the Metal backend. Disabling for now to ensure correct function of outline rendering.

This may require an additional sub-pixel offset in the texture sampling calls, to achieve correct behaviour.

Authored by Apple: Michael Parkin-White

Ref T103412
Ref T96261

Reviewed By: fclem

Maniphest Tasks: T103412, T96261

Differential Revision: https://developer.blender.org/D16934
8e56ded86d Cycles: temporarily disable AMD Vega GPU rendering due to compiler bug
To make daily builds pass while we figure this out.

Ref T104097
0ba5954bb2 Fix T103635: Fix failing EEVEE and OCIO shader compilations in Metal.
Affecting render output preview when tone mapping is used, and EEVEE scenes such as Mr Elephant rendering in pink due to missing shaders.

Authored by Apple: Michael Parkin-White

Ref T103635
Ref T96261

Reviewed By: fclem

Maniphest Tasks: T103635, T96261

Differential Revision: https://developer.blender.org/D16923
1c672f3d1d Fix T103433: Ensure Metal memory allocator is safe for multi-threaded allocation. Resolves crash when baking indirect lighting.
Also applies correct texture usage flag to light bake texture.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem, jbakker

Maniphest Tasks: T96261, T103433

Differential Revision: https://developer.blender.org/D17018
139fb38d4f DRW: Add texture usage host read to Lightcache texture.
Required by Metal backend to have correct usage flags for textures which are read by host.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17020
84c25fdcaa Metal: Improve command buffer handling and workload scheduling.
Improve handling for cases where maximum in-flight command buffer count is exceeded. This can occur during light-baking operations. Ensures the application handles this gracefully and also improves workload pipelining by situationally stalling until GPU work has completed, if too much work is queued up.

This may have a tangible benefit for T103742 by ensuring Blender does not queue up too much GPU work.

Authored by Apple: Michael Parkin-White

Ref T96261
Ref T103742
Depends on D17018

Reviewed By: fclem

Maniphest Tasks: T103742, T96261

Differential Revision: https://developer.blender.org/D17019
ba982119cd Workbench Next
Rewrite of the Workbench engine using C++ and the new Draw Manager API.

The new engine can be enabled in Blender `Preferences > Experimental > Workbench Next`.
After that, the engine can be selected in `Properties > Scene > Render Engine`.
When `Workbench Next` is the active engine, it also handles the `Solid` viewport mode rendering.

The rewrite aims to be functionally equivalent to the current Workbench engine, but it also includes some small fixes/tweaks:
- `In Front` rendered objects now work correctly with DoF and Shadows.
- The `Sampling > Viewport` setting is actually used when the viewport is in `Render Mode`.
- In `Texture` mode, textured materials also use the material properties. (Previously, only non textured materials would)

To do:
- Sculpt PBVH.
- Volume rendering.
- Hair rendering.
- Use the "no_geom" shader versions for shadow rendering.
- Decide the final API for custom visibility culling (Needed for shadows).
- Profile/optimize.

Known Issues:
- Matcaps are not loaded until they’re shown elsewhere. (e.g. when opening the `Viewort Shading` UI)
- Outlines are drawn between different materials of the same object. (Each material submesh has its own object handle)

Reviewed By: fclem

Maniphest Tasks: T101619

Differential Revision: https://developer.blender.org/D16826
e49e5f6f08 Enable USD Preview Surface import by default
The USD Preview Surface material import feature is now considered
stable, so this patch removes this option from the Experimental
category in the UI.

The Import USD Preview option is now enabled by default.

The Experimental box has been removed.

A new Materials box has been added to group the Import
USD Preview Surface, Set Material Blend and Material
Collision Mode options.

Reviewed by: Sybren

Differential Revision: https://developer.blender.org/D17053
fe8bf5e0c7 Fix T104039: GPencil Fill crash in multiframe
The problem was that the stroke array was not reset for 
each iteration of the loop, so the second time around, 
the array was not initialized correctly and 
was left with a NaN value.
8afcecdf1f Cycles: update Intel Graphics compiler to 101.4032 on Windows
A noticeable (>5%) performance regression in oneAPI backend came with
a501a2dbff. Updating to latest graphics
compiler from driver 101.4032 fixes it.

I've tested it with current min-supported drivers and it runs well but
since compatibility of graphics compiler with older drivers isn't
guaranteed, I'm also bumping the min-supported driver versions.

If end-users consider latest drivers too fresh to switch to (version
isn't released as stable on Linux as of today but should be before
Blender 3.5 release), CYCLES_ONEAPI_ALL_DEVICES=1 env variable can be
used.

Intel Graphics Compiler on Linux will be updated in a later commit
so we can then close D16984.

Reviewed By: sergey, LazyDodo
b6b6e47e1d Sculpt: PBVH node splitting for texture paint
`PBVH_Leaf` nodes are now split into a new `PBVH_TexLeaf`
node type when using the paint brush.  These nodes are
split by image pixels, not triangles.  This greatly
increases performance when working with large
textures on low-poly meshes.

Reviewed By: Jeroen Bakker
Differential Revision: https://developer.blender.org/D14900
Ref: D14900
15575b953d Merge By Distance: Optimize algorithm to find duplicate polygons
The most time-consuming operation in merge by distance is to find
duplicate faces (faces that are different but have the same vertices).

Therefore, some strategies were planned to optimize this algorithm:
- Store the corner indices in an array thus avoiding multiple calls of `weld_iter_loop_of_poly_next`;
- Create a map of polygons linked to edges instead of linked to vertices - this decreases the number of connections and reduces the calculation of the intersection of polygon indices.

There are other fields to optimize, like reusing the `wpolys` array
instead of creating a new array of corner offsets. And join some arrays
as members of the same struct to be used in the same buffer.
But for now, it is already a nice optimization. And the new
`poly_find_doubles` function can be reused in the future to create a
generic utility.

The result of the optimization varies greatly depending on the number
of polygons, the size of each polygon and the number of duplicates.
On average it was something around 2 times faster.

Worst case tested (old vs new): 0.1ms vs 0.3ms
Best case tested (old vs new): 10.0ms vs 3.2ms

Differential Revision: https://developer.blender.org/D17071
7fc395354c Cleanup: Use offset indices arguments for curves utilities
Make the functions more flexible and more generic by changing the curves
arguments to the curve offsets. This way, theoretically they could become
normal utility functions in the future. Also do a consistency pass over
the algorithms that generate new curves geometry for naming and
code ordering, and use of utility functions. The functions are really
quite similar, and it's much easier to tell this way.
f24b9a7943 Cleanup: Rename pbvh.cc to pbvh_colors.cc
In preparation for moving pbvh.c to C++, give this file a different name
so git will recognize that future commit as a rename.
79ba1a1ac8 Cleanup: Compiler warnings in new sculpt & workbench
Set but unused variables, unused arguments, unnecessary/incorrect type
casting, missing static qualifier. Unused arguments are removed.
42f8f98ee1 Fix T104088: Geometry nodes modifier boolean lost on undo
After object-mode undo (memfile undo), the value wan't lost, but the
property would be temporarily converted back to integer type in order
to be forward compatible. Now only use the forward compatible
writing when writing undo steps. Auto-saves and similar files are
currently not forward compatible anyway.
f72969f377 Fix T103888: Regression: Side-by-side stereo renders ignore color management
Looks like rB42937493d8253a295a97092315288f961e8c6dba accidentally dropped the
colorspace copy.
0ad4d07f10 Fix: Debug build compile error after recent cleanup commit
79ba1a1ac8 missed that this variable was used in an assert.
36a82314a0 Fix T71137: curve minimum twist producing wrong geometry
Only one point should be used to create a reference rotation for other
points to follow. Using two caused the resulting twist to be
asymmetric, especially noticeable on symmetrical, cyclic curves.

Alternate fix to D11886 which caused T101843.
6279042d21 Cleanup: use const, doc-string for BevList.poly & rename args
It wasn't clear that BevList.poly was used to check cyclic BevList's.
1c90f8209d Cycles: fix rendering with Nishita Sky Texture on Intel Arc GPUs
Speckles and missing lights were experienced in scenes with Nishita Sky
Texture and a Sun Size smaller than 1.5°, such as in Lone Monk and Attic
scenes.
Increasing the precision of cosf fixes it.
a36e2a9b64 Gpencil: Expose stroke and point time properties to API
Two properties are now exposed in python API :
time of each point, and inittime of each stroke.

Reviewed by: Antonio Vazquez

Differential Revision: https://developer.blender.org/D17104
c16bd34316 Fix: memory allocation before guarded allocator is initialized
Use the construct-on-first-use idiom to fix this.
cf332e896f GPencil: Fix unreported double rotation in Fill circles
The help circles to fill areas were rotated with the object rotation,
but as the stroke is part of the object, apply the rot matrix again
produced a double rotation, so it can be removed.
33edef15ed Fix T104095: missing crazy space data while sculpting curves
`remember_deformed_curve_positions_if_necessary` has to be called before
topology changing operations on curves. Otherwise the crazy-space data
is invalid.
4815d0706f Fix T103385: Asset Browser Thumbnails take long time to load
Regression in [0] caused by a change where path joining would
replace a forward slash with a back-slash when joining paths WIN32.
Now the directory is always used as a prefix for the paths returned
by BLI_filelist_dir_contents which resolves the regression.

[0]: 9f6a045e23
21eff2c0ac 3DTexturing: Improve fix seam bleeding for manifold parts of mesh.
Current implementation had some faulty assumtions and had some work
arounds for crashes that were actually limitation of the implementation.

The main reason for this was that the implementation didn't add new
primitives in the same direction it was already adding. Some when
incorrect behavior was detected it was assumed that the part wasn't
manifold (anymore) and didn't fix that part of the mesh.

The new implementation will extract a solution and use this solution
also as the order to generate primitives in uv space.

This patch fixes several crashes and improves the overall quality
when fixing seam bleeding. It also adds additional debug tools
(print_debug) implementation in order to find issues faster in the
future.
10a06dfd11 Code-style: Rename internal parts of pbvh_uv_islands.
- InnerEdge -> FanSegment
- full -> is_manifold
6e4e5f6484 UI: Allow spawning file browser dialog from regular file browser editor
When some path property was displayed in the File Browser, clicking the
icon to open a file browser dialog to choose a file/directory would
show an error. While this makes sense when you are already in a file
browser dialog (we don't support such nested file browser dialogs),
allow it when the file browser is opened as a normal editor, not as a
dialog.
3956c4738f GPencil: Change range for Length value in Simplify modifier
In some cases a smaller value is required. Anyways, the UI value
soft limit is 0.005
0931d91ab6 GPenciil: Small UI tweak
Remove duplicate `Layer` word
6899474615 Fix: crash when adding curves in curves sculpt mode with interpolation
There were two issues:
* The `new_point_counts_per_curve` was one too large, resulting in
  `interpolate_from_neighbors` reading invalid memory.
* Writing the counts into the existing offsets array didn't quite work
  because there can be a collision at the offset right between the
  last old curve and the first new point. There was a race condition
  where this value could be read and written at the same time.
ae80a6696f Geometry Nodes: don't show warning in modifier with multiple geometry inputs
Simon mentioned that this gets in the way more than it helps. No geometry
sockets currently show up in the modifier panel. People may build node groups
that have multiple geometry inputs that can be used when the group is used
as node instead of as modifier.

In the future we could also allow e.g. choosing an object to pass into a geometry
socket. That has the problem that we'd also have to duplicate other functionality
of the Object Info node (original vs. relative space).
fdcb55b285 Cycles: Switch microfacet code to non-separable shadowing-masking term
This gives closer results to what I've seen in papers and other renderers when
using the code to precompute albedo later (to replace MultiGGX).

It's usually a tiny difference, the only case where I've seen it matter is
in the `shader/node_group_float.blend` test - but that's a (single-scatter) GGX
closure with 0.9 roughness, so it's not too surprising. In any case, the new
result looks closer to Eevee, so that's good I guess.

Differential Revision: https://developer.blender.org/D17099
e308b891c8 Cycles: Use faster and exact GGX VNDF sampling algorithm
Based on "Sampling the GGX Distribution of Visible Normals" by Eric Heitz
(https://jcgt.org/published/0007/04/01/).

Also, this removes the lambdaI computation from the Beckmann sampling code and
just recomputes it below. We already need to recompute for two other cases
(GGX and clearcoat), so this makes the code more consistent.

In terms of performance, I don't expect a notable impact since the earlier
computation also was non-trivial, and while it probably was slightly more
accurate, I'd argue that being consistent between evaluation and sampling is
more important than absolute numerical accuracy anyways.

Differential Revision: https://developer.blender.org/D17100
30b34735e3 Cleanup/refactor: Add a new flag for IDTypes that are not read in memfile undo.
Currently only affects 'UI' IDs (WindowManager, Screen, etc.), but in
the future other types may be affected as well.

NOTE: this is only used in readfile code itself, not in the
post-processing performed by `setup_app_data`, as this code is too
specific for such generic handling.
e56f284843 readfile: Fix 'virtual' issue in memfile case.
In many cases when reading undo memfile, n the 'restore id from old
main' part of the process, the 'id_old' is not set, which means that
the call to `BKE_main_idmap_insert_id` would try to dereference a `nullptr`.

In practice this is likely not an issue (see comment in code for details),
but at least explicitely check for a nullptr `id_old` pointer.

Would deffer actual cleanup of this area for after 3.5 is branched out.
a73a2d345f Fix T104044: keep order of UVMaps on load
Use a Vector<std::string> , instead of a Set<std::string> as a Set does
not keep the same order when iterating over it.

Differential Revision: https://developer.blender.org/D17103
361ebe98d5 Draw: Workbench Next: Fix shadow culling after recent cleanup commit
79ba1a1ac8 changed virtual function signatures so they didn't match their parents.
0f52aa0954 Transform: Initialize 'transform_matrix' accordingly
Some transform modes are changeable, so callbacks should be reset
together.

Currently the unchanged `transform_matrix` callback is not a major
issue as it is only used for gizmos and gizmos stop updating when
changing the operator type.
1ad11355a3 Transform: fix use of "snap_point" property
There is not much documentation on the "snap_point" property, but by
code it is possible to note that it serves to set a target snap point
and is of internal use as it is hidden from the Redo panel.

However, this property was still very dependent on Tools settings and
if set to an operator's call, it changes the scene configurations
inadequately.

Therefore,
- remove this dependency from UI for rotation and resize operators,
- do not change the state of the snap in the scene and
- cleanup the code.
c5d9938adc Fix T104073: Unable to add more than two strips in one channel
Originally, function `sequencer_generic_invoke_xy_guess_channel`
looked in what channel the last strip of the same type is and the
channel used for new strip placement. This was changed as a workaround
when sound strips were added below movie strips
(58bea005c5).
Now these workarounds aren't necessary, but the function was left
unchanged.

Current logic is for adding movie strip to channel 1 is:
- Sound is added to channel 1
- Video is added to channel 2
- If there is only video, it is added to channel 1

Since movie may, or may not contain sound, it is not possible to align
added strips in a way that was done before, unless timeline is analyzed
more in detail, but this would be quite inefficient.
Also, note, that the code did not work, if strip is added next to
previous one, so it mostly did not work as intended.

This commit changes:
- Fix alignment not working when strip is added right next to previous
  strip
- Assume that movie strips have sound strip underneath it, so channel
  below last movie strip is picked
- For other strip types, pick channel of the last strip of same type

Ultimately, the code is still rather weak, and better system, like using
channel where strip was manually moved, or concept of "typed channels"
would improve this feature.
b51034b9ca Asset system: use native slash for AssetLibraryIndex.indices_base_path
When constructing run-time paths native slashes are preferred as WIN32
doesn't have full support for forward slashes in paths.
It can also cause problems when performing exact matches on paths
which are normalized, where normalizing one of the paths makes
comparisons fail.

Using the system native slash would have avoided T103385.
0c2b2cdb78 BLI_filelist: minor changes to bli_builddir behavior
- Don't call exit() when memory allocation fails, while unlikely
  internal failures should not be exiting the application.
- Don't print a message when the directory is empty as it's
  unnecessarily noisy.
- Print errors the the stderr & include the reason for opendir failing.
821dee6de4 CMake: de-duplicate option(..) for platform specific defaults
Use a variable for the default instead, avoid duplicate descriptions.
6c310acccc help now includes a GPU section & improve --gpu-backend error
- Include available GPU backends in the GPU backend error.
- Use stderr for the error message.
7416021bf7 Command Line Arguments: all errors now print to the stderr
This was done by some callbacks but not all.
Only use the stdout for status & information.
72c012ab4a Python: enable user site-packages without --python-use-system-env
User site-packages were disabled unless `--python-use-system-env`
argument was given. This was done to prevent Blender's Python
unintentionally using modules that happened to be installed locally,
however it meant so pip installing modules from Blender would fail to
load those modules (for some users).

Enable user site-packages since it's needed for installing additional
packages via pip, see code-comments for details.

Resolves T104000.
e27d1d9bb6 Fix broken `listdir` code.
Error in `bli_builddir` cahnges in B4815d0706fb5 commit.
12ca26afc2 Fix T104089: Removing greasepencil vertex group can leave no active
We should always have an active vertexgroup (making sure this is the
case was just not happening on the greasepencil side).

Now do this (similar to what is done for other object types in
`object_defgroup_remove_common`).

Maniphest Tasks: T104089

Differential Revision: https://developer.blender.org/D17091
69288daa74 Fix T100674: Use plural for axes option in object properties
This commit fixes T100674, Renamed the "axis" label under viewport display
panel to "axes" in object properties.

Differential Revision: https://developer.blender.org/D16650
ffe45ad87a USD import unused materials.
Added a new Import All Materials USD import option.  When this
option is enabled, USD materials not used by any geometry will
be included in the import.  Imported materials with no users
will have a fake user assigned.

Maniphest Tasks: T97195

Differential Revision: https://developer.blender.org/D16172
f954029e97 Curves Sculpt: Add report about missing surface for puff brush
This is done in the other sculpt brushes that require a surface object.
2f9346bc0a Fix T104071: Mix up in Realize Instances tooltip text
A mistake in the node type descriptions gave the node a description for
the reverse curve node.

Differential Revision: https://developer.blender.org/D17111
9ad051140c Revert "Fix T71137: curve minimum twist producing wrong geometry"
This reverts commit 36a82314a0.
as it has broken tests for the last day and a half, it likely just
needs a test file update, but we can't keep this failing longer
than it already has.
fa57c691f6 USD IO CI Tests
Various new CI tests for USD Import / Export functionalty:

Import:
 - Added mesh import tests for topology types and multiple UV sets. (Python)

Export:
 - Added a verification tests for mesh topology. (C++)
 - Added a test to make sure UsdPreviewSurface export conversion of materials
is correct. (C++)

Reviewed by: Sybren and Hans.

Differential Revision: https://developer.blender.org/D16274
c1beaea80f Fix T103587: Redo panel doesn't appear for spin operator
Regression in [0] which cleared the redo-panel if an operator added
its own undo step. This worked for sculpt to fix T101743, but caused
the redo-panel to be cleared for actions who's undo steps where created
by nested operators (which is the case for the spin operator).

Fix by checking an undo-step is added without registering an operator.

[0]: f68e50a263
564673b8ea Fix T71137: curve minimum twist producing wrong geometry
Only one point should be used to create a reference rotation for other
points to follow. Using two caused the resulting twist to be
asymmetric, especially noticeable on symmetrical, cyclic curves.

An update to [0] which broke curve_to_mesh & deform_modifiers tests,
now this change only applies to cyclic curves as the final result was
much greater for non-cyclic curves because of a difference between how
end-point directions are calculated (see code-comments for details).

Alternate fix to D11886 which caused T101843.

[0]: 36a82314a0.
ef39d85d7c Fix T104121: Grease pencil clear function in python not updated in viewport
The clear functions for grease pencil data/frame/layer
was not followed by immediate update in the viewport.
Some notifiers were missing in the rna definition of these functions,
which are added in by this patch.

Reviewed By: Antonio Vazquez

Differential Revision: https://developer.blender.org/D17120
a42f307915 Shader Nodes: Use layers from evaluated mesh
The list was populated from the base (unevaluated) object, but now that
Geometry nodes can generate various layers this is impractical..

Differential Revision: https://developer.blender.org/D17093
f7dd7d5454 Python API: add a method for reordering modifiers.
Add an `object.modifiers.move()` method, similar to the one
for constraints and some other collections. Currently reordering
modifiers requires using operators, which depend on context.

The implementation is straightforward, except for the need to
make the severity of errors reported by the underlying editor
code into a parameter, so that the new Python API function
reports any problems as Python exceptions, and refactoring
the code to allow aborting a blocked move before making any
changes. I also turn the negative index condition from an assert
into an error.

Differential Revision: https://developer.blender.org/D16966
6d79bc0073 ImBuf: Use vector types in transform.cc.
Replace array types with the vector types. No functional changes.
f210842a72 Sequencer: Improve Image Transform Quality When Exporting.
Image Transform use linear or nearest sampling during editing and exporting.
This gets sampling is fine for images that aren't scaled. When sequencing
however you mostly want use some sort of scaling, that leads to poorer
quality.

This change will use sub-sampling to improve the quality. This is only
enabled when rendering. During editing the subsampling is disabled to
keep the user interface reacting as expected.

Another improvement is that image transform is stopped at the moment
it hadn't sampled at least 4 samples for a scan line. In that case we
expect that there are no further samples that would change to result.

In a future patch this could be replaced by a ray/bounding bo intersection
as that would remove some unneeded loops in both the single sampled and
sub sampled approach.
3b17d6c619 Sequencer: Made subsampling a transform option.
There are cases where automatic selection of subsampling doesn't work
This patch move adds a filtering option that
can enable this.
1fd54204b0 Enable commented out code.
Code was disabled for debugging purposes.
3b4486424a Fix repeated transform constraint orientations
On some occasions, as in cases where transform operations are triggered
via gizmos, the constrain orientations that can be toggled with
multiple clicks of X, Y or Z were repeated.

There is no use in maintaining repeated orientations.
d6c9cd445c Geometry Nodes: Skip sorting in topology nodes if possible
When the sort weights are a single value, they have no effect,
so sorting the relevant indices for the element will be wasted work.
The sorting is expensive compared to the rest of the node. In my
simple test of the points of curve node, it became 6 times faster
when the weights are a single value.
9a4c54e8b0 Fix: Curve to Points node has wrong field interface status
In 7536abbe16 changes make possible to input field as Count field.
But changes of declaration probably was forgotten. So now this input
can take field and node will be work. But input link was red. This
patch resolves this issue.

Differential Revision: https://developer.blender.org/D17131
cdef135f6f USD import: Support importing USDZ.
This addressed feature request T99811.

Added the following features to fully support importing USDZ archives:

- Added .usdz to the list of supported extensions.
- Added new USD import options to copy textures from USDZ archives. The
textures may be imported as packed data (the default) or to a directory
on disk.
- Extended the USD material import logic to handle package-relative texture
assets paths by invoking the USD asset resolver to copy the textures from
the USDZ archive to a directory on disk. When importing in Packed mode,
the textures are first saved to Blender's temporary session directory
prior to packing.

The new USD import options are

- Import Textures: Behavior when importing textures from a USDZ archive
- Textures Directory: Path to the directory where imported textures will
be copied
- File Name Collision: Behavior when the name of an imported texture file
conflicts with an existing file

Import Textures menu options:

- None: Don't import textures
- Packed: Import textures as packed data (the default)
- Copy: Copy files to Textures Directory

File Name Collision menu options:

- Use Existing: If a file with the same name already exists, use that
instead of copying (the default)
- Overwrite: Overwrite existing files

Reviewed by: Bastien

Differential Revision: https://developer.blender.org/D17074
3e90390918 Sculpt: Resolve `Shift R` shortcut conflicts
Based on T99607:
- Existing Angle Control shortcuts are removed
- Voxel, Dyntopo and Hair resolution shortcuts are remapped to `R`

Since voxel remeshing is not compatible with dyntopo, each can use the shortcut `R` for the remeshing resolution without causing a conflict.
The shortcut `R` is not currently used for anything important.
The angle control menu is commonly not used.
And sculpt mode is only coincidentally inheriting the rotate operator shortcut on `R` because nothing else is mapped to the key.

Reviewed By: Julien Kaspar and Hans Goudey and Joseph Eagar
Differential Revision: https://developer.blender.org/D16511
Ref D16511
34a6591a07 Fix T98594: missing uv editor redraw with geometry nodes modifier
If an object has a geometry nodes modifier, the UVs on that object might change
in response to any change on any other object.

Now we will redraw the UV editor on any object change, not just the active object.

Differential Revision: https://developer.blender.org/D17124
6c8db7c22b Fix T103868: render uv transform gizmo even if it has zero area
Change the 2D Gizmo drawing function to provide a usable transform matrix,
if it would otherwise be degenerate.

Differential Revision: https://developer.blender.org/D17113
2b4bafeac6 UV: add "similar object" and "similar winding" to uv "select similar"
Adds new options to UV Face selection in the UV Editor, with UV > Select > Select Similar

In multi object edit mode, "Similar Object" selects faces which have the same object.

"Similar Winding" will select faces which have the same winding, i.e. are they
facing upwards or downwards.

Resolves: T103975
Differential Revision: https://developer.blender.org/D17125
b3fd169259 ImBuf: Precalc subsamples to reduce branching.
Micro improvement to store delta uv per subsample. This reduces
branching that might happen on the CPU, but also makes it possible
to add other sub-sampling filters as well.

No changes for the end-user.
71d7c919c0 ImBuf: Limit transform region to pixels that are affected by the transformation.
Only the area where the source buffer will be drawn on the destination buffer
will be evaluated. This will improve performance in sequencer and image editors as
less calcuations needs to happen.
0cce653892 Cleanup: Pass double2 by reference.
Just to be sure if compilers aren't inlining the function that at
least the parameter isn't copied.
d5b026a16c Fix incorrect RNA path for GPencil brush settings, and add it for Curves brush settings.
RNA paths should be relative to their owner ID, not to some other ID!
79f70e48eb Fix: crash in mesh topology nodes
This was broken in rBd6c9cd445cb41480b40.
454057f9df Fix T104175: adding Blur Attribute node with link drag search fails
The node does not support blurring booleans, but that was not handled
property in link drag search.

Differential Revision: https://developer.blender.org/D17139
75d6228583 PyAPI: Generic UIList for CollectionProperties
This patch adds a draw_ui_list() function, which is a wrapper around
layout.template_list(). It implements generic add/remove/move buttons,
passing the correct "row" integer to template_list(), as well as a
drop-down menu, if provided, making it a complete solution for
consistent UILists for addons.

Differential Revision: https://developer.blender.org/D14119
073cf46b2e Fix Generic List move ops clickable with 1 element
Meant to include this piece of feedback from Sybren in D14119.
1fd1d24265 Revert accidental changes to sub-modules
When committing via VSCode's Git UI,
my commit 073cf46b2e
seems to have affected sub-modules.
Gotta be more careful!
138b3815e5 Fix (unreported) missing clear of deprecated Window data on fileread.
rB7f564d74f9ed (6 years ago!) forgot to clear the deprecated
`Window->screen` pointer on file read for recent-enough .blend files.

This is required since a valid value is always written in .blend files
for that pointer, to ensure backward compatibility.

The issue was never detected so far because that pointer is explicitely
reset to NULL after filewrite, which includes any memfile undostep
write, and usually existing UI data is re-used instead of loading the
one from the .blend file, so thedden  assert in `blo_lib_link_restore`
would never be triggered.

Now moved the assert at the end of `setup_app_data` to ensure it always
get checked.
3d7697b325 Tweak to previous commit: move checks on DNA deprecated data at the end of readfile code.
BKE blendfile should not be allowed to deal with DNA deprectaed data, so
move recent check in rB138b3815e528 into BLO readfile, in a new
`blo_read_file_checks` util that is being called at the very end of main
readfile code (`blo_read_file_internal` and `library_link_end`).
46c68c46a5 3D Texturing: Adding more cases where seams can be fixed.
Case added where a corner in uv space share the same edge in 3d space.
This used to work, but was lost when implementing
the new approach.
4635dd6aed Fix T104157: Deleting an active OSL node causes issues
Removing all OSL script nodes from the shader graph would cause that
graph to no longer report it using `KERNEL_FEATURE_SHADER_RAYTRACE`
via `ShaderManager::get_graph_kernel_features`, but the shader object
itself still would have the `has_surface_raytrace` field set.
This caused kernels to be reloaded without shader raytracing support, but
later the `DEVICE_KERNEL_INTEGRATOR_SHADE_SURFACE_RAYTRACE`
kernel would still be invoked since the shader continued to report it
requiring that through the `SD_HAS_RAYTRACE` flag set because of
`has_surface_raytrace`.
Fix that by ensuring `has_surface_raytrace` is reset on every shader update,
so that when all OSL script nodes are deleted it is set to false, and only
stays true when there are still OSL script nodes (or other nodes using it).

Maniphest Tasks: T104157

Differential Revision: https://developer.blender.org/D17140
b67b84bd5d Fix T103984: USD exports pass usdchecker
These changes were authored by Michael B Johnson (drwave).

The default Blender USD export currently produces files that trigger
errors in the usdchecker that ships with USD 22.11.

The changes are:

- Set the defaultPrim if no defaultPrim is set. This sets it to the
first prim in the hierarchy which matches the behaviour of Pixar's
referencing (where referencing a USD layer without a defaultPrim will
pick the first prim) as well as matches the logic in Pixar's Maya USD
exporter code.

- Applies the MaterialBindingAPI to prims with material binding
attributes. This is a relatively new requirement for USD as it will
help for efficiency with upcoming changes to Hydra.

- Removes the preview scope in the USD shader hierarchy, because it
is no longer valid for shaders to have any non-container ancestors in
their hierarchy up until the enclosing Material prim.

Reviewed by: Michael Kowalski

Differential Revision: https://developer.blender.org/D17041
e99ae0a75d Vulkan: Tweaks to CMake configuration.
MoltenVK wasn't found as it was previous part of lib/vulkan.
as lib/vulkan now doesn't contain
the full sdk, we will use a moltenvk folder.

At this moment the moltenvk folder isn't filled, but will eventually be.
000e722c7d Geometry Nodes: Optimize start point case of Points of Curve node
In the node groups for T103730, the "Points of Curve" node is often used to
retrieve the root point of every curve. Since the curve point offsets array
already contains that data directly, we can detect this as a special case and
avoid all the other work.

Differential Revision: https://developer.blender.org/D17128
179605bd2d Fix T104168: No active UV when reading auto-save files
Similar to 6d12d43a05, we should skip the
legacy to generic conversion if there's nothing to convert.
0050d6d399 Cleanup: move function to file where it is used
`drawLine` is only used for constraint, so it should be in
`transform_constraints.c`
f5e76aa39e Cleanup: Array types, const, math API in workbench code
Some miscellaneous cleanups left over from a fix/cleanup combo:
- Use const variables
- Use the C++ `math` namespace functions
- Use `std::array` for arrays with size known at compile time
- Use `MutableSpan` instead of reference to array

Differential Revision: https://developer.blender.org/D17094
328772f2d9 Mesh: Add operator to flip quad tessellation
This adds a new operator: bpy.ops.mesh.flip_quad_tessellation()

This operator rotates the internal loops of the selected quads, allowing
the user to control tessellation without destructively altering the
mesh.

{F14201995}

This operator can be found in the "Face" menu (Ctrl+F) under "Face
Data".

{F14201997}

Reviewed By: campbellbarton, dbystedt

Differential Revision: https://developer.blender.org/D17056
9facc5067a Cleanup: Simplify mesh and point cloud conversion
Since mesh positions are stored as a generic attribute,
the attribute doesn't need special handling here.
cef03c867b UV: cleanup winding
Simplify `BM_uv_element_map_create` by using `BM_face_calc_area_uv_signed`.

Remove unused UV winding code in `BM_uv_vert_map_create`.

Fixes unlikely memory leak in `BKE_mesh_uv_vert_map_create`.

No functional changes.

Differential Revision: https://developer.blender.org/D17137
d7e914270f Fix (unreported): Pasted strip is not active
Broken by renaming strip before comparing name to reference.
3a9e589142 Fix (Unreported): VSE side panel flickering when tweaking offset value
Panel was split by factor calculated from property value string length.
Since these properties have float type now, calculated length was
incorrect.
4e9c6929c1 VSE: Handle drivers when duplicating strips
Most operations where strips are duplicated use `SEQ_animation` API,
which handles keyframe animation. Now drivers are handled as well.

When group of strips is duplicated and driver references other strip,
it will still reference original strip. However, this is much better,
than previous behavior, when strip duplication results in "transfer" of
driver from original strip to duplicated one.

Fixes T104141
89aae4ac82 Node Editor: Controlled node link swapping
Allow to explicitly swap node links by pressing the alt-key while
reconnecting node links. This replaces the old auto-swapping based on
matching prefixes in socket names.

The new behavior works as follows:

* By default plugging links into already occupied (single input)
  sockets will connect the dragged link and remove the existing one.
* Pressing the alt-key while dragging an existing node link from one
  socket to another socket that is already connected will swap the
  links' destinations.
* Pressing the alt-key while dragging a new node link into an already
  linked socket will try to reconnect the existing links into another
  socket of the same type and remove the links, if no matching socket
  is found on the node. This is similar to the old auto-swapping.

Swapping links from or to multi input sockets is not supported.

This commit also makes the link drag tooltip better visible, when using
light themes by using the text theme color.

Reviewed By: Hans Goudey, Simon Thommes

Differential Revision: https://developer.blender.org/D16244
904357d67a Fix: assert when converting between incompatible field types
This results in a compile time error now which hopefully prevents
this specific kind of mistake in the future.
b2534fb866 Fix: anonymous attribute output requested even though it's not used
The code removed here was intended to be an optimization that
avoids creating an additional node to join multiple attribute sets.
However, that optimization did not work, because it did not take
into account whether the single attribute set is required or not.
90253ad2e7 Geometry Nodes: avoid creating a lazy function many times
It's better to use some statically allocated functions instead
of dynamically allocating them all the time.
e497da5fda Fix: off by one error in previous commit
Fixes rB90253ad2e753acde161b38d82bd650d54d3f6581.
042775ad48 Sculpt: Fix T104068, depth calculation error in trim tools
Also made the coplanar padding factor relative.
ad146bd17a Fix T103852: Muting timeline channel does not update image
Add RNA update function to invalidate cache for all strips in channel.
90e9406866 VSE: Add Update scene frame range operator
This operator updates scene strip internal length to reflect target
scene length. Previously scene strip had to be deleted and added from
scratch. Scene strip length in timeline will not be changed.
75c772391d I18n: construct report verbosely when moving objects to collection
When moving or linking an object to a collection, the report was not
properly translatable. In French for instance, it would give
nonsensical half-translated sentences such as "<Object> moved vers
<collection>", instead of "<Object> déplacé vers <collection>".

Instead, separate the report into the four possible translations (one
or multiple objects, linking or moving). This is very verbose and less
legible, but it ensure the sentences can be properly translated,
including plurals in languages which use grammatical agreement.

In addition, use BKE_collection_ui_name_get() to get the collection
name, because the Scene Collection's name is hardcoded, but it can be
localized.

Reviewed By: mont29

Differential Revision: https://developer.blender.org/D17112
db87e2a638 I18n: extract and disambiguate a few messages
Extract:
- EEVEE: Compiling Shaders (the same message exists in EEVEE Next, but
  it uses string concatenation and I don't know yet how to deal with
  those--see T92758)

Disambiguate:
- Pan (audio, camera)
- Box (TextSequence)
- Mix (noun in constraints, GP materials)
- Volume (object type, file system)
- Floor (math integer part, 3D viewport horizontal plane)
  - Impossible to disambiguate the constraint name because
    bConstraintTypeInfo doesn't have a context field.
- Show Overlay (in the sequence editor, use the same message as other
  editors to avoid a confusion with the Frame Overlay feature, also
  called "Show Overlay")

Additionally, fix a few issues reported by Joan Pujolar (@jpujolar)
in T101830.

Reviewed By: mont29

Differential Revision: https://developer.blender.org/D17114
2ff08d6d9c Cleanup: Pass explicit type to `MEM_cnew`.
Better avoid fancy implicit typing in this template, and be clear about
what type is actually being allocated.
d0f55aa671 Vulkan: Fix GLSL compilation errors.
Recent changes in our GLSL libraries didn't compile on Vulkan. This
change reverts a compile directive that was removed, but required
in order to compile using the Vulkan backend.
57552f52b2 Metal: Realtime compositor enablement with addition of GPU Compute.
This patch adds support for compilation and execution of GLSL compute shaders. This, along with a few systematic changes and fixes, enable realtime compositor functionality with the Metal backend on macOS. A number of GLSL source modifications have been made to add the required level of type explicitness, allowing all compilations to succeed.

GLSL Compute shader compilation follows a similar path to Vertex/Fragment translation, with added support for shader atomics, shared memory blocks and barriers.

Texture flags have also been updated to ensure correct read/write specification for textures used within the compositor pipeline. GPU command submission changes have also been made in the high level path, when Metal is used, to address command buffer time-outs caused by certain expensive compute shaders.

Authored by Apple: Michael Parkin-White

Ref T96261
Ref T99210

Reviewed By: fclem

Maniphest Tasks: T99210, T96261

Differential Revision: https://developer.blender.org/D16990
6dde185dc4 Metal: Fix edge-case with point primitive restart index removal where all indices are restarts.
Metal backend does not support primtiive restart for point primtiives. Hence strip_restart_indices removes restart indices by swapping them to the end of the index buffer and reducing the length.
An edge-case existed where all indices within the index buffer were restarts and no valid swap-index would be found, resulting in a buffer underflow.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17088
a36c1cabce Vulkan: Changes to CMake config.
Paths to vulkan libraries, paths and related components were
hardcoded in the platform cmake file. This patch separates
this by using adding CMake modules for Vulkan and ShaderC.

This change has only been applied to the macOs configuration as
that is currently our main platform for development. Other platforms
will be added during the development of the Vulkan back-end.
411345757c Cleanup: Remove unused variable.
Introduced in recent commit.
596ee79a9f Metal: Optimize shader local memory usage.
Due to shader global scope emulation via class interface, global constant arrays in shaders are allocated in per-thread shader local memory. To reduce memory pressure, placing these constant arrays inside function scope will ensure they only reside within device constant memory. This results in a tangible 1.5-2x performance uplift for the specific shaders affected.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17089
62dd0855a9 Cleanup: Remove special handling of 3DCursor in undo code.
Such preserve-across-undo data handling is now done through the IDType
callbacks, see e.g. `scene_undo_preserve` for the 3DCursor case.
d4d4efd3d3 GPU: Use create info for compute test cases.
Compute test case still used legacy API to construct
GLSL shaders. This change will migrate it to use the
GPUShaderCreateInfo's.

In preparation to run test-cases against non-opengl
back-ends.
aca9c131fc Metal: Fix issue with premature safe buffer list flush and optimize memory manager overhead.
Resolve an issue where released buffers were returned to the reusable memory pool before GPU work associated with these buffers had been encoded. Usually release of memory pools is dependent on successful completion of GPU work via command buffer callbacks. However, if the pool refresh operation occurs between encoding of work and submission, buffer ref-count is prematurely decremented.

Patch also ensures safe buffer free lists are only flushed once a set number of buffers have been used. This reduces overhead of small and frequent flushes, without raising the memory ceiling significantly.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17118
ce13d0d326 GPU: Only compile test shaders when test cases option is enabled.
The glsl files + create infos of shaders that are only used
during development where still being compiled into blender.

This isn't needed and shouldn't be included. This change will
only include them when WITH_GTEST and WITH_OPENGL_DRAW_TESTS are
enabled. All other cases those files will be skipped.
c79b55fc05 USD export: add scale and bias for normal maps.
Changes authored by Michael B Johnson (drwave).

This addresses the issue in T102911.

Add scale and bias inputs to ensure the normals are
in tangent space [(-1,-1,-1), (1,1,1)].

This is following the convention as set in the USD Spec
(https://graphics.pixar.com/usd/dev/spec_usdpreviewsurface.html).

Differential Revision: https://developer.blender.org/D17072
f4deed288b USD export: style fixes to previous commit.
Changed to C-style comments and added braces.
87a923fdb6 GPU: Add SSBO binding test to new structure.
This test was added to test the shader info structure binding
information for SSBOs. It still used the legacy GLSL structure.
129093fbce Cycles: Fix crash when rendering with OSL on multiple GPUs
The `MultiDevice` implementation of `get_cpu_osl_memory` returns a
nullptr when there is no CPU device in the mix. As such access to that
crashed in `update_osl_globals`. But that only updates maps that are not
currently used on the GPU anyway, so can just skip that when the CPU
is not used for rendering.

Maniphest Tasks: T104216
f359a39d11 Fix T100028: Convert USD camera properties to mm from USD units.
Authored by Sonny Campbell.

Currently when importing a USD file, some of the camera properties are
ignored, or the units are not converted correctly from USD world units.
On import we currently set the focal length, but not the camera sensor
size (horizontal and vertical aperture), so the camera field of view
is wrong. The sensor size information is in the USD file, but is ignored
for perspective cameras.

USD uses "tenth of a world unit" scale for some physical camera properties
like focal length and aperture.
https://graphics.pixar.com/usd/release/api/class_usd_geom_camera.html#UsdGeom_CameraUnits

I have added the UsdStage's metersPerUnit parameter to the ImportSettings
so the camera can do the required conversion on import. This will convert from
the USD file's world units to millimeters for Blender's camera settings.

Reviewed by: Sybren and makowalski.

Differential Revision: https://developer.blender.org/D16019
ea8fd343eb Gitea: add merge message templates
To add the pull request # at the end of the commit.
27b4916b1a Cleanup: spelling in comments
Also minor changes in comments:
- Reference BLENDER_HISTORY_FILE instead of the literal file-name
  (simplifies looking up usage).
- Use usernames in tags, as noted in code-style.
4f1800d70a Docs: note that delimiting by winding could be supported
Some users requested this behavior since it was removed,
so note that it could be supported again.
b7e178cb7d GPU: Cross test OpenGL tests to Vulkan.
Enhanced the GPU_TEST macro to also handle Vulkan backend
when WITH_VULKAN_BACKEND compilation option has been
enabled.
d8cd8a0852 Cleanup: remove compilation warning
Unused parameter in vk_backend.
d44d165e8a Vulkan: Fix compilation on Linux.
ShaderC was missing and is required for compilation.
59aefaf3d0 Vulkan: Fix assert when compiling transform feedback shaders.
Transform feedback shaders don't have a fragment shader and should not
fail when it is not given.
3d765f6527 GPU: Fix gpu_math_test.glsl test case.
Test results were generated from incorrect code.
Code was fixed, but test results weren't updated.
This patch updates the test results to match the implementation.
- `projection_perspective.w.w == 0.0`
9f866a92dc Fix T104176: Smooth modifier with vergex group not work for negative factors.
Regression from rBabc8d6b12ce9, over three years ago!

Should be backported to the active LTS releases too.
f3bd5458a3 Metal: Optimise shader texture cache usage and branch reduction via point sampling.
Replace texelFetch calls with a texture point-sample rather than a textureRead call. This increases texture cache utilisation when mixing between sampled calls and reads. Bounds checking can also be removed from these functions, reducing instruction count and branch divergence, as the sampler routine handles range clamping.

Authored by Apple: Michael Parkin-White
Ref T96261

Depends on D16923

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17021
a504058dee Metal: Optimize GLSL to MSL translation. Improve cached compilation
Reduces the GLSL to MSL translation stage of shader compilation from 120 ms to 5 ms for complex EEVEE materials. This manifests in faster overall compilations, and faster cache hits for secondary compilations, as the MSL variant is needed as a key.

Startup time is also improved for both first-run and second-run. Note that this change does not affect shader compilation times within the Metal API.

Also disables shader output to disk

Authored by Apple: Michael Parkin-White

Ref T96261
Depends on D16990

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17033
c1e5359eba GPencil: Use BLI_math_matrix_type.hh instead of BLI_math_float4x4.hh
Straightforward port. I took the oportunity to remove some C vector
functions (ex: `copy_v2_v2()`).

Reviewed By: antoniov

Differential Revision: https://developer.blender.org/D17160
59b7aec9a2 VSE: Add missing NULL check in poll
Commit 90e9406866 forgot to add a NULL check for `ed`
a837604d44 BLI: Math: Add `xy()` and `xyz()` swizzle functions
Thoses are added for better component masking syntax.
This avoids the harder to read `float2(my_vec4)`.

This is not meant to be fully usable swizzling support but could be
extended in the future.
6de43f6f04 BLI: Fix invalid swizzle commit
This fix incorrect rBa837604d44a0 commit
1cb04af1df BLI: Fix missing const correctness
This fix incorrect rBa837604d44a0 commit
ce42906b89 Fix wrong spot light blend circle radius in viewport
Was using squared cosine instead of cosine. The problem is obvious for large spread angles.
|before|after
|{F14220946}|{F14220948}
The images are generating by returning `floor(spotmask)` in function `spot_attenuation()` in `lights_lib.glsl`.
fa9fc59b56 Fix T104240: OptiX OSL texture loading broken with displacement
The image manager used to handle OSL textures on the GPU by
default loads images after displacement is evaluated. This is a
problem when the displacement shader uses any textures, hence
why the geometry manager already makes the image manager
load any images used in the displacement shader graph early
(`GeometryManager::device_update_displacement_images`).
This only handled Cycles image nodes however, not OSL nodes, so
if any `texture` calls were made in OSL those would be missed and
therefore crash when accessed on the GPU. Unfortunately it is not
simple to determine which textures referenced by OSL are needed
for displacement, so the solution for now is to simply load all of
them early if true displacement is used.
This patch also fixes the result of the displacement shader not
being used properly in OptiX.

Maniphest Tasks: T104240

Differential Revision: https://developer.blender.org/D17162
11a9578a19 Geometry Nodes: hide group inputs with "Hide Value" enabled in modifier
When the "Hide Value" option of a group input is enabled, only its name
is displayed in group nodes. Modifiers should have the same behavior.
However, for modifiers, only showing the name does not make sense
when the user can't edit the value. Therefore the value is not shown at all.
0a9520ce84 Sculpt: Un-invert expand normal falloff
Normals falloff mask is created inverted compared
to how other falloffs work.  It's now un-inverted
in a final step at the end.

Also exposed the normals falloff smooth steps as
an RNA property.
345dded146 Revert "Geometry Nodes: hide group inputs with "Hide Value" enabled in modifier"
This reverts commit 11a9578a19.

Reverting this because there was a miscommunication between Simon and me. Shortly
before I committed the change, Simon noticed that there are cases when "Hide Value"
is checked to hide the value in a group node, but we still want to show the value
in the modifier.
e515f81318 Cleanup: move swapping objects in a collection to a utility function
Including this logic inline complicated D17016 & was noted as a TODO.
5a97b282e9 Fix (unreported) crash when importing data with custom normals.
The usage of `index` was inverted between destination array of vectors
and source vector in rB3a3d9488a1633.
9b86741ae7 FIx possible return of string without null character
`WM_modalkeymap_items_to_string` is expected to always return a string.

But in the special case of zero length, the returned string was not
terminated with `'\0'`.

This can cause problems with the header of the knife tool for example.
It always uses the returned string.

(This issue was observed when investigating T103804).
a4868f2058 Fix T104136: Crash with Mesh to Volume & Simplify
Blender crashes when Simplify is enabled and set to 0.
This is because mesh_to_volume_grid returns nullptr at voxel size 0.
A simple null-check fixes this problem.

Differential Revision: https://developer.blender.org/D17122
d82ffb9787 Fix T103530: Allow Recursive File Lists
In File Browser, correct full path creation so that it works correctly
in recursive listings.

See D17175 for more details.

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

Reviewed by Julian Eisel
31a6400279 Fix error referencing transition context which doesn't exist
Regression in [0] added reference to constraint which doesn't exist.

[0]: db87e2a638
99520a79b6 Viewport Compositor: Platform support message.
In the previous situation the message was shown for Apple devices.
But this is not correct and confusing.

- Apple with Metal backend are supported, OpenGL on Apple isn't
- Legacy devices on Windows or Linux are also not supported.

This change will check that the capabilities of the GPU match the
requirements to use Viewport compositor. Based on those capabilities
a message is shown and the panel is activated.
199233eee1 Cleanup: Change VMA from CRLF to LF.
To match the rest of our repository.
e1ee86b63c Change default AV1 encoder for "slowest"
Previously, having the "Encoding speed" set to "slowest" would choose
libaom-av1 first and librav1e second. This change makes Blender choose
librav1e first (and has a fallback to whatever other AV1 codec is
available if librav1e is not installed).

Addresses /T103849 on systems where librav1e codec available.

Reviewed By: sergey, ISS

Maniphest Tasks: T103849

Differential Revision: https://developer.blender.org/D17002
d92edca862 Fix: CustomData layers become unsorted in versioning
n versioning, when converting CD_SCULPT_FACE_SETS to CD_PROP_INT32
the layers were not kept properly ordered by type.

This was discovered while investigating T104053

Differential Revision: D17165
6c66f3e2b3 GPU: Remove prototype without implementation.
`GPUShaderInterface(const ShaderCreateInfo&)` is defined but its
implementation has been removed.
644d54a193 GPU: Fix memory leak in VkShader.
std::string makes a copy, without taking ownership.
d77b87eb93 Fix invalid versioning code for meshes
The issue was introduced in d92edca8622: one shall not use
polygon index to index polygon custom data layer.
49ad91b5ab Animation: Enable Pin Icon in the Dope Sheet
Even though the dope sheet respects the pinned channels, it did not show the icon to interact with the pinned state.

This adds the icon to the dope sheet as well.

{F14178715}

Reviewed by: Sybren A. Stüvel
Differential Revision: https://developer.blender.org/D17061
Ref: D17061
c1b85103fe GPU: Added testcase for SSBO/Compute.
Test case is a smaller step towards supporting Vulkan. Other
test cases rely on SSBOs as well so it is better to first satisfy
this step before handling the others.
c2c6707919 Fix T102690: Object can be animated with a single keyframe
Remove some assumptions that an FCurve with a single keyframe always is
extrapolated in constant fashion. There's no reason for the Beziér handles
to be ignored in such a case.

FCurve evaluation already worked properly, it was just the drawing in the
graph editor and the selectability of the handles that needed adjustments.
fe5d54d3d0 Gizmo: add new cage2d draw style for circular shapes
`ED_GIZMO_CAGE2D_STYLE_CIRCLE` now draw circles. The previous `ED_GIZMO_CAGE2D_STYLE_CIRCLE`, which drew rectangles, is renamed to `ED_GIZMO_CAGE2D_STYLE_RECTANGLE`. The meaning of `ED_GIZMO_CAGE2D_STYLE_BOX` is now unclear and probably needs to be renamed too.
Ref T104280

Maniphest Tasks: T104280

Differential Revision: https://developer.blender.org/D17174
04aab7d516 Animation: Add "Select Linked Vertices" to Weight Paint Mode
Adds two operators to select linked  vertices in weight paint mode.
Similar to how it works in edit mode.
Press "L" to select vertices under the cursor,
or CTRL + "L" to select anything linked to the current selection.

Reviewed by: Sybren A. Stüvel, Hans Goudey, Marion Stalke
Differential Revision: https://developer.blender.org/D16848
Ref: D16848
2a19810f97 Fix T104296: crash caused by incorrectly initialized group nodes
Versioning code in `do_versions_after_linking_260` inserted new group input
and output nodes. And (reasonably?) expected sockets to exist on those nodes.
However, `nodeAddStaticNode` did not initialize sockets on nodes with that use
`declare_dynamic` yet. This patch changes it so that `declare_dynamic` is used
in more places, which caused issues during file loading when node groups are
updated in somewhat arbitrary order (not in an order that is based on which
groups use which).

Differential Revision: https://developer.blender.org/D17183
7208938707 Fix T104278: incorrect handling of unavailable linked node groups
The declaration of group nodes using unavailable linked groups contains
a `skip_updating_sockets` tag, which indicates that the node shouldn't
change. This information was not used properly further down the line.
fc2a64e21a Win32: Better Error Handling in BLI_file_attributes
After Win32 API call GetFileAttributesW, check for
INVALID_FILE_ATTRIBUTES, which is returned on error,
usually if file not found.

See D17176 for more details.

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

Reviewed by Ray Molenkamp
fdc81be213 Fix T104223: attribute not propagated to Set Curve Radius node
This declaration change tells the evaluation system that the radius
field is evaluated on the input geometry. Which in turn means that
attributes referenced by the radius field should be propagated to
the geometry.
ca99a59605 Fix T104261: crash when trying to draw viewer overlay for empty curve
`BKE_displist_make_curveTypes` only sets `curve_eval` if the final geometry
of the object actually contains curve data, otherwise it's null.
52de84b0db BLI: Use BLI_math_matrix_type.hh instead of BLI_math_float4x4.hh
Straightforward port. I took the oportunity to remove some C vector
functions (ex: `copy_v2_v2`).

This makes some changes to DRWView to accomodate the alignement
requirements of the float4x4 type.
b5e00a1482 Revert "BLI: Use BLI_math_matrix_type.hh instead of BLI_math_float4x4.hh"
This reverts commit 52de84b0db.

had some build issues on windows i can't quickly resolve, revert for
now while we fix the problems
023277359f Fix T104053: Limit pbvh recursion
The recursion depth was checked for equality with a maximum depth,
allowing leaves with more primitives if a certain depth was reached.

However, a single leaf must always use the same material (including
set_smooth), so if a leaf contained multiple materials it was split
anyway. This meant that in the next recursion step the depth was
larger than the cutoff value and it would go back to recursing until
the number of primitives was small enough, ignoring the recursion
depth for the rest of the process.

In certain edge cases this could lead to a stack overflow.

Even with the check changed from 'equality' to 'larger or equal'
this could still fail in the pathological case where every primitive
has another material. But that can't be helped, and it wouldn't
realistically happen either.

Differential Revsision: https://developer.blender.org/D17188
27e2b32a06 Cleanup: Remove redundant calls to init grids
`BKE_volume_init_grids` gets called in `volume_init_data` that is run
on creating new datablocks so it's unnecessary to run it separately.
c468aeefb5 PyAPI: updates to bl_ui.generic_ui_list which didn't follow conventions
- Replace type annotations with doc-strings, the current conventions is
  not to use type annotations in startup scripts.
- Replace abbreviation "idx" with "index" in public arguments/properties.
- Replace `len(..) > 0` with boolean checks.
- Add `__all__` to list public members.
- Use `arg` instead of `param` for doc-strings.
- Locate the doc-string so it shows as `__doc__`.
9565ea0724 IO: Harmonize UI for selection of axes in OBJ and Collada
Implements T103858: in OBJ importer and exporter, and in Collada
exporter, present axis choices as a dropdown instead of inline button
row.

Reviewed By: Bastien Montagne
Differential Revision: https://developer.blender.org/D17186
a45a881534 Spelling: `familly` -> `family`.
Fix spelling mistake originated from tmp-vulkan branch.
ab3e1809b6 Vulkan: Select graphics queue with compute capabilities.
There might be cases that the graphics queue and compute
queue are separated, but that would be something that we
will solve in the future.
d335db09e0 Fix T90893: Restoring a key in the keymap editor doesn't work if the key is only disabled
Reset `KMI_INACTIVE` flag when restore-item  button is called

Reviewed By: campbellbarton

Differential Revision: https://developer.blender.org/D16773
0f51b5b599 Animation: Add Operator for adding FCurve modifiers to more menus
The operator has the option to add to selected FCurves instead
of only the active, but it was only exposed in the redo panel.
This patch adds the operator to the right-click menu on FCurve channels,
and to the channel menu in the Graph editor.
Both times with configured to add to selected
instead of only the active FCurve

Revied by Reviewed by: Sybren A. Stüvel
Differential Revision: https://developer.blender.org/D17066
Ref: D17066
af0d378177 Cleanup: Move multires reshape header to C++
For continued refactoring of the Mesh data structure. See T103343.
19b63b932d Fix transform gizmo not updating according to state
Whenever a transform operation is activated by gizmo, the gizmo
modal is maintained, but its drawing remains the same even if the
transform mode or constrain is changed.

So update the gizmo according to the mode or constrain set.

NOTE: Currently only 3D view gizmo is affected
ebe8f8ce71 BMesh: Parallelize BMesh to evaluated Mesh conversion
Currently this conversion (which happens when using modifiers in edit
mode, for example) is completely single threaded. It's harder than some
other areas to multithread because BMesh elements don't always know
their indices (and vise versa), and because the dynamic AoS format
used by BMesh makes some typical solutions not helpful.

This patch proposes to split the operation into two steps. The first
updates the indices of BMesh elements and builds tables for easy
iteration later. It also checks if some optional mesh attributes
should be added. The second uses parallel loops over all elements,
copying attribute values and building the Mesh topology.

Both steps process different domains in separate threads (though the
first has to combine faces and loops). Though this isn't proper data
parallelism, it's quite helpful because each domain doesn't affect the
others.

**Timings**
I tested this on a Ryzen 7950x with a 1 million face grid, with no
extra attributes and then with several color attributes and vertex
groups.

| File | Before | After |
| Simple | 101.6 ms | 59.6 ms |
| More Attributes | 149.2 ms | 65.6 ms |

The optimization scales better with more attributes on the BMesh. The
speedup isn't as linear as multithreading other operations, indicating
added overhead. I think this is worth it though, because the user is
usually actively interacting with a mesh in edit mode.

See the differential revision for more timing information.

Differential Revision: https://developer.blender.org/D16249
d204830107 UI: Make uiBut safe for non-trivial construction
No user-visible changes expected.

Essentially, this makes it possible to use C++ types like `std::function`
inside `uiBut`. This has plenty of benefits, for example this should help
significantly reducing unsafe `void *` use (since a `std::function` can hold
arbitrary data while preserving types).

----

I wanted to use a non-trivially-constructible C++ type (`std::function`) inside
`uiBut`. But this would mean we can't use `MEM_cnew()` like allocation anymore.

Rather than writing worse code, allow non-trivial construction for `uiBut`.
Member-initializing all members is annoying since there are so many, but rather
safe than sorry. As we use more C++ types (e.g. convert callbacks to use
`std::function`), this should become less since they initialize properly on
default construction.

Also use proper C++ inheritance for `uiBut` subtypes, the old way to allocate
based on size isn't working anymore.

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

Reviewed by: Hans Goudey
fcc1166821 GPU: Disable verbose GLSL variable names in debug builds
GpuInput::node can be deallocated in some cases. (See T104265)
This is a temp workaround until a proper solution is implemented.
dc79281223 Nodes: Add modal keymap for Node link drag
This will add a proper modal keymap for the node link drag operator.
It allows the user to customize the keys used to start drag and so on.
Also it gets rid of the custom status bar message.

Differential Revision: https://developer.blender.org/D17190
7f958217ad Curves: Use shared caches for evaluated data
Use the `SharedCache` concept introduced in D16204 to share lazily
calculated evaluated data between original and multiple evaluated
curves data-blocks. Combined with D14139, this should basically remove
most costs associated with copying large curves data-blocks (though
they add slightly higher constant overhead). The caches should
interact well with undo steps, limiting recalculations on undo/redo.

Options for avoiding the new overhead associated with the shared
caches are described in T104327 and can be addressed separately.

Simple situations affected by this change are using any of the following data
on an evaluated curves data-block without first invalidating it:
- Evaluated offsets (size of evaluated curves)
- Evaluated positions
- Evaluated tangents
- Evaluated normals
- Evaluated lengths (spline parameter node)
- Internal Bezier and NURBS caches

In a test with 4m points and 170k curves, using curve normals in a
procedural setup that didn't change positions procedurally gave 5x
faster playback speeds. Avoiding recalculating the offsets on every
update saved about 3 ms for every sculpt update for brushes that don't
change topology.

Differential Revision: https://developer.blender.org/D17134
6590a288b0 Fix number sliders not working
Own mistake in d204830107.

For some buttons the type is changed after construction, which means the button
has to be reconstructed. For example number buttons can be turned into number
slider buttons this way. New code was unintentionally overriding the button
type after reconstruction with the old type again.
b454416927 Cycles: add non-uniform scaling to spot light size
Cycles ignores the size of spot lights, therefore the illuminated area doesn't match the gizmo. This patch resolves this discrepancy.
| Before (Cycles) | After (Cycles) | Eevee
|{F14200605}|{F14200595}|{F14200600}|
This is done by scaling the ray direction by the size of the cone. The implementation of `spot_light_attenuation()` in `spot.h` matches `spot_attenuation()` in `lights_lib.glsl`.
**Test file**:
{F14200728}

Differential Revision: https://developer.blender.org/D17129
0220bdc2d5 Cycles: Tests: Add option to increase SPP for manual comparisons
Useful for validating changes when sampling/noise changes:
- First run with BLENDER_TEST_UPDATE=1 and e.g. CYCLESTEST_SPP_MULTIPLIER=32
- Apply your change
- Run with only CYCLESTEST_SPP_MULTIPLIER=32
- Compare
- Reset the SVN repo

Differential Revision: https://developer.blender.org/D17107
73000c792d Cycles: Reorganize Fresnel handling in Microfacet closures
This is both a cleanup and a preparation for the Principled v2 changes.
Notable changes:
- Clearcoat weight is now folded into the closure weight, there's no reason
  to track this separately.
- There's a general-purpose helper for computing a Closure's albedo, which is
  currently used by the denoising albedo and diffuse/gloss/transmission color
  passes.
- The d/g/t color passes didn't account for closure albedo before, this means
  that e.g. metallic shaders with Principled v2 now have their color texture
  included in the glossy color pass. Also fixes T104041 (sheen albedo).
- Instead of precomputing and storing the albedo during shader setup, compute
  it when needed. This is technically redundant since we still need to compute
  it on shader setup to adjust the sample weight, but the operation is cheap
  enough that freeing up the storage seems worth it.
- Future changes (Principled v2) are easier to integrate since the Fresnel
  handling isn't all over the place anymore.
- Fresnel handling in the Multiscattering GGX code is still ugly, but since
  removing that entirely is the next step, putting effort into cleaning it up
  doesn't seem worth it.
- Apart from the d/g/t color passes, no changes to render results are expected.

Differential Revision: https://developer.blender.org/D17101
90f36fc50e Fix (unreported): snap to object origin not respecting clipping planes
There was an incorrect conversion for local clip planes although the
coordinates used are in world positions.
ab9c34e7e7 Fix T104316: Width of headerless panels on regions with overlap
In some cases panels without headers were drawn too wide in sidebars
with region overlap.

Instead of always using the maximum width the view allows, headerless
panels now also use the width calculated in
`panel_draw_width_from_max_width_get`. The function already returns the
correct width in all cases and also takes care of insetting the panels,
when their backdrop needs to be drawn, which is necessary for headerless
panels, too, when there is region overlap.

Reviewed By: Hans Goudey

Differential Revision: http://developer.blender.org/D17194
789e549dba Geometry Nodes: Tweak menu location of sample nodes
There was an inconsistency between geometry sample nodes and mesh/curve
sample nodes, where the latter didn't have a special "Sample" category,
and we categorized as "Operations", which they were not. Also put the
sample category between "Read" and "Write" since the verb name is
more consistent and sampling is an advanced form of reading.
06305e5ca8 Cleanup/refactor: split Edge and Vert Slide code into more specific functions
This makes the code more readable.

In this commit also the `int curr_side_unclamp` member was moved to
`EdgeSlideParams` as it is a common value for all "Containers".
62fc001979 Cleanup: silence warning
```
warning C4457: declaration of 'fac' hides function parameter
message : see declaration of 'fac'
```
1a13940ef8 Fix T88617: Wrong annotation cursor in Preview of sequencer editor
Allow preview region to change cursor as per the selected tool

Reviewed by: campbellbarton, ISS

Differential Revision: https://developer.blender.org/D16878
b2196ebe28 Win32: Relax Debug Assert in BLI_file_attributes
If GetFileAttributesW returns an error, only debug assert if the reason
is file not found.

See D17204 for more details.

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

Reviewed by Ray Molenkamp
d6cd7d1138 WM: correct the return flag from wm_handler_fileselect_do
In the unlikely case an area could not be created OPERATOR_CANCELLED
was returned, this has the same value of WM_HANDLER_HANDLED however
break is logical in this situation and both flags work.
3d6ceb737d Geometry Nodes: parallelize part of Duplicate Elements node
This implements two optimizations:
* If the duplication count is constant, the offsets array can be
  filled directly in parallel.
* Otherwise, extracting the counts from the virtual array is parallelized.
  But there is still a serial loop over all elements in the end to compute
  the offsets.
501352ef05 Cleanup: Move PBVH files to C++
For continued refactoring of the Mesh data structure. See T103343.
b642dc7bc7 Fix: Incorrect forward-compatible saving of face sets
There were two errors with the function used to convert face sets
to the legacy mesh format for keeping forward compatibility:
- It was moved before `CustomData_blend_write_prepare` so it
  operated on an empty span.
- It modified the mesh when it's only supposed to change the copy
  of the layers written to the file.

Differential Revision: https://developer.blender.org/D17210
d3949a4fdb Fix GHOST/Wayland thread-unsafe key-repeat timer checks
Resolve a thread safety issue reported by valgrind's helgrind checker,
although I wasn't able to redo the error in practice.

NULL check on the key-repeat timer also needs to lock, otherwise it's
possible the timer is set in another thread before the lock is acquired.

Now all key-repeat timer access which may run from a thread
locks the timer mutex before any checks or timer manipulation.
7de1a4d1d8 Fix GHOST/Wayland thread-unsafe timer-manager manipulation
Mutex locks for manipulating GHOST_System::m_timerManager from
GHOST_SystemWayland relied on WAYLAND being the only user of the
timer-manager.

This isn't the case as timers are fired from
`GHOST_System::dispatchEvents`.

Resolve by using a separate timer-manager for wayland key-repeat timers.
329eeacc66 Cleanup: Cycles: Remove isotropic microfacet closure setup functions
Turns out these are 100% redundant, so get rid of them.
6d297c35c8 Fix T104371: GPencil merge down layer duplicates wrong frame
The merge down operator was sometimes copying the wrong frame, which altered the animation.
While merging the layers, it is sometimes needed to duplicate a keyframe,
when the lowest layer does not have a keyframe but the highest layer does.
Instead of duplicating the previous keyframe of the lowest layer, the code
was actually duplicating the active frame of the layer which was the current frame in the timeline.

This patch fixes the issue by setting the previous keyframe of the layer as its active frame before duplication.

Related issue: T104371.

Differential Revision: https://developer.blender.org/D17214
0a3df611e7 Fix T103393: Cycles: Undefine __LIGHT_TREE__ on Metal/AMD to fix perf
This patch fixes T103393 by undefining `__LIGHT_TREE__` on Metal/AMD as it has an unexpected & major impact on performance even when light trees are not in use.

Patch authored by Prakash Kamliya.

Reviewed By: brecht

Maniphest Tasks: T103393

Differential Revision: https://developer.blender.org/D17167
be0912a402 Cycles: Prevent use of both AMD and Intel Metal devices at same time
This patch removes the option to select both AMD and Intel GPUs on system that have both. Currently both devices will be selected by default which results in crashes and other poorly understood behaviour. This patch adds precedence for using any discrete AMD GPU over an integrated Intel one. This can be overridden with CYCLES_METAL_FORCE_INTEL.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D17166
654e1e901b Cycles: Use local atomics for faster shader sorting (enabled on Metal)
This patch adds two new kernels: SORT_BUCKET_PASS and SORT_WRITE_PASS. These replace PREFIX_SUM and SORTED_PATHS_ARRAY on supported devices (currently implemented on Metal, but will be trivial to enable on the other backends). The new kernels exploit sort partitioning (see D15331) by sorting each partition separately using local atomics. This can give an overall render speedup of 2-3% depending on architecture. As before, we fall back to the original non-partitioned sorting when the shader count is "too high".

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D16909
7beb487e9a Fix T104353: Crash on opening sculpting template
`t->region` was `NULL`.

It can happen depending on the context.

Caused by rB19b63b932d2b.
4bd3b02984 Python: Suppress BGL deprecation messages after 100 times.
BGL deprecation calls used to be reported on each use. As bgl calls
are typically part of a handler that is triggered at refresh this
could lead to overflow of messages and slowing down systems when
the terminal/console had to be refreshed as well.

This patch only reports the first 100 bgl deprecation calls. This
gives enough feedback to the developer that changes needs to be made
. But still provides good responsiveness to users when they have
such add-on enabled. Only the first frames can have a slowdown.
f2538c7173 Fix T104335: MNEE + OptiX OSL results in illegal address error
The OptiX pipeline created for OSL was missing sufficient continuation
stack to handle the MNEE ray generation program.
deaddbdcff Fix forced snap status being removed when changing transform mode
The `SNAP_FORCED` setting is set to the operation and not the snap
status.

Therefore, this option should not be cleared along with the other
statuses when resetting snapping.

Move then the location of this setting to `TransInfo::modifiers`.
cc623ee7b0 Transform: do not save settings when canceling the operation
If we are canceling, the settings must remain the same as before we
start the operation.
8adebaeb7c Modifiers: measure execution time and provide Python access
The goal is to give technical artists the ability to optimize modifier usage
and/or geometry node groups for performance. In the long term, it
would be useful if Blender could provide its own UI to display profiling
information to users. However, right now, there are too many open
design questions making it infeasible to tackle this in the short term.

This commit uses a simpler approach: Instead of adding new ui for
profiling data, it exposes the execution-time of modifiers in the Python
API. This allows technical artists to access the information and to build
their own UI to display the relevant information. In the long term this
will hopefully also help us to integrate a native ui for this in Blender
by observing how users use this information.

Note: The execution time of a modifier highly depends on what other
things the CPU is doing at the same time. For example, in many more
complex files, many objects and therefore modifiers are evaluated at
the same time by multiple threads which makes the measurement
much less reliable. For best results, make sure that only one object
is evaluated at a time (e.g. by changing it in isolation) and that no
other process on the system keeps the CPU busy.

As shown below, the execution time has to be accessed on the
evaluated object, not the original object.

```lang=python
import bpy
depsgraph = bpy.context.view_layer.depsgraph
ob = bpy.context.active_object
ob_eval = ob.evaluated_get(depsgraph)
modifier_eval = ob_eval.modifiers[0]
print(modifier_eval.execution_time, "s")
```

Differential Revision: https://developer.blender.org/D17185
39e0bbfa55 BKE libquery: Add option to also process `ID.lib` pointer.
This was never needed before, but upcomming work for Brush Asset project
requires it.
9c14039a8f BLI ListBase: Add new 'SplitAfter' given link util.
Allows to easily split a ListBase by moving the part after given link
into a new ListBase.
81f8d74f6d EEVEE: Cleanup: light power / radiance code and document it
All thanks to @weizhen for spoting the inconsistencies.
c7b601c79e Cleanup: Subdiv: Use index instead of pointer
The edge pointer was retrieved from the index and then just
used to calculate the index again. Remove the edge pointer
and only use the index.
85b2bce037 BKE libremap: do not assert on identity pairs.
If identity pairs (i.e. old ID pointer being same as new one) was
forbidden, then this should be asserted against in code defining
remapping, not in code applying it.

But it is actually sometimes usefull to allow/use identity pairs, so
simply early-return on these instead of asserting.
288b13b252 BKE lib remapper: Add new util to overwrite an existing mapping.
Current `BKE_id_remapper_add` would not replace an already existing
mapping rule, now `BKE_id_remapper_add_overwrite` allows that behavior
if necessary.
a3551ed878 BKE main namemap: Add a way to clear all namemaps of a given Main.
Existing `BKE_main_namemap_destroy` is too specific when a entire Main
needs to have its namemaps cleared, since it would not handle the
Library ones.

While in regular situation current code is fine, ID management code that
may also edit linked data needs a wider, simpler clearing tool.
430cc9d7bf Fix T104381: Assert on Circle Select end modal
`em_setup_vivewcontext` cannot be used in this function now as it
expects `obedit` to be a mesh. It also duplicated the viewcontext init.
Instead `BKE_editmesh_from_object` is called only when type is a mesh.
2d994de77c Cycles: MetalRT optimisation for subsurface intersection queries
This patch optimises subsurface intersection queries on MetalRT. Currently intersect_local traverses from the scene root, retrospectively discarding all non-local hits. Using a lookup of bottom level acceleration structures, we can explicitly query only the relevant instance. On M1 Max, with MetalRT selected, this can give a render speedup of 15-20% for scenes like Monster which make heavy use of subsurface scattering.

Patch authored by Marco Giordano.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D17153
75db4c082b Cleanup: Use BitVector instead of BLI_bitmap for subsurf face dot tags
For better type safety and more automatic memory management.
a38d99e0b2 Fix (unreported): Transform gizmo not restoring when changing mode
When activating a rotation with the Transform gizmo for example, some
gizmos are hidden but they don't reappear when changing the mode.

Make sure the gizmos corresponding to the mode always reappear.
d20f992322 Mesh: Avoid copying positions in object mode modifier stack
Remove the use of a separate contiguous positions array now that
they are stored that way in the first place. This allows removing the
complexity of tracking whether it is allocated and deformed in the
mesh modifier stack.

Instead of deferring the creation of the final mesh until after the
positions have been copied and deformed, create the final mesh
first and then deform its positions.

Since vertex and face normals are calculated lazily, we can rely on
individual modifiers to calculate them as necessary and simplify
the modifier stack. This was hard to change before because of the
separate array of deformed positions.

Differential Revision: https://developer.blender.org/D16971
8be3fcab7e Fix tests after recent commit.
`9c14039a8f4b5f` broke blenlib tests in release builds, due to how
`EXPECT_BLI_ASSERT` works (in release builds it just calls the given
function, so if that crashes then the test fails).

For now remove that check in the test.
b0b9e746fa BLI: Use BLI_math_matrix_type.hh instead of BLI_math_float4x4.hh
Straightforward port. I took the oportunity to remove some C vector
functions (ex: copy_v2_v2).

This makes some changes to DRWView to accomodate the alignement
requirements of the float4x4 type.
6dcfb6df9c Cycles: Abstract host memory fallback for GPU devices
Host memory fallback in CUDA and HIP devices is almost identical.
We remove duplicated code and create a shared generic version that
other devices (oneAPI) will be able to use.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D17173
d3500c482f Cleanup: Move DRW_pbvh.h header to C++
For continued refactoring of the Mesh data structure. See T103343.
f152159101 Metal: Guard advanced command buffer debugging behind OS version flag.
Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17181
8703db393b Metal: Ensure explicit return after discard to eliminate differences in behaviour between GPUs.
Discard is not always treated as an explicit return and flow control can continue for required derivative calculations. This behaviour is different in Metal vs OpenGL. Adding return after discards ensures consistency in expectation as behaviour is well-defined.

Authored by Apple: Michael Parkin-White

Ref T96261

Reviewed By: fclem

Maniphest Tasks: T96261

Differential Revision: https://developer.blender.org/D17199
af5706c960 Docs: improve doc-string for WM_operator_flag_only_pass_through_on_press
The doc-string didn't provide any context for how the funciton is
intended to be used.
e27c89c7c7 Docs: added missing documentation for `WindowManager` methods
Added missing documentation for `draw_cursor_add` and
`draw_cursor_remove` methods for `WindowManager`.

Differential Revision: https://developer.blender.org/D14860
dbca0cc9d5 Fix crash on exit under Wayland
Order of free error from [0] caused the timer manager
to be freed before the timer.

[0]: 7de1a4d1d8
622cad7073 Cleanup: minor tweak to recent fix for T10438
Minor change to [0], prefer calling em_setup_viewcontext,
even though there is no functional difference at the moment,
if this function ever performs additional operations than assigning
`ViewContext.em`, it would have to be manually in-lined in
`view3d_circle_select_recalc`.

[0]: 430cc9d7bf
7e8153b07d Keymap: support default shortcut to toggle overlays in all space-types
UV Editor, Image Editor & Sequencer didn't have a shortcut for toggling
overlays. Use the same shortcut as the 3D viewport.

Ref D16959
2609ca2b8e Cleanup: tweaks to cycles/metal preferences
- Auto-format.
- Use raw string for regex.
- Remove redundant assignment.
- Remove duplicate arm64 check.
- Break early out of loop.
buildbot/vdev-code-daily-coordinator Build done. Details
349350b304
Fix T104390: Regression: Object selection in viewport is not working
Caused by alignment difference between C and C++. Asan caught the issue
on startup.

Removing the unused view matrix storage copy avoids this problem.
buildbot/vdev-code-daily-coordinator Build done. Details
8d9d16fb53
Fix #104396: Blender crashes when moving Keyframes in Graph Editor
`t->region->gizmo_map` can be `nullptr`.

Caused by 19b63b932d
buildbot/vdev-code-daily-coordinator Build done. Details
f01bf82480
Curves: Add select pick operator
This adds the `select_pick` function for to `Curves` objects.
It is used in the common `view3d_select` operator.

Pull Request #104406
buildbot/vdev-code-daily-coordinator Build done. Details
f5552d759c
Fix compiler error
buildbot/vdev-code-daily-coordinator Build done. Details
41ddd3d732
Fix: Experimental Panel links modified for Gitea
Modifies the links to point to the new developer site.

Pull Request #104425
buildbot/vdev-code-daily-coordinator Build done. Details
e817cff009
Release: support generating LTS release notes from Gitea
Now a single script to generate both links and release notes. It also includes
the issue ID for the LTS releases, so only the release version needs to be
specified.

Pull Request #104402
53b057aa09 Cleanup: Move 18 sculpt files to C++
To allow further mesh data structure refactoring. See #103343

Pull Request #104436
buildbot/vdev-code-daily-coordinator Build done. Details
5c994d7846
Fix #104297: Cycling geometry nodes viewer ignores sockets
Sockets after the geometry socket were ignored when cycling through
the node's output sockets. If there are multiple geometry sockets, the
behavior could still be refined probably, but this should at least make
basic non-geometry socket cycling work.
buildbot/vdev-code-daily-coordinator Build done. Details
6aa1b5d031
Cleanup: format
09eb4fe19a Fix #103913: Triangulate sometimes creates degenerate triangles
The ear clipping method used by polyfill_2d only excluded concave ears
which meant ears exactly co-linear edges created zero area triangles
even when convex ears are available.

While polyfill_2d prioritizes performance over *pretty* results,
there is no need to pick degenerate triangles with other candidates
are available. As noted in code-comments, callers that require higher
quality tessellation should use BLI_polyfill_beautify.
buildbot/vdev-code-daily-coordinator Build done. Details
4d3bfb3f41
Subdivision Surface: fix a serious performance hit when mixing CPU & GPU.
Subdivision surface efficiency relies on caching pre-computed topology
data for evaluation between frames. However, while eed45d2a23
introduced a second GPU subdiv evaluator type, it still only kept
one slot for caching this runtime data per mesh.

The result is that if the mesh is also needed on CPU, for instance
due to a modifier on a different object (e.g. shrinkwrap), the two
evaluators are used at the same time and fight over the single slot.
This causes the topology data to be discarded and recomputed twice
per frame.

Since avoiding duplicate evaluation is a complex task, this fix
simply adds a second separate cache slot for the GPU data, so that
the cost is simply running subdivision twice, not recomputing topology
twice.

To help diagnostics, I also add a message to show when GPU evaluation
is actually used to the modifier panel. Two frame counters are used
to suppress flicker in the UI panel.

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

Pull Request #104441
Sonny Campbell added 2 commits 2023-02-10 09:40:23 +01:00
96aa7ab367 T99807: Separate logic for changing working directory.
Set dir parameter to const for BLI_change_working_dir.
Added non-ASCII characters to the test directory.

Mac and Linux fixes. Linux now sets PWD when using BLI_change_working_dir. Mac uses NSFileManager through some new Mac-only wrapper functions.

Changed temporary directory to use a directory in the flags_test_asset_dir.
Ensure that operation to change working directory is from the main thread.
Author
Member

This patch also contains the changes from #104525 because it is dependent on the logic to change working directory.

I spoke to Dhruv about the last comment in https://archive.blender.org/developer/D15623 as I was unable to replicate the behaviour he was getting, so it is something we will investigate going forward.

This patch also contains the changes from https://projects.blender.org/blender/blender/pulls/104525 because it is dependent on the logic to change working directory. I spoke to Dhruv about the last comment in https://archive.blender.org/developer/D15623 as I was unable to replicate the behaviour he was getting, so it is something we will investigate going forward.
Bastien Montagne added this to the USD project 2023-02-10 11:09:45 +01:00
Sybren A. Stüvel requested changes 2023-02-13 12:29:49 +01:00
Sybren A. Stüvel left a comment
Member

Nice work, just some minor nags.

Nice work, just some minor nags.
@ -49,0 +51,4 @@
const char *export_filepath() const
{
if (strlen(usdz_filepath) > 0) {

No need to count all the characters when all you want to know is "empty or not". Use either usdz_filepath[0] or BLI_strnlen(usdz_filepath, 1) > 0.

No need to count all the characters when all you want to know is "empty or not". Use either `usdz_filepath[0]` or `BLI_strnlen(usdz_filepath, 1) > 0`.

This is utterly incorrect, usdz_filepath is always true by definition... you want to check usdz_filepath[0] != '\0' here...

But that whole function can simply be return usdz_filepath[0] != '\0';

This is utterly incorrect, `usdz_filepath` is always `true` by definition... you want to check `usdz_filepath[0] != '\0'` here... But that whole function can simply be `return usdz_filepath[0] != '\0';`
Author
Member

I think the null terminator always evaluates to false.

So if you have an empty string with usdz_filepath[0] = '\0' then if(usdz_filepath[0]) will evaluate to false.

The check for if(usdz_filepath) is to make sure that the usdz_filepath has been initialised.

I think the null terminator always evaluates to false. So if you have an empty string with `usdz_filepath[0] = '\0'` then `if(usdz_filepath[0])` will evaluate to false. The check for `if(usdz_filepath)` is to make sure that the `usdz_filepath` has been initialised.
Author
Member

Though maybe your way is more explicit and there's less possibility for confusion?

Though maybe your way is more explicit and there's less possibility for confusion?
Author
Member

Though yeah I just did a check and it looks like the if(usdz_filepath) is unnecessary so I'll remove it.

Though yeah I just did a check and it looks like the `if(usdz_filepath)` is unnecessary so I'll remove it.
@ -59,0 +90,4 @@
pxr::UsdUtilsCreateNewUsdzPackage(pxr::SdfAssetPath(usdc_file), usdz_file);
BLI_change_working_dir(original_working_dir);
char usdz_temp_dirfile[FILE_MAX];

What is a dirfile? I think a term like "full path" would be better than "dirfile".

What is a dirfile? I think a term like "full path" would be better than "dirfile".
SonnyCampbell_Unity marked this conversation as resolved
@ -59,0 +102,4 @@
return false;
}
}
result = BLI_rename(usdz_temp_dirfile, data->usdz_filepath);

Is it guaranteed that the temp "dirfile" is on the same filesystem as usdz_filepath? Have you tested with them being on different filesystems?

Is it guaranteed that the temp "dirfile" is on the same filesystem as `usdz_filepath`? Have you tested with them being on different filesystems?
SonnyCampbell_Unity marked this conversation as resolved
@ -159,19 +218,50 @@ static void export_startjob(void *customdata,
BKE_scene_graph_update_for_newframe(data->depsgraph);
}
if (strlen(data->usdz_filepath) > 0) {

Same as above about counting all the characters.

Now that this logic is used here as well, I actually think that this shows this code is sitting at the wrong abstraction level. What is being queried here is "should this output USD or USDZ?", and the fact that that distinction is made by whether usdz_filepath is empty or not is an implementation detail.

Something like bool ExportJobData::targets_usdz() { return usdz_filepath[0]; } would solve both problems.

Same as above about counting all the characters. Now that this logic is used here as well, I actually think that this shows this code is sitting at the wrong abstraction level. What is being queried here is "should this output USD or USDZ?", and the fact that that distinction is made by whether `usdz_filepath` is empty or not is an implementation detail. Something like `bool ExportJobData::targets_usdz() { return usdz_filepath[0]; }` would solve both problems.
SonnyCampbell_Unity marked this conversation as resolved
@ -160,2 +219,4 @@
}
if (strlen(data->usdz_filepath) > 0) {
if (!perform_usdz_conversion(data)) {

This could just be an && in the same if.

This could just be an `&&` in the same `if`.
Author
Member

As a personal preference I prefer to have functions that actually do logic outside of if() conditions as I find it can be quite easy to miss, so I've moved it to the line above and stored the result in a variable that gets checked.

I can do it like you suggest if you wish, but I find it much more readable this way.

As a personal preference I prefer to have functions that actually do logic outside of `if()` conditions as I find it can be quite easy to miss, so I've moved it to the line above and stored the result in a variable that gets checked. I can do it like you suggest if you wish, but I find it much more readable this way.
@ -166,1 +234,4 @@
static void export_endjob_usdz_cleanup(const ExportJobData *data)
{
if (!BLI_exists(data->unarchived_filepath)) {

Why should this not clean up anything if unarchived_filepath is missing? Wouldn't it be prudent to always erase usdc_temp_dir?

Why should this not clean up anything if `unarchived_filepath` is missing? Wouldn't it be prudent to always erase `usdc_temp_dir`?
Author
Member

usdc_temp_dir is the directory that contains data->unarchived_filepath, so if there is no data->unarchived_filepath there shouldn't be anything to delete.

This is basically so that we don't try to delete anything when there shouldn't be anything there to delete in the first place.

`usdc_temp_dir` is the directory that contains `data->unarchived_filepath`, so if there is no `data->unarchived_filepath` there shouldn't be anything to delete. This is basically so that we don't try to delete anything when there shouldn't be anything there to delete in the first place.
@ -185,1 +275,4 @@
/* To create a usdz file, we must first create a .usd/a/c file and then covert it to .usdz. The
* temporary files will be created in Blender's temporary session storage. The .usdz file will then
* copied to job->usdz_filepath. */

This is not what the code above is doing -- it's moving, not copying.

This is not what the code above is doing -- it's moving, not copying.
SonnyCampbell_Unity marked this conversation as resolved
@ -186,0 +292,4 @@
MEM_freeN(usdc_file);
}
static void set_job_filepath(const char *filepath, blender::io::usd::ExportJobData *job)

Most setters have the parameter order to mimick thing = value, so are in the form setter(thing, value). Swap the two parameters here.

Most setters have the parameter order to mimick `thing = value`, so are in the form `setter(thing, value)`. Swap the two parameters here.
SonnyCampbell_Unity marked this conversation as resolved
@ -0,0 +62,4 @@
BKE_tempdir_init(temp_dir);
const std::string &test_assets_dir = blender::tests::flags_test_asset_dir();
BLI_path_join(output_filename, FILE_MAX, test_assets_dir.c_str(), "usd/output_новый.usdz");

👍 for testing with unicode characters.

Using the assets dir is not that great, though -- same as in #104525. Since this code already uses BKE_tempdir_init(), you can use BKE_tempdir_base(); and std::tmpnam() to generate a name that's guaranteed to be unique.

:+1: for testing with unicode characters. Using the assets dir is not that great, though -- same as in #104525. Since this code already uses `BKE_tempdir_init()`, you can use `BKE_tempdir_base();` and `std::tmpnam()` to generate a name that's guaranteed to be unique.
SonnyCampbell_Unity marked this conversation as resolved
@ -0,0 +73,4 @@
if (BLI_exists(output_filename)) {
BLI_delete(output_filename, false, false);
BLI_delete(temp_dir, true, true);

Why not always delete temp_dir, regardless of whether output_filenaem exists or not?

Why not always delete `temp_dir`, regardless of whether `output_filenaem` exists or not?
SonnyCampbell_Unity marked this conversation as resolved
@ -0,0 +86,4 @@
}
/* File sanity check. */
EXPECT_EQ(BLI_listbase_count(&bfile->main->objects), 4);

Use ASSERT_EQ for such checks. That will stop the test from continuing when it fails.

Use `ASSERT_EQ` for such checks. That will stop the test from continuing when it fails.
SonnyCampbell_Unity marked this conversation as resolved
@ -0,0 +91,4 @@
USDExportParams params{};
bool result = USD_export(context, output_filename, &params, false);
EXPECT_TRUE(result);

Add some logging to this and the following EXPECT calls. When the test fails, it should be clear why it failed. You can do something like:

EXPECT_TRUE(result) << "USD export to " << output_filename << " failed";

If this particular test fails, the rest of the test is useless (it will all fail), so this one can be replaced with ASSERT_TRUE.

Add some logging to this and the following EXPECT calls. When the test fails, it should be clear why it failed. You can do something like: ```cpp EXPECT_TRUE(result) << "USD export to " << output_filename << " failed"; ``` If this particular test fails, the rest of the test is useless (it will all fail), so this one can be replaced with `ASSERT_TRUE`.
SonnyCampbell_Unity marked this conversation as resolved
Sybren A. Stüvel requested changes 2023-02-13 12:29:55 +01:00
Sybren A. Stüvel left a comment
Member

Nice work, just some minor nags.

Nice work, just some minor nags.
Sonny Campbell added 2 commits 2023-02-22 10:48:09 +01:00
14d9b8aa8d Merge branch 'main' into unity/T99807-usdz-refactor
# Conflicts:
#	source/blender/blenlib/BLI_fileops.h
#	source/blender/blenlib/intern/storage.c
#	source/blender/blenlib/intern/storage_apple.mm
#	source/blender/blenlib/tests/BLI_fileops_test.cc
d95e3b3990 Added logs to error fail cases.
Replaced use of `flags_test_assets_dir` with `BKE_tempdir_case()`.
Use `BLI_path_move` to handle moving file across filesystems where `BLI_rename` would fail.
Sonny Campbell added 1 commit 2023-02-22 11:01:12 +01:00
buildbot/vexp-code-patch-coordinator Build done. Details
818a360f24
Merge branch 'main' into unity/T99807-usdz-refactor
Sonny Campbell requested review from Sybren A. Stüvel 2023-02-22 11:02:51 +01:00
Sonny Campbell added the
Module
Core
Interest
Pipeline, Assets & IO
Interest
USD
labels 2023-02-24 10:13:05 +01:00

@blender-bot build

@blender-bot build

@blender-bot build

@blender-bot build
Bastien Montagne approved these changes 2023-02-24 16:22:28 +01:00
Bastien Montagne left a comment
Owner

Issues noted below are fairly bad (as in, obvious mistakes and potential source of bugs), would be good to check at compiler warnings when building...

Hopefully these are the only serious ones, will fix them (since it's trivial) as part of the commit.

For the rest tests are passing and feature looks good, so time to finalize this patch.

Issues noted below are fairly bad (as in, obvious mistakes and potential source of bugs), would be good to check at compiler warnings when building... Hopefully these are the only serious ones, will fix them (since it's trivial) as part of the commit. For the rest tests are passing and feature looks good, so time to finalize this patch.
@ -59,0 +93,4 @@
BLI_split_file_part(data->usdz_filepath, usdz_file, FILE_MAX);
char original_working_dir[FILE_MAX];
BLI_current_working_dir(original_working_dir, FILE_MAX);

This line and the one above are not properly using the API, which expect you to use the returned char pointer.

char original_working_dir_buff[FILE_MAX];
char *original_working_dir = BLI_current_working_dir(original_working_dir_buff, sizeof(original_working_dir_buff));
This line and the one above are not properly using the API, which expect you to use the returned char pointer. ``` char original_working_dir_buff[FILE_MAX]; char *original_working_dir = BLI_current_working_dir(original_working_dir_buff, sizeof(original_working_dir_buff)); ```
@ -0,0 +56,4 @@
}
char original_wd[FILE_MAX];
BLI_current_working_dir(original_wd, FILE_MAX);

Same issue as noted above regarding not using return value from BLI_current_working_dir().

Same issue as noted above regarding not using return value from `BLI_current_working_dir()`.
Author
Member

Realised the usdz_export_test.blend test blend file hasn't been uploaded yet.

Realised the `usdz_export_test.blend` test blend file hasn't been uploaded yet.

Committed as 54f672cbfa from PR #105185.

Committed as 54f672cbfa from PR #105185.
Bastien Montagne closed this pull request 2023-02-26 16:39:21 +01:00
Bastien Montagne removed this from the USD project 2023-02-27 18:23:58 +01:00
Some checks failed
buildbot/vexp-code-patch-coordinator Build done.

Pull request closed

Sign in to join this conversation.
No Label
Interest
Alembic
Interest
Animation & Rigging
Interest
Asset Browser
Interest
Asset Browser Project Overview
Interest
Audio
Interest
Automated Testing
Interest
Blender Asset Bundle
Interest
BlendFile
Interest
Collada
Interest
Compatibility
Interest
Compositing
Interest
Core
Interest
Cycles
Interest
Dependency Graph
Interest
Development Management
Interest
EEVEE
Interest
EEVEE & Viewport
Interest
Freestyle
Interest
Geometry Nodes
Interest
Grease Pencil
Interest
ID Management
Interest
Images & Movies
Interest
Import Export
Interest
Line Art
Interest
Masking
Interest
Metal
Interest
Modeling
Interest
Modifiers
Interest
Motion Tracking
Interest
Nodes & Physics
Interest
OpenGL
Interest
Overlay
Interest
Overrides
Interest
Performance
Interest
Physics
Interest
Pipeline, Assets & IO
Interest
Platforms, Builds & Tests
Interest
Python API
Interest
Render & Cycles
Interest
Render Pipeline
Interest
Sculpt, Paint & Texture
Interest
Text Editor
Interest
Translations
Interest
Triaging
Interest
Undo
Interest
USD
Interest
User Interface
Interest
UV Editing
Interest
VFX & Video
Interest
Video Sequencer
Interest
Virtual Reality
Interest
Vulkan
Interest
Wayland
Interest
Workbench
Interest: X11
Legacy
Blender 2.8 Project
Legacy
Milestone 1: Basic, Local Asset Browser
Legacy
OpenGL Error
Meta
Good First Issue
Meta
Papercut
Meta
Retrospective
Meta
Security
Module
Animation & Rigging
Module
Core
Module
Development Management
Module
EEVEE & Viewport
Module
Grease Pencil
Module
Modeling
Module
Nodes & Physics
Module
Pipeline, Assets & IO
Module
Platforms, Builds & Tests
Module
Python API
Module
Render & Cycles
Module
Sculpt, Paint & Texture
Module
Triaging
Module
User Interface
Module
VFX & Video
Platform
FreeBSD
Platform
Linux
Platform
macOS
Platform
Windows
Priority
High
Priority
Low
Priority
Normal
Priority
Unbreak Now!
Status
Archived
Status
Confirmed
Status
Duplicate
Status
Needs Info from Developers
Status
Needs Information from User
Status
Needs Triage
Status
Resolved
Type
Bug
Type
Design
Type
Known Issue
Type
Patch
Type
Report
Type
To Do
No Milestone
No project
No Assignees
3 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: blender/blender#104556
No description provided.