Compare commits

...

723 Commits

Author SHA1 Message Date
JIANG Kairong
5829a04a17 fix a minor bug when compiling 2016-06-26 20:16:18 +08:00
JIANG Kairong
54f537f5e0 add support for transformed objects 2016-06-26 18:46:53 +08:00
JIANG Kairong
0b9a72a0dc first working version of silhouette brush tool 2016-06-26 11:53:57 +08:00
JIANG Kairong
1ea040281f first attempts to add silhouette brush 2016-06-19 04:39:49 +08:00
bff095184a Cleanup: Don't use f suffix for values in GLSL
Was giving an issues in the past, will avoid it for now.
2016-05-20 18:14:04 +02:00
c6ea288bcf Support voronoi texture in GLSL shading
It gives some slight differences on the plane corners, but can't
really figure out source of the issue here yet.

It's still better than fully white texture for the previews anyway.

At this point we should perhaps ifdef chunks of the code in order
to have faster GLSL compilation and probably even faster compiled
code. Will look into this shortly.
2016-05-20 18:05:29 +02:00
ca8419ed6e Support Cycles magic texture in GLSL viewport 2016-05-20 16:58:56 +02:00
a5a05fc291 Cycles: Fix long compile time with MSVC.
Compile time per kernel increased alot after recent image commits, re-shuffle some code to fix this.

Patch by "LazyDodo".

Differential Revision: https://developer.blender.org/D2012
2016-05-20 16:50:29 +02:00
7ab55d8947 Support gradient Cycles texture in GLSL viewport 2016-05-20 16:39:45 +02:00
b79214bbc5 Support Cycles brick texture in GLSL viewport 2016-05-20 16:13:44 +02:00
0405bbeae2 Support Cycles's checker texture in GLSL shading 2016-05-20 15:18:40 +02:00
9d19533117 Fix T48472: issue in array refactor, causing performance regression in BVH build. 2016-05-20 10:58:11 +02:00
6e416b6bdf Fix T48470: Bendy Bones: Custom Handle References not being cleared when bone deleted
In addition to the original bug report, I've gone through cleaning up a range of
related bugs which only became clear when hunting around the code...

* Custom Handle References weren't getting cleared when the bones they used got
  deleted.  But, neither was the custom bone shape location/transform reference.

* Various places where posebone settings are copied around were also missing code
  to handle the new Bendy Bone properties.

  (WHY DO WE HAVE SO MANY VARIATIONS OF COPYING POSE DATA!?!?)

* If duplicating a Bendy Bone with custom references, and the custom references
  are also selected/duplicated, the new Bendy Bones will use the corresponding
  duplicated bones
2016-05-20 19:09:27 +12:00
75a31c3670 Add Peak Memory as render stamp option
This commit adds Peak Memory to the stamp options, the value is the same one that is already shown in the image viewer.

Requested by @nutel.

Reviewers: campbellbarton

Subscribers: campbellbarton, nutel

Differential Revision: https://developer.blender.org/D1989
2016-05-19 22:57:38 +02:00
ad14c471eb Cycles: Add XML parsing of MappingNodes to Cycles Standalone
Reviewers: dingto, sergey

Differential Revision: https://developer.blender.org/D2009
2016-05-19 21:28:57 +02:00
01e86b2c7d Cleanup: warnings 2016-05-20 05:14:17 +10:00
38f65c500c Fix T48204: Generic Tablet on Linux - Erratic strokes with pressure sensitivity enabled.
Once and for all - I hope!

So, for the records: Xinput1 events' valuators have a first_axis and axis_count defining the 'range'
of valid axes for that event - but valid data in the valuator's array **always** start at zero
(which means that, if event reports first axis as being axis 2, axis 2's value is in axis_data[0]).
2016-05-19 20:30:48 +02:00
dedc995018 Cycles / CUDA: Don't use bundled kernel if Adaptive is enforced by the user. 2016-05-19 16:32:57 +02:00
c5893db5cc Cleanup: misleading indentation 2016-05-19 23:37:23 +10:00
a4a968fd99 Dynapaint: parallelize drip effect.
Was not so far, because this effect is not modifying its 'own' PaintPoint, which means
it's not threadsafe. Since a global lock (mutex or spinlock) would not be much efficient
(we need to lock a given point pretty much all the computaion cycle), and since locking
a same PaintPOint from different threads at the same time is *very* unlikely,
solution here is to use an 'array of locks', one for each PaintPoint (same thing as BLI_bitmap,
using atomic ops to set/clear bits).

Here in own test (complex dynapaint over a huge sphere combining all dynapaint types), it gives
20% speedup of the whole dynapaint simulation!

Note: maybe we'd want to move that kind of bitlock into BLI lib some day - not totally sure how,
so let's keep it local for now...
2016-05-19 14:44:37 +02:00
4b810127ba Dynapaint: fix use of normal normalization in dynamicPaint_generateBakeData().
Vertex's normal is always normalized - and its conversion from short to float should not change that!
On the other hand, linear interpolation of three normals **does not give a normalized vector**
(unless all three inputs are exactly the same).

Also, minor optimization, avoid recomputing that interpolated normal twice for each PaintUVPoint.
2016-05-19 14:44:37 +02:00
c9f1ed1e4c Cycles: Add support for bindless textures.
This adds support for CUDA Texture objects (also known as Bindless textures) for Kepler GPUs (Geforce 6xx and above).
This is used for all 2D/3D textures, data still uses arrays as before.

User benefits:
* No more limits of image textures on Kepler.
 We had 5 float4 and 145 byte4 slots there before, now we have 1024 float4 and 1024 byte4.
 This can be extended further if we need to (just change the define).

* Single channel textures slots (byte and float) are now supported on Kepler as well (1024 slots for each type).

ToDo / Issues:
* 3D textures don't work yet, at least don't show up during render. I have no idea whats wrong yet.
* Dynamically allocate bindless_mapping array?

I hope Fermi still works fine, but that should be tested on a Fermi card before pushing to master.

Part of my GSoC 2016.

Reviewers: sergey, #cycles, brecht

Subscribers: swerner, jtheninja, brecht, sergey

Differential Revision: https://developer.blender.org/D1999
2016-05-19 13:14:37 +02:00
03f846ea12 Ignore vertex color when doing texture paint
It was totally useless to multiply diffuse color with the vertex color
when doing texture painting. It was masking actual texture and only was
forcing artists to create an empty vertex color layer to work this around.
2016-05-19 11:11:21 +02:00
89df6720be CMake: use signed char for recastnavigation
External libraries may need char to be signed.
2016-05-19 07:36:32 +10:00
20678138f7 Cleanup: CMake indentation
Also remove outdated comment
2016-05-19 07:12:14 +10:00
6988061bf1 Cuda wrangler: Fix very nasty bug with multiple scalar type qualifiers 2016-05-18 18:01:37 +02:00
3289f174ee Fix missing modifiers for mesh objects
All modifiers for all non-lattice objects were disabled after recent commit.
2016-05-18 17:36:52 +02:00
e34e5ce332 Theme Color Sets - Dynamically generated icons
The theme color set selector (for Bone Groups) will now show previews of
what each color set looks like. It does so using a 3-color band icon.
2016-05-19 03:25:38 +12:00
f74c7fcca2 Fix T47727: Weird bake results with non integer color values 2016-05-18 15:11:05 +02:00
7a8bd2eaea Fix T47737: Lattice crashes w/ smooth modifier
Add flag for modifiers that support lattice
2016-05-18 22:46:29 +10:00
cade8e25c6 Revert string splitting
Caused error on OSX
2016-05-18 22:05:53 +10:00
1283c66146 Revert part of 4adffde02c to get Windows (MSVC2013) compiling again 2016-05-18 23:42:53 +12:00
41a6829021 Depsgraph: Fix rest pose still using bone constraints 2016-05-18 11:38:52 +02:00
792e147e2c Cycles: Fix compilation error of CUDA kernels after recent volume commit
Apparently the code path with malloc() was enabled for CUDA.
2016-05-18 11:15:28 +02:00
cbe7f9dd03 Cycles: Pole merging for spherical stereo
The idea of pole merge is to fade interocular distance after a certain
altitude to zero when altitude goes closer to a pole. This should prevent
annoyances looking up in the sky or down to the bottom.

Works for both panorama and perspective cameras when Spherical Stereo
is enabled.

Reviewers: dfelinto, brecht

Reviewed By: brecht

Subscribers: sebastian_k

Differential Revision: https://developer.blender.org/D1998
2016-05-18 10:56:57 +02:00
7b356a8565 Cycles: Reduce amount of malloc() calls from the kernel
This commit makes it so malloc() is only happening once per volume and
once per transparent shadow query (per thread), improving scalability of
the code to multiple CPU cores.

Hard to measure this with a low-bottom i7 here currently, but from quick
tests seems volume sampling gave about 3-5% speedup.

The idea is to store allocated memory in kernel globals, which are per
thread on CPU already.

Reviewers: dingto, juicyfruit, lukasstockner97, maiself, brecht

Reviewed By: brecht

Subscribers: Blendify, nutel

Differential Revision: https://developer.blender.org/D1996
2016-05-18 10:14:24 +02:00
2433a537fa Cycles: Explicitly mark arguments as unused 2016-05-18 09:12:47 +02:00
e3218ded41 Fix T48395: Grease Pencil, pressing Ekey to sculpt don't work for left click configurations
When using Left Click select, it wasn't possible to sculpt using E+LMB.

I've changed the order of things in the keymap so that the select operator won't
end up catching and blocking all these events.
2016-05-18 17:23:16 +12:00
1139e51be6 Fix: "Whole Character" Keying Set should not include Location on bones with "connected" joint 2016-05-18 16:29:18 +12:00
4adffde02c Cleanup: cmake, indentation, line length 2016-05-18 11:58:08 +10:00
6f29dbd045 Fix issue in with multiple importance sampling in recent code refactor. 2016-05-18 01:51:30 +02:00
9dc5367c89 Cleanup code style inconsistency in last commits. 2016-05-17 23:41:45 +02:00
2630207ada Fix GCC/Linux build error after finite/isfinite changes. 2016-05-17 23:40:25 +02:00
21fddf7d1c C99/C++11: replace deprecated finite() by isfinite(). 2016-05-17 21:39:16 +02:00
2b73402547 Fix C++11 build issues on OS X, remove references to outdated libs. 2016-05-17 21:39:16 +02:00
0e8cd14dfe Code refactor: use shader pointers rather than shader indexes. 2016-05-17 21:39:16 +02:00
08670d3b81 Code refactor: use dynamic shader node array lengths now that OSL supports them. 2016-05-17 21:39:16 +02:00
93e4ae84ad Code refactor: add some array utility methods, fix leak in assignment operator. 2016-05-17 21:39:16 +02:00
df8097ea2a Bendy Bones: Small ui tweak
Change the order of the bending controls ("Curve XY Offsets") so the user can activate both InX and OutX by holding down the left mouse button. This way, it's easy to bend symmetrically on X or Y.
2016-05-17 18:08:04 +02:00
6cf7cc3393 Fix T48434: Missing meta support in new depsgraph 2016-05-17 17:52:23 +02:00
49aeee5a3d Bendy Bones: Advanced B-Bones for Easier + Simple Rigging
This commit/patch/branch brings a bunch of powerful new options for B-Bones and
for working with B-Bones, making it easier for animators to create their own
rigs, using fewer bones (which also means hopefully lighter + faster rigs ;)
This functionality was first demoed by Daniel at BConf15

Some highlights from this patch include:
* You can now directly control the shape of B-Bones using a series of properties
  instead of being restricted to trying to indirectly control them through the
  neighbouring bones.  See the "Bendy Bones" panel...

* B-Bones can be shaped in EditMode to define a "curved rest pose" for the bone.
  This is useful for things like eyebrows and mouths/eyelids

* You can now make B-Bones use custom bones as their reference bone handles,
  instead of only using the parent/child bones. To do so, enable the
  "Use Custom Reference Handles" toggle. If none are specified, then the BBone will
  only use the Bendy Bone properties.

* Constraints Head/Tail option can now slide along the B-Bone shape, instead of
  just linearly interpolating between the endpoints of the bone.

For more details, see:
* http://aligorith.blogspot.co.nz/2016/05/bendy-bones-dev-update.html
* http://aligorith.blogspot.co.nz/2016/05/an-in-depth-look-at-how-b-bones-work.html



-- Credits --
Original Idea: Daniel M Lara (pepeland)
Original Patch/Research: Jose Molina
Additional Development + Polish: Joshua Leung (aligorith)
Testing/Feedback: Daniel M Lara (pepeland), Juan Pablo Bouza (jpbouza)
2016-05-18 03:19:06 +12:00
29a17d54da Fix CUDA MEMCPY condition, it should only copy 3D, 2D or 1D.
Found by Brecht, thanks!
2016-05-17 00:37:34 +02:00
99d861169f Cycles / Requested Features: Volume was missing in logging print. 2016-05-17 00:36:22 +02:00
b90cc984f7 Usual i18n/UI messgaes fixes... 2016-05-16 21:46:55 +02:00
886ff72301 Remove strict header, gives issues with gcc5x 2016-05-17 05:26:09 +10:00
0096bae8c4 Cleanup: use const args 2016-05-17 03:07:40 +10:00
42f8232046 CustomData: Support for >2gig layers 2016-05-17 03:02:55 +10:00
2b02e03973 Cleanup: simplify checks calculating tangents 2016-05-17 02:18:11 +10:00
688858d3a8 BLI_task: Add new 'BLI_task_parallel_range_finalize()'.
Together with the extended loop callback and userdata_chunk, this allows to perform
cumulative tasks (like aggregation) in a lockfree way using local userdata_chunk to store temp data,
and once all workers have finished, to merge those userdata_chunks in the finalize callback
(from calling thread, so no need to lock here either).

Note that this changes how userdata_chunk is handled (now fully from 'main' thread,
which means a given worker thread will always get the same userdata_chunk, without
being re-initialized anymore to init value at start of each iter chunk).
2016-05-16 17:15:18 +02:00
5a7429c363 BLI_task: Add back lost 'push_from_thread' change to BLI_task_parallel_range() & co. 2016-05-16 17:00:15 +02:00
19955bd152 Fix T48447: Inactive menu items don't grey-out icons 2016-05-17 00:17:26 +10:00
575d7a9666 BLI_task: make foreach loop index hleper lockfree, take II.
New code is actually much, much better than first version, using 'fetch_and_add' atomic op
here allows us to get rid of the loop etc.

The broken CAS issue remains on windows, to be investigated...
2016-05-16 15:57:19 +02:00
75a96f8325 Atomic ops: add 'fetch_and_add_uint32' op.
Needed for next commit.
2016-05-16 15:56:39 +02:00
460d944493 Cleanup rna_Brush_direction_itemf()
Some variants of gcc compilation were reporting 'control reaching end of non-void function' error
in this switch/case maze. Either use break everywhere or not at all (which is simpler, since we
only always return anyway...).
2016-05-16 15:54:18 +02:00
22d53e558d Cycles: Cleanup after recent refactor
Wrong indentation, wrong spacing.
2016-05-16 10:55:50 +02:00
f70b548630 Revert "Docs: smoke typo corrections"
This reverts commit b13bc48932.

Wasn't only typo fixes, broke compiling
2016-05-16 09:28:49 +10:00
b13bc48932 Docs: smoke typo corrections
patch by @Blendify
2016-05-16 07:52:56 +10:00
a1a640f614 Curve Fitting: correct circular tangent length calculation
Method for scaling is still not perfect but quite close.
2016-05-16 07:45:50 +10:00
bb7da630ba Fix T48422: Revert "BLI_task: nano-optimizations to BLI_task_parallel_range feature."
There are some serious issues under windows, causing deadlocks somehow (not reproducible under linux so far).

Until further investigation over why this happens, better to revert to previous
spin-locked behavior.

This reverts commits a83bc4f597 and 98123ae916.
2016-05-15 21:14:40 +02:00
23bdcfe560 BGE: Fix KX_LightObject python API documentation.
Replace "..attribute::" by ".. attribute::".
2016-05-15 14:56:40 +00:00
20714889bf Fix T48425: Armature Symmetrize is flipping Custom Shape parameter.
In case not all bones are selected, not all possible mirrors are set in editbone->temp.ebone,
so we need to search them...
2016-05-15 12:35:01 +02:00
a83bc4f597 Fix an error in new lockfree parallel_range_next_iter_get() helper.
Reading the shared state->iter value after storing it in the 'reference' var could in theory
lead to a race condition setting state->iter value above state->stop, which would be 'deadly'.

This **may** be the cause of T48422, though I was not able to reproduce that issue so far.
2016-05-14 18:06:05 +02:00
b9996a3cc3 Fix Cube generated UV's rotated incorrectly 2016-05-14 23:01:59 +10:00
b1e2f8be23 Fix T48426: Use same length for all header message strings.
Some languages like Chinese or Japanese take three or four bytes per char...

Also fixed some missing translation markers for UI header messages.
2016-05-14 10:00:52 +02:00
ede742917a Correct BM_iter_mesh_bitmap_from_filter return 2016-05-14 04:49:42 +10:00
eeca6372d0 Correct asserts 2016-05-14 04:05:18 +10:00
24e887cd93 Fix script_paths(check_all=True) missing script paths
BLENDER_SYSTEM_SCRIPTS wasn't included in bpy.utils.script_paths()
2016-05-14 03:27:35 +10:00
89c6b58ef5 Fix compilation with strict compiler flags
Some const qualifier was discarding.
2016-05-13 17:37:39 +02:00
8b92d728ae Fix T48421: AO pass broken, only works when AO in cycles is enabled 2016-05-13 17:33:40 +02:00
141c0f8ad1 Cleanup: rna naming, indentation 2016-05-14 01:33:27 +10:00
a91a49ba8e Fix T48416: Impossible to copy a linked object from a file to another one mantaining the linked library.
When writing temp blenbuffer file, libraries of linked datablocks where not tagged correctly, which
means they were not put in the temp Main used to write the buffer, resulting in implicit localization
of linked data.
2016-05-13 14:12:10 +02:00
5e0ec49570 Fix T48416: Impossible to append from another file without localizing also all indirectly linked data.
Previous to 2.77, this used to be default behavior, was changed in rB591f4549c958b.

However, in most append cases, you do want a full localization of your data, so this new behavior
is kept by default, but there is now an option in append operator to only localize the 'first level'
of data (i.e. datablocks from linked library itself, and not those from other 'sub-libraries').
2016-05-13 14:12:10 +02:00
6276726bc4 Fix T47652: Texture shading mode fails to update material colors 2016-05-13 22:16:14 +10:00
029ccca0fe Armature meshdeform evaluation: parallelize computation of bbones deform matrices.
On big and complex rigs like blendrig or koro, it can give up to ~10% more FPS in best cases.
Hard to tackle all cases in tests though, so please report any unexpected slowdown
in armature animation playback!
2016-05-13 12:06:15 +02:00
868cfc5a4a BLI_task: add support for listbase parallelized for loops.
Code by @sergey, with small edits and doc by @mont29.
2016-05-13 12:06:15 +02:00
990fab73ea Cleanup: fix inconsitency in dynamicPaint_outputLayerExists()
Dyna WPaint indeed only uses first output layer, but better be consistent in those cases...
2016-05-13 12:06:15 +02:00
d4b8aa476b Dynapaint: cleanup of BKE code.
Line lengths, monolined 'if' statements, int -> bool, etc.

Also, replaced some internal cooked stuff by BLI helpers (most notably, the
'is inside UV triangle' code in `dynamicPaint_createUVSurface()`), and some
other minor optimizations.
2016-05-13 12:06:15 +02:00
ba6519f0a7 BLI_math: add 'equals_m4m4' (and 'm3' variant) helpers. 2016-05-13 12:06:15 +02:00
0903ee6ce2 Cycles: Scale debug pass with number of samples
This way it's easier to compare different renders together without
worrying about scale too much.
2016-05-13 11:22:18 +02:00
958d613f66 Image editor: Show actual value of single-channel buffer in sample info
Previously if image only had single channel only z buffer value was displaying.
This isn't handy for cases when you've got single channel buffer which is not
a z buffer.

Also fixed possible read past the array.
2016-05-13 11:22:18 +02:00
b72aef92c4 install_deps: Avoid conflicts on Arch-based systems when gcc-multilib is installed
install_deps can fail due to conflict between gcc (referenced by base-devel) and
gcc-multilib if the latter is installed. This avoids the conflict by filtering
the contents of base-devel when needed.

Reviewers: mont29

Differential Revision: https://developer.blender.org/D1944
2016-05-12 18:17:14 -04:00
3c85e1ca1a Cycles: Add support for single channel byte textures.
This way, we also save 3/4th of memory for single channel byte textures (e.g. Bump Maps).

Note: In order for this to work, the texture *must* have 1 channel only.
In Gimp you can e.g. do that via the menu: Image -> Mode -> Grayscale
2016-05-12 14:51:42 +02:00
cde10e774c Fix array bounds compile warning. 2016-05-12 14:20:12 +02:00
86b509229f Fix T48413: editmesh intersect tool crash
Its important to add tri-edge intersections from both sides.
2016-05-12 21:00:08 +10:00
8d3f367c01 Correct debug prints 2016-05-12 20:59:48 +10:00
ea41207c3b Fix depsgraph tagging during the relations build pass.
Followup commit to 18e5e2fa1a. Needs the same
treatment in the second pass when ID tags are reset again.
2016-05-12 09:55:48 +02:00
80b1adf8c2 BMesh: avoid calling delete operator w/ face dissolve
In nearly all cases this isn't needed.
2016-05-12 16:47:30 +10:00
031715f743 Fix missing piece in recent rBce65fae8f32c (support for '+' key).
Thanks to Daniel Rivera (Dr2d4) for the headup!
2016-05-12 08:15:59 +02:00
689e45284b Recent bmesh face-join caused regression (T48407) 2016-05-12 16:11:42 +10:00
8de3303a03 Cleanup: Fix typo. 2016-05-12 02:11:36 +02:00
c5ddbf181e Armature outline drawing used single width line
Only set line width in pose-mode
2016-05-12 07:14:44 +10:00
d3ed8233ff BMesh: use active face fallback w/ select-path
From user perspective, last selected face is the same as the active face,
use this as a fallback.
2016-05-12 07:11:19 +10:00
16ce1b78b0 Cleanup: Remove outdated comment and add new one about slot IDs. 2016-05-11 22:25:48 +02:00
4a4f043bc4 Cycles: Add support for single channel float textures on CPU.
Until now, single channel textures were packed into a float4, wasting 3 floats per pixel. Memory usage of such textures is now reduced by 3/4.
Voxel Attributes such as density, flame and heat benefit from this, but also Bumpmaps with one channel.
This commit also includes some cleanup and code deduplication for image loading.

Example Smoke render from Cosmos Laundromat: http://www.pasteall.org/pic/show.php?id=102972
Memory here went down from ~600MB to ~300MB.

Reviewers: #cycles, brecht

Differential Revision: https://developer.blender.org/D1981
2016-05-11 21:58:34 +02:00
544b76ac9c BMesh: ignore non-manifold face connections
Was showing an error message,
now dissolve the faces that and delimit at non-manifold boundaries.
2016-05-12 06:00:05 +10:00
a46d930d8b BMesh: add BMW_ISLAND_MANIFOLD
An island walker that only walks over manifold edges.
2016-05-12 05:59:59 +10:00
f6948083e9 BMesh Island Walker: use direct loop access 2016-05-12 05:30:20 +10:00
135064c45e BMesh: remove exception from face-join function
Callers need to check for NULL, if we need to know exact cause it could be a return arg.
2016-05-12 04:42:45 +10:00
1b003511be BMesh: boundary walker, skip non-manifold loops
Instead of setting an exception, treat non-manifold edges as boundaries.
2016-05-12 04:39:01 +10:00
674bf2fe58 BMesh: add check for manifold loop 2016-05-12 04:37:36 +10:00
5d93836a61 Cleanup: only use r_ prefix for return args 2016-05-12 04:36:16 +10:00
fbbac6807a Cleanup: unused win32 headers 2016-05-12 04:35:40 +10:00
8dea74bb4f error in last commit 2016-05-12 01:43:56 +10:00
725a088ef9 Correct check for tree being in BVH cache 2016-05-12 01:40:50 +10:00
79d01de6b0 Remove pointer typedef from BVHCache
Used ** arguments unnecessarily,
also replace BLI_linklist_apply with while loop.
2016-05-12 01:40:46 +10:00
63432f1424 Fix crash snapping to mesh with no geometry 2016-05-12 01:00:43 +10:00
92774ff792 Cycles: Use explicit qualifier for single-argument constructors
Almost in all cases we want such constructors to be explicit, there are
exceptions but only in few places.
2016-05-11 16:51:14 +02:00
d57f416e47 Fix incorrect FLT_MIN use 2016-05-11 21:36:42 +10:00
67d2de8828 Transform Volume rewrite/refactor
Take advantage of the efficiency provided by the snap_context.

Also fixes errors:
- volume snap fails based on view angle (T48394).
- multiple instances of dupli-objects break volume calculation.
2016-05-11 20:20:25 +10:00
4a135ad2b7 BMesh: correct fix for face-join removing attached faces 2016-05-11 20:12:52 +10:00
de72dcadbb Fix for inline documentation of FOREACH_NODETREE.
Was missing id macro variable.
2016-05-11 10:53:11 +02:00
18e5e2fa1a Fix for node tree ID tagging in new depsgraph.
Nested node trees are not handled in BKE_main_id_tag_all.
2016-05-11 10:53:11 +02:00
b4b269f38e Depsgraph: Add some missing relations
Those cases requires not only geometry component, but also a transform one
to be ready before evaluation can start.
2016-05-11 09:24:16 +02:00
35531657e5 BLI_kdopbvh: Use distance for BLI_bvhtree_ray_cast_all
Pass distance argument so its possible to limit the range we get all hits from.

Other changes:

- Use boundbox test before calling callback, avoids redundant calls.
- Remove meaningless return value.
- Add doc string, explaining purpose of this function.
2016-05-11 15:01:27 +10:00
a18f4d2bc6 CMake: optional date/time overrides for reproducible builds 2016-05-11 02:47:38 +10:00
c1e4aaa289 Fix T48387: Mirror weights keeps groups assigned
Swapping the weights kept zero weight verts assigned.
2016-05-11 02:47:38 +10:00
e525a06800 BMesh: only remove loose geometry when joining faces
Joining faces could remove faces that happened to share an edge that would normally be removed.
2016-05-11 02:47:38 +10:00
98123ae916 BLI_task: nano-optimizations to BLI_task_parallel_range feature.
This commit makes use of new taskpool feature (instead of allocating own tasks),
and removes the spinlock used to generate chunks (using atomic ops instead).

In best cases (dynamic scheduled loop with light processing func callback), we
get a few percents of speedup, in most cases there is no sensible enhancement.
2016-05-10 17:57:53 +02:00
fdd999042b Depsgraph: A bit of experiment with skipping where_is_bone if channels is taged as done
This is what old dependency graph was doing and apparently this avoids some updates,
however it's not really clear why those nodes are considering done. Maybe just because
of the way how relations are working. But needs a closer investigation.
2016-05-10 17:30:19 +02:00
e343e4a5ba Avoid per-constraint-target call of strlen
It's enough to do one single comparison to see if the string is empty or not.
2016-05-10 17:15:16 +02:00
2786b0bc9d Optimize action constraint by avoid memory allocation 2016-05-10 16:45:27 +02:00
e1a254d8de Attempt to fix blenplayer after recent changes 2016-05-10 16:14:24 +02:00
335274192e Revert "Task scheduler: Avoid mutex lock in number manipulation functions"
Appears mutex was guarateeing number of tasks is not modified at moments
when it's not expected. Removing those mutexes resulted in some hard-to-catch
locks where worker thread were waiting for work by all the tasks were already
done.

This reverts commit a1d8fe052c.
2016-05-10 15:43:03 +02:00
f501dfb085 Depsgraph: Use some more threading when tagging and finalizing evaluation
Also don't reset values there which were re-set on the next evaluation anyway.
2016-05-10 15:42:44 +02:00
a1d8fe052c Task scheduler: Avoid mutex lock in number manipulation functions
It seems using atomic operations here we can avoid having mute without
breaking anything.

Thanks Bastien for double-checking the changes!
2016-05-10 14:59:19 +02:00
9239257806 Fix T48393: Blender player doesn't start on files saved with with cyrillic letters in path 2016-05-10 14:31:00 +02:00
fcc2175710 Fix own mistake in rBd617de965ea20e5d5 from late December 2015.
Brain melt here, intention was to reduce number of tasks in case we have not much chunks of data to loop over,
not to increase it!

Note that this only affected dynamic scheduling.
2016-05-10 13:10:21 +02:00
898d040b0c Depsgraph: For big graphs update pending parents in threads
Gives additional speedup from ~88 to ~91 fps with a test rig.
2016-05-10 13:02:54 +02:00
288bbee5b1 Depsgraph: Comment evaluation priority out for now
It uses some additional compute power and the evaluation priority is
not even used.

This brings fps 88.2 with blenrig_for_debugging.blend on this desktop.
2016-05-10 12:05:09 +02:00
ce2c15deaf Depsgraph: Avoid multipel editors update per same ID
Simple thing, and apparently fps goes up to 80 with the demo file from jpbouza.

Not sure why at this point fps is so much higher than the old dependency graph
here now. And it's definitely something what others should verify as well.
2016-05-10 11:25:57 +02:00
12a20b78d3 Depsgraph: Don't leave active thread if there's only one children node
This reduces stress on the task scheduler and avoids some unwanted overhead
caused by all the threading business in the cases when there's only one
children node. We try to immediately switch to it's evaluation now, keeping
active thread up and running.

This bumps FPS from 58 to 64 on the blenrig test file from jpbouza.
2016-05-10 10:39:38 +02:00
7efa34d078 Task scheduler: Add thread-aware task push routines
This commit implements new function BLI_task_pool_push_from_thread()
who's main goal is to have less parasitic load on the CPU bu avoiding
memory allocations as much as possible, making taks pushing cheaper.

This function expects thread ID, which must be 0 for the thread from
which pool is created from (and from which wait_work() is called) and
for other threads it mush be the ID which was sent to the thread working
function.

This reduces allocations quite a bit in the new dependency graph,
hopefully gaining some visible speedup on a fewzillion core machines
(on my own machine can only see benefit in profiler, which shows
significant reduce of time wasted in the memory allocation).
2016-05-10 10:01:24 +02:00
401e710807 Correct armature-sketch snap context use
Use scene snap mode.
Also allow passing NULL ray-depth which falls back to BVH_RAYCAST_DIST_MAX.
2016-05-10 16:47:57 +10:00
ce65fae8f3 Fix T48369: Missing suport for main '+' key.
Many keyboard layouts (italian, spanish, german...) have direct access to '+' key on main
keyboard area (not the numpad one), ans x11 has own define for this key, so use it instead
of generating an unkown key event.

Note that we most likely have much more missing 'specific' keycodes for non-US keyboard layout,
but think since we already had a 'minus' keyevent, supporting 'plus' one is totally consistent.
And we had a spare space in our defined values just for it even!

This keyevent is only supported/generated by x11 and cocoa Ghost backends for now,
neither SDL nor win32 seem to have matching key events...
2016-05-10 08:29:03 +02:00
76481eaeff Cycles: Add support for float4 textures on OpenCL.
Title says it all, this adds OpenCL float4 texture support.

There is a bug in the code still, I get a "Out of ressources error" on nvidia hardware here, not sure whats wrong yet.
Will investigate further, but maybe someone else has an idea. :)

Reviewers: #cycles, brecht

Subscribers: brecht, candreacchio

Differential Revision: https://developer.blender.org/D1983
2016-05-10 02:53:50 +02:00
dc82c2cd48 View selected support for grease-pencil 2016-05-10 04:37:00 +10:00
119230b565 Cleanup: header, style 2016-05-10 03:03:34 +10:00
d8cf14fa67 Fix T48388: Undo history sculpt mode not visible 2016-05-10 02:42:14 +10:00
9513bdcaea Buildbot: Attempt to make sure install folder is always clean for Win and OSX 2016-05-09 17:34:02 +02:00
ba3ae9ea27 Cleanup and refactor our atomic library.
This commit:
* Removes most of all dirty internal details from public atomi_ops.h file, and move them into /intern private subdir.
* Removes unused 'architectures' (__apple__ and jemalloc).
* Split each implementation into its own file.
* Makes use of C99's limits.h system header to determine pointer and int size, instead of using fix hardcoded list of architectures.
* Introduces new 'faked' atomics ops for floats.

Note that we may add a lot more real and 'faked' atomic operations over integers and floats
(multiplication, division, bitshift, bitwise booleans, etc.), as needs arise.

Reviewers: sergey, campbellbarton

Differential Revision: https://developer.blender.org/D1982
2016-05-09 17:03:08 +02:00
299a25cb35 Fix weight-mirror reporting invalid failed mirror verts
Use vertex tagging instead of clearing mirror index.
2016-05-10 00:57:00 +10:00
f616caa315 CMake: Fix compilation error when toolkit gives empty result
Should we also check whether toolkit exist perhaps?
2016-05-09 16:05:02 +02:00
df07303fbb Depsgraph: Avoid unneeded relations update when canceling transform
This was originally done for T46320 in order to re-store depsgraph state
after all the constraint modifications.

However, it relations were updated if there's any IK chain the the pose,
which is a bit too annoying.
2016-05-09 16:04:26 +02:00
5ae4487351 Missed last commit 2016-05-09 23:51:42 +10:00
6172bdbde8 Remove redundant error checks in grease-pencil tessellation 2016-05-09 23:47:57 +10:00
8b13555b24 Docs: comment polyfill2d functions 2016-05-09 23:47:57 +10:00
9ac35be63a Task scheduler: Don't calloc in performance-critical areas
Majority of the fields are being overwritten anyway, so calloc it
kinda waste of CPU ticks.
2016-05-09 14:54:24 +02:00
86a57b04bf Depsgraph: Store node input/output links in a vector rather than in set
Set is much slower to iterate through (due to cache misses and such) and
the only advantage of using set is faster removal of link. However, we are
iterating links much much more often than removing them, and even when we
are removing links we don't really need to remove link from nodes which it
connects -- we don't support partial depsgraph updates, so removing links
from nodes on destruction is a waste of time.

If we ever want to support partial updates we can have dedicated function
to remove link from nodes it connects.

This gives a surprising increase of fps from 42 to 56 with test file from
Mr. J.P.Bouza (blenrig_for_debugging.blend). Surprising because old DEG is
actually slower here (52 fps). Didn't see any regressions (and don't see
why they will happen), so let's ask our riggers and animators to perform
further speed tests ;)
2016-05-09 12:42:53 +02:00
5dbeea95d0 Depsgraph: Avoid having per-node lock when scheduling children
Use atomic operations instead, should in theory improve timing of
scheduling. However, probably not so visible yet because actual
task scheduling still have some locks and memory allocations.

Baby steps, what would i say.
2016-05-09 11:58:36 +02:00
dc5e02c42c Atomics: Add atomic_fetch_and_or_uint8() function
Hopefully it compiles on all platforms still..
2016-05-09 11:45:43 +02:00
a27772cd66 Fix makesdna not checking alignment for a non-native platform
This was causing alignment issues which were only visible on a platform
of particular bitness, so it was easy to break stuff for 32bit when
working on 64bit platform and vice versa.
2016-05-09 09:54:51 +02:00
3ce3163379 Fixes for GPencil Copy and Paste
* Fix "Attempt to free NULL pointer" when copying strokes for the first time

* Fix poll callback on "paste" operator, so that it is possible to paste
  strokes when there are no editable strokes visible.
2016-05-09 19:42:34 +12:00
d6555d936c Cleanup: Avoid duplicative defines for CPU textures, use the ones from util_texture.h
Also includes some further byte -> byte4 renaming, missed that in last commit.
2016-05-09 09:16:41 +02:00
e0e7d94f79 Fix error introduced by removing faces before executing bridge
Commit 86abddc9, caused an error when the face-region included boundary edges.
Since removing the faces first, caused the edges along the boundaries to be removed.

Add support for deleting faces and internal edges, that keeps boundaries.
2016-05-09 16:21:00 +10:00
69be8d7cbd Fix error in recent snap refactor
Crash in edge snapping
2016-05-09 15:46:34 +10:00
73fab5bb3f Fix crash introduced w/ snap refactor
Create snapping context when in the 3d view,
transforming pose bones and grease-pencil crashed.
2016-05-09 15:46:34 +10:00
dc4c3ce592 GPencil: Added operators to select first and last points of strokes
These are useful for removing overshoots at the end of closed strokes (for fills)
2016-05-09 17:23:36 +12:00
0578d3ef3e Graph Editor: Ctrl-Click keyframing now deselects all existing keyframes by default
Now, when creating new keyframes in the graph editor by ctrl-clicking, only
the newly created keyframes will be selected. This is a little workflow tweak
to make it faster to work, as you no longer have to deselect all, and then
re-select the newly added keys in order to manipulate them.

The old behaviour (not modifying the selection status of the old keys) has been
kept, but is now available via Shift-Ctrl-Click.

Feature request from @Shhlife
2016-05-09 17:23:35 +12:00
9a1e11260c Cleanup: More byte -> byte4 renaming for consistency. 2016-05-09 02:22:01 +02:00
5fe1bea2da Info Header / URLs: Fix community link + https'ification. 2016-05-08 23:38:41 +02:00
98e2135a2d Fix T48380: fix for recent image manager code cleanup. 2016-05-08 21:41:25 +02:00
a815e10211 Code cleanup: use special type instead of node names. 2016-05-08 20:21:04 +02:00
dfe9aa25c3 Code cleanup: tweaks to image manager code found while looking into previous bug. 2016-05-08 20:20:53 +02:00
e362b04c43 Fix T48377: Cycles crash removing float image texture node during viewport render. 2016-05-08 19:48:22 +02:00
5fde5616e0 Fix T48372: missing OS X trackpad scroll support for increasing loop cut / bevel segments. 2016-05-08 19:06:48 +02:00
2d8db0de79 Docs: explain some details of RNA enums 2016-05-09 02:37:34 +10:00
cbaa25eb88 Cycles: Fix two small memory leaks and deduplicate table freeing
This commit makes remove_table skip the freeing if the offset is
already set to invalid - or, if it wasn't, set it to invalid after freeing.

That's what the current code was already doing in the Manager classes,
this change allows them to just call remove without the additional code.

Also, two potential memory leaks where new tables were always allocated
without freeing the old ones are fixed.

Reviewers: sergey, dingto, brecht

Differential Revision: https://developer.blender.org/D1974
2016-05-08 17:44:03 +02:00
6100c2d262 Cleanup: warnings 2016-05-09 01:16:58 +10:00
e2b79a0a24 GPencil Onion Skinning: Setting before/after to -1 will turn off onionskinning in that direction
This is an experimental option that I found would have been useful to have,
when making my earlier anim test. The only contentious point is whether it's
better to use a separate boolean flag (perhaps bound to the labels) instead
of overloading this setting (and describing the usage in the tooltip).
2016-05-09 03:03:40 +12:00
d6fd6d18d7 Fix: Toggling "lock layer" for GPencil layers in the dopesheet didn't update the layers UI 2016-05-09 02:49:32 +12:00
c4a5c26a59 Fix: Lasso select for Grease Pencil doesn't work in the Nodes Editor
In the nodes editor, Ctrl-LMB-drag is taken by "Cut", and it seems impossible
for any other keymap to override that. Instead, the default lasso select hotkey
there is Ctrl-Alt-LMB-drag instead.

To get Grease Pencil lasso select (in GP Editmode) to work in the Nodes Editor too,
this commit adds the Ctrl-Alt-LMB-drag binding here too. However, to make things easier,
this extra binding will be part of the Grease Pencil keymap everywhere. There doesn't
seem to be any conflicts with having this in place - until we find them, this should
be ok to have.
2016-05-09 02:44:21 +12:00
491ad6664e Tweak to GPencil layers UI layout
I'm still not happy with this layout as it is now, but it seems a bit less unbalanced
than what I'd been trying before. So, let's leave this as-is for now.
2016-05-09 02:04:28 +12:00
3f934b06a6 Tweaks for a tooltip I missed during earlier review for D1886 2016-05-09 02:00:23 +12:00
d4ed5c398e A "better" (?) fix for msvc silliness - used in one other place in all of Blender 2016-05-09 01:46:18 +12:00
e43ee5563b Fix compiling on MSVC - M_PI undefined 2016-05-09 01:31:13 +12:00
81c302bbff Action Editor: Initial support for a Properties Region
This commit adds some of the initial support for a properties region in the
Action Editor. There are currently no panels to display, as there is still
a lot of work required to port over the required internal architecture to
support the panels seen in the Graph Editor.
2016-05-09 00:53:52 +12:00
9dbe7bbe9a D1886: GPencil - Add smooth iterations parameter to get better quality
After some test, a new iteration parameter has been added in order to
apply repetitive smoothing to the stroke. By default 1 iteration is applied,
but can used any number between 1 and 3.

The repetition uses different levels of intensity from 100% of the defined smooth
factor for the first loop, 50% for the second and 25% for the third. We use in each
loop a smaller value in order to avoid deform too much the stroke.
2016-05-09 00:53:51 +12:00
dc78e47b77 Fix for D1705: Update to fix the bug with extra triangles that produces glitches in some situations 2016-05-09 00:53:51 +12:00
011786a3f8 GPencil Fills: Small reshuffle of UI buttons
Now, stroke-related things (thickness, volumetric, points) and fill-related things
(HQ fill) are in the relevant columns, instead of having some in each column.
2016-05-09 00:53:50 +12:00
b88535ed28 Code Cleanup: Just a bit more tidying up comments/whitespace/etc.
There is still some instability in how the triangulations are happening,
where the triangle count of the resulting triangulation fluctuates resulting
in weird artifacts sometimes.

To reproduce, try drawing some U-shapes, and keep reloading the file.
2016-05-09 00:53:49 +12:00
af8a54bd8d Fix for potential bug with new GP Fill
While trying to track down why I still keep getting some random "extra" triangles
showing up when reloading files with fills, I noticed that there's an index mismatch
here that may cause problems in some rare cases:

There are "gps->totpoints" items in tmp_triangles, but there should only be
"gps->tot_triangles" triangles in the gps->triangles array. If for whatever reason
some of the triangles in tmp_triangles are invalid, this could have meant that
while a tmp_triangles candidate was skipped, a corresponding slot for a valid
triangle also got skipped.
2016-05-09 00:53:49 +12:00
f5ddcfeb03 Code Cleanups: A bunch of tweaks to tidy up things from the GPencil Fill patch 2016-05-09 00:53:48 +12:00
1d5c71bca7 D1705: Fix Grease Pencil Fill for Concave Shapes
Improve filling for concave shapes using a triangulation of the stroke.
The triangulation information is saved in an internal cache and only is
recalculated if the stroke changes.

The triangulation is not saved in .blend file.

Reviewers: aligorith

Maniphest Tasks: T47102

Differential Revision: https://developer.blender.org/D1705
2016-05-09 00:53:47 +12:00
0411cfea9d Fix T48373: Crash when using dynamic paint with brush material.
`dynamicPaint_doMaterialTex` was called from inside an omp parallel section with brush->dm
itself, and not the local dm copy. Generating looptri data is not thread safe at all...
2016-05-08 11:39:45 +02:00
1955754934 Cycles: Cleanup: Swap order of the RNG-state-initializing for-loops
Swap the for-loops in the RenderBuffer reset code to follow the convention
of looping over y in the outer loop.
The improved cache performance won't really be noticable here, but it's nicer
if it follows the usual style.
2016-05-08 01:22:28 +02:00
e5b4e6b0a3 Clamp dot-product to avoid precision error
Would only happen in degenerate cases.
2016-05-08 00:04:05 +10:00
1c46ecd86b Cleanup: Remove unneded (void) line, we don't have ifdefs here anymore. 2016-05-07 15:55:28 +02:00
a3b42d638b Cleanup: whicespace 2016-05-07 23:58:04 +10:00
b132f3ac7b Correct render-border line width 2016-05-07 23:53:35 +10:00
6d402610c1 Correct error in wrapped array-span-iteration 2016-05-07 23:48:53 +10:00
f5930759a6 Fix T48368: Cycles mix RGB constant folding bug after recent refactor. 2016-05-07 14:21:15 +02:00
68e856da03 Curve Fitting: better fallback when least-square solution fails
Take curvature into account when calculating handle length.

Gives significantly better results for curve dissolve and 10-20% more efficient freehand drawing.
2016-05-07 21:48:00 +10:00
d2296cd5ec Fix error copying cubic data 2016-05-07 21:38:48 +10:00
65dd1d7d08 Fix T48362: Spin tool broken after recent commit.
Typo in rBrBa48d74079, spin tool was now using the wrong view axis.
2016-05-07 11:58:33 +02:00
Martijn Berger
0a277f7428 Fix cycles-xml with OSL support after changes inroduced in 1422f0dd16 2016-05-07 10:50:21 +02:00
4422b3f919 Some fixes for CUDA runtime compile:
* When Baking wasn't used we got an error.
* On top of Volume Nodes (NODES_FEATURE_VOLUME), we now also check if we need volume sampling code,
so we can disable that as well and save some further compilation time.
2016-05-06 23:13:33 +02:00
734d1aec3f Cycles: Make CUDA adaptive feature compile a Debug flag.
If the CUDA Toolkit is installed and the user is on Linux,
adaptive, feature based CUDA runtime compile is now possible to enable via:

* Environment flag CYCLES_CUDA_ADAPTIVE_COMPILE or
* Debug menu (Debug value 256) in the Cycles UI.
2016-05-06 23:13:33 +02:00
bd335f13fe Fix T47657: Using template_list() with invoke_props_dialog()
popups have no wm_region in context, using wm_menu here.

Not working perfect, but at least it prevents crash.
2016-05-06 21:56:54 +02:00
8c2cec937b Fix T48262: Crash when trying to render a scene without camera. 2016-05-06 21:41:56 +02:00
e074554f8f Image Editor: Add border zoom
Use Shift-B, UV border-select-pinned is now Ctrl-B.

Patch from @rav66
2016-05-07 04:32:08 +10:00
ddbc351dd3 Fix recent issue in recent BVH snap/cache
The derivedMesh could free a tree stored by the cache.
Now check the cached tree is valid.
2016-05-07 02:59:19 +10:00
9c6f33c405 Correct in-range assert (zero is valid) 2016-05-07 02:16:21 +10:00
9f96976e59 DerivedMesh: don't allocate a new material array each draw 2016-05-07 02:16:21 +10:00
bd309603c5 Clip invisible parts of image when drawing in 2D textures and GLSL Modes
This commit avoids draw of invisible parts of image in image editor,
making it faster to re-draw the image.

Especially handy when painting on a high-res image when zoomed-in.
2016-05-06 16:54:07 +02:00
dd52bf8fb9 Cleanup: Move full SVM statistics to VLOG(2) verbosity level. 2016-05-06 14:39:41 +02:00
3807bcb3a8 Cleanup: Rename texture slots to float4 and byte, to distinguish from future float (single channel) and half_float slots.
Should be no functional changes, tested CPU and CUDA.
2016-05-06 14:37:35 +02:00
36d8a70b00 Code refactor: Change Cycles ImageManager arrays.
This commit simplifies the code for the image arrays. Instead of having 2 arrays for float and byte textures,
we now use an array here. This simplifies the code (avoids code duplication), and makes it possible to easily extend it
with float1 and half-float types in the future.

Only tested with CPU yet, plus some cleanup / code de-duplication is still possible here.

Reviewers: #cycles, sergey

Reviewed By: #cycles, sergey

Subscribers: jesterking, sergey

Differential Revision: https://developer.blender.org/D1969
2016-05-06 13:20:09 +02:00
8aa3bac7af Tweak precision for interocular distance and convergence plane
Previous number of digits after point was not really useful, especially
for the interocular distance where it's quite common to go sub-cm precision.
2016-05-06 12:32:23 +02:00
ef0c02cb4d Speedup of regular 2D painting
Yet another commit which makes painting aware of multi-threaded systems.
2016-05-06 11:49:09 +02:00
204f55c189 Cloth: Fix shrinking to properly respond to animated min/max and weight.
Enable dynamic restlen recomputation based on sew flag and update the
shrink factor math within it to call the new utility function.
2016-05-06 11:40:20 +03:00
2a9ddc808d Cloth: Change ClothVertex::xrest to actually store the rest position.
Originally the value was only needed when building the springs,
so a pointer to the input data was somewhat ok. However, recalculating
spring length dynamically requires keeping the actual value around.
2016-05-06 11:40:19 +03:00
Luca Rood
fcfbe27826 Part of D1903: Dynamic base mesh for cloth simulation
A function that recalculates cloth spring lengths.
2016-05-06 11:40:19 +03:00
8e1ab9b137 Cloth: Ignore zero-restlen sewing springs in average length computation.
The average length is used to adjust self-collision and stiffness
to match mesh density, and in either case considering the always zero
restlen sewing springs doesn't actually make much sense.

The struct_springs variable is also used for other things like total
spring count, so a new one needed for the true struct springs.
2016-05-06 11:40:19 +03:00
b481e886e5 Cloth: Use Geometrical Mean for averaging cloth shrink factor.
This comes out of considering a one-dimensional transition in weight
on a rectangular cloth grid. At the transition face loop, one side
of each rectangular face would be scaled by k1, and the opposite one
by k2, thus turning the rectangle into a trapezoid. Averaging would
be used to choose the scale factor for the remaining two sides.

If Geometrical Mean, i.e. sqrt(k1*k2) is used, it so happens that the
diagonals of the trapezoid also end up scaled by sqrt(k1*k2) compared
to the original rectangle. This means that the same scale factor is
correct for both structural and shear springs, which is not the case
with simple average.
2016-05-06 11:40:19 +03:00
8d22a8afa0 Cloth: Fix the shrink feature to be controlled by the sewing spring flag.
Previously it was all over the place: without a vertex group it was
always enabled, and with it it depended on the Self Collision option
due to a likely editing mistake. Now it should be in sync with what
disables the fields in the UI.

The verts->shrink_factor field is changed to just cache the vertex
weight, with the shrink_min/shrink_max interpolation done later.
This is because cloth_apply_vgroup only runs if there are vertex
groups, and thus the factor may not update after property changes.

In addition, bending springs are now also affected by the shrink
factor to avoid visible distortion in object shape at high shrink.
2016-05-06 11:40:19 +03:00
ae3f68109d Cloth: Invalidate cache when sewing springs are toggled on or off. 2016-05-06 11:40:19 +03:00
7ecc159f37 Force Fields: Fix Texture with both Use Coordinates and 2D enabled.
From description, Use Coordinates evaluates the texture using
target coordinates in the local space of the force field object.
2D is supposed to ignore the Z coordinate. Thus one would assume
that if both are enabled, the force field effect would move with
the force field object, and Z would be 0.

However, instead first the 2D option projects points onto a plane
passing through the global zero and orthogonal to the local Z,
and only then the resulting point is transformed into local space.
Z is not locked at 0, so procedural textures like Spherical Blend
don't work as expected.

To fix this, apply local transform first, and then just clear Z if 2D.
2016-05-06 11:40:18 +03:00
8cc4f3f52a Implement threaded partial display buffer update
This speeds up update of display buffer when affected area is big enough.

Mainly helpful for cases when doing long fast strokes when painting.
2016-05-06 10:04:29 +02:00
bc1a7d9283 Cleanup: warnings
Values set but not used
2016-05-06 16:49:25 +10:00
304501193b Fix T48356: Bridge tool creates self-intersecting loop
When loops are planar to eachother, initialize their winding based on surrounding geometry.
2016-05-06 10:22:02 +10:00
86abddc96a Fix error bridging edge loops flipping
Calculating the winding failed when faces exist on both sides of the edge.
2016-05-06 08:53:51 +10:00
37ad451b8e Cycles: Comment out unused function arguments 2016-05-05 23:47:22 +02:00
9b89071c9c Multi-thread generated image creation
Gives about 2x speedup on laptop when creating new hires generated image,
regardless of it's type (color, color grid, uv grid).
2016-05-05 23:47:22 +02:00
3064270e13 Correct snap checks for edges & faces
Snap targets can't contain vertices which are being transformed
2016-05-06 07:44:07 +10:00
5e72ea4397 Don't overwrite existing snap context
Re-activating transform would overwrite previous context, leaking memory.
2016-05-06 06:47:21 +10:00
d12378da11 Cleanup: style 2016-05-06 06:34:25 +10:00
ee5eb2a26a Missed last commit 2016-05-06 06:28:36 +10:00
55c4889864 bvhutils: remove bitmap counting
All callers pass in valid number
2016-05-06 06:14:36 +10:00
c5a26bef5d Cleanup: rename getepsilon -> get_epsilon 2016-05-06 06:14:36 +10:00
cc650c3d07 Add asserts to check bvhutils args are correct
Would have prevented previous error going unnoticed.
2016-05-06 06:14:36 +10:00
7efdee7517 Fix crash adding byte color grid images 2016-05-05 22:05:09 +02:00
7b7e7ac4c1 Code cleanup: simplify SVM stack assignment. 2016-05-05 21:43:46 +02:00
0f943337bc Code cleanup: remove some unused functions. 2016-05-05 21:43:46 +02:00
dd8bfa0929 Code refactor: reduce special node types, use generic constant folding. 2016-05-05 21:43:46 +02:00
2cfadecf97 Fix Cycles emission node being unnecessarily tagged as spatially varying. 2016-05-05 21:43:46 +02:00
9a20ff2b52 Fix OS X build error after SSE changes, BLI_math_base.h conflicts with EXR headers. 2016-05-05 21:43:46 +02:00
4aaafcbc45 Fix for fix, sorry for the noise 2016-05-06 05:46:07 +10:00
2812a8f7eb Missed last commit 2016-05-06 05:42:33 +10:00
7122b05ac3 Correct own mistake int recent transform API edits
Need to return number of enabled elements.
2016-05-06 05:40:07 +10:00
46ccc54faf Fix error not using the cached BVH tree 2016-05-06 05:17:34 +10:00
0b5a0d8412 Transform/Snap: EditMesh/BKE_bvhutils API improvements
Separate the creation of trees from EditMesh from the creation of trees from DerivedMesh.
This was meant to simplify the API, but didn't work out so well.

`bvhtree_from_mesh_*` actually is working as `bvhtree_from_derivedmesh_*`.
This is inconsistent with the trees created from EditMesh. Since for create them does not use the DerivedMesh.

In such cases the dm is being used only to cache the tree in the struct DerivedMesh. What is immediately released once
bvhtree is being used in functions that change(tag) the DM cleaning the cache.

- Use a filter function so users of SnapObjectContext can define how edit-mesh elements are handled.
- Remove em_evil.
- bvhtree of EditMesh is now really cached in the snap functions.
- Code becomes organized and easier to maintain.

This is an important patch for future improvements in snapping functions.
2016-05-06 05:01:51 +10:00
88b72925d0 Optimize linear<->sRGB conversion for SSE2 processors
Using SSE2 intrinsics when available for this kind of conversions.

It's not totally accurate, but accurate enough for the purposes where
we're using direct colorspace conversion by-passing OCIO.

Partially based on code from Cycles, partially based on other online
articles:

  https://stackoverflow.com/questions/6475373/optimizations-for-pow-with-const-non-integer-exponent

Makes projection painting on hi-res float textures smoother.

This commit also enables global SSE2 in Blender. It shouldn't
bring any regressions in supported hardware (we require SSE2 since
2.64 now), but should keep an eye on because compilers might have
some bugs with that (unlikely, but possible).
2016-05-05 19:46:06 +02:00
bb6fbc64ae Docs: scanfill.c purpose 2016-05-06 00:45:38 +10:00
c8e9832be3 Fix T48320: Freestyle renders wrong edges of objects which in the other RenderLayer.
FSAA sample files in EXR format are no longer always updated (after some
changes between 2.73 and 2.74 releases), and the reported bug was caused
by old samples from a previous frame that were being merged by mistake.

The present revision addresses the documented issue by entirely skipping
the rendering of auto-generated scenes when there are no Freestyle strokes
to render, which suppresses sample merging of the render layers that were
not rendered.
2016-05-05 23:15:52 +09:00
6f83710af9 Optimize projection painting with big brushes
Multi-threaded partial buffer update, gives about 2x speedup with
big brushes.

Thanks Campbell for testing and benchmarking!
2016-05-05 14:45:00 +02:00
c81d9fda46 Optimize threaded scanline processor
Avoid memory allocation for task data.
2016-05-05 14:18:11 +02:00
c795d31a1f Simplify scanline threaded processor used by GPU_verify_image
Just avoid some unneeded initialization functions when the threaded
processor is simple enough to only depend on current chunk start
scanline and number of scanlines.
2016-05-05 13:16:56 +02:00
f5dcb137f1 Fix project paint using uninitialized edit-region
First stroke always had the minimum rectangle set to 0,0 which could cause a largre region of pixels to be
unnecessarily updated.
2016-05-05 20:57:54 +10:00
9b8bf57361 Curve Fitting: avoid clamping fallback handles. 2016-05-05 20:31:13 +10:00
d0818dbae1 Optimize Blank and Color Grid generated images
Avoid unnecessary pixels linearization gives nice speedup.
2016-05-05 12:04:42 +02:00
dd73d9c54e Correct error in recent smoothview edits 2016-05-05 19:58:45 +10:00
043486e2bc Fix typo in previous commit
Thanks Julian Eisel (Severin) for the heads up!
2016-05-05 11:33:13 +02:00
9aff51661c Optimization for initial display of high res textures in viewport
Multi-thread all the color space conversion operations.

Gives speedup from 0.8 to 0.1 seconds on a model with 4k etxture on it.
2016-05-05 11:28:50 +02:00
8c3c669c2d Image Paint: fix for calls to GPU_free_image while painting
The width and height of of the region to update are often zero,
skip calling GPU_paint_update_image in this case.
2016-05-05 18:52:11 +10:00
08be000637 Fix T48210: Editing all selected buttons fails to auto-key 2016-05-05 02:37:46 +10:00
10bbce30a9 UI: avoid getting the active button when its already known 2016-05-05 02:22:23 +10:00
6601680e8d View3D: apply smoothview before modal view operations 2016-05-05 02:01:18 +10:00
bd1378b56b Cleanup: rename ED_view3d_smooth_view_finish (to force_finish) 2016-05-05 01:51:25 +10:00
e30f0427a5 Fix error in BM_face_exists_overlap_subset
Was re-using loop index, thanks to @bzztploink for spotting!
2016-05-05 01:35:09 +10:00
875df1e2b9 Cycles: Fix hair minimal size doesn't work on GPU and SSE2 only CPUs 2016-05-04 17:14:43 +02:00
ddd6be1834 Compositor: negative color support for ASC-CDL offset
Since the color wheel can't handle negative colors usefully, use a basis value for the initial RGB.
2016-05-05 00:06:55 +10:00
980f3c3693 Fix T48346: Transparent shadows do not work for instanced objects 2016-05-04 14:46:30 +02:00
6f2797b50b Curve Draw: option to apply absolute offset
Offset used curve radius, which isn't useful drawing without any bevel radius.
2016-05-04 15:45:55 +10:00
568514c875 Fix T48340: Smooth view cancels previous view action
Previously users needed to wait for view orbit to finished,
so quickly pressing keys would gave different result.
2016-05-04 03:38:20 +10:00
Julian Eisel
9d3d9ac0b9 Fix 3D View panel header color wrong after theme reset
Caused by wrong alpha value in rB34b30f847429ac (used 0.01, should've been 0.1). Also made sure all editors initialize same default theme values for panels and cleaned up code a bit.
Works fine with old userpref.blend files.
2016-05-03 18:31:37 +02:00
645047708d Fix broken build without IME and/or I18N (caused by rBcb6307162b4c12). 2016-05-03 16:56:52 +02:00
9151095dbe Fix T48328: Outliner: Armature EditMode: crash when selecting bone of a shared amrature in another object's bone list.
Basically, issue is that outliner stores editbones for an edited armature, which are only valid during EditMode.

When more than one object use the same armature, selecting ebones from same armature but under non-edited object
would first select that object (and hence switch out of editmode), and then try to select editbone while editdata
no more exist.

Solution for now is to not change active object in this case - it's not totally ideal (not consistent),
but other solutions (like switching edited object without leaving editmode, or rebuilding (part of)
outliner tree in-between) are horribly hackish and most likely prone to epic failure anyway.
2016-05-03 15:11:42 +02:00
cb6307162b Cache whether current translation language supports IME or not
Solves the weak point mentionedi n previous commit.
2016-05-03 12:38:21 +02:00
b34f177a39 Fix T47841: Shift-space doesn't type space in type-in fields on Windows
Shift-space was reserved for IME support, however IME will only
be enabled on certain languages. We can avoid any IME-related
exceptions form other languages without too much trouble.

There's one weak point around ui_ime_is_lang_supported() tho,
which is it might be doing string comparison a bit too much
often now, this we can avoid by handling those checks from BLT.
2016-05-03 12:20:40 +02:00
bff15770a9 Fix T47424: Blender Internal material node 'mapping' not showing results of animation
Not very efficient solution -- it'll update mapping node on init ntree exec and will
not work for viewport GLSL shading perhaps, but it's as good as it could be within
current dependency graph.

The issue here is that manual edit of values will cause cached matrix re-evaluation.
but using animation does not use rna update callbacks hence no matrix update was
happening.
2016-05-03 11:44:17 +02:00
3dcc05c591 Cleanup: no need to cast for pointer comparison 2016-05-03 18:20:33 +10:00
c2f28864d6 Fix T48169: 1 pixel offset painting 2D textures
Painting at negative locations was using int-rounding.
2016-05-03 17:49:18 +10:00
ead2496e67 Cleanup: use offset macro 2016-05-03 16:40:14 +10:00
1fb17fcf23 UI: limit listview arrow/wheel bindings
Allow Ctrl-Up for eg to be used when in a list view.
2016-05-03 16:17:14 +10:00
e2a6fb1f0b UI: don't show tips when navigating ui-list 2016-05-03 14:59:45 +10:00
9953eeb012 Cleanup: use const for units API
Also make return args explicit.
2016-05-03 13:52:07 +10:00
48d3a8b54b Math Lib: inline project_plane_v3_v3v3 2016-05-03 13:48:00 +10:00
a58a8ebea7 Missed setting handles in curve dissolve 2016-05-03 00:06:12 +10:00
122496dda1 Correct header (can't use uint here) 2016-05-02 21:08:02 +10:00
f28c626574 Fix bl_load_py_modules test
- scripts that execute directly need to include their basedir in the sys.path
- modules which are in a directory without an __init__.py weren't importing.
2016-05-02 21:06:15 +10:00
143f6c4bb2 Curve: new dissolve tool
removes vertices, re-fitting the surrounding handles.
2016-05-02 18:50:12 +10:00
ec9cb57b01 Curve Fitting: expose function for fitting a single curve 2016-05-02 18:50:04 +10:00
915e9eeff1 BLI_array_utils: helper for stepping over contiguous ranges 2016-05-02 18:49:22 +10:00
c1ca667d4a Fix compilation error on Armel architecture
__GCC_HAVE_SYNC_COMPARE_AND_SWAP_n are not defined on this architecture
for some reason, however those functions are available.

Adding a workaround for newly used __sync_fetch_and_and() function.
2016-05-02 09:55:08 +02:00
4e4ff72d13 Fix T48325: Data transfer modifier vertex group selector doesn't work with freestyle data.
Freestyle edge/face marks are (afaik) our only actual customdata bitflags... Original work
kinda assumed we had no such things. :P
2016-05-01 15:36:09 +02:00
1422f0dd16 Fix Cycles external OSL shader not working with relative file paths. 2016-05-01 01:44:52 +02:00
abf6f9f6cf Fix T48118: Vertex Groups not masking particle hair emission correctly
Own regression from rB019ce363b01bba0af, not totally sure why removing the heading
zero value in element_sum broke binary search distribution in random branch, but...

New code makes thing sooo much simpler, by simply getting rid of all zero-weight
items in element_sum (at the cost of adding a temporary extra index mapping array),
that way neither random nor 'even ordered' distribution code has to wory anymore
about skipping zero-weighted items!
2016-04-30 16:56:19 +02:00
b1f6cd5a6a Slight adjustment to curve fitting tangents
Don't let the point spacing give bias to a side.
2016-04-30 16:27:43 +10:00
6ab22064c2 Fix for typo comparing double events
Also remove doubles when filling the final array.
2016-04-30 16:21:06 +10:00
ac163447f8 Cleanup: warnings. spelling 2016-04-30 04:10:34 +10:00
461604c0d5 Fix (unreported) bad 'NULL freeing' with placeholder images.
Looks like code expects some initialized Image data after all, so do it
for placeholders as well (using default generated UV grid).
2016-04-29 18:05:49 +02:00
57eb8539fc Fix crash (segfault) in node editor.
In some cases, we can have nodegroups without attached nodetree, this case is checked
in top `node_group_has_output()` entry point, but not in recursive `node_group_has_output_dfs()`.

Issue appeared after rB42824f4403db3a35, presumably because check on node flag itself
was skipping that case, which is no more possible when using ID tags.

Reported by sebastian_k over IRC, thanks.
2016-04-29 17:37:00 +02:00
467e12514e Fix broken Collada from rBrB6d0cae56e84306ed. 2016-04-29 16:56:20 +02:00
2ba7b3ea1a install_deps: add support for OpenVDB.
Note that recent DEB-based distro have packages for this, even simpler!

Differential Revision: https://developer.blender.org/D1933
2016-04-29 16:45:09 +02:00
de0b480629 install_deps: add check for glew version, too old ones are not compatible with OSD.
In case too old system glew is detected, use the one shipped with blender.

Part of D1933.
2016-04-29 16:43:28 +02:00
3ccc61c03a install_deps: bunch of cleanups, tweaks and micro-fixes.
This commit mostly:
* removes some (very) old messages or hacks (like those for ubuntu 10.4...).
* Moves lib-specific dependencies installations to upper level
  (simpler to manage, and those are small enough packages).
* Uses new dnf package manager for fedora (sigh, we now have tree different commands for fed/suse/rehl).
* fixes or enhances some options for commandline tools.
* Force anew building of oiio package, due to insane dependencies of this one in recent distro.

Part of D1933.
2016-04-29 16:35:37 +02:00
6d0cae56e8 Fix T48290: Hook fails after deleting geometry
Now CD_SHAPEKEY_INDEX customdata is stored in edit-mode when hooks and vertex parents are used.

This also fixes a bug where undo would loose key-index data.

Move to structs for BM_mesh_bm_to/from_me to avoid passing many argument, which mostly aren't used.
2016-04-29 23:39:50 +10:00
b5ce2bbef7 BMesh: when multiple vertices have the same key-index, use the first
Simple error case where many vertices share an original index,
now use the first match instead of the last.
2016-04-29 21:52:09 +10:00
3e32f8e601 Fix T48298: Cycles World environment Texture node, movie doesn't update frame 2016-04-29 10:54:40 +02:00
9e1a9fa5bb Remove redundant selection flush call 2016-04-29 17:29:23 +10:00
d3344ca7b1 Minor optimization to bmesh shape key conversion
Avoid linked linked loop and custom-data lookups per vertex,
use a table of shape-keys with array offsets instead.
2016-04-29 15:02:04 +10:00
636195e402 Fix T48301: Cycles incorrect render with CMJ and viewport samples 0.
Max samples 2147483647 was causing integer overflow.
2016-04-28 23:57:20 +02:00
a48d740798 Fix T48300: 3D view tools outside the 3d view crash 2016-04-29 00:00:43 +10:00
6976be7723 Python: install pyconfig.h on OSX, needed for PIP 2016-04-28 20:46:58 +10:00
94a6019a7b Fix T47715: EXCEPTION_ACCESS_VIOLATION crash when removing modifiers or rendering
The issue was caused by missing indirect dependencies from other scenes in the
current scene depsgraph, which was causing some threading conflicts.

Not sure what would be ideal solution here, for now use stupid but rather robust
approach to solve that. Maybe there's something better to do here tho.
2016-04-28 12:32:59 +02:00
c01c47f79d Depsgraph optimization: Don't schedule tasks for empty "NOOP" nodes.
Currently a lot of the nodes in the new dependency graph are empty placeholders
for organizational purposes. These nodes would, however, still be assigned a task
which gets scheduled and takes up some time for worker threads to pop from the
queue and run. This can be avoided by skipping these nodes during depsgraph
scheduling, and scheduling their childrent right away. Gives a few percent speedup
in BlenRig.
2016-04-28 12:10:58 +02:00
aaf5ee73f0 Fix for O(N^2) runtime tagging in the new depsgraph.
Some of the tagging functions would be called for every operation, and then
in turn tag their ID nodes with all their operations again. With extensive rigs
we get ID nodes with a lot (10,000+) operation nodes, which leads to millions
of unnecessary tagging calls.
2016-04-28 12:03:26 +02:00
8a379e3460 3D Text: avoid checking null character's text on path
Redundant and causes complications when improving text code.
2016-04-28 15:56:41 +10:00
42e6477129 Image view selected didn't account for region size
Now fit the selection with a 1.4x margin (matching 3d view).

Also move border fitting into own function.
2016-04-28 13:46:51 +10:00
6e94ec623d BMesh: limited-dissolve, add check for wire edges
Recent degenerate check crashed on chains of wire edges
2016-04-28 12:50:12 +10:00
2b485e21f4 Minor code simplification in previous commit. 2016-04-27 22:58:00 +02:00
cc692c0924 Fix compiler warning on OS X / clang. 2016-04-27 21:41:40 +02:00
dd8a7342bc Nodes: sort builtin compositor/shader/texture nodes alphabetically in menus
Reviewed By: lukastoenne, dingto, Severin, carter2422

Differential Revision: https://developer.blender.org/D1957
2016-04-27 21:37:14 +02:00
c0ae38f656 Fix artifacts w/ low near clear in bglPolygonOffset 2016-04-27 19:53:24 +10:00
7f0cf3ab38 Sequencer: skip text-effect rendering w/ no alpha 2016-04-27 15:55:50 +10:00
0912bffb84 Sequencer text strip color options
D1930 by @NiKoZLaB
2016-04-27 15:49:13 +10:00
01cdd22a52 Fix alpha blending w/ font drawing & byte buffer 2016-04-27 15:47:49 +10:00
d74957d38c Fix mask active-point being lost on load/undo 2016-04-27 14:34:54 +10:00
ed0db62a3d Mask: always add a new spline when adding a new vert
Previously, adding a new vertex with Ctrl-LMB would move an existing
when there was an active spline but no active point.

This function is used as a fallback, extending an existing active point is already handled.
2016-04-27 14:11:07 +10:00
32e20369a5 New mask points now compensate parent offset 2016-04-27 13:54:48 +10:00
6483b9cb07 Fix T48282: Newly added mask points don't follow parent 2016-04-27 13:12:55 +10:00
9bd51735a1 Cleanup: use const, duplicate header 2016-04-27 13:12:55 +10:00
c2cdc67375 Fix Cycles GLSL image texture node not respecting color space property. 2016-04-27 00:26:06 +02:00
2b3657a838 Code cleanup: minor cleanups for GPU_link return values, normal map node. 2016-04-27 00:09:44 +02:00
1da0d0042a Fix Font filebrowser not showing thumbnails when those are enabled by default in userpref.
Reported by Leon Cheung over IRC, thanks.
2016-04-26 17:18:37 +02:00
bb74e0774c Fix T47992: Stereo 3D Anaglyph rendered Images saved too light 2016-04-26 17:15:33 +02:00
f172f2b146 Cycles: Improve logging about motion blur a bit 2016-04-26 16:17:11 +02:00
ab500eb3f3 Hair edit: Add operator to uniform length of selected hairs
Request by Andy, should help him a lot doing weird and wonderful hair styles.

A bit experimental yet, details of behavior might be changed after some real
usage feedback.
2016-04-26 16:08:06 +02:00
96392c33ef Correct error in recent snap-context commit
Edges currently don't use a BVH-tree,
but would still create and attempt to free the tree.
2016-04-26 23:02:44 +10:00
680b135ec1 Fix T48176: Shrinkwrap crashes when multiple objects uses same target
Annoying bug caused by temp nature of looptri layer for CCGDM.

Fixed in a similar to CCG loops by using lock when allocating and
filling looptri arrays.

Real fix would be to make sure this array is allocated on object
evaluation using DAG's eval_flag, but that's more involved change
which we'll work on later.
2016-04-26 14:44:49 +02:00
86b8c8a042 Fix (unreported) possible freed memory usage when reloading a .blend file.
Operator would call `WM_file_read()` directly whith G.main->name as filepath, which
gets freed whith main during new reading of file... Now use a local copy instead.
2016-04-26 14:27:32 +02:00
2a63ef03f0 Fix missing pose bone hash table in stub poses of action constraints.
This is a follow-up fix for rBa10b2fe. The Action constraint uses a hackish
stub object and pose, which doesn't have a hash table for fast lookups.
This doesn't seem to be a big issue with the old depsgraph, but in the new
depsgraph it creates a large number of cache misses and significant slowdown,
possibly because of additional threading and less simple bone loops.
2016-04-26 14:16:28 +02:00
5abae51a6e Support multiple tangents for BI render & viewport
Normal Map node support for GLSL mode and the internal render (multiple tangents support).

The Normal Map node is a useful node which is present in the Cycles render.
It makes it possible to use normal mapping without additional material node in a node tree.
This patch implements Normal Map node for GLSL mode and the internal render.

Previously only the active UV layer was used to calculate tangents.
2016-04-26 20:43:29 +10:00
98babfa2b8 Fix T48211: Modifying an F-Curve modifier property is not updating the 3D window 2016-04-26 12:15:05 +02:00
2942a492f4 Fix T48259: Vertex painting doesn't trigger refresh of cycles rendered viewport 2016-04-26 11:15:28 +02:00
0f8290ad0e Fix UI message typo. 2016-04-26 10:13:02 +02:00
7b9743261d Minor cleanup in object select code
- break when object in hit-buffer.
- don't measure distance to object centers that can't be projected.
- take pixelsize into account for distance pixel distance limit.
2016-04-26 14:33:31 +10:00
bd40ded9f6 Fix T48203: Pose-Mode overrides Alt-RMB menu select
Now always use menu-select when using Alt-RMB
2016-04-26 14:24:52 +10:00
5b28fdb635 Cleanup: use const for outliner args
Also c99 edits for outliner_find_id
2016-04-26 13:09:42 +10:00
27cc015581 Outliner: "Show Active" support for active bone
Resolves T48229
2016-04-26 12:56:47 +10:00
45d9c9de35 UI messages fixes - no final point ;) 2016-04-25 20:16:34 +02:00
6a7378f50f Cycles: Proper pack of leaves which are bigger than single float4 2016-04-25 18:57:37 +02:00
a10b2fefab Fix for missing pose bone hash in the new dependency graph.
The hash table is used to look up bone poses, particularly during constraint
evaluation. Without this the default BLI_findstring method on a plain ListBase
is used, which is really slow for extensive rigs.
2016-04-25 15:41:03 +02:00
3ac2028df0 Fix T48202: Project paint hangs on UV's w/ sharp corners
Using 'shell-thickness' to offset UV's meant very sharp corners would offset far outside the image
causing project-paint to hang while collecting all pixels for each UV face.

Clamp the maximum offset to prevent this.
2016-04-25 22:21:30 +10:00
42fd1b9abe Cycles: Fix issues with stack allocator in MSVC
Couple of issues here:

- Was a bug in heap memory allocation when run out
  of allowed stack memory.

- Debug MSVC was failing because it uses separate
  allocator for some sort of internal proxy thing,
  which seems to be unable to be using stack memory
  because allocator is being created in non-persistent
  stack location.
2016-04-25 13:50:27 +02:00
34f4c31692 Cycles: Move vector re-allocation out of loops 2016-04-25 12:25:30 +02:00
beaa57d269 Refactor BKE_blender into separate headers
- BKE_blender_version.h (only version defines & versionstr).
- BKE_blender_copybuffer.h (currently only used for view3d copy/paste).
- BKE_blender_undo.h (global undo functions).
- BKE_blendfile.h (high level blend file read/write API).
2016-04-25 19:27:45 +10:00
935998312c Fix T48085: Select linked w/ seam delimit gives random results
This changes behavior so seams aren't used for the bmesh walker.
2016-04-25 18:44:11 +10:00
975a224f12 Cycles: Don't pass RNA pointers by vlaue 2016-04-25 10:04:06 +02:00
fc5a37b94e Recent pydriver update missed setting 'curval'
Using PyObject's for drivers (82b0a9e36) still needs to set the 'current value'
for debug info to display in the UI.

Resolves T48251
2016-04-25 15:27:51 +10:00
45835e227e Cleanup: use bool 2016-04-25 14:57:25 +10:00
e76f94e0fb Fix T48263: Armature modifier crash w/ non-armature objects 2016-04-25 14:41:11 +10:00
727f15f7d8 Docs: note that BMesh loops are accessed via faces
Resolves T48258
2016-04-25 11:57:52 +10:00
Julian Eisel
26564ff343 Event system: Let event pass through after menu poll fails
Part 2 of Fix for T48200. Without this, it's not possible to exit GPencil edit mode using tab key with pies enabled.

Menus are somehow similar to operators, which let the event pass through too after operator poll returns 0. So think we should handle them similar here.
Can't guarantee this is totally safe though ;)
2016-04-23 17:24:00 +02:00
35be6d87e8 Cleanup: cmake 2016-04-24 00:16:44 +10:00
39873891bf Fix T48250: suppress CMake ranlib warnings to avoid issue with Qt Creator
Reviewed By: campbellbarton, brecht

Differential Revision: https://developer.blender.org/D1942
2016-04-23 15:52:38 +02:00
Julian Eisel
16316115da Fix weird wording in driver operator tooltip 2016-04-23 15:12:20 +02:00
57d98a8048 PyAPI: support writing compressed library blends 2016-04-23 22:08:42 +10:00
a3d67456cd GHOST/X11: print description of error event 2016-04-23 18:44:17 +10:00
ab3c1de56d Fix T48173: event.mouse_prev_x/y unreliable. 2016-04-23 03:05:48 +02:00
23a9fede69 Fix T48216: Cycles light fallof node gives black emission in baking. 2016-04-23 02:59:40 +02:00
c41b2bd7c6 Fix T48223: 3D View not refresh after changing Blending mode in NLA.
This fixes a lot of things in NLA RNA update handling (which basically did not update anything previously).

There are more update issues with this editor though...
2016-04-22 16:48:57 +02:00
f69b364b88 Fix (unreported) crash when listing available fmodifier types.
Some types are defined but not yet implemented...
2016-04-22 15:23:59 +02:00
a2779a4606 Fix T48230: Home key when only one keyframe makes the DopeSheet acting weird.
Simply apply same minimal range as in graph editor when we get a zero one from keyframes.
2016-04-22 14:39:37 +02:00
f4ecd24f96 Fix curve snap to surface w/ offset & taper
Adjusting the pressure wasn't re-adjusting the offset.
2016-04-22 21:34:04 +10:00
c12e1a09ec BLF: use float vector passing color args 2016-04-22 20:02:41 +10:00
a9729e6d75 Fix T48236: OpenVDB smoke cache glitches out with smokeless flames.
Issue was that before writing to disk grids are clipped against the
density field's tree to optimize for memory/disk space, which in the
case of simulations with no density field results in all grids having
empty trees.

For now avoid clipping against empty grids, but perhaps in the future it
can be interresting to have some UI parameters to let the user choose
the grid used for clipping.
2016-04-22 11:46:02 +02:00
87dcee0c0c Silence some annoying warnings when doing full build with strict flags
This mainly touches extern libraries and few debug-only places in intern.

Some summary:

- External libraries are not strict at all about missing declarations,
  so we can rather safely remove such warning together with other strict
  flags.

- Bullet has some static functions which are not used.
  Those were commented out.

- Carve now has some unused debug-only functions commented out as well.
  While we're on the way of getting rid of Carve, it makes sense to make
  things a bit cleaner for the time being.

- In LZMA we have some parts disabled which gives some set but unused
  variables which is rather correct.

- Elbeem had quite some variables set and never used because their usage
  is inside of debug-only code which is commented out.

Note about patching upstream libraries: surely one might say that we
have to make local patchset against this, but own experience says it
only gives extra work trying to merge such tweaks to a new upstream
version and usually it's just faster to re-apply such fixes again after
bundling new upstream library.
2016-04-22 10:59:15 +02:00
d2cb0f955b Cycles: Reduce verbosity of logging
Mainly makes logging less verbose when doing progressive sampling in viewport.

Such kind of verbosity is not really possible to be filtered out with `grep`
so let's reshuffle few lines of code.
2016-04-22 10:55:26 +02:00
31632e7f74 NDof device: Check for socket exists before connecting to spnavd
This allows us to get rid of annoying and misleading error printed to the console
about being unable to connect to something.
2016-04-22 10:14:30 +02:00
599b7ad13b Transform Snap: optionally cache the BVH tree
Use the SnapObjectContext to store the bvh tree for reuse.
2016-04-22 16:38:49 +10:00
19e5540ff7 Transform Snap: initial snap context refactor
This introduces a snap-context that can be re-used for casting rays into the scene
(by operators such as walk-mode, ruler and transform code).

This can be used to cache data between calls too.
2016-04-22 16:36:53 +10:00
8dcdde52b1 Cleanup: warnings (double promote, string format) 2016-04-22 12:22:58 +10:00
0b349871d8 Fix T48212: Typos in bpy enum props examples. 2016-04-21 12:16:32 +02:00
7205bac989 Update install_deps.sh for ArchLinux.
The script is updated for ArchLinux, since all dependencies are included in Arch's official repositories.

I've made a few changes, such as enabling OCIO and OSD without requiring locally installed lib-path, and a fix to ''get_package_version_ARCH()' so it ignores package epoch (as in the case of ffmpeg).

I intend to look at OpenVDB next.

Reviewers: mont29

Differential Revision: https://developer.blender.org/D1901
2016-04-21 10:44:46 +02:00
c0943babdf Cleanup: math lib use w/ walk mode 2016-04-21 12:43:35 +10:00
22f2405d1b Mesh Deform Modifier - leave bind settings visible after binding
The 'precision' and 'dynamic' settings for binding are now always visible.
The settings that can not be edited after binding are disabled (not inactive).

I find it useful to see with what settings a mesh was bound, in case
the file is not mine or if I simply lost track of it.
2016-04-20 19:51:59 +01:00
9bd1c8caf7 Cycles: Multi-thread object transform update
Simple idea, use threads when dealing with "Copying Transformations to device"
scene update step. Only do it if there's enough objects in the scene.

Hopefully only brings less synchronization time and doesn't break anything.

From tests on my desktop this brings down transform update time from 58sec to
11sec on victor_cpu.blend scene from out benchmark.
2016-04-20 18:17:24 +02:00
02213b867e Cycles: Stop rendering when bad_alloc happens
This is an attempt to gracefully handle out-of-memory events
and stop rendering with an error message instead of a crash.

It uses bad_alloc exception, and usually i'm not really fond
of exceptions, but for such limited use for errors from which
we can't recover it should be fine.

Ideally we'll need to stop full Cycles Session, so viewport
render and persistent images frees all the memory, but that
we can support later, since it'll mainly related on telling
Blender what to do.

General rules are:

- Use as less exception handles as possible, try to find a
  most geenric pace where to handle those.

  For example, ccl::Session.

- Threads needs own handling, exception trap from one thread
  will not catch exceptions from other threads.

  That's why BVH build needs own thing.

Reviewers: brecht, juicyfruit, dingto, lukasstockner97

Differential Revision: https://developer.blender.org/D1898
2016-04-20 16:19:49 +02:00
e3544c9e28 Cycles: Throw bad_alloc exception when custom allocators failed to allocate memory
This mimics behavior of default allocators in STL and allows all the routines
to catch out-of-memory exceptions and hopefully recover from that situation/
2016-04-20 15:49:52 +02:00
d7e4f920fd Cycles: Use threads to sort reference arrays when searching for split
This commits implements threaded sorting of references when looking for
object spatial split. It mainly useful when doing initial binning, which
happens from main thread.

Gives nice speedup of BVH build for Bunny.blend: 36sec vs. 55sec for
the Rabbit mesh BVH build.

On more complex scenes the speedup is probably minimal, but still nice
to have more instant rendering for simplier scenes.

Some further tests with production scenes would be interesting.

Reviewers: juicyfruit, dingto, lukasstockner97, brecht

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1928
2016-04-20 15:21:44 +02:00
96dc96f0a5 Cycles: Avoid reference copy 2016-04-20 15:03:39 +02:00
48c9208d56 Fix T46903: Missing Render Border Menu items
While other borders are more like a toggle, it is an intrinsic behavior
of those operators. Render Border is intrinsicly split into two operators
and trying to expose it as a toggle will end up with rather confusing
situation when shortcut listed in the menu changes depending on the
context.
2016-04-20 15:02:03 +02:00
e50d229273 Fix T47794: Point density sometime seems stretched when rendered on GPU 2016-04-20 14:42:19 +02:00
b9d9d93ff9 Fix T48162: GPU render gives wrong results in certain volume setups
ideally this part of code should be de-duplicated across __VOLUME_INTERSECT_ALL
and regular code.
2016-04-20 13:49:54 +02:00
4cdd6b9bdd Fix T47812: GPU renders have warmer colors than CPU renders
Seems was a mistake in f2c54df, volume attributes are not supposed to
have repeated texture type.
2016-04-20 12:29:08 +02:00
75c9fe428f Update bundled openjpeg from 1.5.0 to 1.5.2
Solves following issues:

- Quite reasonable amount of paranoid warnings were solved by an upstream
- Upstream seems to have all fixes needed for FreeBSD and OSX already
- Brings all fixes and such from upstream
2016-04-20 10:36:58 +02:00
81a477f4dc Fix T47891: Edges throw shadow in edit mode 2016-04-20 12:59:00 +10:00
4ee5ba41bb Fix T48086: Smart UV Project fails w/ small faces
Epsilon for small faces was too large.

Also suppress exception when all faces area are below the epsilon.
2016-04-20 11:51:03 +10:00
dbf1257b14 Minor optimization for scanfill
Replace angle with with cosine calculation.
2016-04-20 09:53:40 +10:00
38442ae2dc Fix image-space mask-transform crash w/o an image 2016-04-20 09:37:51 +10:00
2ca4d21976 Cleanup: rename cos-angle to match BLI_math 2016-04-20 07:50:48 +10:00
bde7439816 Minor optimization for limited-dissolve
Use dot product instead of angle.
2016-04-20 07:50:48 +10:00
ccbfbeba74 Fix crash in rB37493fb9f - there is no guaranty CTX_wm_foo() will return a valid pointer! 2016-04-19 22:53:18 +02:00
11c9ff1edd Cleanup unused header includes from previous commit. 2016-04-19 22:53:18 +02:00
52e09ed4f9 Cleanup: move operators & related code of files & append/link to relevant dedicated source files.
This commit adds a new `wm_files_link.c` which contains everything related to append/link code,
moved from `wm_operators.c` (rather small currently, but will expand quite a bit with future reload & asset works).

It also moves all load/save .bland files (and related userpref/startup stuff) from `wm_operators.c`
to `wm_files.c` (some helper funcs were already there).

This also makes `wm_operators.c` significantly lighter.
2016-04-19 22:53:18 +02:00
Julian Eisel
dd423a6818 Fix T48198: Missing plus sign to open the tool shelf in text editor
Did not happen when using screen layout saved in default startup.blend
2016-04-19 21:01:55 +02:00
Julian Eisel
37493fb9fe Toggle to standard cursor when opening menus/popups
Cursor is now set to standard arrow-cursor when opening menu, and reset to previous one when closing it. Previously it just stayed as it was before, e.g. the edit mode cross-cursor stayed active even if a menu was opened.

Fixes T48192.
2016-04-19 16:17:34 +02:00
9b48f2b27c Cycles: Improvements and fixes for the resumable render
- Fix wrong current sample reported in the log
- Also includes fix for progressive refine log
- Explicitly print to the stdout that resumable render is enabled
- Print error message and abort when passing wrong values for the
  resumable render. Never waste someone's compute power for wrong
  render!

Fixes T48185: Cycles resumable num chunks breaks sample counter
2016-04-19 12:56:33 +02:00
376c8dd95e Fix T48193: Incorrect keyframe_insert docs 2016-04-19 18:25:56 +10:00
7cc9f6b6f8 Minor edits to last commit
Avoid redundant tests
2016-04-19 13:07:01 +10:00
12b0c03e49 Fix T47998: Limited dissolve fails /w holes
Holes with flat surfaces could have their edges dissolved causing degenerate faces.
Now check that collapsing a vertices isn't creating self-overlapping faces.
2016-04-19 12:18:19 +10:00
74b0591d42 Cleanup: pass event args as const 2016-04-19 12:18:19 +10:00
3068ea34e4 Cycles microdisplacement: add max subdivision setting
This is to prevent situations such as when the camera gets very close to a mesh
and causes it to be tessellated into an excessive amount of micropolygons. In
REYES this is known as the eye-splits problem.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1922
2016-04-18 22:47:24 +02:00
71588300d2 Cycles microdisplacement: fix handling of triangles in DiagSplit
Theres still more room for improvement but this makes things useable.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1921
2016-04-18 22:31:12 +02:00
c42a796e9f Fix: Make it easier to tell if Color Swatches are greyed out or not
This commit makes disabled/inactive color swatches look more obviously disabled
by halving their alpha values. It is necessary because the results of
ui_widget_color_disabled() (which is usually used when disabling widgets)
get overwritten by the color filling code here.

To avoid confusion, the checkerboard background (when the color genuinely has
alpha) will still only show in those cases. That is, when disabled, color swatches
won't show the checkerboard unless the color actually has an alpha component if it
wasn't disabled.
2016-04-19 00:42:59 +12:00
2aafadd4ac Fix T48186: Grease Pencil Smooth brush doesn't work properly - "erase" the stroke thickness
As soon as you started trying to smooth a stroke, the thickness of the stroke
would quickly drop right down to near zero, if "affect pressure" was enabled.

This step got accidentally missed when restoring the affect pressure functionality to
the stroke smoothing brush code, following cleanups from the stroke quality patch.
2016-04-19 00:18:46 +12:00
9f39619dda Cycles microdisplacement: scene level render and preview dicing rates
This makes it easier to control overall dicing rate without having to tweak
every object. The preview rate makes viewport editing more interactive. The
default preview rate of 8 is roughly 64 times faster for some operations.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1919
2016-04-17 20:38:50 +02:00
facc127e72 "View Frame" now works in the sequencer too 2016-04-17 12:27:12 +12:00
1dfbcd88d5 Fix a few compiler warnings with OS X / clang. 2016-04-17 01:05:50 +02:00
667a5ef48e Fix T48171: activating spacebar search menu over text button activates it or shows tooltip. 2016-04-17 00:40:01 +02:00
557544f2c4 Cycles: Refactor Image Texture limits.
Instead of treating Fermi GPU limits as default,
and overriding them for other devices,
we now nicely set them for each platform.

* Due to setting values for all platforms,
we don't have to offset the slot id for OpenCL anymore,
as the image manager wont add float images for OpenCL now.

* Bugfix: TEX_NUM_FLOAT_IMAGES was always 5, even for CPU,
so the code in svm_image.h clamped float textures with alpha on CPU after the 5th slot.

Reviewers: #cycles, brecht

Reviewed By: #cycles, brecht

Subscribers: brecht

Differential Revision: https://developer.blender.org/D1925
2016-04-16 20:49:59 +02:00
b973911fee Anim Editors: "View Frame" Operator - Code Cleanups/Reshuffling + NLA/Timeline Support
* Reshuffled code for existing "View Frame" implementations, and removed leftover
  comment from some of the the copy-and-paste used to build it.
* Added support for this operator in the NLA and Timeline
2016-04-17 03:44:10 +12:00
5d6b695f00 Assorted enum tweaks
* Knock out "Python" FModifier entry - It really hasn't been coded yet!
* Add icon for "Match Indices" driver eyedropper mode. It should help provide
  a bit more of a hint of what it does, but it also doesn't look quite as nice now.
2016-04-17 03:29:29 +12:00
b49fd60060 Experimental Drivers UI Tweak: Use icons for variable types
This commit aims to streamline the driver variables layout a bit
* Each variable type now has an icon. (The loc diff and rot diff ones are placeholders,
  which could deserve something better/dedicated if we continue to use this)
* Instead of taking up an entire row, the variable type dropdown now only shows
  an icon, and is located before the variable name field.

Feedback wanted: Is this more/less confusing than it was?
2016-04-17 03:29:28 +12:00
4572d4d861 Tweaks to Streamline Drivers UI - Don't use uiTemplateAnyID for properties where only objects can be used 2016-04-17 03:29:28 +12:00
64c7306cdb Cycles: Insert util_texture.h in CMakeLists to make Cycles compile again after recent refactory. 2016-04-16 11:58:38 +02:00
9c916b0172 Cleanup: Move texture definitions to util, to avoid bad level include. 2016-04-15 23:02:44 +02:00
34c99fa30a Curve draw fix w/ surface offset + only-first enabled
In this case the initial offset needs to be applied to the rest of the stroke.
2016-04-16 06:47:37 +10:00
6bc2ba2111 Fix T48157: 3D view's depth of field isn't displayed correctly with scene units scale.
focus distance is given in BU, no need to scale it at all.
2016-04-15 16:24:19 +02:00
3165e8740b Fix T48139: Checker texture strange behavior in cycles
Seems particular CUDA implementations has some precision issues,
which made integer coordinate (which was expected to always be
positive) to go negative.
2016-04-15 15:30:30 +02:00
177d051126 UI: copy to selected: add 'single'/'all' options to buttons' menu when relevant.
Same as reset or anim keyframe/driver operators... Inconsistency reported by Leon Cheung
through IRC, thanks.
2016-04-15 15:19:19 +02:00
bce4b7c868 Code Cleanup: Fix up various odds and ends 2016-04-16 01:12:50 +12:00
88c071fbb5 Code Cleanup: Remove unused define left over from earlier versions of this code 2016-04-16 01:12:50 +12:00
209cd5db96 Remove a leftover from older code 2016-04-15 15:06:08 +02:00
3130f4167d Cycles: Optimization to spatial BVH build
Simple fix: release lock earlier.

Reduces spatial split build time from 96 to 53sec on the Bunny.blend
(using studio Intel for benchmark).

NOTE: Timing difference is not that spectacular when comparing numbers
with builds before memory optimization, but even then it's about 20%
faster build.
2016-04-15 14:35:42 +02:00
10320891f0 Fix T48151: Brush texture overlay won't refresh automatically in UV editor when changed in buttons window.
Simple solution is to get rid of this stupid `rna_TextureSlot_brush_update` func, and do what it was doing directly
in BR case of `rna_TextureSlot_update`. That way, all updates to brush texture will invalidate correctly the overlay.

Note that this double definition of texture pointer for brushes looks rather fishy, am really not convinced this helps
keeping things simple and clear at all (what happened here is that texture selector in image paint editor was using
'texture' member of brush itself, which was performing correct RNA update, while context-based brush texture selector
from buttons space was using 'texture' member of the TextureSlot struct, which had default texture update callback
which was not invalidating overlay).
2016-04-15 13:19:41 +02:00
8ac662c77a New freehand curve drawing tool
- Access with Shift-LMB or from the 'Create' toolbar tab.
- Uses curve fitting for bezier curves, with error and corner angle options.
- Optional tablet pressure to curve radius mapping.
- Depth can use the cursor or optionally draw onto the surface,
  for the entire stroke or using the stroke start.
- Stroke plane can optionally be perpendicular to, or aligned to the surface normal.
- Optional radius tapering and for start/end points.
- Supports operator redo and calling from Python.
2016-04-15 20:36:38 +10:00
e56e7bd1ec Add lib for n-dimensional cubic curve fitting
This will be used for calculating bezier curves from freehand drawing,
may be used for other areas too.

Original code from GraphicsGems, 1990 (FitCurve.c),
with updates from OpenToonz, under 3 clause BSD license.
with own minor modifications for integration with Blender:
- support adding extra custom-data.
- improved handle clamping.
2016-04-15 20:33:58 +10:00
f951cc36e2 Cycles: Support heat volume attribute
Similar to velocity, it was kind of supported by the mesh manager but
was missing a code in BlenderSession to get actual values.

In Cycles Heat is an attribute which goes from -1 to 1, where -1 is
the coldest ever temperature, 1 is the hottest ever one.
2016-04-15 12:02:31 +02:00
a52b4378b2 Cycles: Improve error print a bit 2016-04-15 11:24:59 +02:00
3fcbb2bb58 Tests: Fix wrong hash after "no redundant zeroes" commit 2016-04-15 10:37:57 +02:00
69ee6c9866 Drivers Editing: Added "Copy/Paste" buttons beside "Add Variable" for copying all variables from one driver to another
This was a feature request from a few years back (IIRC from ZanQdo?) to make it
easier to reuse one set of driver variables across several different drivers.

Dev Notes:
* Finally it's done! All that trouble for two little buttons.
* Grr... cmake... grrr!
2016-04-15 20:05:09 +12:00
c97b0b14e3 NLA Copy/Paste Modifiers: Apply similar fixes as those done in Graph Editor 2016-04-15 20:05:08 +12:00
344c17f439 Fix T42148: Copying/Pasting FModifiers copies to all selected FCurves, not just active one 2016-04-15 20:05:08 +12:00
26e8798561 FModifiers: Various tweaks for consistency + improved behaviour
* Use an RNA enum callback for NLA FModifier types too
* Cleaned up tooltips for these operators in Graph and NLA editors
* Fix update notifiers after adding FModifiers in the Graph Editor
2016-04-15 20:05:07 +12:00
35a089d960 FModifiers: "Add Modifiers" in Graph/NLA Editor buttons now uses a dropdown instead of a button
This brings the UI here more in line with the Constraints and Modifiers UI's.

TODO:
* The tooltips/descriptions on the operators now need fixing, as we can no longer
  use custom tooltips when defining these buttons.
* The operators need to be fixed to only operate on the active data
2016-04-15 20:05:06 +12:00
6bddad2c4e Code Cleanup: Add proper defines (with ANIM_* prefix) for animation-related copy-paste buffer free callbacks 2016-04-15 20:05:06 +12:00
6401730697 Graph Editor: Move "View" panel to be the last
This change means that when going from having no FCurves active to having
an active FCurve, the properties panels will not get stuck with only showing
the "View" tab, which is not that useful a lot of the time.
2016-04-15 20:05:05 +12:00
b8892cac19 Cycles: Yet another fix for camera in volume
Was an embarrassing glitch in original optimization policy,
the for-loops can't be de-duplicated here.
2016-04-14 17:20:17 +02:00
78c3a5d00f Compositor: Fix image and render layer always extending edges
It was no more possible to translate two images, put one on top of
another in order to do things like mapping VR views.
2016-04-14 11:20:00 +02:00
8ed746683a Remove redundant abs ray/line point functions 2016-04-14 13:04:35 +10:00
416064cd5b Math Lib: ray_point_factor_v3 functions
Gives a bit better precision than creating a line in some cases,
use for ED_view3d_win_to_3d.
2016-04-14 12:00:16 +10:00
bbcb9c68c9 Cycles: Resolve ridiculous amount of memory used by spatial split builder
This was only visible on systems with lots of threads and root of the issue
was that we've been pre-allocating too much memory for all the threads.

Now we only pre-allocate data for the main thread and rest of the threads
does allocation on-demand.

This brings down memory usage from 36Gig to 6.9Gig when building spatial
split for the Bunny.blend file on our Intel beast.

Originally regression was happened by the threaded spacial split builder
commit.
2016-04-13 14:25:21 +02:00
9604db7650 Fix T47813: Cycles Standalone not respecting integrator sample_clamp_direct 2016-04-13 10:39:21 +02:00
c8e2cc21ab Cleanup string includes after versioning commits 2016-04-13 09:45:32 +02:00
3156055e27 Show version number in UI as well 2016-04-13 09:45:30 +02:00
bd7e4d2a3d Tweaks to the version string formation
Couple of things:

- No need to use string streams to format the version string,
  we can do it at compile time and don't bother with anything
  at runtime.

- Function declaration was wring and would have caused linking
  conflicts in cases when util_version.h was included from
  multiple places.

We should have an utility function to get Cycles version so
applications which are linked to Cycles dynamically can query
the version, but that can't be done as an inlined function in
header and would need to be a function properly exported to a
global symbol table (aka, be implemented in a .cpp file).
2016-04-13 09:45:26 +02:00
ed050753ce Add a version number to Cycles standalone
Now Cycles has its own versioning, that is mainly interesting for external projects, which integrate the engine.

We start with version 1.7.0. Reasons for that:

* The engine is too mature for a 1.0 release.
* We assume that Cycles inside of Blender 2.61 was version 0.1. We count upwards in 0.1 steps, therefore Cycles inside of Blender 2.77 would be 1.7.

We use a common versioning scheme here, with 3 decimals for the major, minor and patch level.

At the moment cycles --version can be used to display the version, easy to parse for external projects. The info will be added to the UI later aswell.
2016-04-13 09:45:23 +02:00
84c68dcb3f Cycles: Minor cleanup, whitespace around keyword and preprocessor indent 2016-04-13 08:58:52 +02:00
c1a27a76cf Cycles microdisplacement: preserve smooth normals for linear subdivison
This way we prevent cracks in the model due to discontinuous normals, by using
smooth normals for displacement instead of always getting flat normals after
linear subdivision.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1916
2016-04-13 01:37:33 +02:00
068ee2cd98 Fix T47754: Meshes glitch on cycling Viewport Shading mode with Linked Groups
This is a regression since 4310128 which is cased by really bad logic:
there might be dependencies between dupli-objects, which means _if_ we
really want to ensure derived mesh on dupli creation we have to do it
before any matrix is overwritten.

I'm not sure if such derived mesh trick is really the only way to go
without major refactor, but seems simple fix for now will do it.
2016-04-12 17:16:36 +02:00
3a977ff502 Missed last commit 2016-04-13 00:49:47 +10:00
6cc953fb74 Correct UI messages: hyphenate 'add-ons' 2016-04-13 00:30:38 +10:00
951fad2baa Cycles: Add missing velocity attribute to builtin image loader
For some reason other parts of blender importer were assuming velocity
is supported, but actual loader was not aware of that.

Fixes T48064: Adding velocity attribute crashes render
2016-04-12 13:26:21 +02:00
19539c50c9 Cycles: Avoid crash when accessing non-existing volume attribute 2016-04-12 13:26:21 +02:00
f636b8bfc0 CMake: consistency check now reports stale ignores
Also update ignore list.
2016-04-12 20:12:29 +10:00
d4979f1d66 Remove exception for file which no longer exists 2016-04-12 11:55:44 +02:00
5231b049d7 Fix T47443: Circle & UV Sphere aren't aligned
D1912 by @samb96

Change the starting point of the UV sphere so that it is aligned with the circle, cylinder, and cone primitives.
2016-04-12 19:47:29 +10:00
dc7d6643e1 Remove any wrangler utility scripts 2016-04-12 11:07:23 +02:00
4fae162bce CMake: ignore header 2016-04-12 18:50:08 +10:00
b1ef786a73 CMake: Partially revert recent missing headers commit
The header which was put to the CMake project is not by any means used
during compilation, it is only used when manually updating CUDA wrangler
from CUDA headers.
2016-04-12 08:54:34 +02:00
4a64b36029 Cleanup: use bool 2016-04-12 11:26:06 +10:00
a2db16ba58 CMake: add missing headers 2016-04-12 11:22:30 +10:00
d032c5e46c Cycles microdisplacement: UI tweak to use split column
Reviewed By: brecht, dingto

Differential Revision: https://developer.blender.org/D1917
2016-04-12 00:08:28 +02:00
665467e51e Cycles microdisplacement: refactor to move some tesselation code from SubdMesh to Mesh
Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1915
2016-04-11 23:50:15 +02:00
d456458e06 Cycles microdisplacement: change use subdivision bool to subdivision type enum
This is only the UI change, there is no underlying code change in this commit.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1910
2016-04-11 23:13:51 +02:00
ebfdd7da83 Cycles microdisplacement: perform subdivision dicing in raster space
NOTE: this is only the first of many patches towards completing the subdivison
and displacement system in Cycles. These patches will be reviewed and committed
one by one over the coming weeks.

Reviewed By: brecht, sergey

Differential Revision: https://developer.blender.org/D1909
2016-04-11 23:12:11 +02:00
7d033717ad Cycles: Cleanup, make some comments easier to read on split editors 2016-04-11 18:00:42 +02:00
ac00c17900 Cycles: Remove hair support from volume BVH traversal
There are couple of reasons:

- Volume shader on hair does behave really weird anyway and it's
  not something considered a bug really.

- Volume BVH traversal were only used by camera-in-volume check,
  which doesn't really make sense to take hair into account since
  it'll be rendered wrong anyway.

Such a removal makes both code easier to extend further (as in,
no need to worry about those traversal for hair bvh) and also
reduces stress on GPU compilers.
2016-04-11 17:18:14 +02:00
e4cdda548a Cycles: Remove unused SAH from BVH pack 2016-04-11 17:18:14 +02:00
6cd13a221f Cycles: Rename tri_woop to tri_storage
It's no longer a pre-computed data and just a storage of triangle
coordinates which are faster to access to.
2016-04-11 17:18:14 +02:00
e5a2790ecb Fix T48084: Solidify uses alternate quad-direction
This prevents twisted quads from self-intersecting.

This change makes the duplicate surface match the first vertex in the face,
so the diagonal indices match in the face copy.
2016-04-11 23:04:11 +10:00
90271e7ff1 Fix T48082: Unwrap overwrites face selection
Sync selection option made adding a new UV layer select all edit-mesh faces.
Now just select the UV's, ignoring sync-select option.
2016-04-11 20:27:10 +10:00
45a089c138 Fix T48103: Wrong renders on AMD OpenCL when Light Falloff node is used 2016-04-11 10:54:41 +02:00
2050ecc307 BGE: Fix T48071: Global logic manager
Previously the logic manager was used as a global variable for SCA_ILogicBrick::m_sCurrentLogicManager,
this request to always update it before run any python script and allow call function like
ConvertPythonTo[GameObject/Mesh]. The bug showed in T48071 is that as exepted the global
m_sCurrentLogicManager is not updated with the proper scene logic manager.
Instead of trying to fix it by updating the logic manager everywhere and wait next bug report to add
a similar line. The following patch propose a different way:
- Every logic brick now contain its logic manager to SCA_ILogicBrick::m_logicManager, this value is
  set and get by SCA_ILogicBrick::[Set/Get]LogicManager, It's initialized from blender conversion and
  scene merging.
- Function ConvertPythonTo[GameObject/mesh] now take as first argument the logic manager to find name
  coresponding object or mesh. Only ConvertPythonToCamera doesn't do that because it uses the
  KX_Scene::FindCamera function.

Reviewers: moguri

Differential Revision: https://developer.blender.org/D1913
2016-04-10 23:57:43 +02:00
3a80d5e1d0 Cycles: Fix rare dead-locks on TaskScheduler::exit()
When the Moon is full it was possible to have a dead-lock in task
scheduler's  exit() method.

Similar problem was fixed in Blender's task scheduler 3 years ago
in bae2a2c.
2016-04-10 21:18:54 +02:00
50f9681e15 Docs: comment on line-sphere intersection 2016-04-10 22:46:12 +10:00
019ce363b0 Cleanup a bit particle distribution code.
Also do proper intial/final checks to avoid adding particle on zero-weight extreme items,
instead of using cheap tricks like 'small offset'...
2016-04-09 22:46:27 +02:00
950acb0ced Fix T47983, Take II: Particles - Emit from Verts emits double on one vert.
Previous fix made another issue even more visible, leading to +1 particle on first vert
and none on last one. This commit should fix both original and new issues.
2016-04-09 18:59:05 +02:00
d09a372acb Fix T48078: incorrect OS X command for retrieving number of CPUs on in Makefile. 2016-04-09 00:25:18 +02:00
c1d1c1dc6b Fix T48088: Reproducible crash: Edges + Array Mod + Hair Particles.
Code did not consider the possibility to have no face at all! :P
2016-04-08 16:26:42 +02:00
a5dcda8ad3 Fix broken by D1880 line stipple deactivation 2016-04-08 12:20:43 +03:00
d969192fbe Wide lines + line stipple deprecated API replacement
The patch contains an implementation of the wide lines and the line stipple that is necessary for OpenGL upgrade.

For the implementation I have chosen the geometry shader because it required minimum changes for the wrapper calls and such implementation is the best for the "basic shader" architecture.

There are few shortcomings that can be corrected in future. They all are related to the fact that the lines in one strip are not connected with each other. So the stipple pattern is not continuous on the common vertex of two lines. There is also no continuity of form (each line is an independent rectangular).
But the advantage is that even outdated glBegin, glVertex work! Though with the above restrictions.
Continuity of form and stipple can be implemented with additional attributes, and it will require more changes in calls.

At the moment, the patch replaces calls for some "gestures". It works satisfactorily for "cross" or "rectangular" and not so good for "lasso" and "circle" due to the above-mentioned shortcomings.

Don't forget to set USE_GLSL to true for testing.

Alexander Romanov (Blend4Web Team)

Reviewers: merwin, brecht

Reviewed By: merwin, brecht

Subscribers: aligorith, Evgeny_Rodygin, AlexKowel, yurikovelenov

Differential Revision: https://developer.blender.org/D1880
2016-04-08 10:58:40 +03:00
a51e9ece53 Cycles: Fix misleading remaining time report when using infinite number of samples in viewport 2016-04-06 16:30:52 +02:00
d6ae94b988 Cycles: Fix compilation error of Hair BSDF GLSL shader 2016-04-06 15:40:55 +02:00
42824f4403 Fix missing viewport update when tree output is in a node
There was already an attempt to do it, but it worked incorrect because
of wrong recursion check.
2016-04-06 15:23:26 +02:00
e10ec6ee9a Cycles: Avoid possibly uninitialized variable 2016-04-06 10:51:04 +02:00
5ddf6ca87a Quiet warning for release build 2016-04-06 18:26:39 +10:00
9e3b0350f5 Fix leak w/ missing external mesh customdata 2016-04-06 16:14:30 +10:00
78d39cad8b Tweak fill-region method to produce fewer 'gaps' 2016-04-06 15:07:37 +10:00
16597b691a Fix camera view-border line width 2016-04-06 14:27:37 +10:00
28dad2ec12 Correct error checking for wrong frame range 2016-04-06 09:41:30 +10:00
f5fb4361d2 Cleanup: indentation 2016-04-06 09:30:20 +10:00
cc970dc08a Cleanup: arg docstrings 2016-04-06 09:28:22 +10:00
16f919ea58 Render frame arg parsing, list and range support
Support a comma separated list of frames, as well as frame ranges using the '..' separator.

eg: `blender my.blend --render-frame 1,2,10..40,100..200`
2016-04-06 09:23:15 +10:00
Reinier de Blois
c084520b03 Expose new Recast partitioning methods for navmesh generation
This patch depends on D1747, which upgrades the Recast version.  It exposes the new Recast partitioning methods in the navmesh generation.

Reviewers: campbellbarton, moguri

Reviewed By: moguri

Projects: #bf_blender

Differential Revision: https://developer.blender.org/D1748
2016-04-05 21:39:04 +02:00
Reinier de Blois
176538f613 Update Recast version to 1.5.0
The version of Recast that Blender ships with is from 2009.  This patch updates the Recast version to the latest version, 1.5.0.  The Detour version remains untouched.

Reviewers: campbellbarton, moguri

Reviewed By: moguri

Projects: #bf_blender

Differential Revision: https://developer.blender.org/D1747
2016-04-05 21:38:52 +02:00
214e384fc4 Fix UV-Editor crashes w/ over SHRT_MAX UV's 2016-04-05 22:16:09 +10:00
b8ca4819b2 Revert "Cycles: Remove the Preetham Sky model."
This reverts commit d91316dc67.
2016-04-05 12:25:54 +02:00
46aaa53998 Fix T48054: Blender 2.77 doesn't import blenders fbx, due to recent changes in anim RNA API.
Please do not break API when not absolutely needed, here it was a mere parameter order issue...
2016-04-05 11:51:54 +02:00
db28ff54d6 Fix T47705: Freestyle line glitch.
The addressed issue is a regression from Blender 2.75, after the internal
switch from double to single precision floating-point numbers in the
Freestyle code base.  Face normal calculations require the higher
precision during the computations, even though the results can be stored
as single precision numbers.
2016-04-05 16:15:09 +09:00
9c952bbe85 Cleanup: Typo fixes after BVH commits. 2016-04-05 01:20:45 +02:00
82b0a9e369 PyDriver support for all RNA property types
Support for driver variables that don't resolve to numbers, eg:
objects, bones, curves... etc.

Without this, Python expressions to access this data needed to use an absolute path from `bpy.data`,
however this is inconvenient, breaks easily (based on naming) and wouldn't set the dependencies correctly.
2016-04-05 07:38:57 +10:00
65f279b770 Cycles: Fix wrong camera in volume check when domain is only visible to camera rays 2016-04-04 19:30:38 +02:00
ac8f4ba530 Cycles: Fix regression caused by recent camera-in-volume commit
Stupid me forgot that we don't have stop-element in the stack yet.
2016-04-04 18:24:40 +02:00
a3d6552514 Cycles: Fix regular BVH not having proper visibility flags
This was caused by recent threading commit. Now because of all children
are set when they're ready need to explicitly update all parent's visibility.
2016-04-04 18:11:34 +02:00
d82d9e14e8 Fix T48045: Freestyle ID user decrement error.
This fixes reported issue, but there could be more of those hidden in Freestyle code,
it did not handle user refcount at all (and the fact it by-passes BKE in some places
for efficiency does not help here).

Note that this should be relatively harmless, since freestyle uses own Main during
render, so everything is cleaned up in the end in any case... But better try to
handle IDs correctly here too. :)
2016-04-04 15:49:30 +02:00
f76dec9238 Update hash for an OBJ unit test 2016-04-04 15:22:31 +02:00
bf55afbf26 Cycles: Make spatial split BVH multi-threaded
The title actually covers it all, This commit exploits all the work
being done in previous changes to make it possible to build spatial
splits in threads.

Works quite nicely, but has a downside of some extra memory usage.
In practice it doesn't seem to be a huge problem and that we can
always look into later if it becomes a real showstopper.

In practice it shows some nice speedup:

- BMW27 scene takes 3 now (used to be 4)
- Agent shot takes 5 sec (used to be 80)

Such non-linear speedup is most likely coming from much less amount
of heap re-allocations. A a downside, there's a bit of extra memory
used by BVH arrays. From the tests amount of extra memory is below
0.001% so far, so it's not that bad at all.

Reviewers: brecht, juicyfruit, dingto, lukasstockner97

Differential Revision: https://developer.blender.org/D1820
2016-04-04 14:43:21 +02:00
be2186ad62 Cycles: Solve possible issues with running out of stack memory allocator
Policy here is a bit more complicated, if tree becomes too deep we're
forced to create a leaf node and size of that leaf wouldn't be so well
predicted, which means it's quite tricky to use single stack array for
that.

Made it more official feature that StackAllocator will fall-back to
heap when running out of stack memory.

It's still much better than always using heap allocator.
2016-04-04 14:13:19 +02:00
5ab3a97dbb Cycles: Log overall time spent on building object's BVH
We had per-tree statistics already, but it's a bit tricky to see overall
time because trees could be building in parallel.

In fact, we can now print statistics for any TaskPool.
2016-04-04 13:43:19 +02:00
ba7c2b7b73 Cycles: Log allocation slop factor for BVH arrays
Currently they're staying at 1 (actual size over capacity), but we
will be changing it quite soon in order to avoid having too much
memory re-allocation happening at a BVH build time and will be
playing with different policies for that.
2016-04-04 12:56:56 +02:00
5d25579602 Fix missing ID_SO sound type in outliner's ID types.
Note that we may want to review that some day, we have quite a bit of ID types here that are
'blend file' view only, might be worth splitting the check based on this.
2016-04-04 12:35:59 +02:00
61a8d12ccd Cycles: Tweak to stack allocator used by BVH builder
In some files stack memory was overruning the pre-allocated stack.

Perhaps we should fall-back to a hep-allocated stack so release builds
don't crash in works case but just becoming slower.
2016-04-04 12:23:23 +02:00
8cc7460495 Smoke: Don't use min as an uniform name
This is an attempt to fix report T47991.
2016-04-04 11:58:27 +02:00
673ddd48da Cycles: Make curves modified by a taper object with modifier considered a deform modified
That might consider a bit more objects to be considered deform modified,
but it covers common case of using taper object without require of doing
recursive checks.

In worst case it'll be just some extra synchronization time, no render
time difference will happen for false-positive because of extra checks
happening in Cycles.
2016-04-04 11:39:04 +02:00
2f08d5f761 Fix T48002: Wrong behavior with "RGB to Intensity" in Image textures
There was some extra linearization happening in such cases.
2016-04-04 11:30:35 +02:00
f4875bed89 Fix curve editmode adding 3D primitives w/ 2D curves 2016-04-04 18:36:38 +10:00
0a7ed17099 Fix curve adding 3D nurbs when 2D is set
Ctrl-LMB ignored 2D constraint
2016-04-04 18:36:37 +10:00
097b895c2c Fix curve hide keeping spline active 2016-04-04 18:36:37 +10:00
c868945a43 Fix curve, missing update on Ctrl-LMB 2016-04-04 18:36:37 +10:00
3de9b2ca74 Fix curve add-vertex w/ 2D curves
Project the point onto the 2d place where possible.
2016-04-04 18:36:37 +10:00
8f1223b636 Move some debug print under G.debug
It's not like every debug build is benefiting from this print..
2016-04-04 09:58:14 +02:00
c63398e55a Fix uninitialized variable use w/ VSE transform 2016-04-04 12:44:03 +10:00
d91316dc67 Cycles: Remove the Preetham Sky model.
The improved Hosek / Wilkie model was added during my GSoC 2013 and the default since then.

The older model was kinda kept for compatibility, but after more than 2 years it's time to remove it.
The Hosek / Wilkie model is more realistic anyway, and people who really want a day / night transition can mix the Sky Shader with another one (e.g. color) and fade between the two.
2016-04-02 23:36:14 +02:00
74e40663da Fix T47971: rigid body baking crash due to thread race condition. 2016-04-02 13:04:26 +02:00
b03ff0bbf8 Fix T48030: Can't zoom VSE properties panel 2016-04-02 18:52:52 +11:00
e02d0de36e Fix T47505: Cycles OpenCL rendering crash on Windows.
Restore the boost bug workaround, but without changing the locale.
2016-04-01 20:39:07 +02:00
ce44ffd74f Cycles: Fix wrong camera-in-volume stack when camera ray hits volume domain twice 2016-04-01 18:03:58 +02:00
0f6f921898 Cycles: Temporarily revert index sort commit for spatial split
There are in fact some missing parts to it (Split BVH builder should
be creating bins from result of Object Split constructor).

Doable, but need to quickly fix issue for the studio here, easier to
revert for now.
2016-04-01 17:45:59 +02:00
8e6d6cc4dc Fix T48001: Highlighting selected item in filtered lists.
active index was not reset to 'nothing' in case actual active item was filtered out.
2016-04-01 16:55:34 +02:00
a9cd97673d Knife Project: revert fix for T43896
For now leave precision at half a pixel until we have real fix.
Resolves T48023.
2016-04-02 01:33:10 +11:00
9ca9256693 Cycles: Support deformation motion blur for curves deformed by taper 2016-04-01 15:53:40 +02:00
f318e8322f Cycles: Report thread ID from worker thread to callbacks
Main use case of this ID will be to emulate TLS which otherwise
would require having some platform-specific implementations which
is not always really optimal.

See notes about the argument in util_task.h.
2016-04-01 15:25:35 +02:00
c6b27dd4fa BMesh: improve path-select fill region w/ ngons
Rewrote to work with ngons and and more complex topology, now uses separate function.
Fixes T48009.
2016-04-01 23:36:06 +11:00
Philipp Oeser
ae49f2ed99 Fix T48013: UV Sculpt Brush Does not appear in UV window - but does show up in uv panels (t, n)
Epic fail in recent rB2c3985 :/

To be backported to 2.77a!
2016-04-01 14:22:54 +02:00
f185effa15 Buildbot: Explicitly disable tests on all platforms
They were never running anyway since there's no checkout of
tests folder. We should either make tweaks to buildbot master
to make it to send cloning commands for tests folder and keep
tests working (currently some of them are broken).
2016-04-01 10:33:44 +02:00
42a9f334c8 Update stub for recent BPY API 2016-04-01 18:56:48 +11:00
4738ae085d Cycles: Fix for missing pthread's spin on OSX 2016-04-01 09:16:46 +02:00
314aa17678 Fix When using keying sets, the toggling "all items" in the array target only goes from the index value down, instead of keying all 2016-04-01 12:52:26 +13:00
ee324aacdd Hide layers from UI in template 2016-04-01 10:23:39 +11:00
743739f9dc Cleanup: style/spelling 2016-04-01 10:02:59 +11:00
de21f07f6c Generic check for string being a Py keyword
Driver code used incomplete list of Py keywords
2016-04-01 09:49:16 +11:00
bc318fc470 Use STRPREFIX macro for testing property name 2016-04-01 09:24:50 +11:00
83b5f0268e Fix T48012: Knife Project crash 2016-04-01 06:27:35 +11:00
553ea6de8b Fix NULL check before free 2016-04-01 06:23:35 +11:00
9431fc6764 Cycles: Fix wrong initialization order of mesh flags and object transform 2016-03-31 17:54:03 +02:00
185d002586 Cycles: Fix too many objects being considered an instance 2016-03-31 17:46:22 +02:00
6cc04b408c Cycles: Fix compilation on Win32 after bitscan commit
Need to revisit utility headers a bit more carefully and perhaps
move such utilities outside of simd-related headers.
2016-03-31 16:47:57 +02:00
Julian Eisel
90c19c61d4 Fix memory leak when assigning driver
Also added NULL-checks for RNA paths, though they might be a bit paranoid.
2016-03-31 16:41:50 +02:00
Julian Eisel
60534ee56b Fix memory leak when calling new driver eyedropper
Would return OPERATOR_RUNNING_MODAL for non-modal operator.
2016-03-31 16:27:16 +02:00
de6af2f02a Remove the obsolete windows launcher 2016-03-31 14:07:57 +02:00
c0cb9d75d6 CMAKE disable building the windows launcher, fix type in delayloading of debug dll 2016-03-31 14:05:46 +02:00
791a0852e8 Cycles: Name cleanup and some comments in BVH code 2016-03-31 13:52:38 +02:00
4ec95d621a CMAKE / msvc openmp, delay loading of openmp dll so we can set environment
variable before it is loaded
2016-03-31 13:46:14 +02:00
e2059380de Cycles: Add easy to use spin lock primitive
Currently unused, but will be handy for an upcoming changes.

It'll also be nice to be able to do scoped_lock() for both
Mutex and Spin, but currently it's not really easy to do,
need some changes in typedefs and such, will happen as a
separate commit.
2016-03-31 10:22:11 +02:00
7fd71338f9 Cycles: Expose array's capacity via getter function
This way it's possible to query capacity of an array, which then
could be used for some smart re-allocation and reserve policies.
2016-03-31 10:06:21 +02:00
63d017be90 Cycles: Avoid per-split memory allocation for the new references list 2016-03-31 10:06:21 +02:00
e69a0ab5fc Cycles: Pass BVH builder by const reference to spatial splitters 2016-03-31 10:06:21 +02:00
d9b729e342 Cycles: Only sort indices when finding a best dimension to split
This reduces amount of data being moved back and forth, which should
have positive effect on the performance.
2016-03-31 10:06:21 +02:00
bbbbe68473 Cycles: Wrap spatial split storage into own structure
This has following advantages:

- Localizes all the run-time storage into a single structure,
  which could easily be extended further.

- Storage could be created per-thread, so once builder is
  threaded we wouldn't have any conflicts between threads.

- Global nature of the storage avoids memory re-allocation
  on the runtime, keeping builder as fast as possible.

Currently it's just API changes, which don't affect user at all.
2016-03-31 10:06:21 +02:00
9c420e5e48 Cycles: Use stack storage for temporary data on leaf creation
Uses new StackAllocator from util_stack_allocator. Some tweaks to the stack
storage size are possible, read notes in the code about this.

At this point we might want to rename allocator files to util_allocator_foo.c,
so the stay nicely grouped in the folder.
2016-03-31 10:06:21 +02:00
ffe59c54cb Cycles: Add STL allocator which uses stack memory
At this point we might want to rename allocator files to
util_allocator_foo.c so the stay nicely grouped in the folder.
2016-03-31 10:06:21 +02:00
65b375e798 Cycles: Move non-vectorized bitscan() to util
This way we can use bitscan() from both vectorized and non-vectorized
code, which applies to both kernel and host code.
2016-03-31 10:06:21 +02:00
0b6b094a8c Cycles: Aligned vector was not covered by guarded stat
This was making stats printed by the logging being wrong: they did not
include such memory as BVH storage.
2016-03-31 10:06:21 +02:00
bd68a25505 cmake fix full debug builds on msvc 2016-03-31 08:12:53 +02:00
ec28fe2e6b Fix T47985: VSE GL-render scene strip hangs
Regression in d5f1b9c22,
threading deadlock rendering a scene from the OpenGL preview.
2016-03-31 15:49:24 +11:00
01ce8d80d0 Usual ui messages fixes/tweaks. 2016-03-30 23:39:54 +02:00
f7fc55867a libquery foreach looper: in recursive case, do not bother with NULL id pointers! 2016-03-30 21:36:09 +02:00
cb19948053 Fix T47983: Particles - Emit from Verts emits double on one vert.
When non-random, particle distribution used a small start offset (to avoid
zero-weight faces), which is fine with "continuous" entities like faces, but not
for discrete ones like vertices - in that case it was generating some undesired
"jump" over a few verts in case step was small enough
(i.e. total number of verts/particles was big enough).
2016-03-30 21:04:54 +02:00
756ab5ee2c Use Ctrl-Shift-RMB for to enable 'Fill Region' 2016-03-31 04:30:33 +11:00
a55477d32a Shortest Path Select: option to select all paths between 2 elements
This option selects all paths between source/destination which are no longer than the path found.

Handy for selecting meshes with a grid-topology.
2016-03-31 04:25:19 +11:00
26132eaf1f Partly fix (unreported) particles not updating correctly when changing settings.
Point-cached particles (those using simulations) would not update at all outside of
first frame, due to PSYS_RECALC_RESET flag being ingnored in `system_step()`...

For some mysterious reasons, udate is still non-fully functional outside of startframe
(e.g. changing face distribution between random and jittered), but at least when choosing
'Vertices' you get particles from verts and not faces!
2016-03-30 17:10:54 +02:00
53e85a159a Particles: Fix broken grid distribution in some case from own recent rB201d3938622. 2016-03-30 16:56:32 +02:00
f8b9f4e9bb Cycles: Resumable render implementation for Cycles
This feature is also known by the name Samples Offset, which allows
artists to render animation with given amount of samples N, but then
render more samples, starting from N and ending with M (where M > N)
and merge renders together as if they rendered exactly M samples.

Surely such effect could be achieved by changing Seed variable, but
that has possible issues with correlation artifacts and requiring to
manually deal with per render layer samples and such.

While we can't support all possible renderfarm-related features in
Cycles it's nice to support really commonly used stuff.

Here's a command how to run Blender with the new feature enabled:

  blender -- --cycles-resumable-num-chunks 24 --cycles-resumable-current-chunk 2

This command will divide samples range in 24 parts and render
range #2 (chunk number is 1-based).

This feature might be changed a bit after we'll do some tests here
in the studio with it.
2016-03-30 16:02:27 +02:00
ee364b6358 Fix T47940: Custom bone shapes, select error w/ Open NVidia drivers
Latest nouveau drivers have a bug here, use occlusion queries.
2016-03-31 00:59:04 +11:00
74d3f3746c CMake cleanup target_link_libraries_decoupled 2016-03-30 15:15:17 +02:00
119ce13a41 Fix T46623: OSX bpy.app.binary_path_python incorrect
CMake's PYTHON_EXECUTABLE wasn't set.
2016-03-30 22:50:29 +11:00
722d586257 Fix T47993: noise_vector ignores random seed
Replace hard coded values with offsets derived from the random seed.
2016-03-30 20:43:43 +11:00
93f107729c Fix T48000: Eyedropper sample-merged ignored at first 2016-03-30 17:28:01 +11:00
29bb10ee96 Fix transform center2d for 2d views
While this didn't show up as a bug, the center2d was being calculated with a zero aspect,
causing TransInfo.center2d to be NAN.
2016-03-30 07:15:33 +11:00
37e1e2695c Fix T47814: VSE Scene 'Use Sequence' fails
Conflict with flags between depsgraph and sequencer caused error.
Now pass state of sequencer parents to avoid recursion.
2016-03-30 06:59:36 +11:00
e5e8d67028 Fix T47961: Wipe effects should have 2 inputs 2016-03-30 06:33:35 +11:00
c3ed6010af Fix T47967: Select next active fails in some cases
For cases when there are multiple matches,
find the closest match (with increasingly fuzzy tests) instead of failing.
2016-03-30 05:01:57 +11:00
3a24e6320f Buildbot: Attempt to work-around unsupported clang on OSX machine
Ideally this would need to be fixed by nvcc itself. but they didn't
do that for a long time.
2016-03-29 19:46:10 +02:00
de81607efc Fix error in ghash/gset_ensure_p_ex
The key is needed in the case the ghash resizes.
Caused regression T47984.
2016-03-30 03:04:47 +11:00
201d393862 Fix T47902: Particle grid not using modifier stack, Take II.
Now only fix correct handling of use_modifier_stack for grid distribution,
fixing it globally breaks all existing edited hair systems. :/
2016-03-29 17:45:56 +02:00
a959771626 Revert "Fix T47902: Particle grid not using modifier stack."
This reverts commit 2bd3acf7cd.

Commit is valid in theory - but in practice, it means nearly all edited hair systems
would need to be re-created from scratch... Not nice, so better revert and note in code
that particle distribution is ugly and does not respect 'use modifier stack' option in most cases.
2016-03-29 17:33:08 +02:00
24d931ea58 GPencil New Stroke Smoothing: Don't perform smoothing on pressure values
As noted by Antonio and Daniel, performing smoothing on the pressure values
for new strokes doesn't work that great. From an artist POV, it is apparently
"very strange that line thickness shrink suddenly after drawing it".
2016-03-30 03:21:59 +13:00
3bdd7ba34f Driver Mapping Types: Added temporary icons to break up the two types of mapping behaviours (modal vs manual) 2016-03-30 03:21:58 +13:00
d29b32ae36 RMB Menu: Add icons for delineating each cluster of options in this menu
From T33052 by Harley Acheson (harley)
2016-03-30 03:21:58 +13:00
deffd4352b Drivers Setup: Expose all mapping types for creating drivers
* This includes the "manually create" modes, which correspond to the previous behaviour
  for setting up drivers. This is necessary when the current screen layout is not
  well suited to having multiple property editors open (e.g. small screen or heavily
  subdivided screen).

* Only the modes relevant for the current property type (i.e. array vs single)
  will be shown

* The "Add Driver" entries in the RMB context menu have now been replaced by a
  submenu which will list all the available mapping types.

* NOTE: The code for the ANIM_OT_button_driver_add() operator is perhaps a bit hairy.
  However, it currently allows us to have the desired behaviour. It can always get
  cleaned up later though.
2016-03-30 03:21:57 +13:00
3237ae2855 Add license text for OCIO configuration 2016-03-29 12:54:29 +02:00
003f908f0d Fix T47987: Blender Cycles standalone does not properly read UV coordinates from XML 2016-03-29 10:02:17 +02:00
2fae1719f8 Fix T47986: OBJ Import fails w/ imagepath encoding 2016-03-29 18:30:08 +11:00
b1f918bcc5 Fix T47958: Crash in Walk or Fly Navigation in Camera mode when invoking from non-3DView region 2016-03-28 18:19:43 +02:00
Julian Eisel
37b7b3a935 T47532: Pop-ups drop fast mouse clicks
Caused by rBc24be7ec6e5.

Before rBc24be7ec6e5,  wm_handlers_do always called handlers a second time with event value KM_PRESS in case of a double click. After it, this was only the case for non-LEFTMOUSE events.
Since ui_popup_handler (almost) always returned WM_UI_HANDLER_BREAK, the second handler iteration with KM_PRESS wouldn't run. This fix just makes sure we return WM_UI_HANDLER_CONTINUE for double click events instead (causing second iteration to run).
2016-03-28 16:45:12 +02:00
28ca3ebc5f Fix T47969: Select Random always uses same seed
Increment the seed on each use,
otherwise calling again selects the same order, unless you manually adjust the seed.
2016-03-29 01:24:57 +11:00
d336bb0765 Fix T47972: Blender crash showing particle system.
Do same as with faces - if no orcodata is available, fill orco with current location...
2016-03-28 15:52:59 +02:00
240adb90a5 Fix T47973: Render stamp ignores font alpha 2016-03-29 00:26:55 +11:00
6a099b0c45 BLF: alpha support for drawing to buffer 2016-03-29 00:26:55 +11:00
e2e72a20ec Fix T47931: Missed world shader update when having object dependency 2016-03-28 10:45:29 +02:00
8a9dd6f6fb Fix T47898: Error adding mask node with "Add Mask Node" operator
This operator is intended to be used by drag-n-drop, no user invocation
is expected to happen here. Use Add->Search to quickly add nodes instead.
2016-03-28 10:09:11 +02:00
b7dfef325d Cleanup: Unused variable 2016-03-28 09:36:41 +02:00
ca935abc18 Graph Editor UI: Experimental Tweak - Use tabs for properties region, to make it easier to navigate 2016-03-28 14:46:29 +13:00
96f8bfec2d GPencil: Note that clicking outside the active area also exits draw mode 2016-03-28 14:46:28 +13:00
211b539644 Fix T47959: make tip for 'individual origins' pivot point in UV editor more accurate.
Based on D1877 from Philipp Oeser (lichtwerk), thanks.
2016-03-27 17:18:17 +02:00
c65950dbb4 GPencil: Remove the old UserPrefs-based On/Off Stroke Smoothing method
This never really worked that well, and often ended up being far too strong
to be of practical use. The new options do similar things, but with greater
control, so removing this old method now.
2016-03-28 03:39:26 +13:00
2bb956f6c9 GPencil: Smooth and Subdivision variable/setting naming
On second thought, these might be better names for these... I'm still not 100%
happy with these, but they will do for now.

(Best results currently seem to be with smooth 0.7, and subdivision steps 1 or 2)
2016-03-28 03:21:31 +13:00
fd8f51da08 GPencil: Removed the restriction of not subdividing strokes further if it exceeds GP_STROKE_BUFFER_MAX
Assuming that this subdivision + smoothing mostly only happens at the end of a stroke
anyway, enforcing this max-points limit in some cases was resulting in strokes that
weren't quite getting subdivided properly as the others.
2016-03-28 03:21:30 +13:00
e78a929d68 GPencil: Code Cleanup - Simplify and clarify the code for subdividing a stroke 2016-03-28 03:21:29 +13:00
a7538b19c6 GPencil: Restore ability for Smooth brush to affect pressure values of strokes 2016-03-28 03:21:29 +13:00
00cfbeef11 Code Cleanup - Style tweaks 2016-03-28 03:21:28 +13:00
bfbbc8ec40 Improve grease pencil stroke quality
Improve the quality of current grease pencil strokes adding a new dynamic smooth and subdivision. The level of smooth and subdivide can be adjusted using UI parameters. These options are disabled by default in order to keep the grease pencil stroke compatible with any existing add-on.

Both parameters are defined at layer level.

Reviewers: aligorith

Differential Revision: https://developer.blender.org/D1866
2016-03-28 03:21:28 +13:00
71107208dd More tooltip tweaks
The "UI_OT_eyedropper_id" operator only actually works in the 3D view,
so change the tooltip to match that
2016-03-28 03:21:27 +13:00
Julian Eisel
9adf4cba7d Fix T45075: "Error, region type 2 missing in - name:"File", id:5"
Unexpectedly found out what was going wrong here. If a file was saved with a filebrowser open, we searched for the channel region in the wrong list (see 'ListBase *regionbase = (sl == sa->spacedata.first) ? &sa->regionbase : &sl->regionbase;').

Minor annoyance is that I had to move the loookup to the 2.77.1 version patch now.
2016-03-27 13:45:10 +02:00
7bce3dd3ad Fix T47697: Smoke simulation doesn't work in viewport
Seems to be a division by zero error.

Should be safe for an upcoming 'a' release.
2016-03-27 13:21:33 +02:00
Julian Eisel
9c2704c169 Fix changing view in default video editing layout broken
Own mistake in 802bb42267
Apparently we only store one preview region for all views, didn't know that (makes sense though).
2016-03-27 13:20:30 +02:00
ce71e2e789 Fix T47962: It's possible to set a Sound strip as a modifier Mask. 2016-03-27 13:02:43 +02:00
fb9315ce2a Cleanup: Silence some compiler warnings 2016-03-27 12:36:49 +02:00
e12650bdd1 Driver Eyedropper: Auto detection/correction magic for rotation properties
When linking a rotation property to a non-rotation property (going in either
direction - i.e. rot -> normal, normal -> rot), the driver expression will
now be set so that the new drivers behave as expected (i.e. you get the values
you see, instead of "weird" values that seem several orders of magnitude off).

This may not be that great for everyone (i.e. the rare users out there who
actually like to look at their rotations in radians), but they usually know
what they're doing anyway, so this will be easy to correct.
2016-03-27 18:05:35 +13:00
4b279815d5 Drivers: Add a "none" mode for use when adding drivers
Although it isn't currently exposed, this allows for the old behaviour,
where an "empty" driver was added (without any target assigned yet).
For this reason, it's also referred to as the "Manual" mode.

There are also some attempts at improving the tooltips + names for the
other modes (again, not shown anywhere yet)
2016-03-27 18:05:35 +13:00
6caad32c12 Code Cleanup - Split out the property-button-finding code so that it can be used for other eyedroppers 2016-03-27 18:05:34 +13:00
52f3f6ffa4 Fix crash opening some .blend files after recent fix for hidden preview regions. 2016-03-27 01:55:51 +01:00
e14324daa7 Fix T47758: rigidbody bug with constraint breaking and disable collisions.
This is a regression in Bullet, reverted the problematic change for now with
a custom patch.
2016-03-27 01:32:28 +01:00
273740006e Fix T47668: Cycles OpenCL glass not rendering correctly on AMD.
Work around what appears to be a compiler bug.
2016-03-26 23:45:18 +01:00
9317f9c055 Fix T47939, take II: Check clang package version, not llvm-devel one.
Looks like some distro still provide llvm-3.4-devel, while no more clang-3.4.
Since clang depends on llvm of same version, check clang only should ensure
us we also have matvhing llvm... *sigh*
2016-03-26 21:07:04 +01:00
8fcf774167 Fix T47935: Hair particles; The display percentage parameter breaks after a render is done.
Follow same logic in `psys_render_restore` as in `psys_render_set` - if hair and
display percentage is not 100%, we have to recompute particles...

With regular 'emitter' particles just hiding some is fine (though using random here
will not give a precise proportion...).
2016-03-26 17:41:56 +01:00
112f431c3b Fix T47951: UserId problem on reload.
readfile.c would increment object usercount in three places, where it should not.
Remember kids: Objects are **only** refcounted by Scene's bases, and Object->proxy!
2016-03-26 16:22:17 +01:00
6483c3c280 Fix own regression in rBc08924bf94f2dff - foreach ID looper was broken due to missing initialization.
Quite unbelievable this could slip in... tons of shame on me :/
2016-03-26 16:11:12 +01:00
6a0c187653 Revert "Fix T47896: Scripted Expression string length limit is too short for some autogenerated expressions"
This reverts commit 322f86d6b3.
2016-03-26 23:00:20 +13:00
5759e335c3 Driver Variable Name Validation: Added missing check for zero-length (i.e. "blank") names 2016-03-26 18:02:02 +13:00
0512e20ae9 Driver Setup Workflow Improvement: Property Eyedropper
This commit brings some long requested improvements to the workflow for setting up
drivers, which should make it easier and faster to set up new drivers in a more
interactive fashion.

The new workflow is as follows:
1) Hover over the property (e.g. "Lamp Energy" or "Y Location") or properties ("Rotation")
   you wish to add drivers to. We'll refer to this as the "destination"
2) Ctrl-D to active the new "Add Drivers" eyedropper
3) Click on the property you want to use as the source/target. The property under the
   mouse will be used to drive the property you invoked Ctrl-D on.

For example, to drive the X, Y, and Z location of the Cube using the Y Location of the Lamp,
hover over any of the X/Y/Z location buttons, hit Ctrl-D, then click on the Y-Location
button of the Lamp object. Drivers will be added to the X, Y, and Z Location properties
of the Cube; each driver will have a single variable, which uses the Y-Location Transform
Channel of the Lamp.


Tips:
- Transform properties will automatically create "Transform Channel" driver variables.
  Everything else will use "Single Property" ones

- Due to the way that Blender's UI Context works, you'll need two Properties Panel instances
  open (and to have pinned one of the two to show the properties for the unselected
  object). It's slightly clunky, but necessary for implementing a workflow like this,
  as the UI cannot be manipulated while using eyedroppers to pick data.

- The eyedropper operator implemented here actually has three modes of operation.
  1) The "1-N" (one to many) mode is the default used for Ctrl-D, and "Add Driver to All"
     in the RMB Menu. This is the behaviour described above.
  2) There's also a "1-1" (one to one) mode that is used for the "Add Single Driver" in the
     RMB Menu.
  3) Finally, there's the "N-N" mode (many to many), which isn't currently exposed.
     The point of this is to allow mapping XYZ to XYZ elementwise (i.e. direct copying)
     which is useful for things like locations, rotations, scaling, and colours.


Implementation Notes:
- The bulk of the driver adding logic is in editors/animation/drivers.c, where most of
  the Driver UI operators and tools are defined

- The property eyedropper code is in interface_eyedropper.c along with all the other
  eyedroppers (even though they don't share much actual code in common). However, this
  turns out to be necessary, as we can't get access to many of the low-level buttons API's
  otherwise.

Todo:
- It may be necessary to restore a way to access the old behaviour (i.e. "manual setup")
  in case it is not practical to immediately pick a property.

- Other things to investigate here include extra hotkeys (e.g. Ctrl-Shift-D for Add Single?),
  and to expose the N-N mode.

- Other things we could try include interactively applying scaling factors, picking
  multiple targets (e.g. for location difference and rotation difference drivers),
  and/or other ways of using these property picking methods.
2016-03-26 18:02:02 +13:00
ee9898e0fa Drivers Workflow: Change hotkey for "Add Drivers" to Ctrl-D (it was previously just DKEY)
Just using DKEY for this was resulting in too many drivers being accidentally created
by users drawing using Grease Pencil. This change also works better with the following
workflow changes to the driver setup process.
2016-03-26 18:02:01 +13:00
eac770a33a Fix T47939: Install Deps OSL 1.7.1 and clang-3.5
Until we officially support llvm3.5 or more, only allow for 3.4 llvm packages,
and build own stuff otherwise...
2016-03-26 00:31:41 +01:00
2bd3acf7cd Fix T47902: Particle grid not using modifier stack.
Disclaimer: this is tentative fix, seems to be working but you never know with particles.
If issue arise, we'll just revert this commit and hide 'use modifier stack' option
for grid distribution instead.

This commit also try to make choice of which dm to use during distribution more generic
(deduplication of code), again hopping not to break anything. :P
2016-03-26 00:18:00 +01:00
Julian Eisel
802bb42267 Fix sequencer view in video editing layout containing hidden preview region
Steps to reproduce were:
* Open default video editing layout
* Drag down or click '+' icon in upper right corner of sequencer view
* A preview region appears, even though the view type is not set to sequencer-preview split mode

Another bug that has been there since ages :/ Reported by @Blendify via IRC, thanks!
2016-03-26 00:09:34 +01:00
7607d064d6 Fix Cycles debug panel, being shown in BI as well. 2016-03-25 19:59:18 +01:00
e4a265f058 Cycles: Add an option to build single kernel only which fits current CPU
This seems quite useful for the development, so you don't need to wait
all the kernels to be re-compiled when working on a new feature, which
speeds up re-iteration.

Marked as an advanced option, so if it doesn't work so well in practice
it's safe to revert anyway.
2016-03-25 16:09:05 +01:00
700722f686 Cycles: Cleanup, indent nested preprocessor directives
Quite straightforward, main trick is happening in path_source_replace_includes().

Reviewers: brecht, dingto, lukasstockner97, juicyfruit

Differential Revision: https://developer.blender.org/D1794
2016-03-25 13:55:42 +01:00
0e47e0cc9e Cycles: Use dedicated BVH for subsurface ray casting
This commit makes it so casting subsurface rays will totally ignore all
the BVH nodes and primitives which do not belong to a current object,
making it much simpler traversal code and reduces number of intersection
tests.

Reviewers: brecht, juicyfruit, dingto, lukasstockner97

Differential Revision: https://developer.blender.org/D1823
2016-03-25 13:42:13 +01:00
712a257994 Fix T47928: Crashing save corruption with dynamic paint drip effector groups.
Dynapaint's `foreachIDLink` was mnot handling effector_weights->group pointer...
2016-03-25 13:17:04 +01:00
Julian Eisel
4509559c13 Fix modal bevel OP immediately stopping when called using enter key from search menu
Steps to reproduce were:
* Go to edit mode, select geometry
* Spacebar -> search for bevel OP
* Activate *using enter key*
* Immediately stops when releasing enter key

To fix we simply make sure the initial release event is ignored. For mouse events that wasn't an issue since activating an element is done on key release in menus. An alternative fix would be to do the same for enter key, but that's more risky. Also, checking event value is highly recommended anyway.
2016-03-25 12:31:46 +01:00
7219988258 Revert "Fix T47263: numpad4/6 rotates around worl Z axis and not view Y axis."
This reverts commit fe0ca82b23.

This is a design issue, needs more thinking, for now just revert back to old behavior.
2016-03-25 12:09:59 +01:00
a0a7d823e0 CMake: Disable Cycles OSL for the light configuration
While it was indirectly disabled already, it's handy to use the config
as template and enable certain features. In case of Cycles enabling it
would also enable OSL which is not very expected.
2016-03-25 11:27:08 +01:00
7f3da8f5c9 UI: Presets for scene units
This adds simple preset menu for unit scale scene property.

D1799 by @alm
2016-03-25 05:03:25 +11:00
9dc5e1dbc2 Make IDPreview handling code use new recursive libquery looper. 2016-03-24 16:10:39 +01:00
c08924bf94 Rework library_query foreach looper - add optional recursivity.
This commit:
* Fixes bad handling of 'stop iteration' (by adding a status flag, so that we can actually
  stop in helper functions too, and jumping to a finalize label instead of raw return, to
  allow propper clean up).
* Adds optional recursion into 'ID tree' - callback can also decide to exclude current id_pp
  from recursion. Note that this implies 'readonly', modifying IDs while recursing is not
  something we want to support!
* Changes callback signature/expected behavior: return behavior is now handled through flags,
  and 'parent' ID of id_pp is also passed (since it may not always be root id anymore).

Reviewers: sergey, campbellbarton

Differential Revision: https://developer.blender.org/D1869
2016-03-24 16:10:39 +01:00
60cf62ff4b Cycles: Minor optimization of equirectangular projection
Don't calculate sine twice, store this in a variable instead.

Perhaps compilers can optimize this out, but helping them a but wouldn't hurt.
2016-03-24 15:01:39 +01:00
8249046b82 UI: search operator's by word prefix
Would match middle of words which wasn't very useful in most cases.
2016-03-24 23:30:51 +11:00
70fcecc1f7 Fix BLI_strncasestr use with a single character 2016-03-24 23:30:51 +11:00
bdae647670 Color sources for point density textures based on mesh vertices
This patch adds support for coloring point density textures based on several mesh vertex attributes.

* Vertex Color: Use a vertex color layer for coloring the point density texture
* Vertex Weight: Use a weights from a vertex group as intensity values. (for Blender Render engine the additional color band is used)
* Vertex Normals: Use object-space vertex normals as RGB values.

The vertex color source enum is stored separately from the particle color source, to avoid invalid values when switching.

Note that vertex colors are technically "corner colors" (MLoop), so each vertex can have as many colors as faces it is part of.
For the purpose of point density the mloop colors are simply averaged, which is physically plausible because corners can be viewed
as multiple points in the same location.
2016-03-24 12:07:03 +01:00
8e9a55f1e5 Fix some typos and incorrect tooltips/descriptions 2016-03-24 23:31:06 +13:00
f209529c3d Fix T47910: Knife project fails
Regression in fix for T43896, using screen-space precision here is very problematic,
using lower precision here works for both reports.
2016-03-24 18:27:39 +11:00
7e65b02fb6 Cleanup: use prefix for return args 2016-03-24 18:05:10 +11:00
2a9e3c2bdb Fix incorrect arg type 2016-03-24 17:56:30 +11:00
75849b099f Fix T47838: Walk gravity fails w/ intersecting objects
Regression in 3ad0344, fix from @mano-wii.

More comprehensive fix can be done after 2.77a.
2016-03-24 17:52:31 +11:00
17d0c10096 Driver Keyframing: Some tweaks to make inserting keyframes on Driver F-Curves easier
Now, when trying to insert a keyframe on a driven property (using IKEY, or with
autokeying enabled), the keyframes will get created on the Driver's F-Curve
(instead of creating a new FCurve that goes into the active action, but will never
do anything). Furthermore, the x-value of the new keyframe will be the current
result of the driver expression.

Why/Motivations:
This way, it becomes easier to create corrective drivers, as you can position all
the targets the driver depends on, then adjust the driver value until it does what
you need, and then you keyframe that value to bake it into the Driver F-Curve
(in effect, "training" the computer how to behave in that case).

Usage Notes:
* In practice, that particular workflow is still quite clunky to achieve, due to some
  quirks of how the driver system and the UI widgets interact. Specifically, you'll
  need to disable/mute the driver before trying to edit the setting (to prevent the
  driver from immediately resetting the value - before even autokey fires!). However,
  if you're using the Graph Editor to preview/monitor/manage the keying process, you'll
  then want to re-enable the driver before changing the targets, so that you can see
  how much of a change you'll want to be applying!

* The warning about editing driver values may need to be disabled or selectively
  knocked out. I had it disabled while testing this functionality, but it's actually
  harmless in its current state (if just a bit annoying).
2016-03-24 19:34:52 +13:00
0a3792a65b Fix T47900: VSE adjustment crashes on blank frame
Regression, should have been included in previous fix.
2016-03-24 17:13:25 +11:00
d2244b59d8 Fix dodgy indentation 2016-03-24 15:20:56 +13:00
c4956faf99 Drivers UI: Added name validation/linting for Driver Variables
When attempting to change a driver variable name to an "invalid" name,
an indicator will now be shown beside the offending variable name.
Clicking on this icon will show a popup which provides more information
about why the variable name cannot be used.

Reasons that it knows about are:
1) Starts with number
2) Has a dot
3) Has a space
4) Starts with or contains a special character
5) Starts with an underscore (Python does allow this, but it's bad practice,
   and makes checking security of drivers harder)
6) Is a reserved Python keyword
2016-03-24 15:15:04 +13:00
322f86d6b3 Fix T47896: Scripted Expression string length limit is too short for some autogenerated expressions
While most scripted expressions are quite short (e.g. "var" or "frame + 1"),
those that are autogenerated by scripts (to take into account a wide range of factors)
may require a bit more headroom to operate in.

By doubling the maximum length here, we now make it possible to combine up to 38
3-letter variables in some linear combination (with all factors expressed to 4 dp).
That should be more than enough for anyone or anything for quite a while!

Unfortunately, this does increase memory consumption for drivers across the board.
2016-03-24 13:02:22 +13:00
c1095c7a9f Revert "Fix T47869: OpenColorIO Error with unicode path to config file under Windows"
White the config itself could be loaded this way, lookup tables can not. Additionally,
that's not really clear how to solve the issue with search path which is multi-byte
only in the API.

Reverting for further investigation.

This reverts commit ab4307aa08.
2016-03-23 19:28:16 +01:00
376eb77fd7 Fix T47900: VSE adjustment crashes on blank frame 2016-03-24 05:23:37 +11:00
2103e2112c Fix T47870: Missing viewport update when material output is inside of the group 2016-03-23 15:42:38 +01:00
c87e65542c Fix T47833: View-aligned GPencil strokes move in crazyspace when grabbed
These fixes "seem" to do the right thing now...
2016-03-24 03:32:28 +13:00
ab4307aa08 Fix T47869: OpenColorIO Error with unicode path to config file under Windows 2016-03-23 15:09:36 +01:00
6a4967ca6e AnimEditors: Fuzzy/Multi-Word Name Filtering
Thanks to D1080 by @rockets, I've now been able to easily implement the
ability to type multiple word snippets/partial words into the text filter
field (in the Animation Editors), and have it filter the channels which
contain just some of those parts (instead of having to match everything).

For example, the following search strings will now work:
* "loc rot" or "lo ro" will now filter all location and rotation FCurves
* "col loc" will filter all location and color FCurves
* "scale" will also work as before to filter all scale FCurves

But, the following will not work:
* "lc rt" will NOT filter all location and rotation, as the fuzzy search only
  breaks down the search string based on whitespace placement

By default, this is not enabled when using name filtering (i.e. magnifying glass is checked,
and some filtering text is specified). Instead, you need to enable the "AZ" toggle beside
the name field. This fuzzy matching is not enabled by default as it could end up being
quite a bit slower on really heavy scenes. (There are probably some optimisation
opportunities, but that's only a future option if someone really needs it)
2016-03-24 02:45:14 +13:00
21f31e6054 Fix T47856: Cycles problem when running from multi-byte path
This is a mix of regression and old unsupported configuration.

Regression was caused by some checks added on Blender side which was
checking whether python function returned error or not. This made it
impossible to enable Cycles when running from a file path which can't
be encoded with MBCS codepage.

Non-regression issue was that it wasn't possible to use pre-compiled
CUDA kernels when running from a path with non-ascii multi-byte
characters.

This commit fixes regression and CUDA parts, but OSL still can't be
used from a non-ascii location because it uses non-widechar API to
work with file paths by the looks of it. Not sure we can solve this
just from our side by using some codepage trick (UTF-16?) since even
oslc fails to compile shader when there are non-ascii characters in
the path.
2016-03-23 13:58:31 +01:00
6e31f4f090 Fix T47893: BGE crashes w/ generated mesh data 2016-03-23 23:40:30 +11:00
74399e0a18 Radial Operator: Tweak number of digits displayed for the different property types
* As requested by venomgfx, rotations now only display to 2 decimal places (more than
  enough for rotations in degrees)
* Also, made it so that the "factor" types now show 3 dp (previously only 2, which isn't
  really enough when dealing with values from 0.0 - 1.0)
2016-03-24 01:00:13 +13:00
9815262444 Radial Control Operator: Always show the property name + value on the header
The radial control operator is commonly used for setting sculpt brush Size and Strength
settings. However, when using it, it can often be difficult to remember which hotkey
is responsible for which setting, meaning that you can often accidentally modify the
wrong setting without knowing it (or even what new value you've set it to).

This commit makes it so that the property name and the current value are always shown
on the header. Previously this info was only shown when the doing numeric input.
(It also fixes a bug where the numeric input print would hang around even after it
wasn't being used).
2016-03-24 01:00:12 +13:00
0f501a73ab Fix T47890: Vertex mask w/ subsurf select fails
Regression in GL refactor
2016-03-23 21:02:44 +11:00
80a7efdc1d UI: multi word filtering in search menu
D1080 by @rockets, with own improvements to tests
2016-03-23 18:51:29 +11:00
b0a7e77700 Cleanup: style 2016-03-23 04:47:16 +11:00
c31c53983e Cleanup: style (80-width) 2016-03-23 04:25:08 +11:00
46dd04faed Fix incorrect strncat use 2016-03-23 03:54:04 +11:00
0f1d711681 Fix T47830: Multi-edit w/ ui-list wont highlight
Regression from 4d6b892.
2016-03-23 03:37:23 +11:00
84d8b35d6c Weight Paint: support accumulate for blur brush
This re-applies smoothing based on the previous update.

Can smooth more but harder to get such even distribution.
2016-03-23 01:25:56 +11:00
e2181c2ef2 Fix for crash of point density textures due to undefined point_data on loading. 2016-03-22 15:07:56 +01:00
220a7a4fb1 Weight Paint: blur now smooths connected weights
Previously it would average all points under the brush, giving an off feedback loop that often depended on the
direction of the brush stroke, giving not-very-useful smearing effect.

Now blend brush smooths between connected edges.
2016-03-22 22:37:30 +11:00
29acdb4889 Mesh API: add BKE_mesh_vert_edge_vert_map_create
Handy when you need to reference connected verts directly.
2016-03-22 22:07:45 +11:00
3b5dec4afc Fix T47882: startup camera not upright 2016-03-22 17:22:41 +11:00
121e273bb3 Cleanup: reduce scope for versioning vars 2016-03-22 17:20:17 +11:00
0f63ce61c5 Fix add mesh template 2016-03-22 14:26:48 +11:00
4acd218c02 GPU compositing:
Minor optimization: Store the uniform interface of shaders instead of
re-querying every frame.
2016-03-21 22:43:03 +01:00
Philipp Oeser
2c3985d9e6 Fix T47842: UV sculpt brush widgets are available when not in uv sculpt mode.
rB5b3af3dd made the poll function here slightly too laxist.

To be backported to 2.77 should we make an 'a' release.

Reviewed By: mont29

Differential Revision: https://developer.blender.org/D1861
2016-03-21 15:45:16 +01:00
da2dfaad1a Mirror influence of environment texture in Blender viewport
This patch implements Mirror influence for environment textures. Approach matches the one from BI.
{F281871}
See the video https://youtu.be/BskgCv6dcIE
Example: {F281876}
Alexander (Blend4Web Team)

Reviewers: campbellbarton, merwin, brecht

Reviewed By: brecht

Subscribers: TwisterGE, blueprintrandom, youle, Evgeny_Rodygin, AlexKowel, yurikovelenov

Differential Revision: https://developer.blender.org/D1786
2016-03-21 14:36:33 +03:00
112300a982 Fix T47862: VSE hard cut fails
Regression caused by changing how video length is calculated,
however similar problems could be caused by strip length changing on-disk.
2016-03-21 19:40:41 +11:00
f4840e878b Fix T47848: Fix regression in sequencer GL render
Own changes in 2.77 broke off-screen render with scene render size doesn't match output.
2016-03-21 16:36:20 +11:00
fb5c6333f9 GPU: avoid redundant logic for non-spot lamps 2016-03-21 16:06:04 +11:00
72bf5d13e6 Fix for non spot lamps calculating spot values
Logical error in D1378, also incorrectly used lamp type as a flag.
2016-03-21 16:02:37 +11:00
a0a66e0418 Correct strange icon scaling in preferences 2016-03-21 15:34:34 +11:00
8238f5b33b Fix T47868: Check Box shape doesn't scale 2016-03-21 15:16:43 +11:00
2683dd8b93 Docs: add missing bmesh.ops descriptions 2016-03-20 19:40:03 +11:00
7f03e7cc3c Fix T47837: Filtering UIList broken with recent master.
Using 32nd bit of integer with our int RNA prop is not a good idea, it does not
really support unsigned int even with PROP_UNSIGNED type...

Most likely this has been unveiled by recent work over property clamping in RNA.

Not critical, but should be backported should we make an 'a' release.
2016-03-19 17:06:32 +01:00
26f2fe9528 mathutils.bvhtree: Add find_nearest_range API call
Returns all elements within a radius.
Similar to kdtree.find_range
2016-03-19 18:31:56 +11:00
1a7596951a BLI_kdopbvh: Pass center to to range callback
Useful when BLI_bvhtree_range_query callback calculates a new position to measure from.
2016-03-19 18:31:56 +11:00
6aeb1f7f56 Fix: "pchan_name" field in SDNA for names of bone targets for drivers was too short
When all the names in Blender were updated to go from having 32 characters to 64,
the "pchan_name" field in the DriverTarget struct was missed. This meant that if you
had a bone with a suitably long name, it would have been impossible to use values from this
bone in a driver.

The only reason this probably hasn't been discovered yet is because the standard/old depsgraph
doesn't work that well for bones in the same armatures, so setups where this may have
occurred are not that common.

To prevent this problem from happening in future, I've added the standard "MAX_ID_NAME-2"
comment to the comments on each line likely to be impacted by such changes, making it
easier for whoever does a search and replace in future :)
2016-03-19 17:48:29 +13:00
3d59be3001 Sequencer: expose GL preview alpha in scene UI
While this isn't essential, accessing this setting required navigating to each scene and using render menu.
Expose in sequencer UI for more convenient access.
2016-03-18 20:05:08 +11:00
cc12fc1f11 Fix T47806: Blender animation player stop working correctly with XVID codec
Something weird, seems some buffers _might_ be shared between codec context
and frame, which is quite weird. Could be a bug in FFmpeg or could be wrong
API usage somewhere else..
2016-03-18 11:50:06 +05:00
9777c5b0ca Fix T47827: Single Channel Preview Error
Fix by @sergey with own fix for big endian.
2016-03-17 23:52:49 +11:00
49182111fb ImBuf: Some tweaks to FFmpeg frame free policy
Th intention is to make sure we don't free buffers which were not allocated
by FFmpeg.

This is a possible fix for T47806.
2016-03-17 14:45:10 +05:00
eb32aa827a Sequencer: add frame-jump to menu 2016-03-17 11:02:14 +11:00
6952d75e3b Fix missing 'anim_data' in RNA API of Freestyle's linestyle.
Reported by Manuel Rais on ML, thanks.
2016-03-16 20:21:02 +01:00
3274dbceb1 Sequencer: Alt-RMB select handle now always selects strip
Was possible to do Alt-RMB on a strips handle - which only make the strip active (but didn't select).
This isn't really useful, so just select the strip and its handles in this case.
2016-03-17 00:26:50 +11:00
23e608b6fb Fix T47818: GPencil Sculpt Brush settings update when adjusted using scrollwheel while sculpting 2016-03-17 01:12:30 +13:00
Julian Eisel
386872b98b Fix text on collapsed node not positioned correctly with high DPI
Reported by @JacquesLucke via IRC, thx!
2016-03-16 12:53:57 +01:00
bd5bfad723 Fix T47807: Toggle header shortcut doesn't work 2016-03-16 11:33:32 +11:00
2f4ea47566 CMake: only show py module install options when used 2016-03-15 23:52:34 +11:00
31731bc834 Fix T47734: Rest Position is not working with new Deps 2016-03-15 16:13:25 +05:00
b7deea029a Fix T47780: Icons don't update in floating panels 2016-03-15 21:13:41 +11:00
859 changed files with 35751 additions and 17633 deletions

View File

@@ -166,7 +166,7 @@ option_defaults_init(
)
# customize...
if (UNIX AND NOT APPLE)
if(UNIX AND NOT APPLE)
# some of these libraries are problematic on Linux
# disable less important dependencies by default
set(_init_CODEC_FFMPEG OFF)
@@ -218,6 +218,10 @@ if(${CMAKE_VERSION} VERSION_LESS 2.8.8)
# add_library OBJECT arg unsupported
set(WITH_BUILDINFO OFF)
endif()
set(BUILDINFO_OVERRIDE_DATE "" CACHE STRING "Use instead of the current date for reproducable builds (empty string disables this option)")
set(BUILDINFO_OVERRIDE_TIME "" CACHE STRING "Use instead of the current time for reproducable builds (empty string disables this option)")
mark_as_advanced(BUILDINFO_OVERRIDE_DATE)
mark_as_advanced(BUILDINFO_OVERRIDE_TIME)
option(WITH_IK_ITASC "Enable ITASC IK solver (only disable for development & for incompatible C++ compilers)" ON)
option(WITH_IK_SOLVER "Enable Legacy IK solver (only disable for development)" ON)
@@ -362,19 +366,23 @@ if(UNIX AND NOT APPLE)
mark_as_advanced(WITH_BOOST_ICU)
endif()
endif()
option(WITH_PYTHON_INSTALL "Copy system python into the blender install folder" ON)
option(WITH_PYTHON_INSTALL_NUMPY "Copy system numpy into the blender install folder" ON)
set(PYTHON_NUMPY_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'numpy' module")
mark_as_advanced(PYTHON_NUMPY_PATH)
if(WITH_PYTHON_INSTALL)
option(WITH_PYTHON_INSTALL_NUMPY "Copy system numpy into the blender install folder" ON)
set(PYTHON_NUMPY_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'numpy' module")
mark_as_advanced(PYTHON_NUMPY_PATH)
if(UNIX AND NOT APPLE)
option(WITH_PYTHON_INSTALL_REQUESTS "Copy system requests into the blender install folder" ON)
set(PYTHON_REQUESTS_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'requests' module")
mark_as_advanced(PYTHON_REQUESTS_PATH)
endif()
endif()
option(WITH_CPU_SSE "Enable SIMD instruction if they're detected on the host machine" ON)
mark_as_advanced(WITH_CPU_SSE)
if(UNIX AND NOT APPLE)
option(WITH_PYTHON_INSTALL_REQUESTS "Copy system requests into the blender install folder" ON)
set(PYTHON_REQUESTS_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'requests' module")
mark_as_advanced(PYTHON_REQUESTS_PATH)
endif()
# Cycles
option(WITH_CYCLES "Enable Cycles Render Engine" ON)
option(WITH_CYCLES_STANDALONE "Build Cycles standalone application" OFF)
@@ -386,8 +394,10 @@ mark_as_advanced(CYCLES_CUDA_BINARIES_ARCH)
unset(PLATFORM_DEFAULT)
option(WITH_CYCLES_LOGGING "Build Cycles with logging support" ON)
option(WITH_CYCLES_DEBUG "Build Cycles with extra debug capabilities" OFF)
option(WITH_CYCLES_NATIVE_ONLY "Build Cycles with native kernel only (which fits current CPU, use for development only)" OFF)
mark_as_advanced(WITH_CYCLES_LOGGING)
mark_as_advanced(WITH_CYCLES_DEBUG)
mark_as_advanced(WITH_CYCLES_NATIVE_ONLY)
option(WITH_CUDA_DYNLOAD "Dynamically load CUDA libraries at runtime" ON)
mark_as_advanced(WITH_CUDA_DYNLOAD)
@@ -509,8 +519,8 @@ if(APPLE)
if(NOT CMAKE_OSX_ARCHITECTURES)
set(CMAKE_OSX_ARCHITECTURES x86_64 CACHE STRING
"Choose the architecture you want to build Blender for: i386, x86_64 or ppc"
FORCE)
"Choose the architecture you want to build Blender for: i386, x86_64 or ppc"
FORCE)
endif()
if(NOT DEFINED OSX_SYSTEM)
@@ -520,15 +530,20 @@ if(APPLE)
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
# workaround for incorrect cmake xcode lookup for developer previews - XCODE_VERSION does not take xcode-select path into accout
# but would always look into /Applications/Xcode.app while dev versions are named Xcode<version>-DP<preview_number>
execute_process(COMMAND xcode-select --print-path OUTPUT_VARIABLE XCODE_CHECK OUTPUT_STRIP_TRAILING_WHITESPACE)
# workaround for incorrect cmake xcode lookup for developer previews - XCODE_VERSION does not
# take xcode-select path into account but would always look into /Applications/Xcode.app
# while dev versions are named Xcode<version>-DP<preview_number>
execute_process(
COMMAND xcode-select --print-path
OUTPUT_VARIABLE XCODE_CHECK OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE "/Contents/Developer" "" XCODE_BUNDLE ${XCODE_CHECK}) # truncate to bundlepath in any case
if(${CMAKE_GENERATOR} MATCHES "Xcode")
if(${XCODE_VERSION} VERSION_GREATER 4.2) # earlier xcode has no bundled developer dir, no sense in getting xcode path from
string(SUBSTRING "${XCODE_CHECK}" 14 6 DP_NAME) # reduce to XCode name without dp extension
# earlier xcode has no bundled developer dir, no sense in getting xcode path from
if(${XCODE_VERSION} VERSION_GREATER 4.2)
# reduce to XCode name without dp extension
string(SUBSTRING "${XCODE_CHECK}" 14 6 DP_NAME)
if(${DP_NAME} MATCHES Xcode5)
set(XCODE_VERSION 5)
endif()
@@ -555,25 +570,30 @@ if(APPLE)
message(STATUS "Detected OS X ${OSX_SYSTEM} and Xcode ${XCODE_VERSION} at ${XCODE_BUNDLE}")
if(${XCODE_VERSION} VERSION_LESS 4.3)
set(CMAKE_OSX_SYSROOT /Developer/SDKs/MacOSX${OSX_SYSTEM}.sdk CACHE PATH "" FORCE) # use guaranteed existing sdk
# use guaranteed existing sdk
set(CMAKE_OSX_SYSROOT /Developer/SDKs/MacOSX${OSX_SYSTEM}.sdk CACHE PATH "" FORCE)
else()
# note: xcode-select path could be ambigous, cause /Applications/Xcode.app/Contents/Developer or /Applications/Xcode.app would be allowed
# note: xcode-select path could be ambigous,
# cause /Applications/Xcode.app/Contents/Developer or /Applications/Xcode.app would be allowed
# so i use a selfcomposed bundlepath here
set(OSX_SYSROOT_PREFIX ${XCODE_BUNDLE}/Contents/Developer/Platforms/MacOSX.platform)
message(STATUS "OSX_SYSROOT_PREFIX: " ${OSX_SYSROOT_PREFIX})
set(OSX_DEVELOPER_PREFIX /Developer/SDKs/MacOSX${OSX_SYSTEM}.sdk) # use guaranteed existing sdk
set(CMAKE_OSX_SYSROOT ${OSX_SYSROOT_PREFIX}/${OSX_DEVELOPER_PREFIX} CACHE PATH "" FORCE)
if(${CMAKE_GENERATOR} MATCHES "Xcode")
set(CMAKE_XCODE_ATTRIBUTE_SDKROOT macosx${OSX_SYSTEM}) # to silence sdk not found warning, just overrides CMAKE_OSX_SYSROOT
# to silence sdk not found warning, just overrides CMAKE_OSX_SYSROOT
set(CMAKE_XCODE_ATTRIBUTE_SDKROOT macosx${OSX_SYSTEM})
endif()
endif()
if(OSX_SYSTEM MATCHES 10.9)
set(CMAKE_FIND_ROOT_PATH ${CMAKE_OSX_SYSROOT}) # make sure syslibs and headers are looked up in sdk ( expecially for 10.9 openGL atm. )
# make sure syslibs and headers are looked up in sdk ( expecially for 10.9 openGL atm. )
set(CMAKE_FIND_ROOT_PATH ${CMAKE_OSX_SYSROOT})
endif()
if(NOT CMAKE_OSX_DEPLOYMENT_TARGET)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.6" CACHE STRING "" FORCE) # 10.6 is our min. target, if you use higher sdk, weak linking happens
# 10.6 is our min. target, if you use higher sdk, weak linking happens
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.6" CACHE STRING "" FORCE)
endif()
if(NOT ${CMAKE_GENERATOR} MATCHES "Xcode")
@@ -582,8 +602,6 @@ if(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
add_definitions("-DMACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}")
endif()
option(WITH_LIBS10.5 "Use 10.5 libs (needed for 64bit builds)" OFF)
endif()
@@ -591,7 +609,10 @@ endif()
# Check for conflicting/unsupported configurations
if(NOT WITH_BLENDER AND NOT WITH_PLAYER AND NOT WITH_CYCLES_STANDALONE)
message(FATAL_ERROR "At least one of WITH_BLENDER or WITH_PLAYER or WITH_CYCLES_STANDALONE must be enabled, nothing to do!")
message(FATAL_ERROR
"At least one of WITH_BLENDER or WITH_PLAYER or "
"WITH_CYCLES_STANDALONE must be enabled, nothing to do!"
)
endif()
if(NOT WITH_GAMEENGINE AND WITH_PLAYER)
@@ -655,7 +676,8 @@ if(NOT WITH_BOOST)
set_and_warn(WITH_OPENAL OFF) # depends on AUDASPACE
set_and_warn(WITH_GAMEENGINE OFF) # depends on AUDASPACE
set_and_warn(WITH_PLAYER OFF) # depends on GAMEENGINE
elseif(WITH_CYCLES OR WITH_OPENIMAGEIO OR WITH_AUDASPACE OR WITH_INTERNATIONAL OR WITH_OPENVDB OR WITH_OPENCOLORIO OR WITH_MOD_BOOLEAN)
elseif(WITH_CYCLES OR WITH_OPENIMAGEIO OR WITH_AUDASPACE OR WITH_INTERNATIONAL OR
WITH_OPENVDB OR WITH_OPENCOLORIO OR WITH_MOD_BOOLEAN)
# Keep enabled
else()
# New dependency graph needs either Boost or C++11 for function bindings.
@@ -752,18 +774,22 @@ endif()
if(WITH_INTERNATIONAL)
if(NOT EXISTS "${CMAKE_SOURCE_DIR}/release/datafiles/locale/languages")
message(WARNING "Translation path '${CMAKE_SOURCE_DIR}/release/datafiles/locale' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems, disabling 'WITH_INTERNATIONAL'.")
message(WARNING
"Translation path '${CMAKE_SOURCE_DIR}/release/datafiles/locale' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems, disabling 'WITH_INTERNATIONAL'."
)
set(WITH_INTERNATIONAL OFF)
endif()
endif()
if(WITH_PYTHON)
if(NOT EXISTS "${CMAKE_SOURCE_DIR}/release/scripts/addons/modules")
message(WARNING "Addons path '${CMAKE_SOURCE_DIR}/release/scripts/addons' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems: * CONTINUING WITHOUT ADDONS *")
message(WARNING
"Addons path '${CMAKE_SOURCE_DIR}/release/scripts/addons' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems: * CONTINUING WITHOUT ADDONS *"
)
endif()
endif()
@@ -797,21 +823,6 @@ set(PLATFORM_LINKFLAGS "")
set(PLATFORM_LINKFLAGS_DEBUG "")
# For alternate Python locations the commandline can be used to override detected/default cache settings, e.g:
# On Unix:
# cmake ../blender \
# -D PYTHON_VERSION=3.5 \
# -D PYTHON_INCLUDE_DIR=/opt/py35/include/python3.5d \
# -D PYTHON_LIBRARY=/opt/py35/lib/libpython3.5d.so
#
# On Macs:
# cmake ../blender \
# -D PYTHON_INCLUDE_DIR=/System/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5 \
# -D PYTHON_LIBPATH=/System/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/config \
# -G Xcode
#
# When changing any of this remember to update the notes in doc/build_systems/cmake.txt
#-----------------------------------------------------------------------------
#Platform specifics
@@ -1034,7 +1045,11 @@ if(UNIX AND NOT APPLE)
if(${OSL_LIBRARY_VERSION_MAJOR} EQUAL "1" AND ${OSL_LIBRARY_VERSION_MINOR} LESS "6")
# Note: --whole-archive is needed to force loading of all symbols in liboslexec,
# otherwise LLVM is missing the osl_allocate_closure_component function
set(OSL_LIBRARIES ${OSL_OSLCOMP_LIBRARY} -Wl,--whole-archive ${OSL_OSLEXEC_LIBRARY} -Wl,--no-whole-archive ${OSL_OSLQUERY_LIBRARY})
set(OSL_LIBRARIES
${OSL_OSLCOMP_LIBRARY}
-Wl,--whole-archive ${OSL_OSLEXEC_LIBRARY}
-Wl,--no-whole-archive ${OSL_OSLQUERY_LIBRARY}
)
endif()
else()
message(STATUS "OSL not found, disabling it from Cycles")
@@ -1105,7 +1120,13 @@ if(UNIX AND NOT APPLE)
set(PUGIXML_LIBRARIES "")
endif()
set(OPENIMAGEIO_LIBRARIES ${OPENIMAGEIO_LIBRARIES} ${PNG_LIBRARIES} ${JPEG_LIBRARIES} ${ZLIB_LIBRARIES} ${BOOST_LIBRARIES})
set(OPENIMAGEIO_LIBRARIES
${OPENIMAGEIO_LIBRARIES}
${PNG_LIBRARIES}
${JPEG_LIBRARIES}
${ZLIB_LIBRARIES}
${BOOST_LIBRARIES}
)
set(OPENIMAGEIO_LIBPATH) # TODO, remove and reference the absolute path everywhere
set(OPENIMAGEIO_DEFINITIONS "")
@@ -1146,7 +1167,9 @@ if(UNIX AND NOT APPLE)
if(WITH_LLVM OR WITH_SDL_DYNLOAD)
# Fix for conflict with Mesa llvmpipe
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -Wl,--version-script='${CMAKE_SOURCE_DIR}/source/creator/blender.map'")
set(PLATFORM_LINKFLAGS
"${PLATFORM_LINKFLAGS} -Wl,--version-script='${CMAKE_SOURCE_DIR}/source/creator/blender.map'"
)
endif()
if(WITH_OPENSUBDIV)
@@ -1249,7 +1272,10 @@ elseif(WIN32)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SAFESEH:NO")
set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /SAFESEH:NO")
list(APPEND PLATFORM_LINKLIBS ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 advapi32 shfolder shell32 ole32 oleaut32 uuid psapi Dbghelp)
list(APPEND PLATFORM_LINKLIBS
ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32
advapi32 shfolder shell32 ole32 oleaut32 uuid psapi Dbghelp
)
if(WITH_INPUT_IME)
list(APPEND PLATFORM_LINKLIBS imm32)
@@ -1287,7 +1313,8 @@ elseif(WIN32)
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /MT")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} /MT")
set(PLATFORM_LINKFLAGS "/SUBSYSTEM:CONSOLE /STACK:2097152 /INCREMENTAL:NO /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:msvcmrt.lib /NODEFAULTLIB:msvcurt.lib /NODEFAULTLIB:msvcrtd.lib")
set(PLATFORM_LINKFLAGS "/SUBSYSTEM:CONSOLE /STACK:2097152 /INCREMENTAL:NO ")
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:msvcmrt.lib /NODEFAULTLIB:msvcurt.lib /NODEFAULTLIB:msvcrtd.lib ")
# Ignore meaningless for us linker warnings.
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /ignore:4049 /ignore:4217 /ignore:4221")
@@ -1302,6 +1329,17 @@ elseif(WIN32)
set(PLATFORM_LINKFLAGS_DEBUG "/IGNORE:4099 /NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libc.lib")
# Use dynamic loading for OpenMP
if(WITH_OPENMP)
if(MSVC_VERSION EQUAL 1800)
set(OPENMP_DLL_NAME "vcomp120")
else()
set(OPENMP_DLL_NAME "vcomp140")
endif()
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /DELAYLOAD:${OPENMP_DLL_NAME}.dll delayimp.lib")
set(PLATFORM_LINKFLAGS_DEBUG "${PLATFORM_LINKFLAGS_DEBUG} /DELAYLOAD:${OPENMP_DLL_NAME}d.dll delayimp.lib")
endif()
if(NOT DEFINED LIBDIR)
# Setup 64bit and 64bit windows systems
@@ -1330,9 +1368,9 @@ elseif(WIN32)
# Add each of our libraries to our cmake_prefix_path so find_package() could work
file(GLOB children RELATIVE ${LIBDIR} ${LIBDIR}/*)
foreach(child ${children})
if(IS_DIRECTORY ${LIBDIR}/${child})
list(APPEND CMAKE_PREFIX_PATH ${LIBDIR}/${child})
endif()
if(IS_DIRECTORY ${LIBDIR}/${child})
list(APPEND CMAKE_PREFIX_PATH ${LIBDIR}/${child})
endif()
endforeach()
set(ZLIB_INCLUDE_DIRS ${LIBDIR}/zlib/include)
@@ -1437,23 +1475,28 @@ elseif(WIN32)
set(OPENEXR_INCLUDE_DIRS ${OPENEXR_INCLUDE_DIR} ${OPENEXR}/include/OpenEXR)
set(OPENEXR_LIBPATH ${OPENEXR}/lib)
set(OPENEXR_LIBRARIES
${OPENEXR_LIBPATH}/Iex-2_2.lib
${OPENEXR_LIBPATH}/Half.lib
${OPENEXR_LIBPATH}/IlmImf-2_2.lib
${OPENEXR_LIBPATH}/Imath-2_2.lib
${OPENEXR_LIBPATH}/IlmThread-2_2.lib
optimized ${OPENEXR_LIBPATH}/Iex-2_2.lib
optimized ${OPENEXR_LIBPATH}/Half.lib
optimized ${OPENEXR_LIBPATH}/IlmImf-2_2.lib
optimized ${OPENEXR_LIBPATH}/Imath-2_2.lib
optimized ${OPENEXR_LIBPATH}/IlmThread-2_2.lib
debug ${OPENEXR_LIBPATH}/Iex-2_2_d.lib
debug ${OPENEXR_LIBPATH}/Half_d.lib
debug ${OPENEXR_LIBPATH}/IlmImf-2_2_d.lib
debug ${OPENEXR_LIBPATH}/Imath-2_2_d.lib
debug ${OPENEXR_LIBPATH}/IlmThread-2_2_d.lib
)
endif()
endif()
if(WITH_IMAGE_TIFF)
# Try to find tiff first then complain and set static and maybe wrong paths
find_package(TIFF)
if(NOT TIFF_FOUND)
message(WARNING "Using HARDCODED libtiff locations")
set(TIFF_LIBRARY ${LIBDIR}/tiff/lib/libtiff.lib)
set(TIFF_INCLUDE_DIR ${LIBDIR}/tiff/include)
endif()
# Try to find tiff first then complain and set static and maybe wrong paths
find_package(TIFF)
if(NOT TIFF_FOUND)
message(WARNING "Using HARDCODED libtiff locations")
set(TIFF_LIBRARY ${LIBDIR}/tiff/lib/libtiff.lib)
set(TIFF_INCLUDE_DIR ${LIBDIR}/tiff/include)
endif()
endif()
if(WITH_JACK)
@@ -1508,12 +1551,17 @@ elseif(WIN32)
set(BOOST_DEBUG_POSTFIX "vc140-mt-sgd-1_60.lib")
endif()
set(BOOST_LIBRARIES
optimized libboost_date_time-${BOOST_POSTFIX} optimized libboost_filesystem-${BOOST_POSTFIX}
optimized libboost_date_time-${BOOST_POSTFIX}
optimized libboost_filesystem-${BOOST_POSTFIX}
optimized libboost_regex-${BOOST_POSTFIX}
optimized libboost_system-${BOOST_POSTFIX} optimized libboost_thread-${BOOST_POSTFIX}
debug libboost_date_time-${BOOST_DEBUG_POSTFIX} debug libboost_filesystem-${BOOST_DEBUG_POSTFIX}
optimized libboost_system-${BOOST_POSTFIX}
optimized libboost_thread-${BOOST_POSTFIX}
debug libboost_date_time-${BOOST_DEBUG_POSTFIX}
debug libboost_filesystem-${BOOST_DEBUG_POSTFIX}
debug libboost_regex-${BOOST_DEBUG_POSTFIX}
debug libboost_system-${BOOST_DEBUG_POSTFIX} debug libboost_thread-${BOOST_DEBUG_POSTFIX})
debug libboost_system-${BOOST_DEBUG_POSTFIX}
debug libboost_thread-${BOOST_DEBUG_POSTFIX}
)
if(WITH_CYCLES_OSL)
set(BOOST_LIBRARIES ${BOOST_LIBRARIES}
optimized libboost_wave-${BOOST_POSTFIX}
@@ -1580,12 +1628,12 @@ elseif(WIN32)
endif()
if(WITH_OPENVDB)
set(BLOSC_LIBRARIES ${LIBDIR}/blosc/lib/libblosc.lib)
set(TBB_LIBRARIES ${LIBDIR}/tbb/lib/tbb.lib)
set(BLOSC_LIBRARIES optimized ${LIBDIR}/blosc/lib/libblosc.lib debug ${LIBDIR}/blosc/lib/libblosc_d.lib)
set(TBB_LIBRARIES optimized ${LIBDIR}/tbb/lib/tbb.lib debug ${LIBDIR}/tbb/lib/tbb_debug.lib)
set(TBB_INCLUDE_DIR ${LIBDIR}/tbb/include)
set(OPENVDB ${LIBDIR}/openvdb)
set(OPENVDB_INCLUDE_DIRS ${OPENVDB}/include ${TBB_INCLUDE_DIR})
set(OPENVDB_LIBRARIES openvdb ${TBB_LIBRARIES} ${BLOSC_LIBRARIES})
set(OPENVDB_LIBRARIES optimized openvdb debug openvdb_d ${TBB_LIBRARIES} ${BLOSC_LIBRARIES})
set(OPENVDB_LIBPATH ${LIBDIR}/openvdb/lib)
endif()
@@ -1642,7 +1690,8 @@ elseif(WIN32)
#endif
int main(void) { return 0; }
"
WITH_MINGW64)
WITH_MINGW64
)
if(NOT DEFINED LIBDIR)
if(WITH_MINGW64)
@@ -1663,7 +1712,10 @@ elseif(WIN32)
message(FATAL_ERROR "Windows requires pre-compiled libs at: '${LIBDIR}'")
endif()
list(APPEND PLATFORM_LINKLIBS -lshell32 -lshfolder -lgdi32 -lmsvcrt -lwinmm -lmingw32 -lm -lws2_32 -lz -lstdc++ -lole32 -luuid -lwsock32 -lpsapi -ldbghelp)
list(APPEND PLATFORM_LINKLIBS
-lshell32 -lshfolder -lgdi32 -lmsvcrt -lwinmm -lmingw32 -lm -lws2_32
-lz -lstdc++ -lole32 -luuid -lwsock32 -lpsapi -ldbghelp
)
if(WITH_INPUT_IME)
list(APPEND PLATFORM_LINKLIBS -limm32)
@@ -1732,7 +1784,14 @@ elseif(WIN32)
${OPENCOLLADA}/include/opencollada/GeneratedSaxParser
)
set(OPENCOLLADA_LIBPATH ${OPENCOLLADA}/lib/opencollada)
set(OPENCOLLADA_LIBRARIES OpenCOLLADAStreamWriter OpenCOLLADASaxFrameworkLoader OpenCOLLADAFramework OpenCOLLADABaseUtils GeneratedSaxParser UTF MathMLSolver buffer ftoa xml)
set(OPENCOLLADA_LIBRARIES
OpenCOLLADAStreamWriter
OpenCOLLADASaxFrameworkLoader
OpenCOLLADAFramework
OpenCOLLADABaseUtils
GeneratedSaxParser
UTF MathMLSolver buffer ftoa xml
)
set(PCRE_LIBRARIES pcre)
endif()
@@ -1805,12 +1864,14 @@ elseif(WIN32)
if(WITH_INTERNATIONAL)
set(BOOST_LIBRARIES ${BOOST_LIBRARIES}
optimized boost_locale-${BOOST_POSTFIX}
debug boost_locale-${BOOST_DEBUG_POSTFIX})
debug boost_locale-${BOOST_DEBUG_POSTFIX}
)
endif()
if(WITH_CYCLES_OSL)
set(BOOST_LIBRARIES ${BOOST_LIBRARIES}
optimized boost_wave-${BOOST_POSTFIX}
debug boost_wave-${BOOST_DEBUG_POSTFIX})
debug boost_wave-${BOOST_DEBUG_POSTFIX}
)
endif()
set(BOOST_LIBPATH ${BOOST}/lib)
set(BOOST_DEFINITIONS "-DBOOST_ALL_NO_LIB -DBOOST_THREAD_USE_LIB ")
@@ -1919,7 +1980,14 @@ elseif(WIN32)
find_library(OSL_LIB_EXEC_DEBUG NAMES oslexec_d PATHS ${CYCLES_OSL}/lib)
find_library(OSL_LIB_COMP_DEBUG NAMES oslcomp_d PATHS ${CYCLES_OSL}/lib)
find_library(OSL_LIB_QUERY_DEBUG NAMES oslquery_d PATHS ${CYCLES_OSL}/lib)
list(APPEND OSL_LIBRARIES optimized ${OSL_LIB_COMP} optimized ${OSL_LIB_EXEC} optimized ${OSL_LIB_QUERY} debug ${OSL_LIB_EXEC_DEBUG} debug ${OSL_LIB_COMP_DEBUG} debug ${OSL_LIB_QUERY_DEBUG})
list(APPEND OSL_LIBRARIES
optimized ${OSL_LIB_COMP}
optimized ${OSL_LIB_EXEC}
optimized ${OSL_LIB_QUERY}
debug ${OSL_LIB_EXEC_DEBUG}
debug ${OSL_LIB_COMP_DEBUG}
debug ${OSL_LIB_QUERY_DEBUG}
)
find_path(OSL_INCLUDE_DIR OSL/oslclosure.h PATHS ${CYCLES_OSL}/include)
find_program(OSL_COMPILER NAMES oslc PATHS ${CYCLES_OSL}/bin)
@@ -1933,20 +2001,8 @@ elseif(WIN32)
elseif(APPLE)
if(${CMAKE_OSX_DEPLOYMENT_TARGET} STREQUAL "10.5" OR ${CMAKE_OSX_DEPLOYMENT_TARGET} STRGREATER "10.5")
set(WITH_LIBS10.5 ON CACHE BOOL "Use 10.5 libs" FORCE) # valid also for 10.6/7/8/9
endif()
if(NOT DEFINED LIBDIR)
if(WITH_LIBS10.5)
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-9.x.universal)
else()
if(CMAKE_OSX_ARCHITECTURES MATCHES i386)
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-8.x.i386)
else()
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-8.0.0-powerpc)
endif()
endif()
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-9.x.universal)
else()
message(STATUS "Using pre-compiled LIBDIR: ${LIBDIR}")
endif()
@@ -1998,22 +2054,30 @@ elseif(APPLE)
if(NOT WITH_PYTHON_MODULE AND NOT WITH_PYTHON_FRAMEWORK)
# normally cached but not since we include them with blender
set(PYTHON_INCLUDE_DIR "${LIBDIR}/python/include/python${PYTHON_VERSION}m")
# set(PYTHON_EXECUTABLE "${LIBDIR}/python/bin/python${PYTHON_VERSION}") # not used yet
set(PYTHON_EXECUTABLE "${LIBDIR}/python/bin/python${PYTHON_VERSION}m")
set(PYTHON_LIBRARY python${PYTHON_VERSION}m)
set(PYTHON_LIBPATH "${LIBDIR}/python/lib/python${PYTHON_VERSION}")
# set(PYTHON_LINKFLAGS "-u _PyMac_Error") # won't build with this enabled
else()
# module must be compiled against Python framework
set(PYTHON_INCLUDE_DIR "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/include/python${PYTHON_VERSION}m")
set(PYTHON_EXECUTABLE "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/bin/python${PYTHON_VERSION}")
set(_py_framework "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}")
set(PYTHON_INCLUDE_DIR "${_py_framework}/include/python${PYTHON_VERSION}m")
set(PYTHON_EXECUTABLE "${_py_framework}/bin/python${PYTHON_VERSION}m")
set(PYTHON_LIBPATH "${_py_framework}/lib/python${PYTHON_VERSION}/config-${PYTHON_VERSION}m")
#set(PYTHON_LIBRARY python${PYTHON_VERSION})
set(PYTHON_LIBPATH "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/lib/python${PYTHON_VERSION}/config-${PYTHON_VERSION}m")
#set(PYTHON_LINKFLAGS "-u _PyMac_Error -framework Python") # won't build with this enabled
unset(_py_framework)
endif()
# uncached vars
set(PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIR}")
set(PYTHON_LIBRARIES "${PYTHON_LIBRARY}")
if(NOT EXISTS "${PYTHON_EXECUTABLE}")
message(FATAL_ERROR "Python executable missing: ${PYTHON_EXECUTABLE}")
endif()
endif()
if(WITH_FFTW3)
@@ -2046,7 +2110,10 @@ elseif(APPLE)
if(WITH_CODEC_FFMPEG)
set(FFMPEG ${LIBDIR}/ffmpeg)
set(FFMPEG_INCLUDE_DIRS ${FFMPEG}/include)
set(FFMPEG_LIBRARIES avcodec avdevice avformat avutil mp3lame swscale x264 xvidcore theora theoradec theoraenc vorbis vorbisenc vorbisfile ogg)
set(FFMPEG_LIBRARIES
avcodec avdevice avformat avutil
mp3lame swscale x264 xvidcore theora theoradec theoraenc vorbis vorbisenc vorbisfile ogg
)
set(FFMPEG_LIBPATH ${FFMPEG}/lib)
endif()
@@ -2057,13 +2124,13 @@ elseif(APPLE)
)
mark_as_advanced(SYSTEMSTUBS_LIBRARY)
if(SYSTEMSTUBS_LIBRARY)
list(APPEND PLATFORM_LINKLIBS stdc++ SystemStubs)
else()
list(APPEND PLATFORM_LINKLIBS stdc++)
list(APPEND PLATFORM_LINKLIBS SystemStubs)
endif()
set(PLATFORM_CFLAGS "-pipe -funsigned-char")
set(PLATFORM_LINKFLAGS "-fexceptions -framework CoreServices -framework Foundation -framework IOKit -framework AppKit -framework Cocoa -framework Carbon -framework AudioUnit -framework AudioToolbox -framework CoreAudio")
set(PLATFORM_LINKFLAGS
"-fexceptions -framework CoreServices -framework Foundation -framework IOKit -framework AppKit -framework Cocoa -framework Carbon -framework AudioUnit -framework AudioToolbox -framework CoreAudio"
)
if(WITH_CODEC_QUICKTIME)
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -framework QTKit")
if(CMAKE_OSX_ARCHITECTURES MATCHES i386)
@@ -2072,6 +2139,12 @@ elseif(APPLE)
endif()
endif()
if(WITH_CXX11)
list(APPEND PLATFORM_LINKLIBS c++)
else()
list(APPEND PLATFORM_LINKLIBS stdc++)
endif()
# XXX - SOME MAC DEV PLEASE TEST WITH THE SDK INSTALLED!
# ALSO SHOULD BE MOVED INTO OWN MODULE WHEN FUNCTIONAL
if(WITH_INPUT_NDOF)
@@ -2095,7 +2168,8 @@ elseif(APPLE)
endif()
if(WITH_PYTHON_MODULE OR WITH_PYTHON_FRAMEWORK)
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/Python")# force cmake to link right framework
# force cmake to link right framework
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/Python")
endif()
if(WITH_OPENCOLLADA)
@@ -2110,10 +2184,18 @@ elseif(APPLE)
)
set(OPENCOLLADA_LIBPATH ${OPENCOLLADA}/lib)
set(OPENCOLLADA_LIBRARIES "OpenCOLLADASaxFrameworkLoader -lOpenCOLLADAFramework -lOpenCOLLADABaseUtils -lOpenCOLLADAStreamWriter -lMathMLSolver -lGeneratedSaxParser -lxml2 -lbuffer -lftoa")
set(OPENCOLLADA_LIBRARIES
OpenCOLLADASaxFrameworkLoader
-lOpenCOLLADAFramework
-lOpenCOLLADABaseUtils
-lOpenCOLLADAStreamWriter
-lMathMLSolver
-lGeneratedSaxParser
-lxml2 -lbuffer -lftoa
)
# Use UTF functions from collada if LLVM is not enabled
if(NOT WITH_LLVM)
set(OPENCOLLADA_LIBRARIES "${OPENCOLLADA_LIBRARIES} -lUTF")
list(APPEND OPENCOLLADA_LIBRARIES -lUTF)
endif()
# pcre is bundled with openCollada
#set(PCRE ${LIBDIR}/pcre)
@@ -2155,7 +2237,14 @@ elseif(APPLE)
if(WITH_BOOST)
set(BOOST ${LIBDIR}/boost)
set(BOOST_INCLUDE_DIR ${BOOST}/include)
set(BOOST_LIBRARIES boost_date_time-mt boost_filesystem-mt boost_regex-mt boost_system-mt boost_thread-mt boost_wave-mt)
set(BOOST_LIBRARIES
boost_date_time-mt
boost_filesystem-mt
boost_regex-mt
boost_system-mt
boost_thread-mt
boost_wave-mt
)
if(WITH_INTERNATIONAL)
list(APPEND BOOST_LIBRARIES boost_locale-mt)
endif()
@@ -2176,8 +2265,22 @@ elseif(APPLE)
if(WITH_OPENIMAGEIO)
set(OPENIMAGEIO ${LIBDIR}/openimageio)
set(OPENIMAGEIO_INCLUDE_DIRS ${OPENIMAGEIO}/include)
set(OPENIMAGEIO_LIBRARIES ${OPENIMAGEIO}/lib/libOpenImageIO.a ${PNG_LIBRARIES} ${JPEG_LIBRARIES} ${TIFF_LIBRARY} ${OPENEXR_LIBRARIES} ${ZLIB_LIBRARIES})
set(OPENIMAGEIO_LIBPATH ${OPENIMAGEIO}/lib ${JPEG_LIBPATH} ${PNG_LIBPATH} ${TIFF_LIBPATH} ${OPENEXR_LIBPATH} ${ZLIB_LIBPATH})
set(OPENIMAGEIO_LIBRARIES
${OPENIMAGEIO}/lib/libOpenImageIO.a
${PNG_LIBRARIES}
${JPEG_LIBRARIES}
${TIFF_LIBRARY}
${OPENEXR_LIBRARIES}
${ZLIB_LIBRARIES}
)
set(OPENIMAGEIO_LIBPATH
${OPENIMAGEIO}/lib
${JPEG_LIBPATH}
${PNG_LIBPATH}
${TIFF_LIBPATH}
${OPENEXR_LIBPATH}
${ZLIB_LIBPATH}
)
set(OPENIMAGEIO_DEFINITIONS "-DOIIO_STATIC_BUILD")
set(OPENIMAGEIO_IDIFF "${LIBDIR}/openimageio/bin/idiff")
endif()
@@ -2270,8 +2373,14 @@ elseif(APPLE)
include_directories(${LIBDIR}/openmp/include)
link_directories(${LIBDIR}/openmp/lib)
# This is a workaround for our helperbinaries ( datatoc, masgfmt, ... ),
# They are linked also to omp lib, so we need it in builddir for runtime exexcution, TODO: remove all unneeded dependencies from these
execute_process(COMMAND ditto -arch ${CMAKE_OSX_ARCHITECTURES} ${LIBDIR}/openmp/lib/libiomp5.dylib ${CMAKE_BINARY_DIR}/Resources/lib/libiomp5.dylib) # for intermediate binaries, in respect to lib ID
# They are linked also to omp lib, so we need it in builddir for runtime exexcution,
# TODO: remove all unneeded dependencies from these
# for intermediate binaries, in respect to lib ID
execute_process(
COMMAND ditto -arch ${CMAKE_OSX_ARCHITECTURES}
${LIBDIR}/openmp/lib/libiomp5.dylib
${CMAKE_BINARY_DIR}/Resources/lib/libiomp5.dylib)
endif()
endif()
endif()
@@ -2297,7 +2406,20 @@ elseif(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth=1024")
endif()
# Get rid of eventually clashes, we export some symbols explicite as local
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -Xlinker -unexported_symbols_list -Xlinker ${CMAKE_SOURCE_DIR}/source/creator/osx_locals.map")
set(PLATFORM_LINKFLAGS
"${PLATFORM_LINKFLAGS} -Xlinker -unexported_symbols_list -Xlinker ${CMAKE_SOURCE_DIR}/source/creator/osx_locals.map"
)
if(WITH_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -stdlib=libc++")
endif()
# Suppress ranlib "has no symbols" warnings (workaround for T48250)
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> -no_warning_for_no_symbols -c <TARGET>")
set(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -no_warning_for_no_symbols -c <TARGET>")
endif()
#-----------------------------------------------------------------------------
@@ -2309,38 +2431,50 @@ endif()
if(WITH_CYCLES)
if(NOT WITH_OPENIMAGEIO)
message(FATAL_ERROR "Cycles requires WITH_OPENIMAGEIO, the library may not have been found. Configure OIIO or disable WITH_CYCLES")
message(FATAL_ERROR
"Cycles requires WITH_OPENIMAGEIO, the library may not have been found. "
"Configure OIIO or disable WITH_CYCLES"
)
endif()
if(NOT WITH_BOOST)
message(FATAL_ERROR "Cycles requires WITH_BOOST, the library may not have been found. Configure BOOST or disable WITH_CYCLES")
message(FATAL_ERROR
"Cycles requires WITH_BOOST, the library may not have been found. "
"Configure BOOST or disable WITH_CYCLES"
)
endif()
if(WITH_CYCLES_OSL)
if(NOT WITH_LLVM)
message(FATAL_ERROR "Cycles OSL requires WITH_LLVM, the library may not have been found. Configure LLVM or disable WITH_CYCLES_OSL")
message(FATAL_ERROR
"Cycles OSL requires WITH_LLVM, the library may not have been found. "
"Configure LLVM or disable WITH_CYCLES_OSL"
)
endif()
endif()
endif()
if(WITH_INTERNATIONAL)
if(NOT WITH_BOOST)
message(FATAL_ERROR "Internationalization requires WITH_BOOST, the library may not have been found. Configure BOOST or disable WITH_INTERNATIONAL")
message(FATAL_ERROR
"Internationalization requires WITH_BOOST, the library may not have been found. "
"Configure BOOST or disable WITH_INTERNATIONAL"
)
endif()
endif()
# See TEST_SSE_SUPPORT() for how this is defined.
if(WITH_RAYOPTIMIZATION)
if(SUPPORT_SSE_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE__ -D__MMX__)
endif()
if(SUPPORT_SSE2_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE2_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE2__)
if(NOT SUPPORT_SSE_BUILD) # dont double up
add_definitions(-D__MMX__)
endif()
# Do it globally, SSE2 is required for quite some time now.
# Doing it now allows to use SSE/SSE2 in inline headers.
if(SUPPORT_SSE_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE__ -D__MMX__)
endif()
if(SUPPORT_SSE2_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE2_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE2__)
if(NOT SUPPORT_SSE_BUILD) # dont double up
add_definitions(-D__MMX__)
endif()
endif()
@@ -2410,7 +2544,10 @@ if(WITH_GL_PROFILE_COMPAT OR WITH_GL_PROFILE_CORE)
elseif(WITH_GL_PROFILE_ES20)
if(WITH_SYSTEM_GLES)
if(NOT OPENGLES_LIBRARY)
message(FATAL_ERROR "Unable to find OpenGL ES libraries. Install them or disable WITH_SYSTEM_GLES.")
message(FATAL_ERROR
"Unable to find OpenGL ES libraries. "
"Install them or disable WITH_SYSTEM_GLES."
)
endif()
list(APPEND BLENDER_GL_LIBRARIES OPENGLES_LIBRARY)
@@ -2422,7 +2559,10 @@ elseif(WITH_GL_PROFILE_ES20)
list(APPEND BLENDER_GL_LIBRARIES "${OPENGLES_LIBRARY}")
if(NOT OPENGLES_LIBRARY)
message(FATAL_ERROR "To compile WITH_GL_EGL you need to set OPENGLES_LIBRARY to the file path of an OpenGL ES 2.0 library.")
message(FATAL_ERROR
"To compile WITH_GL_EGL you need to set OPENGLES_LIBRARY "
"to the file path of an OpenGL ES 2.0 library."
)
endif()
endif()
@@ -2434,7 +2574,10 @@ elseif(WITH_GL_PROFILE_ES20)
mark_as_advanced(OPENGLES_DLL)
if(NOT OPENGLES_DLL)
message(FATAL_ERROR "To compile WITH_GL_PROFILE_ES20 you need to set OPENGLES_DLL to the file path of an OpenGL ES 2.0 runtime dynamic link library (DLL).")
message(FATAL_ERROR
"To compile WITH_GL_PROFILE_ES20 you need to set OPENGLES_DLL to the file "
"path of an OpenGL ES 2.0 runtime dynamic link library (DLL)."
)
endif()
if(WITH_GL_ANGLE)
@@ -2448,7 +2591,10 @@ elseif(WITH_GL_PROFILE_ES20)
mark_as_advanced(D3DCOMPILER_DLL)
if(D3DCOMPILER_DLL STREQUAL "")
message(FATAL_ERROR "To compile WITH_GL_ANGLE you need to set D3DCOMPILER_DLL to the file path of a copy of the DirectX redistributable DLL file: D3DCompiler_46.dll")
message(FATAL_ERROR
"To compile WITH_GL_ANGLE you need to set D3DCOMPILER_DLL to the file "
"path of a copy of the DirectX redistributable DLL file: D3DCompiler_46.dll"
)
endif()
endif()
@@ -2462,7 +2608,10 @@ if(WITH_GL_EGL)
if(WITH_SYSTEM_GLES)
if(NOT OPENGLES_EGL_LIBRARY)
message(FATAL_ERROR "Unable to find OpenGL ES libraries. Install them or disable WITH_SYSTEM_GLES.")
message(FATAL_ERROR
"Unable to find OpenGL ES libraries. "
"Install them or disable WITH_SYSTEM_GLES."
)
endif()
list(APPEND BLENDER_GL_LIBRARIES OPENGLES_EGL_LIBRARY)
@@ -2474,7 +2623,10 @@ if(WITH_GL_EGL)
list(APPEND BLENDER_GL_LIBRARIES "${OPENGLES_LIBRARY}" "${OPENGLES_EGL_LIBRARY}")
if(NOT OPENGLES_EGL_LIBRARY)
message(FATAL_ERROR "To compile WITH_GL_EGL you need to set OPENGLES_EGL_LIBRARY to the file path of an EGL library.")
message(FATAL_ERROR
"To compile WITH_GL_EGL you need to set OPENGLES_EGL_LIBRARY "
"to the file path of an EGL library."
)
endif()
endif()
@@ -2486,7 +2638,10 @@ if(WITH_GL_EGL)
mark_as_advanced(OPENGLES_EGL_DLL)
if(NOT OPENGLES_EGL_DLL)
message(FATAL_ERROR "To compile WITH_GL_EGL you need to set OPENGLES_EGL_DLL to the file path of an EGL runtime dynamic link library (DLL).")
message(FATAL_ERROR
"To compile WITH_GL_EGL you need to set OPENGLES_EGL_DLL "
"to the file path of an EGL runtime dynamic link library (DLL)."
)
endif()
endif()
@@ -2651,7 +2806,9 @@ endif()
if(WITH_LIBMV)
set(CERES_DEFINES)
if(SHARED_PTR_FOUND)
if(WITH_CXX11)
# nothing to be done
elseif(SHARED_PTR_FOUND)
if(SHARED_PTR_TR1_MEMORY_HEADER)
list(APPEND CERES_DEFINES -DCERES_TR1_MEMORY_HEADER)
endif()
@@ -2662,7 +2819,9 @@ if(WITH_LIBMV)
message(FATAL_ERROR "Ceres: Unable to find shared_ptr.")
endif()
if(HAVE_STD_UNORDERED_MAP_HEADER)
if(WITH_CXX11)
list(APPEND CERES_DEFINES -DCERES_STD_UNORDERED_MAP)
elseif(HAVE_STD_UNORDERED_MAP_HEADER)
if(HAVE_UNORDERED_MAP_IN_STD_NAMESPACE)
list(APPEND CERES_DEFINES -DCERES_STD_UNORDERED_MAP)
else()
@@ -2864,10 +3023,12 @@ endif()
# be most problematic.
if(WITH_PYTHON)
if(NOT EXISTS "${PYTHON_INCLUDE_DIR}/Python.h")
message(FATAL_ERROR "Missing: \"${PYTHON_INCLUDE_DIR}/Python.h\",\n"
"Set the cache entry 'PYTHON_INCLUDE_DIR' to point "
"to a valid python include path. Containing "
"Python.h for python version \"${PYTHON_VERSION}\"")
message(FATAL_ERROR
"Missing: \"${PYTHON_INCLUDE_DIR}/Python.h\",\n"
"Set the cache entry 'PYTHON_INCLUDE_DIR' to point "
"to a valid python include path. Containing "
"Python.h for python version \"${PYTHON_VERSION}\""
)
endif()
if(WIN32 OR APPLE)
@@ -3005,7 +3166,7 @@ if(FIRST_RUN)
string(LENGTH "${_msg}" _len)
while("32" GREATER "${_len}")
set(_msg "${_msg} ")
math(EXPR _len "${_len} + 1")
math(EXPR _len "${_len} + 1")
endwhile()
set(_config_msg "${_config_msg}\n${_msg}${${_setting}}" PARENT_SCOPE)

View File

@@ -87,13 +87,13 @@ ifndef NPROCS
NPROCS:=$(shell nproc)
endif
ifeq ($(OS), Darwin)
NPROCS:=$(shell sysctl -a | grep "hw.ncpu" | cut -d" " -f3)
NPROCS:=$(shell sysctl -n hw.ncpu)
endif
ifeq ($(OS), FreeBSD)
NPROCS:=$(shell sysctl -a | grep "hw.ncpu" | cut -d" " -f2 )
NPROCS:=$(shell sysctl -n hw.ncpu)
endif
ifeq ($(OS), NetBSD)
NPROCS:=$(shell sysctl -a | grep "hw.ncpu" | cut -d" " -f2 )
NPROCS:=$(shell sysctl -n hw.ncpu)
endif
endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,11 @@
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -13,7 +13,7 @@
set(LLVM_VERSION_MAJOR 3)
set(LLVM_VERSION_MINOR 1)
@@ -14,7 +14,7 @@
set(LLVM_VERSION_MINOR 4)
-set(PACKAGE_VERSION "\${LLVM_VERSION_MAJOR}.\${LLVM_VERSION_MINOR}svn")
+set(PACKAGE_VERSION "\${LLVM_VERSION_MAJOR}.\${LLVM_VERSION_MINOR}")
if (NOT PACKAGE_VERSION)
- set(PACKAGE_VERSION "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}svn")
+ set(PACKAGE_VERSION "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}")
endif()
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
option(LLVM_INSTALL_TOOLCHAIN_ONLY "Only include toolchain files in the 'install' target." OFF)

View File

@@ -87,7 +87,7 @@ c['change_source'] = GitPoller(
# CODEBASES
#
# Allow to controll separately things like branches for each repo and submodules.
# Allow to control separately things like branches for each repo and submodules.
all_repositories = {
r'git://git.blender.org/blender.git': 'blender',

View File

@@ -56,7 +56,6 @@ if 'cmake' in builder:
chroot_name = None # If not None command will be delegated to that chroot
cuda_chroot_name = None # If not None cuda compilationcommand will be delegated to that chroot
build_cubins = True # Whether to build Cycles CUDA kernels
remove_install_dir = False # Remove installation folder before building
bits = 64
# Config file to be used (relative to blender's sources root)
@@ -70,13 +69,12 @@ if 'cmake' in builder:
cuda_cmake_options = []
if builder.startswith('mac'):
install_dir = None
# Set up OSX architecture
if builder.endswith('x86_64_10_6_cmake'):
cmake_extra_options.append('-DCMAKE_OSX_ARCHITECTURES:STRING=x86_64')
cmake_extra_options.append('-DCUDA_NVCC_EXECUTABLE=/usr/local/cuda-hack/bin/nvcc')
elif builder.startswith('win'):
install_dir = None
if builder.startswith('win64'):
cmake_options.append(['-G', '"Visual Studio 12 2013 Win64"'])
elif builder.startswith('win32'):
@@ -90,7 +88,6 @@ if 'cmake' in builder:
deb_name = "jessie"
elif glibc == 'glibc211':
deb_name = "squeeze"
remove_install_dir = True
cmake_config_file = "build_files/buildbot/config/blender_linux.cmake"
cmake_player_config_file = "build_files/buildbot/config/blender_linux_player.cmake"
if builder.endswith('x86_64_cmake'):
@@ -116,8 +113,7 @@ if 'cmake' in builder:
if 'cuda' not in targets:
cmake_options += cuda_cmake_options
if install_dir:
cmake_options.append("-DCMAKE_INSTALL_PREFIX=%s" % (install_dir))
cmake_options.append("-DCMAKE_INSTALL_PREFIX=%s" % (install_dir))
cmake_options += cmake_extra_options
@@ -132,10 +128,8 @@ if 'cmake' in builder:
cuda_chroot_prefix = chroot_prefix[:]
# Make sure no garbage remained from the previous run
# (only do it if builder requested this)
if remove_install_dir:
if os.path.isdir(install_dir):
shutil.rmtree(install_dir)
if os.path.isdir(install_dir):
shutil.rmtree(install_dir)
for target in targets:
print("Building target %s" % (target))
@@ -187,7 +181,7 @@ if 'cmake' in builder:
sys.exit(retcode)
if builder.startswith('linux') and target == 'cuda':
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender.h")
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender_version.h")
blender_version = int(parse_header_file(blender_h, 'BLENDER_VERSION'))
blender_version = "%d.%d" % (blender_version // 100, blender_version % 100)
kernels = os.path.join(target_build_dir, 'intern', 'cycles', 'kernel')

View File

@@ -130,7 +130,7 @@ if builder.find('cmake') != -1:
blenderplayer = os.path.join(install_dir, 'blenderplayer')
buildinfo_h = os.path.join(build_dir, "source", "creator", "buildinfo.h")
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender.h")
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender_version.h")
# Get version information
blender_version = int(parse_header_file(blender_h, 'BLENDER_VERSION'))

View File

@@ -35,9 +35,8 @@ blender_dir = '../blender.git'
if "cmake" in builder:
# cmake
if "linux" in builder or 'mac' in builder:
print("Automated tests are still DISABLED!")
sys.exit(0)
print("Automated tests are still DISABLED!")
sys.exit(0)
build_dir = os.path.abspath(os.path.join('..', 'build', builder))
chroot_name = None

View File

@@ -1,5 +1,10 @@
# This is called by cmake as an extermal process from
# This is called by cmake as an external process from
# ./source/creator/CMakeLists.txt to write ./source/creator/buildinfo.h
# Caller must define:
# SOURCE_DIR
# Optional overrides:
# BUILD_DATE
# BUILD_TIME
# Extract working copy information for SOURCE_DIR into MY_XXX variables
# with a default in case anything fails, for example when using git-svn
@@ -128,12 +133,19 @@ endif()
# BUILD_PLATFORM and BUILD_PLATFORM are taken from CMake
# but BUILD_DATE and BUILD_TIME are platform dependent
if(UNIX)
execute_process(COMMAND date "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND date "+%H:%M:%S" OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if(WIN32)
execute_process(COMMAND cmd /c date /t OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND cmd /c time /t OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT BUILD_DATE)
execute_process(COMMAND date "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if(NOT BUILD_TIME)
execute_process(COMMAND date "+%H:%M:%S" OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
elseif(WIN32)
if(NOT BUILD_DATE)
execute_process(COMMAND cmd /c date /t OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if(NOT BUILD_TIME)
execute_process(COMMAND cmd /c time /t OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
endif()
# Write a file with the BUILD_HASH define

View File

@@ -240,9 +240,10 @@ def cmake_get_src(f):
filen.close()
def is_ignore(f):
for ig in IGNORE:
def is_ignore(f, ignore_used):
for index, ig in enumerate(IGNORE):
if ig in f:
ignore_used[index] = True
return True
return False
@@ -283,10 +284,12 @@ def main():
del is_err
del errs
ignore_used = [False] * len(IGNORE)
# now check on files not accounted for.
print("\nC/C++ Files CMake doesnt know about...")
for cf in sorted(source_list(SOURCE_DIR, is_c)):
if not is_ignore(cf):
if not is_ignore(cf, ignore_used):
if cf not in global_c:
print("missing_c: ", cf)
@@ -303,7 +306,7 @@ def main():
print("\nC/C++ Headers CMake doesnt know about...")
for hf in sorted(source_list(SOURCE_DIR, is_c_header)):
if not is_ignore(hf):
if not is_ignore(hf, ignore_used):
if hf not in global_h:
print("missing_h: ", hf)
@@ -324,5 +327,12 @@ def main():
if i > 1:
traceback.print_exc()
# Check ignores aren't stale
print("\nCheck for unused 'IGNORE' paths...")
for index, ig in enumerate(IGNORE):
if not ignore_used[index]:
print("unused ignore: %r" % ig)
if __name__ == "__main__":
main()

View File

@@ -3,11 +3,7 @@ import os
IGNORE = (
"/test/",
"/tests/gtests/",
"/BSP_GhostTest/",
"/release/",
"/xembed/",
"/TerraplayNetwork/",
"/ik_glut_test/",
# specific source files
"extern/bullet2/src/BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.cpp",
@@ -18,31 +14,8 @@ IGNORE = (
"extern/bullet2/src/BulletDynamics/Character/btKinematicCharacterController.cpp",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btHinge2Constraint.cpp",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.cpp",
"extern/eltopo/common/meshes/ObjLoader.cpp",
"extern/eltopo/common/meshes/meshloader.cpp",
"extern/eltopo/common/openglutils.cpp",
"extern/eltopo/eltopo3d/broadphase_blenderbvh.cpp",
"source/blender/imbuf/intern/imbuf_cocoa.m",
"extern/recastnavigation/Recast/Source/RecastLog.cpp",
"extern/recastnavigation/Recast/Source/RecastTimer.cpp",
"intern/audaspace/SRC/AUD_SRCResampleFactory.cpp",
"intern/audaspace/SRC/AUD_SRCResampleReader.cpp",
"intern/cycles/render/film_response.cpp",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_2.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_d.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_9.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_d.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_4_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_4_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_4_d.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_2.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_d.cc",
"extern/bullet2/src/BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h",
"extern/bullet2/src/BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.h",
@@ -52,20 +25,12 @@ IGNORE = (
"extern/bullet2/src/BulletDynamics/Character/btKinematicCharacterController.h",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btHinge2Constraint.h",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.h",
"extern/eltopo/common/meshes/Edge.hpp",
"extern/eltopo/common/meshes/ObjLoader.hpp",
"extern/eltopo/common/meshes/TriangleIndex.hpp",
"extern/eltopo/common/meshes/meshloader.h",
"extern/eltopo/eltopo3d/broadphase_blenderbvh.h",
"extern/recastnavigation/Recast/Include/RecastLog.h",
"extern/recastnavigation/Recast/Include/RecastTimer.h",
"extern/carve/include/carve/config.h",
"extern/carve/include/carve/random/random.h",
"extern/carve/patches/files/config.h",
"extern/carve/patches/files/random.h",
"intern/audaspace/SRC/AUD_SRCResampleFactory.h",
"intern/audaspace/SRC/AUD_SRCResampleReader.h",
"intern/cycles/render/film_response.h",
"extern/carve/include/carve/config.h",
"extern/carve/include/carve/external/boost/random.hpp",
"extern/carve/patches/files/config.h",
"extern/carve/patches/files/random.hpp",
)
UTF8_CHECK = True

View File

@@ -54,7 +54,7 @@ set(WITH_PLAYER ON CACHE BOOL "" FORCE)
set(WITH_MEM_JEMALLOC ON CACHE BOOL "" FORCE)
# platform dependant options
# platform dependent options
if(UNIX AND NOT APPLE)
set(WITH_JACK ON CACHE BOOL "" FORCE)
set(WITH_DOC_MANPAGE ON CACHE BOOL "" FORCE)
@@ -69,7 +69,7 @@ elseif(WIN32)
set(WITH_CODEC_SNDFILE OFF CACHE BOOL "" FORCE)
set(WITH_CYCLES_OSL OFF CACHE BOOL "" FORCE)
endif()
elseif (APPLE)
elseif(APPLE)
set(WITH_JACK ON CACHE BOOL "" FORCE)
set(WITH_CODEC_QUICKTIME ON CACHE BOOL "" FORCE)
set(WITH_OPENSUBDIV OFF CACHE BOOL "" FORCE)

View File

@@ -14,6 +14,7 @@ set(WITH_CODEC_AVI OFF CACHE BOOL "" FORCE)
set(WITH_CODEC_FFMPEG OFF CACHE BOOL "" FORCE)
set(WITH_CODEC_SNDFILE OFF CACHE BOOL "" FORCE)
set(WITH_CYCLES OFF CACHE BOOL "" FORCE)
set(WITH_CYCLES_OSL OFF CACHE BOOL "" FORCE)
set(WITH_FFTW3 OFF CACHE BOOL "" FORCE)
set(WITH_LIBMV OFF CACHE BOOL "" FORCE)
set(WITH_LLVM OFF CACHE BOOL "" FORCE)

View File

@@ -141,22 +141,6 @@ function(target_link_libraries_debug
endforeach()
endfunction()
function(target_link_libraries_decoupled
target
libraries_var
)
if(NOT MSVC)
target_link_libraries(${target} ${${libraries_var}})
else()
# For MSVC we link to different libraries depending whether
# release or debug target is being built.
file_list_suffix(_libraries_debug "${${libraries_var}}" "_d")
target_link_libraries_debug(${target} "${_libraries_debug}")
target_link_libraries_optimized(${target} "${${libraries_var}}")
endif()
endfunction()
# Nicer makefiles with -I/1/foo/ instead of -I/1/2/3/../../foo/
# use it instead of include_directories()
function(blender_include_dirs
@@ -412,14 +396,7 @@ function(setup_liblinks
endif()
target_link_libraries(${target} ${JPEG_LIBRARIES})
if(WITH_IMAGE_OPENEXR)
if(WIN32 AND NOT UNIX AND NOT CMAKE_COMPILER_IS_GNUCC)
file_list_suffix(OPENEXR_LIBRARIES_DEBUG "${OPENEXR_LIBRARIES}" "_d")
target_link_libraries_debug(${target} "${OPENEXR_LIBRARIES_DEBUG}")
target_link_libraries_optimized(${target} "${OPENEXR_LIBRARIES}")
unset(OPENEXR_LIBRARIES_DEBUG)
else()
target_link_libraries(${target} ${OPENEXR_LIBRARIES})
endif()
target_link_libraries(${target} ${OPENEXR_LIBRARIES})
endif()
if(WITH_IMAGE_OPENJPEG AND WITH_SYSTEM_OPENJPEG)
target_link_libraries(${target} ${OPENJPEG_LIBRARIES})
@@ -601,6 +578,7 @@ function(SETUP_BLENDER_SORTED_LIBS)
ge_phys_bullet
bf_intern_smoke
extern_lzma
extern_curve_fit_nd
ge_logic_ketsji
extern_recastnavigation
ge_logic
@@ -990,6 +968,7 @@ macro(remove_strict_flags)
remove_cc_flag(
"-Wstrict-prototypes"
"-Wmissing-prototypes"
"-Wmissing-declarations"
"-Wmissing-format-attribute"
"-Wunused-local-typedefs"
"-Wunused-macros"
@@ -1071,6 +1050,19 @@ macro(remove_strict_flags_file
endmacro()
# External libs may need 'signed char' to be default.
macro(remove_cc_flag_unsigned_char)
if(CMAKE_C_COMPILER_ID MATCHES "^(GNU|Clang|Intel)$")
remove_cc_flag("-funsigned-char")
elseif(MSVC)
remove_cc_flag("/J")
else()
message(WARNING
"Compiler '${CMAKE_C_COMPILER_ID}' failed to disable 'unsigned char' flag."
"Build files need updating."
)
endif()
endmacro()
function(ADD_CHECK_C_COMPILER_FLAG
_CFLAGS
@@ -1117,10 +1109,10 @@ function(get_blender_version)
# - BLENDER_VERSION_CYCLE (alpha, beta, rc, release)
# So cmake depends on BKE_blender.h, beware of inf-loops!
CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender.h
${CMAKE_BINARY_DIR}/source/blender/blenkernel/BKE_blender.h.done)
CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender_version.h
${CMAKE_BINARY_DIR}/source/blender/blenkernel/BKE_blender_version.h.done)
file(STRINGS ${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender.h _contents REGEX "^#define[ \t]+BLENDER_.*$")
file(STRINGS ${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender_version.h _contents REGEX "^#define[ \t]+BLENDER_.*$")
string(REGEX REPLACE ".*#define[ \t]+BLENDER_VERSION[ \t]+([0-9]+).*" "\\1" _out_version "${_contents}")
string(REGEX REPLACE ".*#define[ \t]+BLENDER_SUBVERSION[ \t]+([0-9]+).*" "\\1" _out_subversion "${_contents}")

View File

@@ -11,6 +11,10 @@
*
*/
/** \defgroup curve_fit Curve Fitting Library
* \ingroup extern
*/
/** \defgroup bullet Bullet Physics Library
* \ingroup extern
* \see \ref bulletdoc

View File

@@ -20,7 +20,7 @@ bpy.types.Scene.my_settings = \
bpy.props.CollectionProperty(type=SceneSettingItem)
# Assume an armature object selected
print("Adding 3 values!")
print("Adding 2 values!")
my_item = bpy.context.scene.my_settings.add()
my_item.name = "Spam"

View File

@@ -48,9 +48,9 @@ bpy.types.Scene.test_array = bpy.props.BoolVectorProperty(size=2, get=get_array,
# Note: the getter/setter callback must use integer identifiers!
test_items = [
("RED", "Red", "", 1),
("GREEN", "Red", "", 2),
("BLUE", "Red", "", 3),
("YELLOW", "Red", "", 4),
("GREEN", "Green", "", 2),
("BLUE", "Blue", "", 3),
("YELLOW", "Yellow", "", 4),
]

View File

@@ -60,37 +60,37 @@ base class --- :class:`KX_GameObject`
:type: float (read only)
..attribute:: shadowFrustumSize
.. attribute:: shadowFrustumSize
Size of the frustum used for creating the shadowmap.
:type: float (read only)
..attribute:: shadowBindId
.. attribute:: shadowBindId
The OpenGL shadow texture bind number/id.
:type: int (read only)
..attribute:: shadowMapType
.. attribute:: shadowMapType
The shadow shadow map type (0 -> Simple; 1 -> Variance)
:type: int (read only)
..attribute:: shadowBias
.. attribute:: shadowBias
The shadow buffer sampling bias.
:type: float (read only)
..attribute:: shadowBleedBias
.. attribute:: shadowBleedBias
The bias for reducing light-bleed on variance shadow maps.
:type: float (read only)
..attribute:: useShadow
.. attribute:: useShadow
Returns True if the light has Shadow option activated, else returns False.

View File

@@ -33,10 +33,10 @@ SSH_UPLOAD="/data/www/vhosts/www.blender.org/api" # blender_python_api_VERSION,
# "_".join(str(v) for v in bpy.app.version)
# custom blender vars
blender_srcdir=$(dirname -- $0)/../..
blender_version=$(grep "BLENDER_VERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_version_char=$(grep "BLENDER_VERSION_CHAR\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_version_cycle=$(grep "BLENDER_VERSION_CYCLE\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_subversion=$(grep "BLENDER_SUBVERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_version=$(grep "BLENDER_VERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
blender_version_char=$(grep "BLENDER_VERSION_CHAR\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
blender_version_cycle=$(grep "BLENDER_VERSION_CYCLE\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
blender_subversion=$(grep "BLENDER_SUBVERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
if [ "$blender_version_cycle" = "release" ] ; then
BLENDER_VERSION=$(expr $blender_version / 100)_$(expr $blender_version % 100)$blender_version_char"_release"

View File

@@ -23,6 +23,9 @@
#
# ***** END GPL LICENSE BLOCK *****
# Libs that adhere to strict flags
add_subdirectory(curve_fit_nd)
# Otherwise we get warnings here that we cant fix in external projects
remove_strict_flags()

View File

@@ -233,3 +233,92 @@ index e05bdcc..dbcf2b6 100644
#include "btVector3.h"
diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp
index e0e8bc7..a788268 100644
--- a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp
+++ b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp
@@ -425,50 +425,38 @@ void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
}
+bool btRigidBody::checkCollideWithOverride(const btCollisionObject* co) const
+{
+ const btRigidBody* otherRb = btRigidBody::upcast(co);
+ if (!otherRb)
+ return true;
+
+ for (int i = 0; i < m_constraintRefs.size(); ++i)
+ {
+ const btTypedConstraint* c = m_constraintRefs[i];
+ if (c->isEnabled())
+ if (&c->getRigidBodyA() == otherRb || &c->getRigidBodyB() == otherRb)
+ return false;
+ }
+
+ return true;
+}
void btRigidBody::addConstraintRef(btTypedConstraint* c)
{
- ///disable collision with the 'other' body
-
int index = m_constraintRefs.findLinearSearch(c);
- //don't add constraints that are already referenced
- //btAssert(index == m_constraintRefs.size());
if (index == m_constraintRefs.size())
- {
- m_constraintRefs.push_back(c);
- btCollisionObject* colObjA = &c->getRigidBodyA();
- btCollisionObject* colObjB = &c->getRigidBodyB();
- if (colObjA == this)
- {
- colObjA->setIgnoreCollisionCheck(colObjB, true);
- }
- else
- {
- colObjB->setIgnoreCollisionCheck(colObjA, true);
- }
- }
+ m_constraintRefs.push_back(c);
+
+ m_checkCollideWith = true;
}
void btRigidBody::removeConstraintRef(btTypedConstraint* c)
{
- int index = m_constraintRefs.findLinearSearch(c);
- //don't remove constraints that are not referenced
- if(index < m_constraintRefs.size())
- {
- m_constraintRefs.remove(c);
- btCollisionObject* colObjA = &c->getRigidBodyA();
- btCollisionObject* colObjB = &c->getRigidBodyB();
- if (colObjA == this)
- {
- colObjA->setIgnoreCollisionCheck(colObjB, false);
- }
- else
- {
- colObjB->setIgnoreCollisionCheck(colObjA, false);
- }
- }
+ m_constraintRefs.remove(c);
+ m_checkCollideWith = m_constraintRefs.size() > 0;
}
int btRigidBody::calculateSerializeBufferSize() const
diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h
index 1d177db..c2f8c5d 100644
--- a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h
+++ b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h
@@ -509,6 +509,8 @@ public:
return (getBroadphaseProxy() != 0);
}
+ virtual bool checkCollideWithOverride(const btCollisionObject* co) const;
+
void addConstraintRef(btTypedConstraint* c);
void removeConstraintRef(btTypedConstraint* c);

View File

@@ -425,50 +425,38 @@ void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
}
bool btRigidBody::checkCollideWithOverride(const btCollisionObject* co) const
{
const btRigidBody* otherRb = btRigidBody::upcast(co);
if (!otherRb)
return true;
for (int i = 0; i < m_constraintRefs.size(); ++i)
{
const btTypedConstraint* c = m_constraintRefs[i];
if (c->isEnabled())
if (&c->getRigidBodyA() == otherRb || &c->getRigidBodyB() == otherRb)
return false;
}
return true;
}
void btRigidBody::addConstraintRef(btTypedConstraint* c)
{
///disable collision with the 'other' body
int index = m_constraintRefs.findLinearSearch(c);
//don't add constraints that are already referenced
//btAssert(index == m_constraintRefs.size());
if (index == m_constraintRefs.size())
{
m_constraintRefs.push_back(c);
btCollisionObject* colObjA = &c->getRigidBodyA();
btCollisionObject* colObjB = &c->getRigidBodyB();
if (colObjA == this)
{
colObjA->setIgnoreCollisionCheck(colObjB, true);
}
else
{
colObjB->setIgnoreCollisionCheck(colObjA, true);
}
}
m_constraintRefs.push_back(c);
m_checkCollideWith = true;
}
void btRigidBody::removeConstraintRef(btTypedConstraint* c)
{
int index = m_constraintRefs.findLinearSearch(c);
//don't remove constraints that are not referenced
if(index < m_constraintRefs.size())
{
m_constraintRefs.remove(c);
btCollisionObject* colObjA = &c->getRigidBodyA();
btCollisionObject* colObjB = &c->getRigidBodyB();
if (colObjA == this)
{
colObjA->setIgnoreCollisionCheck(colObjB, false);
}
else
{
colObjB->setIgnoreCollisionCheck(colObjA, false);
}
}
m_constraintRefs.remove(c);
m_checkCollideWith = m_constraintRefs.size() > 0;
}
int btRigidBody::calculateSerializeBufferSize() const

View File

@@ -509,6 +509,8 @@ public:
return (getBroadphaseProxy() != 0);
}
virtual bool checkCollideWithOverride(const btCollisionObject* co) const;
void addConstraintRef(btTypedConstraint* c);
void removeConstraintRef(btTypedConstraint* c);

View File

@@ -51,6 +51,7 @@ namespace {
bottom_out = -displacement.cross(top_out) + rotation_matrix * bottom_in;
}
/*
void InverseSpatialTransform(const btMatrix3x3 &rotation_matrix,
const btVector3 &displacement,
const btVector3 &top_in,
@@ -80,6 +81,7 @@ namespace {
top_out = a_top.cross(b_top);
bottom_out = a_bottom.cross(b_top) + a_top.cross(b_bottom);
}
*/
}

View File

@@ -1127,6 +1127,7 @@ int nattrb=0;
int hasbounds=0;
int result = sscanf(node,"%d %d %d %d",&nnode,&ndims,&nattrb,&hasbounds);
result = sscanf(node,"%d %d %d %d",&nnode,&ndims,&nattrb,&hasbounds);
(void)result;
node += nextLine(node);
pos.resize(nnode);
@@ -1208,10 +1209,10 @@ if(ele&&ele[0])
}
}
}
printf("Nodes: %u\r\n",psb->m_nodes.size());
printf("Links: %u\r\n",psb->m_links.size());
printf("Faces: %u\r\n",psb->m_faces.size());
printf("Tetras: %u\r\n",psb->m_tetras.size());
printf("Nodes: %d\r\n",psb->m_nodes.size());
printf("Links: %d\r\n",psb->m_links.size());
printf("Faces: %d\r\n",psb->m_faces.size());
printf("Tetras: %d\r\n",psb->m_tetras.size());
return(psb);
}

View File

@@ -422,7 +422,7 @@ static inline btVector3 BaryCoord( const btVector3& a,
}
//
static btScalar ImplicitSolve( btSoftBody::ImplicitFn* fn,
static inline btScalar ImplicitSolve( btSoftBody::ImplicitFn* fn,
const btVector3& a,
const btVector3& b,
const btScalar accuracy,
@@ -504,7 +504,7 @@ static inline btScalar VolumeOf( const btVector3& x0,
}
//
static void EvaluateMedium( const btSoftBodyWorldInfo* wfi,
static inline void EvaluateMedium( const btSoftBodyWorldInfo* wfi,
const btVector3& x,
btSoftBody::sMedium& medium)
{

View File

@@ -157,6 +157,7 @@ namespace carve {
return pointInPoly(points, p2_adapt_ident(), p);
}
#if 0
static int lineSegmentPolyIntersections(const P2Vector &points,
LineSegment2 line,
std::vector<PolyIntersectionInfo> &out) {
@@ -224,6 +225,7 @@ namespace carve {
}
return count;
}
#endif
struct FwdSort {
bool operator()(const PolyIntersectionInfo &a,
@@ -239,6 +241,7 @@ namespace carve {
}
};
#if 0
static int sortedLineSegmentPolyIntersections(const P2Vector &points,
LineSegment2 line,
std::vector<PolyIntersectionInfo> &out) {
@@ -253,6 +256,7 @@ namespace carve {
}
return count;
}
#endif
bool pickContainedPoint(const std::vector<P2> &poly, P2 &result) {
return pickContainedPoint(poly, p2_adapt_ident(), result);

View File

@@ -28,6 +28,7 @@ namespace carve {
namespace geom3d {
namespace {
#if 0
int is_same(const std::vector<const Vector *> &a,
const std::vector<const Vector *> &b) {
if (a.size() != b.size()) return false;
@@ -52,6 +53,7 @@ not_fwd:
not_rev:
return 0;
}
#endif
}
bool planeIntersection(const Plane &a, const Plane &b, Ray &r) {

View File

@@ -236,6 +236,7 @@ namespace {
#if 0
void dump_intersections(std::ostream &out, carve::csg::Intersections &csg_intersections) {
std::vector<dump_data> temp;
@@ -284,13 +285,14 @@ namespace {
vertices.push_back(i_pt->v);
}
}
#endif
carve::point::PointSet points(vertices);
std::string outf("/tmp/intersection-points.ply");
::writePLY(outf, &points, true);
#endif
}
#endif
@@ -481,6 +483,7 @@ void carve::csg::CSG::makeVertexIntersections() {
#if 0
static carve::mesh::MeshSet<3>::vertex_t *chooseWeldPoint(
const carve::csg::detail::VSet &equivalent,
carve::csg::VertexPool &vertex_pool) {
@@ -537,7 +540,7 @@ static const carve::mesh::MeshSet<3>::vertex_t *weld(
}
return weld_point;
}
#endif
void carve::csg::CSG::groupIntersections() {
@@ -1219,6 +1222,7 @@ void carve::csg::CSG::makeFaceEdges(carve::csg::EdgeClassification &eclass,
*
* @param fll
*/
#if 0
static void checkFaceLoopIntegrity(carve::csg::FaceLoopList &fll) {
static carve::TimingName FUNC_NAME("CSG::checkFaceLoopIntegrity()");
carve::TimingBlock block(FUNC_NAME);
@@ -1245,7 +1249,7 @@ static void checkFaceLoopIntegrity(carve::csg::FaceLoopList &fll) {
}
}
}
#endif
/**

View File

@@ -139,6 +139,7 @@ namespace carve {
#if 0
static void walkGraphSegment(carve::csg::detail::VVSMap &shared_edge_graph,
const carve::csg::detail::VSet &branch_points,
V2 initial,
@@ -215,7 +216,7 @@ namespace carve {
#endif
#endif
}
#endif
static carve::geom3d::Vector perpendicular(const carve::geom3d::Vector &v) {
@@ -383,6 +384,7 @@ namespace carve {
#if 0
static void traceIntersectionGraph(const V2Set &shared_edges,
const FLGroupList & /* a_loops_grouped */,
const FLGroupList & /* b_loops_grouped */,
@@ -416,6 +418,7 @@ namespace carve {
walkGraphSegment(shared_edge_graph, branch_points, V2(v1, v2), a_edge_map, b_edge_map, out);
}
}
#endif
void hashByPerimeter(FLGroupList &grp, PerimMap &perim_map) {
for (FLGroupList::iterator i = grp.begin(); i != grp.end(); ++i) {

View File

@@ -1409,6 +1409,7 @@ namespace {
return s.str().substr(1);
}
#if 0
void dumpAsGraph(carve::mesh::MeshSet<3>::face_t *face,
const std::vector<carve::mesh::MeshSet<3>::vertex_t *> &base_loop,
const carve::csg::V2Set &face_edges,
@@ -1450,6 +1451,7 @@ namespace {
}
std::cerr << "};\n";
}
#endif
void generateOneFaceLoop(carve::mesh::MeshSet<3>::face_t *face,
const carve::csg::detail::Data &data,

View File

@@ -43,6 +43,7 @@ namespace carve {
};
namespace {
#if 0
void cplx_sqrt(double re, double im,
double &re_1, double &im_1,
double &re_2, double &im_2) {
@@ -57,7 +58,9 @@ namespace carve {
im_2 = -im_1;
}
}
#endif
#if 0
void cplx_cbrt(double re, double im,
double &re_1, double &im_1,
double &re_2, double &im_2,
@@ -76,6 +79,7 @@ namespace carve {
im_3 = r * sin(t + M_TWOPI * 2.0 / 3.0);
}
}
#endif
void add_root(std::vector<Root> &roots, double root) {
for (size_t i = 0; i < roots.size(); ++i) {
@@ -250,6 +254,7 @@ namespace carve {
e2.normalize();
}
#if 0
static void eig3(const Matrix3 &m,
double l,
carve::geom::vector<3> &e1,
@@ -259,6 +264,7 @@ namespace carve {
e2.x = 0.0; e2.y = 1.0; e2.z = 0.0;
e3.x = 0.0; e3.y = 0.0; e3.z = 1.0;
}
#endif
void eigSolveSymmetric(const Matrix3 &m,
double &l1, carve::geom::vector<3> &e1,

View File

@@ -774,7 +774,6 @@ namespace carve {
// connectivity information in the Polyhedron.
mesh::MeshSet<3> *meshFromPolyhedron(const poly::Polyhedron *poly, int manifold_id) {
typedef mesh::Vertex<3> vertex_t;
typedef mesh::Vertex<3>::vector_t vector_t;
typedef mesh::Edge<3> edge_t;
typedef mesh::Face<3> face_t;
typedef mesh::Mesh<3> mesh_t;
@@ -884,7 +883,6 @@ namespace carve {
// construct a Polyhedron from a MeshSet
poly::Polyhedron *polyhedronFromMesh(const mesh::MeshSet<3> *mesh, int manifold_id) {
typedef poly::Polyhedron poly_t;
typedef poly::Polyhedron::vertex_t vertex_t;
typedef poly::Polyhedron::edge_t edge_t;
typedef poly::Polyhedron::face_t face_t;

View File

@@ -33,8 +33,9 @@ set(INC_SYS
)
set(SRC
include/cuew.h
src/cuew.c
include/cuew.h
)
blender_add_lib(extern_cuew "${SRC}" "${INC}" "${INC_SYS}")

View File

@@ -1,35 +0,0 @@
CUDA_ERRORS={
'CUDA_SUCCESS': "No errors",
'CUDA_ERROR_INVALID_VALUE': "Invalid value",
'CUDA_ERROR_OUT_OF_MEMORY': "Out of memory",
'CUDA_ERROR_NOT_INITIALIZED': "Driver not initialized",
'CUDA_ERROR_DEINITIALIZED': "Driver deinitialized",
'CUDA_ERROR_NO_DEVICE': "No CUDA-capable device available",
'CUDA_ERROR_INVALID_DEVICE': "Invalid device",
'CUDA_ERROR_INVALID_IMAGE': "Invalid kernel image",
'CUDA_ERROR_INVALID_CONTEXT': "Invalid context",
'CUDA_ERROR_CONTEXT_ALREADY_CURRENT': "Context already current",
'CUDA_ERROR_MAP_FAILED': "Map failed",
'CUDA_ERROR_UNMAP_FAILED': "Unmap failed",
'CUDA_ERROR_ARRAY_IS_MAPPED': "Array is mapped",
'CUDA_ERROR_ALREADY_MAPPED': "Already mapped",
'CUDA_ERROR_NO_BINARY_FOR_GPU': "No binary for GPU",
'CUDA_ERROR_ALREADY_ACQUIRED': "Already acquired",
'CUDA_ERROR_NOT_MAPPED': "Not mapped",
'CUDA_ERROR_NOT_MAPPED_AS_ARRAY': "Mapped resource not available for access as an array",
'CUDA_ERROR_NOT_MAPPED_AS_POINTER': "Mapped resource not available for access as a pointer",
'CUDA_ERROR_ECC_UNCORRECTABLE': "Uncorrectable ECC error detected",
'CUDA_ERROR_UNSUPPORTED_LIMIT': "CUlimit not supported by device",
'CUDA_ERROR_INVALID_SOURCE': "Invalid source",
'CUDA_ERROR_FILE_NOT_FOUND': "File not found",
'CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND': "Link to a shared object failed to resolve",
'CUDA_ERROR_SHARED_OBJECT_INIT_FAILED': "Shared object initialization failed",
'CUDA_ERROR_INVALID_HANDLE': "Invalid handle",
'CUDA_ERROR_NOT_FOUND': "Not found",
'CUDA_ERROR_NOT_READY': "CUDA not ready",
'CUDA_ERROR_LAUNCH_FAILED': "Launch failed",
'CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES': "Launch exceeded resources",
'CUDA_ERROR_LAUNCH_TIMEOUT': "Launch exceeded timeout",
'CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING': "Launch with incompatible texturing",
'CUDA_ERROR_UNKNOWN': "Unknown error",
}

View File

@@ -1,125 +0,0 @@
extra_code = """
static void path_join(const char *path1,
const char *path2,
int maxlen,
char *result) {
#if defined(WIN32) || defined(_WIN32)
const char separator = '\\\\';
#else
const char separator = '/';
#endif
int n = snprintf(result, maxlen, "%s%c%s", path1, separator, path2);
if (n != -1 && n < maxlen) {
result[n] = '\\0';
}
else {
result[maxlen - 1] = '\\0';
}
}
static int path_exists(const char *path) {
struct stat st;
if (stat(path, &st)) {
return 0;
}
return 1;
}
const char *cuewCompilerPath(void) {
#ifdef _WIN32
const char *defaultpaths[] = {"C:/CUDA/bin", NULL};
const char *executable = "nvcc.exe";
#else
const char *defaultpaths[] = {
"/Developer/NVIDIA/CUDA-5.0/bin",
"/usr/local/cuda-5.0/bin",
"/usr/local/cuda/bin",
"/Developer/NVIDIA/CUDA-6.0/bin",
"/usr/local/cuda-6.0/bin",
"/Developer/NVIDIA/CUDA-5.5/bin",
"/usr/local/cuda-5.5/bin",
NULL};
const char *executable = "nvcc";
#endif
int i;
const char *binpath = getenv("CUDA_BIN_PATH");
static char nvcc[65536];
if (binpath) {
path_join(binpath, executable, sizeof(nvcc), nvcc);
if (path_exists(nvcc))
return nvcc;
}
for (i = 0; defaultpaths[i]; ++i) {
path_join(defaultpaths[i], executable, sizeof(nvcc), nvcc);
if (path_exists(nvcc))
return nvcc;
}
#ifndef _WIN32
{
FILE *handle = popen("which nvcc", "r");
if (handle) {
char buffer[4096] = {0};
int len = fread(buffer, 1, sizeof(buffer) - 1, handle);
buffer[len] = '\\0';
pclose(handle);
if (buffer[0])
return "nvcc";
}
}
#endif
return NULL;
}
int cuewCompilerVersion(void) {
const char *path = cuewCompilerPath();
const char *marker = "Cuda compilation tools, release ";
FILE *pipe;
int major, minor;
char *versionstr;
char buf[128];
char output[65536] = "\\0";
char command[65536] = "\\0";
if (path == NULL)
return 0;
/* get --version output */
strncpy(command, path, sizeof(command));
strncat(command, " --version", sizeof(command) - strlen(path));
pipe = popen(command, "r");
if (!pipe) {
fprintf(stderr, "CUDA: failed to run compiler to retrieve version");
return 0;
}
while (!feof(pipe)) {
if (fgets(buf, sizeof(buf), pipe) != NULL) {
strncat(output, buf, sizeof(output) - strlen(output) - 1);
}
}
pclose(pipe);
/* parse version number */
versionstr = strstr(output, marker);
if (versionstr == NULL) {
fprintf(stderr, "CUDA: failed to find version number in:\\n\\n%s\\n", output);
return 0;
}
versionstr += strlen(marker);
if (sscanf(versionstr, "%d.%d", &major, &minor) < 2) {
fprintf(stderr, "CUDA: failed to parse version number from:\\n\\n%s\\n", output);
return 0;
}
return 10 * major + minor;
}
"""

View File

@@ -1,640 +0,0 @@
#!/usr/bin/env python3
#
# Copyright 2014 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
# This script generates either header or implementation file from
# a CUDA header files.
#
# Usage: cuew hdr|impl [/path/to/cuda/includes]
# - hdr means header file will be generated and printed to stdout.
# - impl means implementation file will be generated and printed to stdout.
# - /path/to/cuda/includes is a path to a folder with cuda.h and cudaGL.h
# for which wrangler will be generated.
import os
import sys
from cuda_errors import CUDA_ERRORS
from pycparser import c_parser, c_ast, parse_file
from subprocess import Popen, PIPE
INCLUDE_DIR = "/usr/include"
LIB = "CUEW"
REAL_LIB = "CUDA"
VERSION_MAJOR = "1"
VERSION_MINOR = "2"
COPYRIGHT = """/*
* Copyright 2011-2014 Blender Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/"""
FILES = ["cuda.h", "cudaGL.h", 'nvrtc.h']
TYPEDEFS = []
FUNC_TYPEDEFS = []
SYMBOLS = []
DEFINES = []
DEFINES_V2 = []
ERRORS = []
class FuncDefVisitor(c_ast.NodeVisitor):
indent = 0
prev_complex = False
dummy_typedefs = ['size_t', 'CUdeviceptr']
def _get_quals_string(self, node):
if node.quals:
return ' '.join(node.quals) + ' '
return ''
def _get_ident_type(self, node):
if isinstance(node, c_ast.PtrDecl):
return self._get_ident_type(node.type.type) + '*'
if isinstance(node, c_ast.ArrayDecl):
return self._get_ident_type(node.type)
elif isinstance(node, c_ast.Struct):
if node.name:
return 'struct ' + node.name
else:
self.indent += 1
struct = self._stringify_struct(node)
self.indent -= 1
return "struct {\n" + \
struct + (" " * self.indent) + "}"
elif isinstance(node, c_ast.Union):
self.indent += 1
union = self._stringify_struct(node)
self.indent -= 1
return "union {\n" + union + (" " * self.indent) + "}"
elif isinstance(node, c_ast.Enum):
if node.name is not None:
return 'enum ' + node.name
else:
return 'enum '
elif isinstance(node, c_ast.TypeDecl):
return self._get_ident_type(node.type)
else:
return node.names[0]
def _stringify_param(self, param):
param_type = param.type
result = self._get_quals_string(param)
result += self._get_ident_type(param_type)
if param.name:
result += ' ' + param.name
if isinstance(param_type, c_ast.ArrayDecl):
# TODO(sergey): Workaround to deal with the
# preprocessed file where array size got
# substituded.
dim = param_type.dim.value
if param.name == "reserved" and dim == "64":
dim = "CU_IPC_HANDLE_SIZE"
result += '[' + dim + ']'
return result
def _stringify_params(self, params):
result = []
for param in params:
result.append(self._stringify_param(param))
return ', '.join(result)
def _stringify_struct(self, node):
result = ""
children = node.children()
for child in children:
member = self._stringify_param(child[1])
result += (" " * self.indent) + member + ";\n"
return result
def _stringify_enum(self, node):
result = ""
children = node.children()
for child in children:
if isinstance(child[1], c_ast.EnumeratorList):
enumerators = child[1].enumerators
for enumerator in enumerators:
result += (" " * self.indent) + enumerator.name
if enumerator.value:
result += " = " + enumerator.value.value
result += ",\n"
if enumerator.name.startswith("CUDA_ERROR_"):
ERRORS.append(enumerator.name)
return result
def visit_Decl(self, node):
if node.type.__class__.__name__ == 'FuncDecl':
if isinstance(node.type, c_ast.FuncDecl):
func_decl = node.type
func_decl_type = func_decl.type
typedef = 'typedef '
symbol_name = None
if isinstance(func_decl_type, c_ast.TypeDecl):
symbol_name = func_decl_type.declname
typedef += self._get_quals_string(func_decl_type)
typedef += self._get_ident_type(func_decl_type.type)
typedef += ' CUDAAPI'
typedef += ' t' + symbol_name
elif isinstance(func_decl_type, c_ast.PtrDecl):
ptr_type = func_decl_type.type
symbol_name = ptr_type.declname
typedef += self._get_quals_string(ptr_type)
typedef += self._get_ident_type(func_decl_type)
typedef += ' CUDAAPI'
typedef += ' t' + symbol_name
typedef += '(' + \
self._stringify_params(func_decl.args.params) + \
');'
SYMBOLS.append(symbol_name)
FUNC_TYPEDEFS.append(typedef)
def visit_Typedef(self, node):
if node.name in self.dummy_typedefs:
return
complex = False
type = self._get_ident_type(node.type)
quals = self._get_quals_string(node)
if isinstance(node.type.type, c_ast.Struct):
self.indent += 1
struct = self._stringify_struct(node.type.type)
self.indent -= 1
typedef = quals + type + " {\n" + struct + "} " + node.name
complex = True
elif isinstance(node.type.type, c_ast.Enum):
self.indent += 1
enum = self._stringify_enum(node.type.type)
self.indent -= 1
typedef = quals + type + " {\n" + enum + "} " + node.name
complex = True
else:
typedef = quals + type + " " + node.name
if complex or self.prev_complex:
typedef = "\ntypedef " + typedef + ";"
else:
typedef = "typedef " + typedef + ";"
TYPEDEFS.append(typedef)
self.prev_complex = complex
def get_latest_cpp():
path_prefix = "/usr/bin"
for cpp_version in ["9", "8", "7", "6", "5", "4"]:
test_cpp = os.path.join(path_prefix, "cpp-4." + cpp_version)
if os.path.exists(test_cpp):
return test_cpp
return None
def preprocess_file(filename, cpp_path):
args = [cpp_path, "-I./"]
if filename.endswith("GL.h"):
args.append("-DCUDAAPI= ")
args.append(filename)
try:
pipe = Popen(args,
stdout=PIPE,
universal_newlines=True)
text = pipe.communicate()[0]
except OSError as e:
raise RuntimeError("Unable to invoke 'cpp'. " +
'Make sure its path was passed correctly\n' +
('Original error: %s' % e))
return text
def parse_files():
parser = c_parser.CParser()
cpp_path = get_latest_cpp()
for filename in FILES:
filepath = os.path.join(INCLUDE_DIR, filename)
dummy_typedefs = {}
text = preprocess_file(filepath, cpp_path)
if filepath.endswith("GL.h"):
dummy_typedefs = {
"CUresult": "int",
"CUgraphicsResource": "void *",
"CUdevice": "void *",
"CUcontext": "void *",
"CUdeviceptr": "void *",
"CUstream": "void *"
}
text = "typedef int GLint;\n" + text
text = "typedef unsigned int GLuint;\n" + text
text = "typedef unsigned int GLenum;\n" + text
text = "typedef long size_t;\n" + text
for typedef in sorted(dummy_typedefs):
text = "typedef " + dummy_typedefs[typedef] + " " + \
typedef + ";\n" + text
ast = parser.parse(text, filepath)
with open(filepath) as f:
lines = f.readlines()
for line in lines:
if line.startswith("#define"):
line = line[8:-1]
token = line.split()
if token[0] not in ("__cuda_cuda_h__",
"CUDA_CB",
"CUDAAPI",
"CUDAGL_H",
"__NVRTC_H__"):
DEFINES.append(token)
for line in lines:
# TODO(sergey): Use better matching rule for _v2 symbols.
if line[0].isspace() and line.lstrip().startswith("#define"):
line = line[12:-1]
token = line.split()
if len(token) == 2 and (token[1].endswith("_v2") or
token[1].endswith("_v2)")):
if token[1].startswith('__CUDA_API_PTDS') or \
token[1].startswith('__CUDA_API_PTSZ'):
token[1] = token[1][16:-1]
DEFINES_V2.append(token)
v = FuncDefVisitor()
for typedef in dummy_typedefs:
v.dummy_typedefs.append(typedef)
v.visit(ast)
FUNC_TYPEDEFS.append('')
SYMBOLS.append('')
def print_copyright():
print(COPYRIGHT)
print("")
def open_header_guard():
print("#ifndef __%s_H__" % (LIB))
print("#define __%s_H__" % (LIB))
print("")
print("#ifdef __cplusplus")
print("extern \"C\" {")
print("#endif")
print("")
def close_header_guard():
print("")
print("#ifdef __cplusplus")
print("}")
print("#endif")
print("")
print("#endif /* __%s_H__ */" % (LIB))
def print_header():
print_copyright()
open_header_guard()
# Fot size_t.
print("#include <stdlib.h>")
print("")
print("/* Defines. */")
print("#define %s_VERSION_MAJOR %s" % (LIB, VERSION_MAJOR))
print("#define %s_VERSION_MINOR %s" % (LIB, VERSION_MINOR))
print("")
for define in DEFINES:
print('#define %s' % (' '.join(define)))
print("")
print("""/* Functions which changed 3.1 -> 3.2 for 64 bit stuff,
* the cuda library has both the old ones for compatibility and new
* ones with _v2 postfix,
*/""")
for define in DEFINES_V2:
print('#define %s' % (' '.join(define)))
print("")
print("/* Types. */")
# We handle this specially because of the file is
# getting preprocessed.
print("""#if defined(__x86_64) || defined(AMD64) || defined(_M_AMD64)
typedef unsigned long long CUdeviceptr;
#else
typedef unsigned int CUdeviceptr;
#endif
""")
for typedef in TYPEDEFS:
print('%s' % (typedef))
# TDO(sergey): This is only specific to CUDA wrapper.
print("""
#ifdef _WIN32
# define CUDAAPI __stdcall
# define CUDA_CB __stdcall
#else
# define CUDAAPI
# define CUDA_CB
#endif
""")
print("/* Function types. */")
for func_typedef in FUNC_TYPEDEFS:
print('%s' % (func_typedef))
print("")
print("/* Function declarations. */")
for symbol in SYMBOLS:
if symbol:
print('extern t%s *%s;' % (symbol, symbol))
else:
print("")
print("")
print("enum {")
print(" CUEW_SUCCESS = 0,")
print(" CUEW_ERROR_OPEN_FAILED = -1,")
print(" CUEW_ERROR_ATEXIT_FAILED = -2,")
print("};")
print("")
print("int %sInit(void);" % (LIB.lower()))
# TODO(sergey): Get rid of hardcoded CUresult.
print("const char *%sErrorString(CUresult result);" % (LIB.lower()))
print("const char *cuewCompilerPath(void);")
print("int cuewCompilerVersion(void);")
close_header_guard()
def print_dl_wrapper():
print("""#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# include <windows.h>
/* Utility macros. */
typedef HMODULE DynamicLibrary;
# define dynamic_library_open(path) LoadLibraryA(path)
# define dynamic_library_close(lib) FreeLibrary(lib)
# define dynamic_library_find(lib, symbol) GetProcAddress(lib, symbol)
#else
# include <dlfcn.h>
typedef void* DynamicLibrary;
# define dynamic_library_open(path) dlopen(path, RTLD_NOW)
# define dynamic_library_close(lib) dlclose(lib)
# define dynamic_library_find(lib, symbol) dlsym(lib, symbol)
#endif
""")
def print_dl_helper_macro():
print("""#define _LIBRARY_FIND_CHECKED(lib, name) \\
name = (t##name *)dynamic_library_find(lib, #name); \\
assert(name);
#define _LIBRARY_FIND(lib, name) \\
name = (t##name *)dynamic_library_find(lib, #name);
#define %s_LIBRARY_FIND_CHECKED(name) \\
_LIBRARY_FIND_CHECKED(cuda_lib, name)
#define %s_LIBRARY_FIND(name) _LIBRARY_FIND(cuda_lib, name)
#define NVRTC_LIBRARY_FIND_CHECKED(name) \\
_LIBRARY_FIND_CHECKED(nvrtc_lib, name)
#define NVRTC_LIBRARY_FIND(name) _LIBRARY_FIND(nvrtc_lib, name)
static DynamicLibrary cuda_lib;
static DynamicLibrary nvrtc_lib;""" % (REAL_LIB, REAL_LIB))
print("")
def print_dl_helpers():
print("""static DynamicLibrary dynamic_library_open_find(const char **paths) {
int i = 0;
while (paths[i] != NULL) {
DynamicLibrary lib = dynamic_library_open(paths[i]);
if (lib != NULL) {
return lib;
}
++i;
}
return NULL;
}
static void %sExit(void) {
if(cuda_lib != NULL) {
/* Ignore errors. */
dynamic_library_close(cuda_lib);
cuda_lib = NULL;
}
}""" % (LIB.lower()))
print("")
def print_lib_path():
# TODO(sergey): get rid of hardcoded libraries.
print("""#ifdef _WIN32
/* Expected in c:/windows/system or similar, no path needed. */
const char *cuda_paths[] = {"nvcuda.dll", NULL};
const char *nvrtc_paths[] = {"nvrtc.dll", NULL};
#elif defined(__APPLE__)
/* Default installation path. */
const char *cuda_paths[] = {"/usr/local/cuda/lib/libcuda.dylib", NULL};
const char *nvrtc_paths[] = {"/usr/local/cuda/lib/libnvrtc.dylib", NULL};
#else
const char *cuda_paths[] = {"libcuda.so", NULL};
const char *nvrtc_paths[] = {"libnvrtc.so",
# if defined(__x86_64__) || defined(_M_X64)
"/usr/local/cuda/lib64/libnvrtc.so",
#else
"/usr/local/cuda/lib/libnvrtc.so",
#endif
NULL};
#endif""")
def print_init_guard():
print(""" static int initialized = 0;
static int result = 0;
int error, driver_version;
if (initialized) {
return result;
}
initialized = 1;
error = atexit(cuewExit);
if (error) {
result = CUEW_ERROR_ATEXIT_FAILED;
return result;
}
/* Load library. */
cuda_lib = dynamic_library_open_find(cuda_paths);
nvrtc_lib = dynamic_library_open_find(nvrtc_paths);
/* CUDA library is mandatory to have, while nvrtc might be missing. */
if (cuda_lib == NULL) {
result = CUEW_ERROR_OPEN_FAILED;
return result;
}""")
print("")
def print_driver_version_guard():
# TODO(sergey): Currently it's hardcoded for CUDA only.
print(""" /* Detect driver version. */
driver_version = 1000;
%s_LIBRARY_FIND_CHECKED(cuDriverGetVersion);
if (cuDriverGetVersion) {
cuDriverGetVersion(&driver_version);
}
/* We require version 4.0. */
if (driver_version < 4000) {
result = CUEW_ERROR_OPEN_FAILED;
return result;
}""" % (REAL_LIB))
def print_dl_init():
print("int %sInit(void) {" % (LIB.lower()))
print(" /* Library paths. */")
print_lib_path()
print_init_guard()
print_driver_version_guard()
print(" /* Fetch all function pointers. */")
for symbol in SYMBOLS:
if symbol:
if not symbol.startswith('nvrtc'):
print(" %s_LIBRARY_FIND(%s);" % (REAL_LIB, symbol))
else:
print("")
print(" if (nvrtc_lib != NULL) {")
for symbol in SYMBOLS:
if symbol and symbol.startswith('nvrtc'):
print(" NVRTC_LIBRARY_FIND(%s);" % (symbol))
print(" }")
print("")
print(" result = CUEW_SUCCESS;")
print(" return result;")
print("}")
def print_implementation():
print_copyright()
# TODO(sergey): Get rid of hardcoded header.
print("""#ifdef _MSC_VER
# define snprintf _snprintf
# define popen _popen
# define pclose _pclose
# define _CRT_SECURE_NO_WARNINGS
#endif
""")
print("#include <cuew.h>")
print("#include <assert.h>")
print("#include <stdio.h>")
print("#include <string.h>")
print("#include <sys/stat.h>")
print("")
print_dl_wrapper()
print_dl_helper_macro()
print("/* Function definitions. */")
for symbol in SYMBOLS:
if symbol:
print('t%s *%s;' % (symbol, symbol))
else:
print("")
print("")
print_dl_helpers()
print("/* Implementation function. */")
print_dl_init()
print("")
# TODO(sergey): Get rid of hardcoded CUresult.
print("const char *%sErrorString(CUresult result) {" % (LIB.lower()))
print(" switch(result) {")
print(" case CUDA_SUCCESS: return \"No errors\";")
for error in ERRORS:
if error in CUDA_ERRORS:
str = CUDA_ERRORS[error]
else:
temp = error[11:].replace('_', ' ')
str = temp[0] + temp[1:].lower()
print(" case %s: return \"%s\";" % (error, str))
print(" default: return \"Unknown CUDA error value\";")
print(" }")
print("}")
from cuda_extra import extra_code
print(extra_code)
if __name__ == "__main__":
if len(sys.argv) != 2 and len(sys.argv) != 3:
print("Usage: %s hdr|impl [/path/to/cuda/toolkit/include]" %
(sys.argv[0]))
exit(1)
if len(sys.argv) == 3:
INCLUDE_DIR = sys.argv[2]
parse_files()
if sys.argv[1] == "hdr":
print_header()
elif sys.argv[1] == "impl":
print_implementation()
else:
print("Unknown command %s" % (sys.argv[1]))
exit(1)

View File

@@ -1,10 +0,0 @@
#!/bin/sh
# This script invokes cuew_gen.py and updates the
# header and source files in the repository.
SCRIPT=`realpath -s $0`
DIR=`dirname $SCRIPT`
python ${DIR}/cuew_gen.py hdr $@ > $DIR/../include/cuew.h
python ${DIR}/cuew_gen.py impl $@ > $DIR/../src/cuew.c

View File

@@ -1,3 +0,0 @@
/* This file is needed to workaround issue with parsing system headers. */
typedef long size_t;

View File

@@ -131,8 +131,8 @@ typedef struct CUsurfref_st* CUsurfref;
typedef struct CUevent_st* CUevent;
typedef struct CUstream_st* CUstream;
typedef struct CUgraphicsResource_st* CUgraphicsResource;
typedef unsigned CUtexObject;
typedef unsigned CUsurfObject;
typedef unsigned long long CUtexObject;
typedef unsigned long long CUsurfObject;
typedef struct CUuuid_st {
char bytes[16];
@@ -603,7 +603,7 @@ typedef struct CUDA_ARRAY_DESCRIPTOR_st {
size_t Width;
size_t Height;
CUarray_format Format;
unsigned NumChannels;
unsigned int NumChannels;
} CUDA_ARRAY_DESCRIPTOR;
typedef struct CUDA_ARRAY3D_DESCRIPTOR_st {
@@ -611,8 +611,8 @@ typedef struct CUDA_ARRAY3D_DESCRIPTOR_st {
size_t Height;
size_t Depth;
CUarray_format Format;
unsigned NumChannels;
unsigned Flags;
unsigned int NumChannels;
unsigned int Flags;
} CUDA_ARRAY3D_DESCRIPTOR;
typedef struct CUDA_RESOURCE_DESC_st {
@@ -627,13 +627,13 @@ typedef struct CUDA_RESOURCE_DESC_st {
struct {
CUdeviceptr devPtr;
CUarray_format format;
unsigned numChannels;
unsigned int numChannels;
size_t sizeInBytes;
} linear;
struct {
CUdeviceptr devPtr;
CUarray_format format;
unsigned numChannels;
unsigned int numChannels;
size_t width;
size_t height;
size_t pitchInBytes;
@@ -642,14 +642,14 @@ typedef struct CUDA_RESOURCE_DESC_st {
int reserved[32];
} reserved;
} res;
unsigned flags;
unsigned int flags;
} CUDA_RESOURCE_DESC;
typedef struct CUDA_TEXTURE_DESC_st {
CUaddress_mode addressMode[3];
CUfilter_mode filterMode;
unsigned flags;
unsigned maxAnisotropy;
unsigned int flags;
unsigned int maxAnisotropy;
CUfilter_mode mipmapFilterMode;
float mipmapLevelBias;
float minMipmapLevelClamp;
@@ -700,19 +700,19 @@ typedef struct CUDA_RESOURCE_VIEW_DESC_st {
size_t width;
size_t height;
size_t depth;
unsigned firstMipmapLevel;
unsigned lastMipmapLevel;
unsigned firstLayer;
unsigned lastLayer;
unsigned reserved[16];
unsigned int firstMipmapLevel;
unsigned int lastMipmapLevel;
unsigned int firstLayer;
unsigned int lastLayer;
unsigned int reserved[16];
} CUDA_RESOURCE_VIEW_DESC;
typedef struct CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_st {
unsigned p2pToken;
unsigned vaSpaceToken;
unsigned long long p2pToken;
unsigned int vaSpaceToken;
} CUDA_POINTER_ATTRIBUTE_P2P_TOKENS;
typedef unsigned GLenum;
typedef unsigned GLuint;
typedef unsigned int GLenum;
typedef unsigned int GLuint;
typedef int GLint;
typedef enum CUGLDeviceList_enum {
@@ -751,7 +751,7 @@ typedef struct _nvrtcProgram* nvrtcProgram;
/* Function types. */
typedef CUresult CUDAAPI tcuGetErrorString(CUresult error, const char* pStr);
typedef CUresult CUDAAPI tcuGetErrorName(CUresult error, const char* pStr);
typedef CUresult CUDAAPI tcuInit(unsigned Flags);
typedef CUresult CUDAAPI tcuInit(unsigned int Flags);
typedef CUresult CUDAAPI tcuDriverGetVersion(int* driverVersion);
typedef CUresult CUDAAPI tcuDeviceGet(CUdevice* device, int ordinal);
typedef CUresult CUDAAPI tcuDeviceGetCount(int* count);
@@ -762,17 +762,17 @@ typedef CUresult CUDAAPI tcuDeviceGetProperties(CUdevprop* prop, CUdevice dev);
typedef CUresult CUDAAPI tcuDeviceComputeCapability(int* major, int* minor, CUdevice dev);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxRetain(CUcontext* pctx, CUdevice dev);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxRelease(CUdevice dev);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxSetFlags(CUdevice dev, unsigned flags);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxGetState(CUdevice dev, unsigned* flags, int* active);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxSetFlags(CUdevice dev, unsigned int flags);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxGetState(CUdevice dev, unsigned int* flags, int* active);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxReset(CUdevice dev);
typedef CUresult CUDAAPI tcuCtxCreate_v2(CUcontext* pctx, unsigned flags, CUdevice dev);
typedef CUresult CUDAAPI tcuCtxCreate_v2(CUcontext* pctx, unsigned int flags, CUdevice dev);
typedef CUresult CUDAAPI tcuCtxDestroy_v2(CUcontext ctx);
typedef CUresult CUDAAPI tcuCtxPushCurrent_v2(CUcontext ctx);
typedef CUresult CUDAAPI tcuCtxPopCurrent_v2(CUcontext* pctx);
typedef CUresult CUDAAPI tcuCtxSetCurrent(CUcontext ctx);
typedef CUresult CUDAAPI tcuCtxGetCurrent(CUcontext* pctx);
typedef CUresult CUDAAPI tcuCtxGetDevice(CUdevice* device);
typedef CUresult CUDAAPI tcuCtxGetFlags(unsigned* flags);
typedef CUresult CUDAAPI tcuCtxGetFlags(unsigned int* flags);
typedef CUresult CUDAAPI tcuCtxSynchronize(void);
typedef CUresult CUDAAPI tcuCtxSetLimit(CUlimit limit, size_t value);
typedef CUresult CUDAAPI tcuCtxGetLimit(size_t* pvalue, CUlimit limit);
@@ -780,43 +780,43 @@ typedef CUresult CUDAAPI tcuCtxGetCacheConfig(CUfunc_cache* pconfig);
typedef CUresult CUDAAPI tcuCtxSetCacheConfig(CUfunc_cache config);
typedef CUresult CUDAAPI tcuCtxGetSharedMemConfig(CUsharedconfig* pConfig);
typedef CUresult CUDAAPI tcuCtxSetSharedMemConfig(CUsharedconfig config);
typedef CUresult CUDAAPI tcuCtxGetApiVersion(CUcontext ctx, unsigned* version);
typedef CUresult CUDAAPI tcuCtxGetApiVersion(CUcontext ctx, unsigned int* version);
typedef CUresult CUDAAPI tcuCtxGetStreamPriorityRange(int* leastPriority, int* greatestPriority);
typedef CUresult CUDAAPI tcuCtxAttach(CUcontext* pctx, unsigned flags);
typedef CUresult CUDAAPI tcuCtxAttach(CUcontext* pctx, unsigned int flags);
typedef CUresult CUDAAPI tcuCtxDetach(CUcontext ctx);
typedef CUresult CUDAAPI tcuModuleLoad(CUmodule* module, const char* fname);
typedef CUresult CUDAAPI tcuModuleLoadData(CUmodule* module, const void* image);
typedef CUresult CUDAAPI tcuModuleLoadDataEx(CUmodule* module, const void* image, unsigned numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuModuleLoadDataEx(CUmodule* module, const void* image, unsigned int numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuModuleLoadFatBinary(CUmodule* module, const void* fatCubin);
typedef CUresult CUDAAPI tcuModuleUnload(CUmodule hmod);
typedef CUresult CUDAAPI tcuModuleGetFunction(CUfunction* hfunc, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuModuleGetGlobal_v2(CUdeviceptr* dptr, size_t* bytes, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuModuleGetTexRef(CUtexref* pTexRef, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuModuleGetSurfRef(CUsurfref* pSurfRef, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuLinkCreate_v2(unsigned numOptions, CUjit_option* options, void* optionValues, CUlinkState* stateOut);
typedef CUresult CUDAAPI tcuLinkAddData_v2(CUlinkState state, CUjitInputType type, void* data, size_t size, const char* name, unsigned numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkAddFile_v2(CUlinkState state, CUjitInputType type, const char* path, unsigned numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkCreate_v2(unsigned int numOptions, CUjit_option* options, void* optionValues, CUlinkState* stateOut);
typedef CUresult CUDAAPI tcuLinkAddData_v2(CUlinkState state, CUjitInputType type, void* data, size_t size, const char* name, unsigned int numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkAddFile_v2(CUlinkState state, CUjitInputType type, const char* path, unsigned int numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkComplete(CUlinkState state, void* cubinOut, size_t* sizeOut);
typedef CUresult CUDAAPI tcuLinkDestroy(CUlinkState state);
typedef CUresult CUDAAPI tcuMemGetInfo_v2(size_t* free, size_t* total);
typedef CUresult CUDAAPI tcuMemAlloc_v2(CUdeviceptr* dptr, size_t bytesize);
typedef CUresult CUDAAPI tcuMemAllocPitch_v2(CUdeviceptr* dptr, size_t* pPitch, size_t WidthInBytes, size_t Height, unsigned ElementSizeBytes);
typedef CUresult CUDAAPI tcuMemAllocPitch_v2(CUdeviceptr* dptr, size_t* pPitch, size_t WidthInBytes, size_t Height, unsigned int ElementSizeBytes);
typedef CUresult CUDAAPI tcuMemFree_v2(CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuMemGetAddressRange_v2(CUdeviceptr* pbase, size_t* psize, CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuMemAllocHost_v2(void* pp, size_t bytesize);
typedef CUresult CUDAAPI tcuMemFreeHost(void* p);
typedef CUresult CUDAAPI tcuMemHostAlloc(void* pp, size_t bytesize, unsigned Flags);
typedef CUresult CUDAAPI tcuMemHostGetDevicePointer_v2(CUdeviceptr* pdptr, void* p, unsigned Flags);
typedef CUresult CUDAAPI tcuMemHostGetFlags(unsigned* pFlags, void* p);
typedef CUresult CUDAAPI tcuMemAllocManaged(CUdeviceptr* dptr, size_t bytesize, unsigned flags);
typedef CUresult CUDAAPI tcuMemHostAlloc(void* pp, size_t bytesize, unsigned int Flags);
typedef CUresult CUDAAPI tcuMemHostGetDevicePointer_v2(CUdeviceptr* pdptr, void* p, unsigned int Flags);
typedef CUresult CUDAAPI tcuMemHostGetFlags(unsigned int* pFlags, void* p);
typedef CUresult CUDAAPI tcuMemAllocManaged(CUdeviceptr* dptr, size_t bytesize, unsigned int flags);
typedef CUresult CUDAAPI tcuDeviceGetByPCIBusId(CUdevice* dev, const char* pciBusId);
typedef CUresult CUDAAPI tcuDeviceGetPCIBusId(char* pciBusId, int len, CUdevice dev);
typedef CUresult CUDAAPI tcuIpcGetEventHandle(CUipcEventHandle* pHandle, CUevent event);
typedef CUresult CUDAAPI tcuIpcOpenEventHandle(CUevent* phEvent, CUipcEventHandle handle);
typedef CUresult CUDAAPI tcuIpcGetMemHandle(CUipcMemHandle* pHandle, CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuIpcOpenMemHandle(CUdeviceptr* pdptr, CUipcMemHandle handle, unsigned Flags);
typedef CUresult CUDAAPI tcuIpcOpenMemHandle(CUdeviceptr* pdptr, CUipcMemHandle handle, unsigned int Flags);
typedef CUresult CUDAAPI tcuIpcCloseMemHandle(CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuMemHostRegister_v2(void* p, size_t bytesize, unsigned Flags);
typedef CUresult CUDAAPI tcuMemHostRegister_v2(void* p, size_t bytesize, unsigned int Flags);
typedef CUresult CUDAAPI tcuMemHostUnregister(void* p);
typedef CUresult CUDAAPI tcuMemcpy(CUdeviceptr dst, CUdeviceptr src, size_t ByteCount);
typedef CUresult CUDAAPI tcuMemcpyPeer(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount);
@@ -842,40 +842,40 @@ typedef CUresult CUDAAPI tcuMemcpyAtoHAsync_v2(void* dstHost, CUarray srcArray,
typedef CUresult CUDAAPI tcuMemcpy2DAsync_v2(const CUDA_MEMCPY2D* pCopy, CUstream hStream);
typedef CUresult CUDAAPI tcuMemcpy3DAsync_v2(const CUDA_MEMCPY3D* pCopy, CUstream hStream);
typedef CUresult CUDAAPI tcuMemcpy3DPeerAsync(const CUDA_MEMCPY3D_PEER* pCopy, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD8_v2(CUdeviceptr dstDevice, unsigned uc, size_t N);
typedef CUresult CUDAAPI tcuMemsetD16_v2(CUdeviceptr dstDevice, unsigned us, size_t N);
typedef CUresult CUDAAPI tcuMemsetD32_v2(CUdeviceptr dstDevice, unsigned ui, size_t N);
typedef CUresult CUDAAPI tcuMemsetD2D8_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned uc, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D16_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned us, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D32_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned ui, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD8Async(CUdeviceptr dstDevice, unsigned uc, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD16Async(CUdeviceptr dstDevice, unsigned us, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD32Async(CUdeviceptr dstDevice, unsigned ui, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D8Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned uc, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D16Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned us, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D32Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned ui, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD8_v2(CUdeviceptr dstDevice, unsigned char uc, size_t N);
typedef CUresult CUDAAPI tcuMemsetD16_v2(CUdeviceptr dstDevice, unsigned short us, size_t N);
typedef CUresult CUDAAPI tcuMemsetD32_v2(CUdeviceptr dstDevice, unsigned int ui, size_t N);
typedef CUresult CUDAAPI tcuMemsetD2D8_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D16_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D32_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD8Async(CUdeviceptr dstDevice, unsigned char uc, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD16Async(CUdeviceptr dstDevice, unsigned short us, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD32Async(CUdeviceptr dstDevice, unsigned int ui, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D8Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D16Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D32Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuArrayCreate_v2(CUarray* pHandle, const CUDA_ARRAY_DESCRIPTOR* pAllocateArray);
typedef CUresult CUDAAPI tcuArrayGetDescriptor_v2(CUDA_ARRAY_DESCRIPTOR* pArrayDescriptor, CUarray hArray);
typedef CUresult CUDAAPI tcuArrayDestroy(CUarray hArray);
typedef CUresult CUDAAPI tcuArray3DCreate_v2(CUarray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pAllocateArray);
typedef CUresult CUDAAPI tcuArray3DGetDescriptor_v2(CUDA_ARRAY3D_DESCRIPTOR* pArrayDescriptor, CUarray hArray);
typedef CUresult CUDAAPI tcuMipmappedArrayCreate(CUmipmappedArray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, unsigned numMipmapLevels);
typedef CUresult CUDAAPI tcuMipmappedArrayGetLevel(CUarray* pLevelArray, CUmipmappedArray hMipmappedArray, unsigned level);
typedef CUresult CUDAAPI tcuMipmappedArrayCreate(CUmipmappedArray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, unsigned int numMipmapLevels);
typedef CUresult CUDAAPI tcuMipmappedArrayGetLevel(CUarray* pLevelArray, CUmipmappedArray hMipmappedArray, unsigned int level);
typedef CUresult CUDAAPI tcuMipmappedArrayDestroy(CUmipmappedArray hMipmappedArray);
typedef CUresult CUDAAPI tcuPointerGetAttribute(void* data, CUpointer_attribute attribute, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuPointerSetAttribute(const void* value, CUpointer_attribute attribute, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuPointerGetAttributes(unsigned numAttributes, CUpointer_attribute* attributes, void* data, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuStreamCreate(CUstream* phStream, unsigned Flags);
typedef CUresult CUDAAPI tcuStreamCreateWithPriority(CUstream* phStream, unsigned flags, int priority);
typedef CUresult CUDAAPI tcuPointerGetAttributes(unsigned int numAttributes, CUpointer_attribute* attributes, void* data, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuStreamCreate(CUstream* phStream, unsigned int Flags);
typedef CUresult CUDAAPI tcuStreamCreateWithPriority(CUstream* phStream, unsigned int flags, int priority);
typedef CUresult CUDAAPI tcuStreamGetPriority(CUstream hStream, int* priority);
typedef CUresult CUDAAPI tcuStreamGetFlags(CUstream hStream, unsigned* flags);
typedef CUresult CUDAAPI tcuStreamWaitEvent(CUstream hStream, CUevent hEvent, unsigned Flags);
typedef CUresult CUDAAPI tcuStreamAddCallback(CUstream hStream, CUstreamCallback callback, void* userData, unsigned flags);
typedef CUresult CUDAAPI tcuStreamAttachMemAsync(CUstream hStream, CUdeviceptr dptr, size_t length, unsigned flags);
typedef CUresult CUDAAPI tcuStreamGetFlags(CUstream hStream, unsigned int* flags);
typedef CUresult CUDAAPI tcuStreamWaitEvent(CUstream hStream, CUevent hEvent, unsigned int Flags);
typedef CUresult CUDAAPI tcuStreamAddCallback(CUstream hStream, CUstreamCallback callback, void* userData, unsigned int flags);
typedef CUresult CUDAAPI tcuStreamAttachMemAsync(CUstream hStream, CUdeviceptr dptr, size_t length, unsigned int flags);
typedef CUresult CUDAAPI tcuStreamQuery(CUstream hStream);
typedef CUresult CUDAAPI tcuStreamSynchronize(CUstream hStream);
typedef CUresult CUDAAPI tcuStreamDestroy_v2(CUstream hStream);
typedef CUresult CUDAAPI tcuEventCreate(CUevent* phEvent, unsigned Flags);
typedef CUresult CUDAAPI tcuEventCreate(CUevent* phEvent, unsigned int Flags);
typedef CUresult CUDAAPI tcuEventRecord(CUevent hEvent, CUstream hStream);
typedef CUresult CUDAAPI tcuEventQuery(CUevent hEvent);
typedef CUresult CUDAAPI tcuEventSynchronize(CUevent hEvent);
@@ -884,23 +884,23 @@ typedef CUresult CUDAAPI tcuEventElapsedTime(float* pMilliseconds, CUevent hStar
typedef CUresult CUDAAPI tcuFuncGetAttribute(int* pi, CUfunction_attribute attrib, CUfunction hfunc);
typedef CUresult CUDAAPI tcuFuncSetCacheConfig(CUfunction hfunc, CUfunc_cache config);
typedef CUresult CUDAAPI tcuFuncSetSharedMemConfig(CUfunction hfunc, CUsharedconfig config);
typedef CUresult CUDAAPI tcuLaunchKernel(CUfunction f, unsigned gridDimX, unsigned gridDimY, unsigned gridDimZ, unsigned blockDimX, unsigned blockDimY, unsigned blockDimZ, unsigned sharedMemBytes, CUstream hStream, void* kernelParams, void* extra);
typedef CUresult CUDAAPI tcuLaunchKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void* kernelParams, void* extra);
typedef CUresult CUDAAPI tcuFuncSetBlockShape(CUfunction hfunc, int x, int y, int z);
typedef CUresult CUDAAPI tcuFuncSetSharedSize(CUfunction hfunc, unsigned bytes);
typedef CUresult CUDAAPI tcuParamSetSize(CUfunction hfunc, unsigned numbytes);
typedef CUresult CUDAAPI tcuParamSeti(CUfunction hfunc, int offset, unsigned value);
typedef CUresult CUDAAPI tcuFuncSetSharedSize(CUfunction hfunc, unsigned int bytes);
typedef CUresult CUDAAPI tcuParamSetSize(CUfunction hfunc, unsigned int numbytes);
typedef CUresult CUDAAPI tcuParamSeti(CUfunction hfunc, int offset, unsigned int value);
typedef CUresult CUDAAPI tcuParamSetf(CUfunction hfunc, int offset, float value);
typedef CUresult CUDAAPI tcuParamSetv(CUfunction hfunc, int offset, void* ptr, unsigned numbytes);
typedef CUresult CUDAAPI tcuParamSetv(CUfunction hfunc, int offset, void* ptr, unsigned int numbytes);
typedef CUresult CUDAAPI tcuLaunch(CUfunction f);
typedef CUresult CUDAAPI tcuLaunchGrid(CUfunction f, int grid_width, int grid_height);
typedef CUresult CUDAAPI tcuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream);
typedef CUresult CUDAAPI tcuParamSetTexRef(CUfunction hfunc, int texunit, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuOccupancyMaxActiveBlocksPerMultiprocessor(int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize);
typedef CUresult CUDAAPI tcuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize, unsigned flags);
typedef CUresult CUDAAPI tcuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize, unsigned int flags);
typedef CUresult CUDAAPI tcuOccupancyMaxPotentialBlockSize(int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit);
typedef CUresult CUDAAPI tcuOccupancyMaxPotentialBlockSizeWithFlags(int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit, unsigned flags);
typedef CUresult CUDAAPI tcuTexRefSetArray(CUtexref hTexRef, CUarray hArray, unsigned Flags);
typedef CUresult CUDAAPI tcuTexRefSetMipmappedArray(CUtexref hTexRef, CUmipmappedArray hMipmappedArray, unsigned Flags);
typedef CUresult CUDAAPI tcuOccupancyMaxPotentialBlockSizeWithFlags(int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit, unsigned int flags);
typedef CUresult CUDAAPI tcuTexRefSetArray(CUtexref hTexRef, CUarray hArray, unsigned int Flags);
typedef CUresult CUDAAPI tcuTexRefSetMipmappedArray(CUtexref hTexRef, CUmipmappedArray hMipmappedArray, unsigned int Flags);
typedef CUresult CUDAAPI tcuTexRefSetAddress_v2(size_t* ByteOffset, CUtexref hTexRef, CUdeviceptr dptr, size_t bytes);
typedef CUresult CUDAAPI tcuTexRefSetAddress2D_v3(CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR* desc, CUdeviceptr dptr, size_t Pitch);
typedef CUresult CUDAAPI tcuTexRefSetFormat(CUtexref hTexRef, CUarray_format fmt, int NumPackedComponents);
@@ -909,8 +909,8 @@ typedef CUresult CUDAAPI tcuTexRefSetFilterMode(CUtexref hTexRef, CUfilter_mode
typedef CUresult CUDAAPI tcuTexRefSetMipmapFilterMode(CUtexref hTexRef, CUfilter_mode fm);
typedef CUresult CUDAAPI tcuTexRefSetMipmapLevelBias(CUtexref hTexRef, float bias);
typedef CUresult CUDAAPI tcuTexRefSetMipmapLevelClamp(CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp);
typedef CUresult CUDAAPI tcuTexRefSetMaxAnisotropy(CUtexref hTexRef, unsigned maxAniso);
typedef CUresult CUDAAPI tcuTexRefSetFlags(CUtexref hTexRef, unsigned Flags);
typedef CUresult CUDAAPI tcuTexRefSetMaxAnisotropy(CUtexref hTexRef, unsigned int maxAniso);
typedef CUresult CUDAAPI tcuTexRefSetFlags(CUtexref hTexRef, unsigned int Flags);
typedef CUresult CUDAAPI tcuTexRefGetAddress_v2(CUdeviceptr* pdptr, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetArray(CUarray* phArray, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetMipmappedArray(CUmipmappedArray* phMipmappedArray, CUtexref hTexRef);
@@ -921,10 +921,10 @@ typedef CUresult CUDAAPI tcuTexRefGetMipmapFilterMode(CUfilter_mode* pfm, CUtexr
typedef CUresult CUDAAPI tcuTexRefGetMipmapLevelBias(float* pbias, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetMipmapLevelClamp(float* pminMipmapLevelClamp, float* pmaxMipmapLevelClamp, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetMaxAnisotropy(int* pmaxAniso, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetFlags(unsigned* pFlags, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetFlags(unsigned int* pFlags, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefCreate(CUtexref* pTexRef);
typedef CUresult CUDAAPI tcuTexRefDestroy(CUtexref hTexRef);
typedef CUresult CUDAAPI tcuSurfRefSetArray(CUsurfref hSurfRef, CUarray hArray, unsigned Flags);
typedef CUresult CUDAAPI tcuSurfRefSetArray(CUsurfref hSurfRef, CUarray hArray, unsigned int Flags);
typedef CUresult CUDAAPI tcuSurfRefGetArray(CUarray* phArray, CUsurfref hSurfRef);
typedef CUresult CUDAAPI tcuTexObjectCreate(CUtexObject* pTexObject, const CUDA_RESOURCE_DESC* pResDesc, const CUDA_TEXTURE_DESC* pTexDesc, const CUDA_RESOURCE_VIEW_DESC* pResViewDesc);
typedef CUresult CUDAAPI tcuTexObjectDestroy(CUtexObject texObject);
@@ -935,27 +935,27 @@ typedef CUresult CUDAAPI tcuSurfObjectCreate(CUsurfObject* pSurfObject, const CU
typedef CUresult CUDAAPI tcuSurfObjectDestroy(CUsurfObject surfObject);
typedef CUresult CUDAAPI tcuSurfObjectGetResourceDesc(CUDA_RESOURCE_DESC* pResDesc, CUsurfObject surfObject);
typedef CUresult CUDAAPI tcuDeviceCanAccessPeer(int* canAccessPeer, CUdevice dev, CUdevice peerDev);
typedef CUresult CUDAAPI tcuCtxEnablePeerAccess(CUcontext peerContext, unsigned Flags);
typedef CUresult CUDAAPI tcuCtxEnablePeerAccess(CUcontext peerContext, unsigned int Flags);
typedef CUresult CUDAAPI tcuCtxDisablePeerAccess(CUcontext peerContext);
typedef CUresult CUDAAPI tcuGraphicsUnregisterResource(CUgraphicsResource resource);
typedef CUresult CUDAAPI tcuGraphicsSubResourceGetMappedArray(CUarray* pArray, CUgraphicsResource resource, unsigned arrayIndex, unsigned mipLevel);
typedef CUresult CUDAAPI tcuGraphicsSubResourceGetMappedArray(CUarray* pArray, CUgraphicsResource resource, unsigned int arrayIndex, unsigned int mipLevel);
typedef CUresult CUDAAPI tcuGraphicsResourceGetMappedMipmappedArray(CUmipmappedArray* pMipmappedArray, CUgraphicsResource resource);
typedef CUresult CUDAAPI tcuGraphicsResourceGetMappedPointer_v2(CUdeviceptr* pDevPtr, size_t* pSize, CUgraphicsResource resource);
typedef CUresult CUDAAPI tcuGraphicsResourceSetMapFlags_v2(CUgraphicsResource resource, unsigned flags);
typedef CUresult CUDAAPI tcuGraphicsMapResources(unsigned count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGraphicsUnmapResources(unsigned count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGraphicsResourceSetMapFlags_v2(CUgraphicsResource resource, unsigned int flags);
typedef CUresult CUDAAPI tcuGraphicsMapResources(unsigned int count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGraphicsUnmapResources(unsigned int count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGetExportTable(const void* ppExportTable, const CUuuid* pExportTableId);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterBuffer(CUgraphicsResource* pCudaResource, GLuint buffer, unsigned Flags);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterImage(CUgraphicsResource* pCudaResource, GLuint image, GLenum target, unsigned Flags);
typedef CUresult CUDAAPI tcuGLGetDevices_v2(unsigned* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned cudaDeviceCount, CUGLDeviceList deviceList);
typedef CUresult CUDAAPI tcuGLCtxCreate_v2(CUcontext* pCtx, unsigned Flags, CUdevice device);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterBuffer(CUgraphicsResource* pCudaResource, GLuint buffer, unsigned int Flags);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterImage(CUgraphicsResource* pCudaResource, GLuint image, GLenum target, unsigned int Flags);
typedef CUresult CUDAAPI tcuGLGetDevices_v2(unsigned int* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned int cudaDeviceCount, CUGLDeviceList deviceList);
typedef CUresult CUDAAPI tcuGLCtxCreate_v2(CUcontext* pCtx, unsigned int Flags, CUdevice device);
typedef CUresult CUDAAPI tcuGLInit(void);
typedef CUresult CUDAAPI tcuGLRegisterBufferObject(GLuint buffer);
typedef CUresult CUDAAPI tcuGLMapBufferObject_v2(CUdeviceptr* dptr, size_t* size, GLuint buffer);
typedef CUresult CUDAAPI tcuGLUnmapBufferObject(GLuint buffer);
typedef CUresult CUDAAPI tcuGLUnregisterBufferObject(GLuint buffer);
typedef CUresult CUDAAPI tcuGLSetBufferObjectMapFlags(GLuint buffer, unsigned Flags);
typedef CUresult CUDAAPI tcuGLSetBufferObjectMapFlags(GLuint buffer, unsigned int Flags);
typedef CUresult CUDAAPI tcuGLMapBufferObjectAsync_v2(CUdeviceptr* dptr, size_t* size, GLuint buffer, CUstream hStream);
typedef CUresult CUDAAPI tcuGLUnmapBufferObjectAsync(GLuint buffer, CUstream hStream);

35
extern/curve_fit_nd/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,35 @@
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENSE BLOCK *****
set(INC
.
)
set(INC_SYS
)
set(SRC
intern/curve_fit_cubic.c
intern/curve_fit_corners_detect.c
intern/curve_fit_inline.h
curve_fit_nd.h
)
blender_add_lib(extern_curve_fit_nd "${SRC}" "${INC}" "${INC_SYS}")

162
extern/curve_fit_nd/curve_fit_nd.h vendored Normal file
View File

@@ -0,0 +1,162 @@
/*
* Copyright (c) 2016, DWANGO Co., Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __CURVE_FIT_ND_H__
#define __CURVE_FIT_ND_H__
/** \file curve_fit_nd.h
* \ingroup curve_fit
*/
/* curve_fit_cubic.c */
/**
* Takes a flat array of points and evalues that to calculate a bezier spline.
*
* \param points, points_len: The array of points to calculate a cubics from.
* \param dims: The number of dimensions for for each element in \a points.
* \param error_threshold: the error threshold to allow for,
* the curve will be within this distance from \a points.
* \param corners, corners_len: indices for points which will not have aligned tangents (optional).
* This can use the output of #curve_fit_corners_detect_db which has been included
* to evaluate a line to detect corner indices.
*
* \param r_cubic_array, r_cubic_array_len: Resulting array of tangents and knots, formatted as follows:
* ``r_cubic_array[r_cubic_array_len][3][dims]``,
* where each point has 0 and 2 for the tangents and the middle index 1 for the knot.
* The size of the *flat* array will be ``r_cubic_array_len * 3 * dims``.
* \param r_corner_index_array, r_corner_index_len: Corner indices in in \a r_cubic_array (optional).
* This allows you to access corners on the resulting curve.
*
* \returns zero on success, nonzero is reserved for error values.
*/
int curve_fit_cubic_to_points_db(
const double *points,
const unsigned int points_len,
const unsigned int dims,
const double error_threshold,
const unsigned int *corners,
unsigned int corners_len,
double **r_cubic_array, unsigned int *r_cubic_array_len,
unsigned int **r_cubic_orig_index,
unsigned int **r_corner_index_array, unsigned int *r_corner_index_len);
int curve_fit_cubic_to_points_fl(
const float *points,
const unsigned int points_len,
const unsigned int dims,
const float error_threshold,
const unsigned int *corners,
const unsigned int corners_len,
float **r_cubic_array, unsigned int *r_cubic_array_len,
unsigned int **r_cubic_orig_index,
unsigned int **r_corners_index_array, unsigned int *r_corners_index_len);
/**
* Takes a flat array of points and evalues that to calculate handle lengths.
*
* \param points, points_len: The array of points to calculate a cubics from.
* \param dims: The number of dimensions for for each element in \a points.
* \param error_threshold: the error threshold to allow for,
* \param tan_l, tan_r: Normalized tangents the handles will be aligned to.
* Note that tangents must both point along the direction of the \a points,
* so \a tan_l points in the same direction of the resulting handle,
* where \a tan_r will point the opposite direction of its handle.
*
* \param r_handle_l, r_handle_r: Resulting calculated handles.
* \param r_error_sq: The maximum distance (squared) this curve diverges from \a points.
*/
int curve_fit_cubic_to_points_single_db(
const double *points,
const unsigned int points_len,
const unsigned int dims,
const double error_threshold,
const double tan_l[],
const double tan_r[],
double r_handle_l[],
double r_handle_r[],
double *r_error_sq);
int curve_fit_cubic_to_points_single_fl(
const float *points,
const unsigned int points_len,
const unsigned int dims,
const float error_threshold,
const float tan_l[],
const float tan_r[],
float r_handle_l[],
float r_handle_r[],
float *r_error_sq);
/* curve_fit_corners_detect.c */
/**
* A helper function that takes a line and outputs its corner indices.
*
* \param points, points_len: Curve to evaluate.
* \param dims: The number of dimensions for for each element in \a points.
* \param radius_min: Corners on the curve between points below this radius are ignored.
* \param radius_max: Corners on the curve above this radius are ignored.
* \param samples_max: Prevent testing corners beyond this many points
* (prevents a large radius taking excessive time to compute).
* \param angle_threshold: Angles above this value are considered corners
* (higher value for fewer corners).
*
* \param r_corners, r_corners_len: Resulting array of corners.
*
* \returns zero on success, nonzero is reserved for error values.
*/
int curve_fit_corners_detect_db(
const double *points,
const unsigned int points_len,
const unsigned int dims,
const double radius_min,
const double radius_max,
const unsigned int samples_max,
const double angle_threshold,
unsigned int **r_corners,
unsigned int *r_corners_len);
int curve_fit_corners_detect_fl(
const float *points,
const unsigned int points_len,
const unsigned int dims,
const float radius_min,
const float radius_max,
const unsigned int samples_max,
const float angle_threshold,
unsigned int **r_corners,
unsigned int *r_corners_len);
#endif /* __CURVE_FIT_ND_H__ */

View File

@@ -0,0 +1,468 @@
/*
* Copyright (c) 2016, Blender Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file curve_fit_corners_detect.c
* \ingroup curve_fit
*/
#include <math.h>
#include <float.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include "../curve_fit_nd.h"
typedef unsigned int uint;
#include "curve_fit_inline.h"
#ifdef _MSC_VER
# define alloca(size) _alloca(size)
#endif
#if !defined(_MSC_VER)
# define USE_VLA
#endif
#ifdef USE_VLA
# ifdef __GNUC__
# pragma GCC diagnostic ignored "-Wvla"
# endif
#else
# ifdef __GNUC__
# pragma GCC diagnostic error "-Wvla"
# endif
#endif
/* -------------------------------------------------------------------- */
/** \name Simple Vector Math Lib
* \{ */
static double cos_vnvnvn(
const double v0[], const double v1[], const double v2[],
const uint dims)
{
#ifdef USE_VLA
double dvec0[dims];
double dvec1[dims];
#else
double *dvec0 = alloca(sizeof(double) * dims);
double *dvec1 = alloca(sizeof(double) * dims);
#endif
normalize_vn_vnvn(dvec0, v0, v1, dims);
normalize_vn_vnvn(dvec1, v1, v2, dims);
double d = dot_vnvn(dvec0, dvec1, dims);
/* sanity check */
d = max(-1.0, min(1.0, d));
return d;
}
static double angle_vnvnvn(
const double v0[], const double v1[], const double v2[],
const uint dims)
{
return acos(cos_vnvnvn(v0, v1, v2, dims));
}
static bool isect_line_sphere_vn(
const double l1[],
const double l2[],
const double sp[],
const double r,
uint dims,
double r_p1[]
#if 0 /* UNUSED */
double r_p2[]
#endif
)
{
#ifdef USE_VLA
double ldir[dims];
double tvec[dims];
#else
double *ldir = alloca(sizeof(double) * dims);
double *tvec = alloca(sizeof(double) * dims);
#endif
sub_vn_vnvn(ldir, l2, l1, dims);
sub_vn_vnvn(tvec, l1, sp, dims);
const double a = len_squared_vn(ldir, dims);
const double b = 2.0 * dot_vnvn(ldir, tvec, dims);
const double c = len_squared_vn(sp, dims) + len_squared_vn(l1, dims) - (2.0 * dot_vnvn(sp, l1, dims)) - sq(r);
const double i = b * b - 4.0 * a * c;
if ((i < 0.0) || (a == 0.0)) {
return false;
}
else if (i == 0.0) {
/* one intersection */
const double mu = -b / (2.0 * a);
mul_vnvn_fl(r_p1, ldir, mu, dims);
iadd_vnvn(r_p1, l1, dims);
return true;
}
else if (i > 0.0) {
/* # avoid calc twice */
const double i_sqrt = sqrt(i);
double mu;
/* Note: when l1 is inside the sphere and l2 is outside.
* the first intersection point will always be between the pair. */
/* first intersection */
mu = (-b + i_sqrt) / (2.0 * a);
mul_vnvn_fl(r_p1, ldir, mu, dims);
iadd_vnvn(r_p1, l1, dims);
#if 0
/* second intersection */
mu = (-b - i_sqrt) / (2.0 * a);
mul_vnvn_fl(r_p2, ldir, mu, dims);
iadd_vnvn(r_p2, l1, dims);
#endif
return true;
}
else {
return false;
}
}
/** \} */
/* -------------------------------------------------------------------- */
static bool point_corner_measure(
const double *points,
const uint points_len,
const uint i,
const uint i_prev_init,
const uint i_next_init,
const double radius,
const uint samples_max,
const uint dims,
double r_p_prev[], uint *r_i_prev_next,
double r_p_next[], uint *r_i_next_prev)
{
const double *p = &points[i * dims];
uint sample;
uint i_prev = i_prev_init;
uint i_prev_next = i_prev + 1;
sample = 0;
while (true) {
if ((i_prev == -1) || (sample++ > samples_max)) {
return false;
}
else if (len_squared_vnvn(p, &points[i_prev * dims], dims) < radius) {
i_prev -= 1;
}
else {
break;
}
}
uint i_next = i_next_init;
uint i_next_prev = i_next - 1;
sample = 0;
while (true) {
if ((i_next == points_len) || (sample++ > samples_max)) {
return false;
}
else if (len_squared_vnvn(p, &points[i_next * dims], dims) < radius) {
i_next += 1;
}
else {
break;
}
}
/* find points on the sphere */
if (!isect_line_sphere_vn(
&points[i_prev * dims], &points[i_prev_next * dims], p, radius, dims,
r_p_prev))
{
return false;
}
if (!isect_line_sphere_vn(
&points[i_next * dims], &points[i_next_prev * dims], p, radius, dims,
r_p_next))
{
return false;
}
*r_i_prev_next = i_prev_next;
*r_i_next_prev = i_next_prev;
return true;
}
static double point_corner_angle(
const double *points,
const uint points_len,
const uint i,
const double radius_mid,
const double radius_max,
const double angle_threshold,
const double angle_threshold_cos,
/* prevent locking up when for example `radius_min` is very large
* (possibly larger then the curve).
* In this case we would end up checking every point from every other point,
* never reaching one that was outside the `radius_min`. */
/* prevent locking up when for e */
const uint samples_max,
const uint dims)
{
assert(angle_threshold_cos == cos(angle_threshold));
if (i == 0 || i == points_len - 1) {
return 0.0;
}
const double *p = &points[i * dims];
/* initial test */
if (cos_vnvnvn(&points[(i - 1) * dims], p, &points[(i + 1) * dims], dims) > angle_threshold_cos) {
return 0.0;
}
#ifdef USE_VLA
double p_mid_prev[dims];
double p_mid_next[dims];
#else
double *p_mid_prev = alloca(sizeof(double) * dims);
double *p_mid_next = alloca(sizeof(double) * dims);
#endif
uint i_mid_prev_next, i_mid_next_prev;
if (point_corner_measure(
points, points_len,
i, i - 1, i + 1,
radius_mid,
samples_max,
dims,
p_mid_prev, &i_mid_prev_next,
p_mid_next, &i_mid_next_prev))
{
const double angle_mid_cos = cos_vnvnvn(p_mid_prev, p, p_mid_next, dims);
/* compare as cos and flip direction */
/* if (angle_mid > angle_threshold) { */
if (angle_mid_cos < angle_threshold_cos) {
#ifdef USE_VLA
double p_max_prev[dims];
double p_max_next[dims];
#else
double *p_max_prev = alloca(sizeof(double) * dims);
double *p_max_next = alloca(sizeof(double) * dims);
#endif
uint i_max_prev_next, i_max_next_prev;
if (point_corner_measure(
points, points_len,
i, i - 1, i + 1,
radius_max,
samples_max,
dims,
p_max_prev, &i_max_prev_next,
p_max_next, &i_max_next_prev))
{
const double angle_mid = acos(angle_mid_cos);
const double angle_max = angle_vnvnvn(p_max_prev, p, p_max_next, dims) / 2.0;
const double angle_diff = angle_mid - angle_max;
if (angle_diff > angle_threshold) {
return angle_diff;
}
}
}
}
return 0.0;
}
int curve_fit_corners_detect_db(
const double *points,
const uint points_len,
const uint dims,
const double radius_min, /* ignore values below this */
const double radius_max, /* ignore values above this */
const uint samples_max,
const double angle_threshold,
uint **r_corners,
uint *r_corners_len)
{
const double angle_threshold_cos = cos(angle_threshold);
uint corners_len = 0;
/* Use the difference in angle between the mid-max radii
* to detect the difference between a corner and a sharp turn. */
const double radius_mid = (radius_min + radius_max) / 2.0;
/* we could ignore first/last- but simple to keep aligned with the point array */
double *points_angle = malloc(sizeof(double) * points_len);
points_angle[0] = 0.0;
*r_corners = NULL;
*r_corners_len = 0;
for (uint i = 0; i < points_len; i++) {
points_angle[i] = point_corner_angle(
points, points_len, i,
radius_mid, radius_max,
angle_threshold, angle_threshold_cos,
samples_max,
dims);
if (points_angle[i] != 0.0) {
corners_len++;
}
}
if (corners_len == 0) {
free(points_angle);
return 0;
}
/* Clean angle limits!
*
* How this works:
* - Find contiguous 'corners' (where the distance is less or equal to the error threshold).
* - Keep track of the corner with the highest angle
* - Clear every other angle (so they're ignored when setting corners). */
{
const double radius_min_sq = sq(radius_min);
uint i_span_start = 0;
while (i_span_start < points_len) {
uint i_span_end = i_span_start;
if (points_angle[i_span_start] != 0.0) {
uint i_next = i_span_start + 1;
uint i_best = i_span_start;
while (i_next < points_len) {
if ((points_angle[i_next] == 0.0) ||
(len_squared_vnvn(
&points[(i_next - 1) * dims],
&points[i_next * dims], dims) > radius_min_sq))
{
break;
}
else {
if (points_angle[i_best] < points_angle[i_next]) {
i_best = i_next;
}
i_span_end = i_next;
i_next += 1;
}
}
if (i_span_start != i_span_end) {
uint i = i_span_start;
while (i <= i_span_end) {
if (i != i_best) {
/* we could use some other error code */
assert(points_angle[i] != 0.0);
points_angle[i] = 0.0;
corners_len--;
}
i += 1;
}
}
}
i_span_start = i_span_end + 1;
}
}
/* End angle limit cleaning! */
corners_len += 2; /* first and last */
uint *corners = malloc(sizeof(uint) * corners_len);
uint i_corner = 0;
corners[i_corner++] = 0;
for (uint i = 0; i < points_len; i++) {
if (points_angle[i] != 0.0) {
corners[i_corner++] = i;
}
}
corners[i_corner++] = points_len - 1;
assert(i_corner == corners_len);
free(points_angle);
*r_corners = corners;
*r_corners_len = corners_len;
return 0;
}
int curve_fit_corners_detect_fl(
const float *points,
const uint points_len,
const uint dims,
const float radius_min, /* ignore values below this */
const float radius_max, /* ignore values above this */
const uint samples_max,
const float angle_threshold,
uint **r_corners,
uint *r_corners_len)
{
const uint points_flat_len = points_len * dims;
double *points_db = malloc(sizeof(double) * points_flat_len);
for (uint i = 0; i < points_flat_len; i++) {
points_db[i] = (double)points[i];
}
int result = curve_fit_corners_detect_db(
points_db, points_len,
dims,
radius_min, radius_max,
samples_max,
angle_threshold,
r_corners, r_corners_len);
free(points_db);
return result;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,293 @@
/*
* Copyright (c) 2016, Blender Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file curve_fit_inline.h
* \ingroup curve_fit
*/
/** \name Simple Vector Math Lib
* \{ */
#ifdef _MSC_VER
# define MINLINE static __forceinline
#else
# define MINLINE static inline
#endif
MINLINE double sq(const double d)
{
return d * d;
}
#ifndef _MSC_VER
MINLINE double min(const double a, const double b)
{
return b < a ? b : a;
}
MINLINE double max(const double a, const double b)
{
return a < b ? b : a;
}
#endif
MINLINE void zero_vn(
double v0[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = 0.0;
}
}
MINLINE void flip_vn_vnvn(
double v_out[], const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] + (v0[j] - v1[j]);
}
}
MINLINE void copy_vnvn(
double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = v1[j];
}
}
MINLINE void copy_vnfl_vndb(
float v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = (float)v1[j];
}
}
MINLINE void copy_vndb_vnfl(
double v0[], const float v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = (double)v1[j];
}
}
MINLINE double dot_vnvn(
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += v0[j] * v1[j];
}
return d;
}
MINLINE void add_vn_vnvn(
double v_out[], const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] + v1[j];
}
}
MINLINE void sub_vn_vnvn(
double v_out[], const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] - v1[j];
}
}
MINLINE void iadd_vnvn(
double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] += v1[j];
}
}
MINLINE void isub_vnvn(
double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] -= v1[j];
}
}
MINLINE void madd_vn_vnvn_fl(
double v_out[],
const double v0[], const double v1[],
const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] + v1[j] * f;
}
}
MINLINE void msub_vn_vnvn_fl(
double v_out[],
const double v0[], const double v1[],
const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] - v1[j] * f;
}
}
MINLINE void miadd_vn_vn_fl(
double v_out[], const double v0[], double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] += v0[j] * f;
}
}
#if 0
MINLINE void misub_vn_vn_fl(
double v_out[], const double v0[], double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] -= v0[j] * f;
}
}
#endif
MINLINE void mul_vnvn_fl(
double v_out[],
const double v0[], const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] * f;
}
}
MINLINE void imul_vn_fl(double v0[], const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] *= f;
}
}
MINLINE double len_squared_vnvn(
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += sq(v0[j] - v1[j]);
}
return d;
}
MINLINE double len_squared_vn(
const double v0[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += sq(v0[j]);
}
return d;
}
MINLINE double len_vnvn(
const double v0[], const double v1[], const uint dims)
{
return sqrt(len_squared_vnvn(v0, v1, dims));
}
MINLINE double len_vn(
const double v0[], const uint dims)
{
return sqrt(len_squared_vn(v0, dims));
}
/* special case, save us negating a copy, then getting the length */
MINLINE double len_squared_negated_vnvn(
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += sq(v0[j] + v1[j]);
}
return d;
}
MINLINE double len_negated_vnvn(
const double v0[], const double v1[], const uint dims)
{
return sqrt(len_squared_negated_vnvn(v0, v1, dims));
}
MINLINE double normalize_vn(
double v0[], const uint dims)
{
double d = len_squared_vn(v0, dims);
if (d != 0.0 && ((d = sqrt(d)) != 0.0)) {
imul_vn_fl(v0, 1.0 / d, dims);
}
return d;
}
/* v_out = (v0 - v1).normalized() */
MINLINE double normalize_vn_vnvn(
double v_out[],
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
double a = v0[j] - v1[j];
d += sq(a);
v_out[j] = a;
}
if (d != 0.0 && ((d = sqrt(d)) != 0.0)) {
imul_vn_fl(v_out, 1.0 / d, dims);
}
return d;
}
MINLINE bool is_almost_zero_ex(double val, double eps)
{
return (-eps < val) && (val < eps);
}
MINLINE bool is_almost_zero(double val)
{
return is_almost_zero_ex(val, 1e-8);
}
MINLINE bool equals_vnvn(
const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
if (v0[j] != v1[j]) {
return false;
}
}
return true;
}
/** \} */

View File

@@ -42,7 +42,7 @@ Write a bit
@param bio BIO handle
@param b Bit to write (0 or 1)
*/
static void bio_putbit(opj_bio_t *bio, int b);
static void bio_putbit(opj_bio_t *bio, unsigned int b);
/**
Read a bit
@param bio BIO handle
@@ -78,7 +78,7 @@ static int bio_byteout(opj_bio_t *bio) {
if (bio->bp >= bio->end) {
return 1;
}
*bio->bp++ = bio->buf >> 8;
*bio->bp++ = (unsigned char)(bio->buf >> 8);
return 0;
}
@@ -92,7 +92,7 @@ static int bio_bytein(opj_bio_t *bio) {
return 0;
}
static void bio_putbit(opj_bio_t *bio, int b) {
static void bio_putbit(opj_bio_t *bio, unsigned int b) {
if (bio->ct == 0) {
bio_byteout(bio);
}
@@ -126,7 +126,7 @@ void bio_destroy(opj_bio_t *bio) {
}
int bio_numbytes(opj_bio_t *bio) {
return (bio->bp - bio->start);
return (int)(bio->bp - bio->start);
}
void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len) {

View File

@@ -29,8 +29,6 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include "opj_includes.h"

View File

@@ -30,6 +30,7 @@
*/
#include "opj_includes.h"
#include <assert.h>
/* ----------------------------------------------------------------------- */
@@ -106,6 +107,7 @@ int OPJ_CALLCONV cio_tell(opj_cio_t *cio) {
* pos : position, in number of bytes, from the beginning of the stream
*/
void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) {
assert((cio->start + pos) <= cio->end);
cio->bp = cio->start + pos;
}
@@ -113,6 +115,7 @@ void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) {
* Number of bytes left before the end of the stream.
*/
int cio_numbytesleft(opj_cio_t *cio) {
assert((cio->end - cio->bp) >= 0);
return cio->end - cio->bp;
}
@@ -139,6 +142,7 @@ opj_bool cio_byteout(opj_cio_t *cio, unsigned char v) {
* Read a byte.
*/
unsigned char cio_bytein(opj_cio_t *cio) {
assert(cio->bp >= cio->start);
if (cio->bp >= cio->end) {
opj_event_msg(cio->cinfo, EVT_ERROR, "read error: passed the end of the codestream (start = %d, current = %d, end = %d\n", cio->start, cio->bp, cio->end);
return 0;
@@ -152,7 +156,7 @@ unsigned char cio_bytein(opj_cio_t *cio) {
* v : value to write
* n : number of bytes to write
*/
unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n) {
unsigned int cio_write(opj_cio_t *cio, unsigned int64 v, int n) {
int i;
for (i = n - 1; i >= 0; i--) {
if( !cio_byteout(cio, (unsigned char) ((v >> (i << 3)) & 0xff)) )
@@ -173,7 +177,7 @@ unsigned int cio_read(opj_cio_t *cio, int n) {
unsigned int v;
v = 0;
for (i = n - 1; i >= 0; i--) {
v += cio_bytein(cio) << (i << 3);
v += (unsigned int)cio_bytein(cio) << (i << 3);
}
return v;
}
@@ -184,6 +188,10 @@ unsigned int cio_read(opj_cio_t *cio, int n) {
* n : number of bytes to skip
*/
void cio_skip(opj_cio_t *cio, int n) {
assert((cio->bp + n) >= cio->bp);
if (((cio->bp + n) < cio->start) || ((cio->bp + n) > cio->end)) {
assert(0);
}
cio->bp += n;
}

View File

@@ -31,6 +31,13 @@
#ifndef __CIO_H
#define __CIO_H
#if defined(_MSC_VER) || defined(__BORLANDC__)
#define int64 __int64
#else
#define int64 long long
#endif
/**
@file cio.h
@brief Implementation of a byte input-output process (CIO)
@@ -63,7 +70,7 @@ Write some bytes
@param n Number of bytes to write
@return Returns the number of bytes written or 0 if an error occured
*/
unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n);
unsigned int cio_write(opj_cio_t *cio, unsigned int64 v, int n);
/**
Read some bytes
@param cio CIO handle

View File

@@ -103,18 +103,17 @@ opj_bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ..
va_list arg;
int str_length/*, i, j*/; /* UniPG */
char message[MSG_SIZE];
memset(message, 0, MSG_SIZE);
/* initialize the optional parameter list */
va_start(arg, fmt);
/* check the length of the format string */
str_length = (strlen(fmt) > MSG_SIZE) ? MSG_SIZE : strlen(fmt);
/* parse the format string and put the result in 'message' */
vsprintf(message, fmt, arg); /* UniPG */
str_length = vsnprintf(message, MSG_SIZE, fmt, arg); /* UniPG */
/* deinitialize the optional parameter list */
va_end(arg);
/* output the message to the user program */
msg_handler(message, cinfo->client_data);
if( str_length > -1 && str_length < MSG_SIZE )
msg_handler(message, cinfo->client_data);
else return OPJ_FALSE;
}
return OPJ_TRUE;

View File

@@ -40,7 +40,7 @@ opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *c
image->color_space = clrspc;
image->numcomps = numcmpts;
/* allocate memory for the per-component information */
image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof(opj_image_comp_t));
image->comps = (opj_image_comp_t*)opj_calloc(1,image->numcomps * sizeof(opj_image_comp_t));
if(!image->comps) {
fprintf(stderr,"Unable to allocate memory for image.\n");
opj_image_destroy(image);
@@ -86,3 +86,4 @@ void OPJ_CALLCONV opj_image_destroy(opj_image_t *image) {
opj_free(image);
}
}

View File

@@ -32,6 +32,7 @@
*/
#include "opj_includes.h"
#include <assert.h>
/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
/*@{*/
@@ -404,6 +405,7 @@ static void j2k_write_siz(opj_j2k_t *j2k) {
static void j2k_read_siz(opj_j2k_t *j2k) {
int len, i;
int n_comps;
opj_cio_t *cio = j2k->cio;
opj_image_t *image = j2k->image;
@@ -422,12 +424,33 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
if ((image->x0<0)||(image->x1<0)||(image->y0<0)||(image->y1<0)) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"%s: invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
"invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
image->x0,image->x1,image->y0,image->y1);
return;
}
n_comps = (len - 36 - 2 ) / 3;
assert( (len - 36 - 2 ) % 3 == 0 );
image->numcomps = cio_read(cio, 2); /* Csiz */
assert( n_comps == image->numcomps );
(void)n_comps;
/* testcase 4035.pdf.SIGSEGV.d8b.3375 */
if (image->x0 > image->x1 || image->y0 > image->y1) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Error with SIZ marker: negative image size (%d x %d)\n", image->x1 - image->x0, image->y1 - image->y0);
return;
}
/* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
if (!(cp->tdx * cp->tdy)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", cp->tdx, cp->tdy);
return;
}
/* testcase 1610.pdf.SIGSEGV.59c.681 */
if (((int64)image->x1) * ((int64)image->y1) != (image->x1 * image->y1)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Prevent buffer overflow (x1: %d, y1: %d)\n", image->x1, image->y1);
return;
}
#ifdef USE_JPWL
if (j2k->cp->correct) {
@@ -466,11 +489,19 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
/* update components number in the jpwl_exp_comps filed */
cp->exp_comps = image->numcomps;
}
#else
(void)len;
#endif /* USE_JPWL */
/* prevent division by zero */
if (!(cp->tdx * cp->tdy)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "invalid tile size (tdx: %d, tdy: %d)\n", cp->tdx, cp->tdy);
return;
}
image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
for (i = 0; i < image->numcomps; i++) {
int tmp, w, h;
int tmp;
tmp = cio_read(cio, 1); /* Ssiz_i */
image->comps[i].prec = (tmp & 0x7f) + 1;
image->comps[i].sgnd = tmp >> 7;
@@ -506,9 +537,11 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
}
#endif /* USE_JPWL */
/* TODO: unused ? */
w = int_ceildiv(image->x1 - image->x0, image->comps[i].dx);
h = int_ceildiv(image->y1 - image->y0, image->comps[i].dy);
/* prevent division by zero */
if (!(image->comps[i].dx * image->comps[i].dy)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: invalid component size (dx: %d, dy: %d)\n", image->comps[i].dx, image->comps[i].dy);
return;
}
image->comps[i].resno_decoded = 0; /* number of resolution decoded */
image->comps[i].factor = cp->reduce; /* reducing factor per component */
@@ -517,6 +550,15 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
/* gdal_fuzzer_check_number_of_tiles.jp2 */
if (cp->tw == 0 || cp->th == 0 || cp->tw > 65535 / cp->th) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
cp->tw, cp->th);
return;
}
#ifdef USE_JPWL
if (j2k->cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
@@ -558,7 +600,17 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
#endif /* USE_JPWL */
cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
if (cp->tcps == NULL)
{
opj_event_msg(j2k->cinfo, EVT_ERROR, "Out of memory\n");
return;
}
cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int));
if (cp->tileno == NULL)
{
opj_event_msg(j2k->cinfo, EVT_ERROR, "Out of memory\n");
return;
}
cp->tileno_size = 0;
#ifdef USE_JPWL
@@ -684,6 +736,12 @@ static void j2k_read_cox(opj_j2k_t *j2k, int compno) {
"of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
j2k->state |= J2K_STATE_ERR;
}
if( tccp->numresolutions > J2K_MAXRLVLS ) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions is too big: %d vs max= %d. Truncating.\n\n",
compno, tccp->numresolutions, J2K_MAXRLVLS);
j2k->state |= J2K_STATE_ERR;
tccp->numresolutions = J2K_MAXRLVLS;
}
tccp->cblkw = cio_read(cio, 1) + 2; /* SPcox (E) */
tccp->cblkh = cio_read(cio, 1) + 2; /* SPcox (F) */
@@ -753,6 +811,7 @@ static void j2k_read_cod(opj_j2k_t *j2k) {
opj_image_t *image = j2k->image;
len = cio_read(cio, 2); /* Lcod */
(void)len;
tcp->csty = cio_read(cio, 1); /* Scod */
tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1); /* SGcod (A) */
tcp->numlayers = cio_read(cio, 2); /* SGcod (B) */
@@ -806,7 +865,14 @@ static void j2k_read_coc(opj_j2k_t *j2k) {
opj_cio_t *cio = j2k->cio;
len = cio_read(cio, 2); /* Lcoc */
(void)len;
compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
if (compno >= image->numcomps) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad component number in COC (%d out of a maximum of %d)\n",
compno, image->numcomps);
return;
}
tcp->tccps[compno].csty = cio_read(cio, 1); /* Scoc */
j2k_read_cox(j2k, compno);
}
@@ -877,6 +943,8 @@ static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) {
opj_event_msg(j2k->cinfo, EVT_WARNING ,
"bad number of subbands in Sqcx (%d) regarding to J2K_MAXBANDS (%d) \n"
"- limiting number of bands to J2K_MAXBANDS and try to move to the next markers\n", numbands, J2K_MAXBANDS);
/* edf_c2_1013627.jp2 */
numbands = 1;
}
#endif /* USE_JPWL */
@@ -988,9 +1056,16 @@ static void j2k_read_qcc(opj_j2k_t *j2k) {
/* keep your private count of tiles */
backup_compno++;
};
}
#endif /* USE_JPWL */
if ((compno < 0) || (compno >= numcomp)) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad component number in QCC (%d out of a maximum of %d)\n",
compno, j2k->image->numcomps);
return;
}
j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2));
}
@@ -1036,6 +1111,15 @@ static void j2k_read_poc(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Lpoc */
numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));
if( numpchgs >= 32 )
{
/* edf_c2_1103421.jp2 */
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad number of POCS (%d out of a maximum of %d)\n",
numpchgs, 32);
numpchgs = 0;
}
for (i = old_poc; i < numpchgs + old_poc; i++) {
opj_poc_t *poc;
poc = &tcp->pocs[i];
@@ -1058,9 +1142,12 @@ static void j2k_read_crg(opj_j2k_t *j2k) {
int numcomps = j2k->image->numcomps;
len = cio_read(cio, 2); /* Lcrg */
(void)len;
for (i = 0; i < numcomps; i++) {
Xcrg_i = cio_read(cio, 2); /* Xcrg_i */
(void)Xcrg_i;
Ycrg_i = cio_read(cio, 2); /* Ycrg_i */
(void)Ycrg_i;
}
}
@@ -1072,13 +1159,16 @@ static void j2k_read_tlm(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Ltlm */
Ztlm = cio_read(cio, 1); /* Ztlm */
(void)Ztlm;
Stlm = cio_read(cio, 1); /* Stlm */
ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
SP = (Stlm >> 6) & 0x01;
tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
for (i = 0; i < tile_tlm; i++) {
Ttlm_i = cio_read(cio, ST); /* Ttlm_i */
(void)Ttlm_i;
Ptlm_i = cio_read(cio, SP ? 4 : 2); /* Ptlm_i */
(void)Ptlm_i;
}
}
@@ -1089,6 +1179,7 @@ static void j2k_read_plm(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Lplm */
Zplm = cio_read(cio, 1); /* Zplm */
(void)Zplm;
len -= 3;
while (len > 0) {
Nplm = cio_read(cio, 4); /* Nplm */
@@ -1114,6 +1205,7 @@ static void j2k_read_plt(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Lplt */
Zplt = cio_read(cio, 1); /* Zplt */
(void)Zplt;
for (i = len - 3; i > 0; i--) {
add = cio_read(cio, 1);
packet_len = (packet_len << 7) + add; /* Iplt_i */
@@ -1261,6 +1353,7 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
opj_cio_t *cio = j2k->cio;
len = cio_read(cio, 2);
(void)len;
tileno = cio_read(cio, 2);
#ifdef USE_JPWL
@@ -1269,7 +1362,7 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
static int backup_tileno = 0;
/* tileno is negative or larger than the number of tiles!!! */
if ((tileno < 0) || (tileno > (cp->tw * cp->th))) {
if ((tileno < 0) || (tileno >= (cp->tw * cp->th))) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (cp->tw * cp->th));
@@ -1286,8 +1379,18 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
/* keep your private count of tiles */
backup_tileno++;
};
}
else
#endif /* USE_JPWL */
{
/* tileno is negative or larger than the number of tiles!!! */
if ((tileno < 0) || (tileno >= (cp->tw * cp->th))) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (cp->tw * cp->th));
return;
}
}
if (cp->tileno_size == 0) {
cp->tileno[cp->tileno_size] = tileno;
@@ -1325,8 +1428,18 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
totlen);
}
};
}
else
#endif /* USE_JPWL */
{
/* totlen is negative or larger than the bytes left!!! */
if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
totlen, cio_numbytesleft(cio) + 8);
return;
}
}
if (!totlen)
totlen = cio_numbytesleft(cio) + 8;
@@ -1478,7 +1591,13 @@ static void j2k_read_sod(opj_j2k_t *j2k) {
}
data = j2k->tile_data[curtileno];
data_ptr = data; /* store in case of failure */
data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char));
if( data == NULL ) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not reallocated\n" );
opj_free( data_ptr );
return;
}
data_ptr = data + j2k->tile_len[curtileno];
for (i = 0; i < len; i++) {
@@ -1518,8 +1637,10 @@ static void j2k_read_rgn(opj_j2k_t *j2k) {
int numcomps = j2k->image->numcomps;
len = cio_read(cio, 2); /* Lrgn */
(void)len;
compno = cio_read(cio, numcomps <= 256 ? 1 : 2); /* Crgn */
roisty = cio_read(cio, 1); /* Srgn */
(void)roisty;
#ifdef USE_JPWL
if (j2k->cp->correct) {
@@ -1536,6 +1657,13 @@ static void j2k_read_rgn(opj_j2k_t *j2k) {
};
#endif /* USE_JPWL */
if (compno >= numcomps) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad component number in RGN (%d out of a maximum of %d)\n",
compno, j2k->image->numcomps);
return;
}
tcp->tccps[compno].roishift = cio_read(cio, 1); /* SPrgn */
}
@@ -1554,7 +1682,7 @@ static void j2k_write_eoc(opj_j2k_t *j2k) {
static void j2k_read_eoc(opj_j2k_t *j2k) {
int i, tileno;
opj_bool success;
opj_bool success = OPJ_FALSE;
/* if packets should be decoded */
if (j2k->cp->limit_decoding != DECODE_ALL_BUT_PACKETS) {
@@ -1562,11 +1690,17 @@ static void j2k_read_eoc(opj_j2k_t *j2k) {
tcd_malloc_decode(tcd, j2k->image, j2k->cp);
for (i = 0; i < j2k->cp->tileno_size; i++) {
tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info);
tileno = j2k->cp->tileno[i];
success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
opj_free(j2k->tile_data[tileno]);
j2k->tile_data[tileno] = NULL;
tcd_free_decode_tile(tcd, i);
if (j2k->cp->tileno[i] != -1)
{
tileno = j2k->cp->tileno[i];
success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
assert( tileno != -1 );
opj_free(j2k->tile_data[tileno]);
j2k->tile_data[tileno] = NULL;
tcd_free_decode_tile(tcd, i);
}
else
success = OPJ_FALSE;
if (success == OPJ_FALSE) {
j2k->state |= J2K_STATE_ERR;
break;
@@ -1737,6 +1871,17 @@ void j2k_destroy_decompress(opj_j2k_t *j2k) {
opj_free(j2k->tile_len);
}
if(j2k->tile_data != NULL) {
if(j2k->cp != NULL) {
for (i = 0; i < j2k->cp->tileno_size; i++) {
int tileno = j2k->cp->tileno[i];
if( tileno != -1 )
{
opj_free(j2k->tile_data[tileno]);
j2k->tile_data[tileno] = NULL;
}
}
}
opj_free(j2k->tile_data);
}
if(j2k->default_tcp != NULL) {
@@ -1856,9 +2001,15 @@ opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *c
#endif /* USE_JPWL */
if (id >> 8 != 0xff) {
opj_image_destroy(image);
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
return 0;
if(cio_numbytesleft(cio) != 0) /* not end of file reached and no EOC */
{
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
opj_image_destroy(image);
return 0;
}
opj_event_msg(cinfo, EVT_WARNING, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
j2k->state = J2K_STATE_NEOC;
break;
}
e = j2k_dec_mstab_lookup(id);
/* Check if the marker is known*/
@@ -1877,7 +2028,10 @@ opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *c
(*e->handler)(j2k);
}
if (j2k->state & J2K_STATE_ERR)
{
opj_image_destroy(image);
return NULL;
}
if (j2k->state == J2K_STATE_MT) {
break;
@@ -1888,6 +2042,11 @@ opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *c
}
if (j2k->state == J2K_STATE_NEOC) {
j2k_read_eoc(j2k);
/* Check one last time for errors during decoding before returning */
if (j2k->state & J2K_STATE_ERR) {
opj_image_destroy(image);
return NULL;
}
}
if (j2k->state != J2K_STATE_MT) {
@@ -1949,9 +2108,15 @@ opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestre
id = cio_read(cio, 2);
if (id >> 8 != 0xff) {
opj_image_destroy(image);
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
return 0;
if(cio_numbytesleft(cio) != 0) /* no end of file reached and no EOC */
{
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
opj_image_destroy(image);
return 0;
}
opj_event_msg(cinfo, EVT_WARNING, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
j2k->state = J2K_STATE_NEOC;
break;
}
e = j2k_dec_mstab_lookup(id);
if (!(j2k->state & e->states)) {

View File

@@ -30,6 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_includes.h"
#include <assert.h>
/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
/*@{*/
@@ -172,6 +173,9 @@ static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_bo
}
else if (box->length == 0) {
box->length = cio_numbytesleft(cio) + 8;
} else if (box->length < 0) {
opj_event_msg(cinfo, EVT_ERROR, "Integer overflow in box->length\n");
return OPJ_FALSE; /* TODO: actually check jp2_read_boxhdr's return value */
}
return OPJ_TRUE;
@@ -206,7 +210,10 @@ static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if(jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_IHDR != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
return OPJ_FALSE;
@@ -279,7 +286,10 @@ static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_BPCC != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
return OPJ_FALSE;
@@ -469,7 +479,7 @@ static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
for(i = 0; i < nr_channels; ++i)
{
/* Cji */
*entries++ = cio_read(cio, channel_size[i]>>3);
*entries++ = cio_read(cio, (channel_size[i]+7)>>3);
}
}
@@ -512,10 +522,8 @@ static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
{
opj_jp2_cdef_info_t *info;
int color_space;
unsigned short i, n, cn, typ, asoc, acn;
color_space = image->color_space;
info = color->jp2_cdef->info;
n = color->jp2_cdef->n;
@@ -525,6 +533,7 @@ static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
if((asoc = info[i].asoc) == 0) continue;
cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
(void)typ;
if(cn != acn)
{
@@ -639,90 +648,173 @@ opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color)
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
do
{
if (JP2_JP2H != box.type)
{
if (box.type == JP2_JP2C)
{
opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
return OPJ_FALSE;
}
cio_skip(cio, box.length - 8);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
do {
if (JP2_JP2H != box.type)
{
if (box.type == JP2_JP2C)
{
opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
return OPJ_FALSE;
}
if (box.length <= 8) return OPJ_FALSE;
cio_skip(cio, box.length - 8);
if(cio->bp >= cio->end) return OPJ_FALSE;
if(cio->bp >= cio->end) return OPJ_FALSE;
jp2_read_boxhdr(cinfo, cio, &box);
}
} while(JP2_JP2H != box.type);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
}
} while(JP2_JP2H != box.type);
if (!jp2_read_ihdr(jp2, cio))
return OPJ_FALSE;
jp2h_end = box.init_pos + box.length;
if (jp2->bpc == 255)
{
if (!jp2_read_bpcc(jp2, cio))
return OPJ_FALSE;
}
jp2_read_boxhdr(cinfo, cio, &box);
if (jp2->bpc == 255)
{
if (!jp2_read_bpcc(jp2, cio))
return OPJ_FALSE;
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
while(cio_tell(cio) < jp2h_end)
{
if(box.type == JP2_COLR)
{
if( !jp2_read_colr(jp2, cio, &box, color))
{
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
while(cio_tell(cio) < jp2h_end)
{
if(box.type == JP2_COLR)
{
if( !jp2_read_colr(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
{
if( !jp2_read_cdef(jp2, cio, &box, color))
{
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
{
if( !jp2_read_cdef(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
{
if( !jp2_read_pclr(jp2, cio, &box, color))
{
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
{
if( !jp2_read_pclr(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
{
if( !jp2_read_cmap(jp2, cio, &box, color))
{
{
if( !jp2_read_cmap(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
}/* while(cio_tell(cio) < box_end) */
}/* while(cio_tell(cio) < box_end) */
cio_seek(cio, jp2h_end);
cio_seek(cio, jp2h_end);
/* Part 1, I.5.3.3 : 'must contain at least one' */
return (color->jp2_has_colr == 1);
/* Part 1, I.5.3.3 : 'must contain at least one' */
return (color->jp2_has_colr == 1);
}/* jp2_read_jp2h() */
static opj_bool opj_jp2_check_color(opj_image_t *image, opj_jp2_color_t *color, opj_common_ptr cinfo)
{
int i;
/* testcase 4149.pdf.SIGSEGV.cf7.3501 */
if (color->jp2_cdef) {
opj_jp2_cdef_info_t *info = color->jp2_cdef->info;
int n = color->jp2_cdef->n;
for (i = 0; i < n; i++) {
if (info[i].cn >= image->numcomps) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].cn, image->numcomps);
return OPJ_FALSE;
}
if (info[i].asoc > 0 && (info[i].asoc - 1) >= image->numcomps) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].asoc - 1, image->numcomps);
return OPJ_FALSE;
}
}
}
/* testcases 451.pdf.SIGSEGV.f4c.3723, 451.pdf.SIGSEGV.5b5.3723 and
66ea31acbb0f23a2bbc91f64d69a03f5_signal_sigsegv_13937c0_7030_5725.pdf */
if (color->jp2_pclr && color->jp2_pclr->cmap) {
int nr_channels = color->jp2_pclr->nr_channels;
opj_jp2_cmap_comp_t *cmap = color->jp2_pclr->cmap;
opj_bool *pcol_usage, is_sane = OPJ_TRUE;
/* verify that all original components match an existing one */
for (i = 0; i < nr_channels; i++) {
if (cmap[i].cmp >= image->numcomps) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", cmap[i].cmp, image->numcomps);
is_sane = OPJ_FALSE;
}
}
pcol_usage = opj_calloc(nr_channels, sizeof(opj_bool));
if (!pcol_usage) {
opj_event_msg(cinfo, EVT_ERROR, "Unexpected OOM.\n");
return OPJ_FALSE;
}
/* verify that no component is targeted more than once */
for (i = 0; i < nr_channels; i++) {
int pcol = cmap[i].pcol;
assert(cmap[i].mtyp == 0 || cmap[i].mtyp == 1);
if (pcol >= nr_channels) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component/palette index for direct mapping %d.\n", pcol);
is_sane = OPJ_FALSE;
}
else if (pcol_usage[pcol] && cmap[i].mtyp == 1) {
opj_event_msg(cinfo, EVT_ERROR, "Component %d is mapped twice.\n", pcol);
is_sane = OPJ_FALSE;
}
else if (cmap[i].mtyp == 0 && cmap[i].pcol != 0) {
/* I.5.3.5 PCOL: If the value of the MTYP field for this channel is 0, then
* the value of this field shall be 0. */
opj_event_msg(cinfo, EVT_ERROR, "Direct use at #%d however pcol=%d.\n", i, pcol);
is_sane = OPJ_FALSE;
}
else
pcol_usage[pcol] = OPJ_TRUE;
}
/* verify that all components are targeted at least once */
for (i = 0; i < nr_channels; i++) {
if (!pcol_usage[i] && cmap[i].mtyp != 0) {
opj_event_msg(cinfo, EVT_ERROR, "Component %d doesn't have a mapping.\n", i);
is_sane = OPJ_FALSE;
}
}
opj_free(pcol_usage);
if (!is_sane) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio,
opj_codestream_info_t *cstr_info)
{
@@ -756,6 +848,10 @@ opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio,
}
if (!jp2->ignore_pclr_cmap_cdef){
if (!opj_jp2_check_color(image, &color, cinfo)) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to decode PCRL box\n");
return NULL;
}
/* Set Image Color Space */
if (jp2->enumcs == 16)
@@ -839,8 +935,10 @@ static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_FTYP != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
return OPJ_FALSE;
@@ -849,6 +947,14 @@ static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
jp2->brand = cio_read(cio, 4); /* BR */
jp2->minversion = cio_read(cio, 4); /* MinV */
jp2->numcl = (box.length - 16) / 4;
/* edf_c2_1673169.jp2 */
if (cio_numbytesleft(cio) < ((int)jp2->numcl * 4)) {
opj_event_msg(cinfo, EVT_ERROR, "Not enough bytes in FTYP Box "
"(expected %d, but only %d left)\n",
((int)jp2->numcl * 4), cio_numbytesleft(cio));
return OPJ_FALSE;
}
jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
for (i = 0; i < (int)jp2->numcl; i++) {
@@ -897,15 +1003,20 @@ static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
do {
if(JP2_JP2C != box.type) {
if (box.length <= 8) return OPJ_FALSE;
cio_skip(cio, box.length - 8);
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
}
} while(JP2_JP2C != box.type);
*j2k_codestream_offset = cio_tell(cio);
if (box.length <= 8) return OPJ_FALSE;
*j2k_codestream_length = box.length - 8;
return OPJ_TRUE;
@@ -930,7 +1041,10 @@ static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_JP != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
return OPJ_FALSE;
@@ -1070,6 +1184,7 @@ void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
if(jp2) {
memset(jp2, 0, sizeof(opj_jp2_t));
jp2->cinfo = cinfo;
/* create the J2K codec */
jp2->j2k = j2k_create_compress(cinfo);

View File

@@ -135,6 +135,10 @@ typedef enum COLOR_SPACE {
CLRSPC_SYCC = 3 /**< YUV */
} OPJ_COLOR_SPACE;
#define ENUMCS_SRGB 16
#define ENUMCS_GRAY 17
#define ENUMCS_SYCC 18
/**
Supported codec
*/

View File

@@ -3,7 +3,7 @@
* the endian check is a blender define */
/* create config.h for CMake */
#define PACKAGE_VERSION "1.5.0"
#define PACKAGE_VERSION "1.5.2"
#define HAVE_INTTYPES_H
#define HAVE_MEMORY_H
@@ -23,6 +23,7 @@
/* #undef HAVE_LIBLCMS2 */
/* #undef HAVE_LCMS1_H */
/* #undef HAVE_LCMS2_H */
/* #undef USE_SYSTEM_GETOPT */
/* Byte order. */
/* All compilers that support Mac OS X define either __BIG_ENDIAN__ or

View File

@@ -89,18 +89,17 @@ Most compilers implement their own version of this keyword ...
/* MSVC and Borland C do not have lrintf */
#if defined(_MSC_VER) || defined(__BORLANDC__)
static INLINE long lrintf(float f){
#ifdef _M_X64
return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f));
#else
int i;
#ifdef _M_IX86
long int i;
_asm{
fld f
fistp i
};
return i;
#endif
#else
return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f));
#endif /* _M_IX86 */
}
#endif

View File

@@ -83,8 +83,10 @@ Allocate memory aligned to a 16 byte boundry
#else /* Not _WIN32 */
#if defined(__sun)
#define HAVE_MEMALIGN
#elif defined(__FreeBSD__)
#define HAVE_POSIX_MEMALIGN
/* Linux x86_64 and OSX always align allocations to 16 bytes */
#elif !defined(__amd64__) && !defined(__APPLE__)
#elif !defined(__amd64__) && !defined(__APPLE__) && !defined(_AIX)
#define HAVE_MEMALIGN
#include <malloc.h>
#endif

View File

@@ -1,13 +0,0 @@
Index: extern/libopenjpeg/opj_malloc.h
===================================================================
--- extern/libopenjpeg/opj_malloc.h (revision 27736)
+++ extern/libopenjpeg/opj_malloc.h (working copy)
@@ -76,7 +76,7 @@
#if defined(__sun)
#define HAVE_MEMALIGN
#elif defined(__GNUC__)
- #ifndef __APPLE__
+ #if !defined(__APPLE__) && !defined(__FreeBSD__)
#define HAVE_MEMALIGN
#include <malloc.h>
#endif

View File

@@ -1,17 +0,0 @@
Index: opj_malloc.h
===================================================================
--- opj_malloc.h (revision 15089)
+++ opj_malloc.h (working copy)
@@ -76,8 +76,10 @@
#if defined(__sun)
#define HAVE_MEMALIGN
#elif defined(__GNUC__)
- #define HAVE_MEMALIGN
- #include <malloc.h>
+ #ifndef __APPLE__
+ #define HAVE_MEMALIGN
+ #include <malloc.h>
+ #endif
/* Linux x86_64 and OSX always align allocations to 16 bytes */
#elif !defined(__amd64__) && !defined(__APPLE__)
/* FIXME: Yes, this is a big assumption */

View File

@@ -1577,6 +1577,7 @@ void t1_decode_cblks(
opj_free(cblk->segs);
} /* cblkno */
opj_free(precinct->cblks.dec);
precinct->cblks.dec = NULL;
} /* precno */
} /* bandno */
} /* resno */

View File

@@ -30,6 +30,7 @@
*/
#include "opj_includes.h"
#include <assert.h>
/** @defgroup T2 T2 - Implementation of a tier-2 coding */
/*@{*/
@@ -64,7 +65,7 @@ static int t2_encode_packet(opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterato
@param cblksty
@param first
*/
static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first);
static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first);
/**
Decode a packet of a tile from a source buffer
@param t2 T2 handle
@@ -296,9 +297,17 @@ static int t2_encode_packet(opj_tcd_tile_t * tile, opj_tcp_t * tcp, opj_pi_itera
return (c - dest);
}
static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) {
static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) {
opj_tcd_seg_t* seg;
cblk->segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t));
opj_tcd_seg_t* segs;
segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t));
if (segs == NULL)
{
return OPJ_FALSE;
}
cblk->segs = segs;
seg = &cblk->segs[index];
seg->data = NULL;
seg->dataindex = 0;
@@ -316,6 +325,8 @@ static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int fi
} else {
seg->maxpasses = 109;
}
return OPJ_TRUE;
}
static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile,
@@ -330,13 +341,15 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
int precno = pi->precno; /* precinct value */
int layno = pi->layno; /* quality layer value */
opj_tcd_resolution_t* res = &tile->comps[compno].resolutions[resno];
unsigned char *hd = NULL;
int present;
opj_bio_t *bio = NULL; /* BIO component */
opj_tcd_resolution_t* res;
assert(&tile->comps[compno] != NULL);
res = &tile->comps[compno].resolutions[resno];
if (layno == 0) {
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
@@ -462,12 +475,22 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
cblk->numlenbits += increment;
segno = 0;
if (!cblk->numsegs) {
t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1);
if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1))
{
opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
bio_destroy(bio);
return -999;
}
} else {
segno = cblk->numsegs - 1;
if (cblk->segs[segno].numpasses == cblk->segs[segno].maxpasses) {
++segno;
t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0))
{
opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
bio_destroy(bio);
return -999;
}
}
}
n = cblk->numnewpasses;
@@ -478,7 +501,12 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
n -= cblk->segs[segno].numnewpasses;
if (n > 0) {
++segno;
t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0))
{
opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
bio_destroy(bio);
return -999;
}
}
} while (n > 0);
}
@@ -714,7 +742,11 @@ int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj
} else {
e = 0;
}
if(e == -999) return -999;
if(e == -999)
{
pi_destroy(pi, cp, tileno);
return -999;
}
/* progression in resolution */
image->comps[pi[pino].compno].resno_decoded =
(e > 0) ?

View File

@@ -30,7 +30,9 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#define _ISOC99_SOURCE /* lrintf is C99 */
#include "opj_includes.h"
#include <assert.h>
void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) {
int tileno, compno, resno, bandno, precno;/*, cblkno;*/
@@ -249,7 +251,9 @@ void tcd_malloc_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int c
cbgwidthexpn = pdx - 1;
cbgheightexpn = pdy - 1;
}
(void)brcbgyend;
(void)brcbgxend;
cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -333,8 +337,10 @@ void tcd_malloc_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int c
cblk->y0 = int_max(cblkystart, prc->y0);
cblk->x1 = int_min(cblkxend, prc->x1);
cblk->y1 = int_min(cblkyend, prc->y1);
cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char));
cblk->data = (unsigned char*) opj_calloc(9728+2, sizeof(unsigned char));
/* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */
cblk->data[0] = 0;
cblk->data[1] = 0;
cblk->data += 2;
cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
@@ -509,6 +515,8 @@ void tcd_init_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int cur
cbgwidthexpn = pdx - 1;
cbgheightexpn = pdy - 1;
}
(void)brcbgyend;
(void)brcbgxend;
cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -594,6 +602,8 @@ void tcd_init_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int cur
cblk->y1 = int_min(cblkyend, prc->y1);
cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char));
/* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */
cblk->data[0] = 0;
cblk->data[1] = 0;
cblk->data += 2;
cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
@@ -614,7 +624,7 @@ void tcd_malloc_decode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp) {
tcd->image = image;
tcd->tcd_image->tw = cp->tw;
tcd->tcd_image->th = cp->th;
tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tcd_tile_t));
tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(cp->tw * cp->th, sizeof(opj_tcd_tile_t));
/*
Allocate place to store the decoded data = final image
@@ -690,6 +700,12 @@ void tcd_malloc_decode_tile(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp,
opj_tccp_t *tccp = &tcp->tccps[compno];
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
if (tccp->numresolutions <= 0)
{
cp->tileno[tileno] = -1;
return;
}
/* border of each tile component (global) */
tilec->x0 = int_ceildiv(tile->x0, image->comps[compno].dx);
tilec->y0 = int_ceildiv(tile->y0, image->comps[compno].dy);
@@ -749,6 +765,8 @@ void tcd_malloc_decode_tile(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp,
cbgwidthexpn = pdx - 1;
cbgheightexpn = pdy - 1;
}
(void)brcbgyend;
(void)brcbgxend;
cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -1370,16 +1388,31 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
if (l == -999) {
eof = 1;
opj_event_msg(tcd->cinfo, EVT_ERROR, "tcd_decode: incomplete bistream\n");
return OPJ_FALSE;
}
/*------------------TIER1-----------------*/
t1_time = opj_clock(); /* time needed to decode a tile */
t1 = t1_create(tcd->cinfo);
if (t1 == NULL)
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
t1_destroy(t1);
return OPJ_FALSE;
}
for (compno = 0; compno < tile->numcomps; ++compno) {
opj_tcd_tilecomp_t* tilec = &tile->comps[compno];
/* The +3 is headroom required by the vectorized DWT */
tilec->data = (int*) opj_aligned_malloc((((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0))+3) * sizeof(int));
if (tilec->data == NULL)
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
t1_destroy(t1);
return OPJ_FALSE;
}
t1_decode_cblks(t1, tilec, &tcd->tcp->tccps[compno]);
}
t1_destroy(t1);
@@ -1394,13 +1427,15 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
int numres2decode;
if (tcd->cp->reduce != 0) {
tcd->image->comps[compno].resno_decoded =
tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
if (tcd->image->comps[compno].resno_decoded < 0) {
if ( tile->comps[compno].numresolutions < ( tcd->cp->reduce - 1 ) ) {
opj_event_msg(tcd->cinfo, EVT_ERROR, "Error decoding tile. The number of resolutions to remove [%d+1] is higher than the number "
" of resolutions in the original codestream [%d]\nModify the cp_reduce parameter.\n", tcd->cp->reduce, tile->comps[compno].numresolutions);
return OPJ_FALSE;
}
else {
tcd->image->comps[compno].resno_decoded =
tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
}
}
numres2decode = tcd->image->comps[compno].resno_decoded + 1;
@@ -1421,6 +1456,13 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
int n = (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0);
if (tile->numcomps >= 3 ){
/* testcase 1336.pdf.asan.47.376 */
if ((tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0) < n ||
( tile->comps[1].x1 - tile->comps[1].x0) * (tile->comps[1].y1 - tile->comps[1].y0) < n ||
( tile->comps[2].x1 - tile->comps[2].x0) * (tile->comps[2].y1 - tile->comps[2].y0) < n) {
opj_event_msg(tcd->cinfo, EVT_ERROR, "Tiles don't all have the same dimension. Skip the MCT step.\n");
return OPJ_FALSE;
}
if (tcd->tcp->tccps[0].qmfbid == 1) {
mct_decode(
tile->comps[0].data,
@@ -1452,18 +1494,33 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
int tw = tilec->x1 - tilec->x0;
int w = imagec->w;
int i, j;
int offset_x = int_ceildivpow2(imagec->x0, imagec->factor);
int offset_y = int_ceildivpow2(imagec->y0, imagec->factor);
/* NR-DEC-2977.pdf.asan.67.2198.jp2-52-decode */
if( res->x0 - offset_x < 0 || res->x1 - offset_x < 0
|| res->y0 - offset_y < 0 || res->y1 - offset_y < 0 )
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Impossible offsets %d / %d\n", offset_x, offset_y);
return OPJ_FALSE;
}
assert( 0 <= res->x0 - offset_x && 0 <= res->x1 - offset_x );
assert( 0 <= res->y0 - offset_y && 0 <= res->y1 - offset_y );
int i, j;
if(!imagec->data){
imagec->data = (int*) opj_malloc(imagec->w * imagec->h * sizeof(int));
}
if (!imagec->data)
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
return OPJ_FALSE;
}
if(tcd->tcp->tccps[compno].qmfbid == 1) {
for(j = res->y0; j < res->y1; ++j) {
for(i = res->x0; i < res->x1; ++i) {
int v = tilec->data[i - res->x0 + (j - res->y0) * tw];
v += adjust;
/*assert( (i - offset_x) + (j - offset_y) * w >= 0 );*/
imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
}
}
@@ -1473,6 +1530,7 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
float tmp = ((float*)tilec->data)[i - res->x0 + (j - res->y0) * tw];
int v = lrintf(tmp);
v += adjust;
/*assert( (i - offset_x) + (j - offset_y) * w >= 0 );*/
imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
}
}
@@ -1492,32 +1550,51 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
void tcd_free_decode(opj_tcd_t *tcd) {
opj_tcd_image_t *tcd_image = tcd->tcd_image;
int i = 0;
for (i = 0; i < tcd_image->tw * tcd_image->th; i++)
{
tcd_free_decode_tile(tcd, i);
}
opj_free(tcd_image->tiles);
}
void tcd_free_decode_tile(opj_tcd_t *tcd, int tileno) {
int compno,resno,bandno,precno;
int compno,resno,bandno,precno,cblkno;
opj_tcd_image_t *tcd_image = tcd->tcd_image;
opj_tcd_tile_t *tile = &tcd_image->tiles[tileno];
for (compno = 0; compno < tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
for (precno = 0; precno < res->ph * res->pw; precno++) {
opj_tcd_precinct_t *prec = &band->precincts[precno];
if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree);
if (prec->incltree != NULL) tgt_destroy(prec->incltree);
if (tile->comps != NULL) {
for (compno = 0; compno < tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
for (precno = 0; precno < res->ph * res->pw; precno++) {
opj_tcd_precinct_t *prec = &band->precincts[precno];
if (prec->cblks.dec != NULL) {
for (cblkno = 0; cblkno < prec->cw * prec->ch; ++cblkno) {
opj_tcd_cblk_dec_t* cblk = &prec->cblks.dec[cblkno];
opj_free(cblk->data);
opj_free(cblk->segs);
}
opj_free(prec->cblks.dec);
}
if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree);
if (prec->incltree != NULL) tgt_destroy(prec->incltree);
}
opj_free(band->precincts);
}
opj_free(band->precincts);
}
opj_free(tilec->resolutions);
}
opj_free(tilec->resolutions);
opj_free(tile->comps);
tile->comps = NULL;
}
opj_free(tile->comps);
}

View File

@@ -1919,11 +1919,10 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize
static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
{
UInt32 beforeSize = kNumOpts;
Bool btMode;
if (!RangeEnc_Alloc(&p->rc, alloc))
return SZ_ERROR_MEM;
btMode = (p->matchFinderBase.btMode != 0);
#ifdef COMPRESS_MF_MT
Bool btMode = (p->matchFinderBase.btMode != 0);;
p->mtMode = (p->multiThread && !p->fastMode && btMode);
#endif

View File

@@ -23,9 +23,11 @@
#
# ***** END GPL LICENSE BLOCK *****
remove_cc_flag_unsigned_char()
set(INC
Recast/Include
Detour/Include
Recast/Include
Detour/Include
)
set(INC_SYS
@@ -33,38 +35,38 @@ set(INC_SYS
)
set(SRC
recast-capi.cpp
recast-capi.h
recast-capi.cpp
recast-capi.h
Detour/Source/DetourCommon.cpp
Detour/Source/DetourNode.cpp
Detour/Source/DetourStatNavMesh.cpp
Detour/Source/DetourStatNavMeshBuilder.cpp
Detour/Source/DetourTileNavMesh.cpp
Detour/Source/DetourTileNavMeshBuilder.cpp
Detour/Source/DetourCommon.cpp
Detour/Source/DetourNode.cpp
Detour/Source/DetourStatNavMesh.cpp
Detour/Source/DetourStatNavMeshBuilder.cpp
Detour/Source/DetourTileNavMesh.cpp
Detour/Source/DetourTileNavMeshBuilder.cpp
Detour/Include/DetourCommon.h
Detour/Include/DetourNode.h
Detour/Include/DetourStatNavMesh.h
Detour/Include/DetourStatNavMeshBuilder.h
Detour/Include/DetourTileNavMesh.h
Detour/Include/DetourTileNavMeshBuilder.h
Detour/Include/DetourCommon.h
Detour/Include/DetourNode.h
Detour/Include/DetourStatNavMesh.h
Detour/Include/DetourStatNavMeshBuilder.h
Detour/Include/DetourTileNavMesh.h
Detour/Include/DetourTileNavMeshBuilder.h
Recast/Source/Recast.cpp
Recast/Source/RecastAlloc.cpp
Recast/Source/RecastArea.cpp
Recast/Source/RecastContour.cpp
Recast/Source/RecastFilter.cpp
Recast/Source/RecastLayers.cpp
Recast/Source/RecastMesh.cpp
Recast/Source/RecastMeshDetail.cpp
Recast/Source/RecastRasterization.cpp
Recast/Source/RecastRegion.cpp
Recast/Source/Recast.cpp
Recast/Source/RecastAlloc.cpp
Recast/Source/RecastArea.cpp
Recast/Source/RecastContour.cpp
Recast/Source/RecastFilter.cpp
Recast/Source/RecastLayers.cpp
Recast/Source/RecastMesh.cpp
Recast/Source/RecastMeshDetail.cpp
Recast/Source/RecastRasterization.cpp
Recast/Source/RecastRegion.cpp
Recast/Include/Recast.h
Recast/Include/RecastAlloc.h
Recast/Include/RecastAssert.h
Recast/Include/Recast.h
Recast/Include/RecastAlloc.h
Recast/Include/RecastAssert.h
)
blender_add_lib(extern_recastnavigation "${SRC}" "${INC}" "${INC_SYS}")

File diff suppressed because it is too large Load Diff

View File

@@ -19,6 +19,8 @@
#ifndef RECASTALLOC_H
#define RECASTALLOC_H
#include <stddef.h>
/// Provides hint values to the memory allocator on how long the
/// memory is expected to be used.
enum rcAllocHint
@@ -28,30 +30,32 @@ enum rcAllocHint
};
/// A memory allocation function.
// @param[in] size The size, in bytes of memory, to allocate.
// @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use.
// @param[in] size The size, in bytes of memory, to allocate.
// @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use.
// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
/// @see rcAllocSetCustom
typedef void* (rcAllocFunc)(int size, rcAllocHint hint);
typedef void* (rcAllocFunc)(size_t size, rcAllocHint hint);
/// A memory deallocation function.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAllocFunc.
/// @see rcAllocSetCustom
// @param[in] ptr
typedef void (rcFreeFunc)(void* ptr);
/// Sets the base custom allocation functions to be used by Recast.
/// @param[in] allocFunc The memory allocation function to be used by #rcAlloc
/// @param[in] freeFunc The memory de-allocation function to be used by #rcFree
/// @param[in] allocFunc The memory allocation function to be used by #rcAlloc
/// @param[in] freeFunc The memory de-allocation function to be used by #rcFree
void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc);
/// Allocates a memory block.
/// @param[in] size The size, in bytes of memory, to allocate.
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
/// @param[in] size The size, in bytes of memory, to allocate.
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
void* rcAlloc(int size, rcAllocHint hint);
/// @see rcFree
void* rcAlloc(size_t size, rcAllocHint hint);
/// Deallocates a memory block.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
/// @see rcAlloc
void rcFree(void* ptr);
@@ -60,42 +64,58 @@ class rcIntArray
{
int* m_data;
int m_size, m_cap;
inline rcIntArray(const rcIntArray&);
inline rcIntArray& operator=(const rcIntArray&);
public:
void doResize(int n);
// Explicitly disabled copy constructor and copy assignment operator.
rcIntArray(const rcIntArray&);
rcIntArray& operator=(const rcIntArray&);
public:
/// Constructs an instance with an initial array size of zero.
inline rcIntArray() : m_data(0), m_size(0), m_cap(0) {}
rcIntArray() : m_data(0), m_size(0), m_cap(0) {}
/// Constructs an instance initialized to the specified size.
/// @param[in] n The initial size of the integer array.
inline rcIntArray(int n) : m_data(0), m_size(0), m_cap(0) { resize(n); }
inline ~rcIntArray() { rcFree(m_data); }
/// @param[in] n The initial size of the integer array.
rcIntArray(int n) : m_data(0), m_size(0), m_cap(0) { resize(n); }
~rcIntArray() { rcFree(m_data); }
/// Specifies the new size of the integer array.
/// @param[in] n The new size of the integer array.
void resize(int n);
/// @param[in] n The new size of the integer array.
void resize(int n)
{
if (n > m_cap)
doResize(n);
m_size = n;
}
/// Push the specified integer onto the end of the array and increases the size by one.
/// @param[in] item The new value.
inline void push(int item) { resize(m_size+1); m_data[m_size-1] = item; }
/// @param[in] item The new value.
void push(int item) { resize(m_size+1); m_data[m_size-1] = item; }
/// Returns the value at the end of the array and reduces the size by one.
/// @return The value at the end of the array.
inline int pop() { if (m_size > 0) m_size--; return m_data[m_size]; }
int pop()
{
if (m_size > 0)
m_size--;
return m_data[m_size];
}
/// The value at the specified array index.
/// @warning Does not provide overflow protection.
/// @param[in] i The index of the value.
inline const int& operator[](int i) const { return m_data[i]; }
/// @param[in] i The index of the value.
const int& operator[](int i) const { return m_data[i]; }
/// The value at the specified array index.
/// @warning Does not provide overflow protection.
/// @param[in] i The index of the value.
inline int& operator[](int i) { return m_data[i]; }
/// @param[in] i The index of the value.
int& operator[](int i) { return m_data[i]; }
/// The current size of the integer array.
inline int size() const { return m_size; }
int size() const { return m_size; }
};
/// A simple helper class used to delete an array when it goes out of scope.
@@ -110,13 +130,18 @@ public:
inline rcScopedDelete() : ptr(0) {}
/// Constructs an instance with the specified pointer.
/// @param[in] p An pointer to an allocated array.
/// @param[in] p An pointer to an allocated array.
inline rcScopedDelete(T* p) : ptr(p) {}
inline ~rcScopedDelete() { rcFree(ptr); }
/// The root array pointer.
/// @return The root array pointer.
inline operator T*() { return ptr; }
private:
// Explicitly disabled copy constructor and copy assignment operator.
rcScopedDelete(const rcScopedDelete&);
rcScopedDelete& operator=(const rcScopedDelete&);
};
#endif

View File

@@ -24,7 +24,7 @@
#ifdef NDEBUG
// From http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
# define rcAssert(x) do { (void)sizeof(x); } while((void)(__LINE__ == -1), false)
# define rcAssert(x) do { (void)sizeof(x); } while((void)(__LINE__==-1),false)
#else
# include <assert.h>
# define rcAssert assert

View File

@@ -1,80 +0,0 @@
//
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef RECAST_LOG_H
#define RECAST_LOG_H
enum rcLogCategory
{
RC_LOG_PROGRESS = 1,
RC_LOG_WARNING,
RC_LOG_ERROR,
};
class rcLog
{
public:
rcLog();
~rcLog();
void log(rcLogCategory category, const char* format, ...);
inline void clear() { m_messageCount = 0; m_textPoolSize = 0; }
inline int getMessageCount() const { return m_messageCount; }
inline char getMessageType(int i) const { return *m_messages[i]; }
inline const char* getMessageText(int i) const { return m_messages[i]+1; }
private:
static const int MAX_MESSAGES = 1000;
const char* m_messages[MAX_MESSAGES];
int m_messageCount;
static const int TEXT_POOL_SIZE = 8000;
char m_textPool[TEXT_POOL_SIZE];
int m_textPoolSize;
};
struct rcBuildTimes
{
int rasterizeTriangles;
int buildCompact;
int buildContours;
int buildContoursTrace;
int buildContoursSimplify;
int filterBorder;
int filterWalkable;
int filterMarkReachable;
int buildPolymesh;
int buildDistanceField;
int buildDistanceFieldDist;
int buildDistanceFieldBlur;
int buildRegions;
int buildRegionsReg;
int buildRegionsExp;
int buildRegionsFlood;
int buildRegionsFilter;
int buildDetailMesh;
int mergePolyMesh;
int mergePolyMeshDetail;
};
void rcSetLog(rcLog* log);
rcLog* rcGetLog();
void rcSetBuildTimes(rcBuildTimes* btimes);
rcBuildTimes* rcGetBuildTimes();
#endif // RECAST_LOG_H

View File

@@ -1,31 +0,0 @@
//
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef RECAST_TIMER_H
#define RECAST_TIMER_H
#ifdef __GNUC__
#include <stdint.h>
typedef int64_t rcTimeVal;
#else
typedef __int64 rcTimeVal;
#endif
rcTimeVal rcGetPerformanceTimer();
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end);
#endif // RECAST_TIMER_H

View File

@@ -208,12 +208,11 @@ void rcCalcGridSize(const float* bmin, const float* bmax, float cs, int* w, int*
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcAllocHeightfield, rcHeightfield
bool rcCreateHeightfield(rcContext* /*ctx*/, rcHeightfield& hf, int width, int height,
bool rcCreateHeightfield(rcContext* ctx, rcHeightfield& hf, int width, int height,
const float* bmin, const float* bmax,
float cs, float ch)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
hf.width = width;
hf.height = height;
@@ -239,19 +238,18 @@ static void calcTriNormal(const float* v0, const float* v1, const float* v2, flo
/// @par
///
/// Only sets the aread id's for the walkable triangles. Does not alter the
/// Only sets the area id's for the walkable triangles. Does not alter the
/// area id's for unwalkable triangles.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
void rcMarkWalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAngle,
void rcMarkWalkableTriangles(rcContext* ctx, const float walkableSlopeAngle,
const float* verts, int /*nv*/,
const int* tris, int nt,
unsigned char* areas)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI);
@@ -269,19 +267,18 @@ void rcMarkWalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAngle,
/// @par
///
/// Only sets the aread id's for the unwalkable triangles. Does not alter the
/// Only sets the area id's for the unwalkable triangles. Does not alter the
/// area id's for walkable triangles.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
void rcClearUnwalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAngle,
void rcClearUnwalkableTriangles(rcContext* ctx, const float walkableSlopeAngle,
const float* verts, int /*nv*/,
const int* tris, int nt,
unsigned char* areas)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI);
@@ -297,10 +294,9 @@ void rcClearUnwalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAng
}
}
int rcGetHeightFieldSpanCount(rcContext* /*ctx*/, rcHeightfield& hf)
int rcGetHeightFieldSpanCount(rcContext* ctx, rcHeightfield& hf)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
const int w = hf.width;
const int h = hf.height;
@@ -322,7 +318,7 @@ int rcGetHeightFieldSpanCount(rcContext* /*ctx*/, rcHeightfield& hf)
/// @par
///
/// This is just the beginning of the process of fully building a compact heightfield.
/// Various filters may be applied applied, then the distance field and regions built.
/// Various filters may be applied, then the distance field and regions built.
/// E.g: #rcBuildDistanceField and #rcBuildRegions
///
/// See the #rcConfig documentation for more information on the configuration parameters.
@@ -333,7 +329,7 @@ bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const i
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
const int w = hf.width;
const int h = hf.height;
@@ -439,13 +435,13 @@ bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const i
if ((top - bot) >= walkableHeight && rcAbs((int)ns.y - (int)s.y) <= walkableClimb)
{
// Mark direction as walkable.
const int idx = k - (int)nc.index;
if (idx < 0 || idx > MAX_LAYERS)
const int lidx = k - (int)nc.index;
if (lidx < 0 || lidx > MAX_LAYERS)
{
tooHighNeighbour = rcMax(tooHighNeighbour, idx);
tooHighNeighbour = rcMax(tooHighNeighbour, lidx);
continue;
}
rcSetCon(s, dir, idx);
rcSetCon(s, dir, lidx);
break;
}
}
@@ -460,8 +456,6 @@ bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const i
ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)",
tooHighNeighbour, MAX_LAYERS);
}
ctx->stopTimer(RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
return true;
}
@@ -490,4 +484,4 @@ static int getCompactHeightFieldMemoryusage(const rcCompactHeightfield& chf)
size += sizeof(rcCompactCell) * chf.width * chf.height;
return size;
}
*/
*/

View File

@@ -20,7 +20,7 @@
#include <string.h>
#include "RecastAlloc.h"
static void *rcAllocDefault(int size, rcAllocHint)
static void *rcAllocDefault(size_t size, rcAllocHint)
{
return malloc(size);
}
@@ -41,7 +41,7 @@ void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc)
}
/// @see rcAllocSetCustom
void* rcAlloc(int size, rcAllocHint hint)
void* rcAlloc(size_t size, rcAllocHint hint)
{
return sRecastAllocFunc(size, hint);
}
@@ -72,17 +72,13 @@ void rcFree(void* ptr)
/// Using this method ensures the array is at least large enough to hold
/// the specified number of elements. This can improve performance by
/// avoiding auto-resizing during use.
void rcIntArray::resize(int n)
void rcIntArray::doResize(int n)
{
if (n > m_cap)
{
if (!m_cap) m_cap = n;
while (m_cap < n) m_cap *= 2;
int* newData = (int*)rcAlloc(m_cap*sizeof(int), RC_ALLOC_TEMP);
if (m_size && newData) memcpy(newData, m_data, m_size*sizeof(int));
rcFree(m_data);
m_data = newData;
}
m_size = n;
if (!m_cap) m_cap = n;
while (m_cap < n) m_cap *= 2;
int* newData = (int*)rcAlloc(m_cap*sizeof(int), RC_ALLOC_TEMP);
if (m_size && newData) memcpy(newData, m_data, m_size*sizeof(int));
rcFree(m_data);
m_data = newData;
}

View File

@@ -41,7 +41,7 @@ bool rcErodeWalkableArea(rcContext* ctx, int radius, rcCompactHeightfield& chf)
const int w = chf.width;
const int h = chf.height;
ctx->startTimer(RC_TIMER_ERODE_AREA);
rcScopedTimer timer(ctx, RC_TIMER_ERODE_AREA);
unsigned char* dist = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!dist)
@@ -75,8 +75,8 @@ bool rcErodeWalkableArea(rcContext* ctx, int radius, rcCompactHeightfield& chf)
{
const int nx = x + rcGetDirOffsetX(dir);
const int ny = y + rcGetDirOffsetY(dir);
const int ni = (int)chf.cells[nx+ny*w].index + rcGetCon(s, dir);
if (chf.areas[ni] != RC_NULL_AREA)
const int nidx = (int)chf.cells[nx+ny*w].index + rcGetCon(s, dir);
if (chf.areas[nidx] != RC_NULL_AREA)
{
nc++;
}
@@ -215,8 +215,6 @@ bool rcErodeWalkableArea(rcContext* ctx, int radius, rcCompactHeightfield& chf)
rcFree(dist);
ctx->stopTimer(RC_TIMER_ERODE_AREA);
return true;
}
@@ -245,7 +243,7 @@ bool rcMedianFilterWalkableArea(rcContext* ctx, rcCompactHeightfield& chf)
const int w = chf.width;
const int h = chf.height;
ctx->startTimer(RC_TIMER_MEDIAN_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MEDIAN_AREA);
unsigned char* areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!areas)
@@ -306,8 +304,6 @@ bool rcMedianFilterWalkableArea(rcContext* ctx, rcCompactHeightfield& chf)
memcpy(chf.areas, areas, sizeof(unsigned char)*chf.spanCount);
rcFree(areas);
ctx->stopTimer(RC_TIMER_MEDIAN_AREA);
return true;
}
@@ -322,7 +318,7 @@ void rcMarkBoxArea(rcContext* ctx, const float* bmin, const float* bmax, unsigne
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_BOX_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MARK_BOX_AREA);
int minx = (int)((bmin[0]-chf.bmin[0])/chf.cs);
int miny = (int)((bmin[1]-chf.bmin[1])/chf.ch);
@@ -357,9 +353,6 @@ void rcMarkBoxArea(rcContext* ctx, const float* bmin, const float* bmax, unsigne
}
}
}
ctx->stopTimer(RC_TIMER_MARK_BOX_AREA);
}
@@ -391,7 +384,7 @@ void rcMarkConvexPolyArea(rcContext* ctx, const float* verts, const int nverts,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MARK_CONVEXPOLY_AREA);
float bmin[3], bmax[3];
rcVcopy(bmin, verts);
@@ -448,10 +441,86 @@ void rcMarkConvexPolyArea(rcContext* ctx, const float* verts, const int nverts,
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
}
int rcOffsetPoly(const float* verts, const int nverts, const float offset,
float* outVerts, const int maxOutVerts)
{
const float MITER_LIMIT = 1.20f;
int n = 0;
for (int i = 0; i < nverts; i++)
{
const int a = (i+nverts-1) % nverts;
const int b = i;
const int c = (i+1) % nverts;
const float* va = &verts[a*3];
const float* vb = &verts[b*3];
const float* vc = &verts[c*3];
float dx0 = vb[0] - va[0];
float dy0 = vb[2] - va[2];
float d0 = dx0*dx0 + dy0*dy0;
if (d0 > 1e-6f)
{
d0 = 1.0f/rcSqrt(d0);
dx0 *= d0;
dy0 *= d0;
}
float dx1 = vc[0] - vb[0];
float dy1 = vc[2] - vb[2];
float d1 = dx1*dx1 + dy1*dy1;
if (d1 > 1e-6f)
{
d1 = 1.0f/rcSqrt(d1);
dx1 *= d1;
dy1 *= d1;
}
const float dlx0 = -dy0;
const float dly0 = dx0;
const float dlx1 = -dy1;
const float dly1 = dx1;
float cross = dx1*dy0 - dx0*dy1;
float dmx = (dlx0 + dlx1) * 0.5f;
float dmy = (dly0 + dly1) * 0.5f;
float dmr2 = dmx*dmx + dmy*dmy;
bool bevel = dmr2 * MITER_LIMIT*MITER_LIMIT < 1.0f;
if (dmr2 > 1e-6f)
{
const float scale = 1.0f / dmr2;
dmx *= scale;
dmy *= scale;
}
if (bevel && cross < 0.0f)
{
if (n+2 >= maxOutVerts)
return 0;
float d = (1.0f - (dx0*dx1 + dy0*dy1))*0.5f;
outVerts[n*3+0] = vb[0] + (-dlx0+dx0*d)*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] + (-dly0+dy0*d)*offset;
n++;
outVerts[n*3+0] = vb[0] + (-dlx1-dx1*d)*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] + (-dly1-dy1*d)*offset;
n++;
}
else
{
if (n+1 >= maxOutVerts)
return 0;
outVerts[n*3+0] = vb[0] - dmx*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] - dmy*offset;
n++;
}
}
return n;
}
/// @par
///
/// The value of spacial parameters are in world units.
@@ -463,7 +532,7 @@ void rcMarkCylinderArea(rcContext* ctx, const float* pos,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CYLINDER_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MARK_CYLINDER_AREA);
float bmin[3], bmax[3];
bmin[0] = pos[0] - r;
@@ -519,6 +588,4 @@ void rcMarkCylinderArea(rcContext* ctx, const float* pos,
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CYLINDER_AREA);
}

View File

@@ -20,6 +20,7 @@
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Recast.h"
#include "RecastAlloc.h"
#include "RecastAssert.h"
@@ -36,7 +37,7 @@ static int getCornerHeight(int x, int y, int i, int dir,
unsigned int regs[4] = {0,0,0,0};
// Combine region and area codes in order to prevent
// border vertices which are in between two areas to be removed.
// border vertices which are in between two areas to be removed.
regs[0] = chf.spans[i].reg | (chf.areas[i] << 16);
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
@@ -187,27 +188,6 @@ static float distancePtSeg(const int x, const int z,
const int px, const int pz,
const int qx, const int qz)
{
/* float pqx = (float)(qx - px);
float pqy = (float)(qy - py);
float pqz = (float)(qz - pz);
float dx = (float)(x - px);
float dy = (float)(y - py);
float dz = (float)(z - pz);
float d = pqx*pqx + pqy*pqy + pqz*pqz;
float t = pqx*dx + pqy*dy + pqz*dz;
if (d > 0)
t /= d;
if (t < 0)
t = 0;
else if (t > 1)
t = 1;
dx = px + t*pqx - x;
dy = py + t*pqy - y;
dz = pz + t*pqz - z;
return dx*dx + dy*dy + dz*dz;*/
float pqx = (float)(qx - px);
float pqz = (float)(qz - pz);
float dx = (float)(x - px);
@@ -257,13 +237,13 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
simplified.push(points[i*4+2]);
simplified.push(i);
}
}
}
}
if (simplified.size() == 0)
{
// If there is no connections at all,
// create some initial points for the simplification process.
// create some initial points for the simplification process.
// Find lower-left and upper-right vertices of the contour.
int llx = points[0];
int lly = points[1];
@@ -311,19 +291,19 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
{
int ii = (i+1) % (simplified.size()/4);
const int ax = simplified[i*4+0];
const int az = simplified[i*4+2];
const int ai = simplified[i*4+3];
const int bx = simplified[ii*4+0];
const int bz = simplified[ii*4+2];
const int bi = simplified[ii*4+3];
int ax = simplified[i*4+0];
int az = simplified[i*4+2];
int ai = simplified[i*4+3];
int bx = simplified[ii*4+0];
int bz = simplified[ii*4+2];
int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
float maxd = 0;
int i_max = -1;
int maxi = -1;
int ci, cinc, endi;
// Traverse the segment in lexilogical order so that the
// max deviation is calculated similarly when traversing
// opposite segments.
@@ -338,6 +318,8 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
cinc = pn-1;
ci = (bi+cinc) % pn;
endi = ai;
rcSwap(ax, bx);
rcSwap(az, bz);
}
// Tessellate only outer edges or edges between areas.
@@ -350,7 +332,7 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
if (d > maxd)
{
maxd = d;
i_max = ci;
maxi = ci;
}
ci = (ci+cinc) % pn;
}
@@ -359,7 +341,7 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (i_max != -1 && maxd > (maxError*maxError))
if (maxi != -1 && maxd > (maxError*maxError))
{
// Add space for the new point.
simplified.resize(simplified.size()+4);
@@ -372,10 +354,10 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = points[i_max*4+0];
simplified[(i+1)*4+1] = points[i_max*4+1];
simplified[(i+1)*4+2] = points[i_max*4+2];
simplified[(i+1)*4+3] = i_max;
simplified[(i+1)*4+0] = points[maxi*4+0];
simplified[(i+1)*4+1] = points[maxi*4+1];
simplified[(i+1)*4+2] = points[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
}
else
{
@@ -397,11 +379,11 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
const int bx = simplified[ii*4+0];
const int bz = simplified[ii*4+2];
const int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
int i_max = -1;
int maxi = -1;
int ci = (ai+1) % pn;
// Tessellate only outer edges or edges between areas.
bool tess = false;
// Wall edges.
@@ -420,22 +402,20 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
// Round based on the segments in lexilogical order so that the
// max tesselation is consistent regardles in which direction
// segments are traversed.
if (bx > ax || (bx == ax && bz > az))
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
if (n > 1)
{
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
i_max = (ai + n/2) % pn;
}
else
{
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
i_max = (ai + (n+1)/2) % pn;
if (bx > ax || (bx == ax && bz > az))
maxi = (ai + n/2) % pn;
else
maxi = (ai + (n+1)/2) % pn;
}
}
}
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (i_max != -1)
if (maxi != -1)
{
// Add space for the new point.
simplified.resize(simplified.size()+4);
@@ -448,10 +428,10 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = points[i_max*4+0];
simplified[(i+1)*4+1] = points[i_max*4+1];
simplified[(i+1)*4+2] = points[i_max*4+2];
simplified[(i+1)*4+3] = i_max;
simplified[(i+1)*4+0] = points[maxi*4+0];
simplified[(i+1)*4+1] = points[maxi*4+1];
simplified[(i+1)*4+2] = points[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
}
else
{
@@ -466,37 +446,11 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
// and the neighbour region is take from the next raw point.
const int ai = (simplified[i*4+3]+1) % pn;
const int bi = simplified[i*4+3];
simplified[i*4+3] = (points[ai*4+3] & RC_CONTOUR_REG_MASK) | (points[bi*4+3] & RC_BORDER_VERTEX);
simplified[i*4+3] = (points[ai*4+3] & (RC_CONTOUR_REG_MASK|RC_AREA_BORDER)) | (points[bi*4+3] & RC_BORDER_VERTEX);
}
}
static void removeDegenerateSegments(rcIntArray& simplified)
{
// Remove adjacent vertices which are equal on xz-plane,
// or else the triangulator will get confused.
for (int i = 0; i < simplified.size()/4; ++i)
{
int ni = i+1;
if (ni >= (simplified.size()/4))
ni = 0;
if (simplified[i*4+0] == simplified[ni*4+0] &&
simplified[i*4+2] == simplified[ni*4+2])
{
// Degenerate segment, remove.
for (int j = i; j < simplified.size()/4-1; ++j)
{
simplified[j*4+0] = simplified[(j+1)*4+0];
simplified[j*4+1] = simplified[(j+1)*4+1];
simplified[j*4+2] = simplified[(j+1)*4+2];
simplified[j*4+3] = simplified[(j+1)*4+3];
}
simplified.resize(simplified.size()-4);
}
}
}
static int calcAreaOfPolygon2D(const int* verts, const int nverts)
{
int area = 0;
@@ -509,54 +463,155 @@ static int calcAreaOfPolygon2D(const int* verts, const int nverts)
return (area+1) / 2;
}
inline bool ileft(const int* a, const int* b, const int* c)
// TODO: these are the same as in RecastMesh.cpp, consider using the same.
// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
inline int area2(const int* a, const int* b, const int* c)
{
return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]) <= 0;
return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
}
static void getClosestIndices(const int* vertsa, const int nvertsa,
const int* vertsb, const int nvertsb,
int& ia, int& ib)
// Exclusive or: true iff exactly one argument is true.
// The arguments are negated to ensure that they are 0/1
// values. Then the bitwise Xor operator may apply.
// (This idea is due to Michael Baldwin.)
inline bool xorb(bool x, bool y)
{
int closestDist = 0xfffffff;
ia = -1, ib = -1;
for (int i = 0; i < nvertsa; ++i)
return !x ^ !y;
}
// Returns true iff c is strictly to the left of the directed
// line through a to b.
inline bool left(const int* a, const int* b, const int* c)
{
return area2(a, b, c) < 0;
}
inline bool leftOn(const int* a, const int* b, const int* c)
{
return area2(a, b, c) <= 0;
}
inline bool collinear(const int* a, const int* b, const int* c)
{
return area2(a, b, c) == 0;
}
// Returns true iff ab properly intersects cd: they share
// a point interior to both segments. The properness of the
// intersection is ensured by using strict leftness.
static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
{
// Eliminate improper cases.
if (collinear(a,b,c) || collinear(a,b,d) ||
collinear(c,d,a) || collinear(c,d,b))
return false;
return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
}
// Returns T iff (a,b,c) are collinear and point c lies
// on the closed segement ab.
static bool between(const int* a, const int* b, const int* c)
{
if (!collinear(a, b, c))
return false;
// If ab not vertical, check betweenness on x; else on y.
if (a[0] != b[0])
return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
else
return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
}
// Returns true iff segments ab and cd intersect, properly or improperly.
static bool intersect(const int* a, const int* b, const int* c, const int* d)
{
if (intersectProp(a, b, c, d))
return true;
else if (between(a, b, c) || between(a, b, d) ||
between(c, d, a) || between(c, d, b))
return true;
else
return false;
}
static bool vequal(const int* a, const int* b)
{
return a[0] == b[0] && a[2] == b[2];
}
static bool intersectSegCountour(const int* d0, const int* d1, int i, int n, const int* verts)
{
// For each edge (k,k+1) of P
for (int k = 0; k < n; k++)
{
const int in = (i+1) % nvertsa;
const int ip = (i+nvertsa-1) % nvertsa;
const int* va = &vertsa[i*4];
const int* van = &vertsa[in*4];
const int* vap = &vertsa[ip*4];
int k1 = next(k, n);
// Skip edges incident to i.
if (i == k || i == k1)
continue;
const int* p0 = &verts[k * 4];
const int* p1 = &verts[k1 * 4];
if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
continue;
for (int j = 0; j < nvertsb; ++j)
if (intersect(d0, d1, p0, p1))
return true;
}
return false;
}
static bool inCone(int i, int n, const int* verts, const int* pj)
{
const int* pi = &verts[i * 4];
const int* pi1 = &verts[next(i, n) * 4];
const int* pin1 = &verts[prev(i, n) * 4];
// If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
if (leftOn(pin1, pi, pi1))
return left(pi, pj, pin1) && left(pj, pi, pi1);
// Assume (i-1,i,i+1) not collinear.
// else P[i] is reflex.
return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
}
static void removeDegenerateSegments(rcIntArray& simplified)
{
// Remove adjacent vertices which are equal on xz-plane,
// or else the triangulator will get confused.
int npts = simplified.size()/4;
for (int i = 0; i < npts; ++i)
{
int ni = next(i, npts);
if (vequal(&simplified[i*4], &simplified[ni*4]))
{
const int* vb = &vertsb[j*4];
// vb must be "infront" of va.
if (ileft(vap,va,vb) && ileft(va,van,vb))
// Degenerate segment, remove.
for (int j = i; j < simplified.size()/4-1; ++j)
{
const int dx = vb[0] - va[0];
const int dz = vb[2] - va[2];
const int d = dx*dx + dz*dz;
if (d < closestDist)
{
ia = i;
ib = j;
closestDist = d;
}
simplified[j*4+0] = simplified[(j+1)*4+0];
simplified[j*4+1] = simplified[(j+1)*4+1];
simplified[j*4+2] = simplified[(j+1)*4+2];
simplified[j*4+3] = simplified[(j+1)*4+3];
}
simplified.resize(simplified.size()-4);
npts--;
}
}
}
static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
{
const int maxVerts = ca.nverts + cb.nverts + 2;
int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM);
if (!verts)
return false;
int nv = 0;
// Copy contour A.
for (int i = 0; i <= ca.nverts; ++i)
{
@@ -584,7 +639,7 @@ static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
rcFree(ca.verts);
ca.verts = verts;
ca.nverts = nv;
rcFree(cb.verts);
cb.verts = 0;
cb.nverts = 0;
@@ -592,18 +647,179 @@ static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
return true;
}
struct rcContourHole
{
rcContour* contour;
int minx, minz, leftmost;
};
struct rcContourRegion
{
rcContour* outline;
rcContourHole* holes;
int nholes;
};
struct rcPotentialDiagonal
{
int vert;
int dist;
};
// Finds the lowest leftmost vertex of a contour.
static void findLeftMostVertex(rcContour* contour, int* minx, int* minz, int* leftmost)
{
*minx = contour->verts[0];
*minz = contour->verts[2];
*leftmost = 0;
for (int i = 1; i < contour->nverts; i++)
{
const int x = contour->verts[i*4+0];
const int z = contour->verts[i*4+2];
if (x < *minx || (x == *minx && z < *minz))
{
*minx = x;
*minz = z;
*leftmost = i;
}
}
}
static int compareHoles(const void* va, const void* vb)
{
const rcContourHole* a = (const rcContourHole*)va;
const rcContourHole* b = (const rcContourHole*)vb;
if (a->minx == b->minx)
{
if (a->minz < b->minz)
return -1;
if (a->minz > b->minz)
return 1;
}
else
{
if (a->minx < b->minx)
return -1;
if (a->minx > b->minx)
return 1;
}
return 0;
}
static int compareDiagDist(const void* va, const void* vb)
{
const rcPotentialDiagonal* a = (const rcPotentialDiagonal*)va;
const rcPotentialDiagonal* b = (const rcPotentialDiagonal*)vb;
if (a->dist < b->dist)
return -1;
if (a->dist > b->dist)
return 1;
return 0;
}
static void mergeRegionHoles(rcContext* ctx, rcContourRegion& region)
{
// Sort holes from left to right.
for (int i = 0; i < region.nholes; i++)
findLeftMostVertex(region.holes[i].contour, &region.holes[i].minx, &region.holes[i].minz, &region.holes[i].leftmost);
qsort(region.holes, region.nholes, sizeof(rcContourHole), compareHoles);
int maxVerts = region.outline->nverts;
for (int i = 0; i < region.nholes; i++)
maxVerts += region.holes[i].contour->nverts;
rcScopedDelete<rcPotentialDiagonal> diags((rcPotentialDiagonal*)rcAlloc(sizeof(rcPotentialDiagonal)*maxVerts, RC_ALLOC_TEMP));
if (!diags)
{
ctx->log(RC_LOG_WARNING, "mergeRegionHoles: Failed to allocated diags %d.", maxVerts);
return;
}
rcContour* outline = region.outline;
// Merge holes into the outline one by one.
for (int i = 0; i < region.nholes; i++)
{
rcContour* hole = region.holes[i].contour;
int index = -1;
int bestVertex = region.holes[i].leftmost;
for (int iter = 0; iter < hole->nverts; iter++)
{
// Find potential diagonals.
// The 'best' vertex must be in the cone described by 3 cosequtive vertices of the outline.
// ..o j-1
// |
// | * best
// |
// j o-----o j+1
// :
int ndiags = 0;
const int* corner = &hole->verts[bestVertex*4];
for (int j = 0; j < outline->nverts; j++)
{
if (inCone(j, outline->nverts, outline->verts, corner))
{
int dx = outline->verts[j*4+0] - corner[0];
int dz = outline->verts[j*4+2] - corner[2];
diags[ndiags].vert = j;
diags[ndiags].dist = dx*dx + dz*dz;
ndiags++;
}
}
// Sort potential diagonals by distance, we want to make the connection as short as possible.
qsort(diags, ndiags, sizeof(rcPotentialDiagonal), compareDiagDist);
// Find a diagonal that is not intersecting the outline not the remaining holes.
index = -1;
for (int j = 0; j < ndiags; j++)
{
const int* pt = &outline->verts[diags[j].vert*4];
bool intersect = intersectSegCountour(pt, corner, diags[i].vert, outline->nverts, outline->verts);
for (int k = i; k < region.nholes && !intersect; k++)
intersect |= intersectSegCountour(pt, corner, -1, region.holes[k].contour->nverts, region.holes[k].contour->verts);
if (!intersect)
{
index = diags[j].vert;
break;
}
}
// If found non-intersecting diagonal, stop looking.
if (index != -1)
break;
// All the potential diagonals for the current vertex were intersecting, try next vertex.
bestVertex = (bestVertex + 1) % hole->nverts;
}
if (index == -1)
{
ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to find merge points for %p and %p.", region.outline, hole);
continue;
}
if (!mergeContours(*region.outline, *hole, index, bestVertex))
{
ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to merge contours %p and %p.", region.outline, hole);
continue;
}
}
}
/// @par
///
/// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen
/// parameters control how closely the simplified contours will match the raw contours.
///
/// Simplified contours are generated such that the vertices for portals between areas match up.
/// Simplified contours are generated such that the vertices for portals between areas match up.
/// (They are considered mandatory vertices.)
///
/// Setting @p maxEdgeLength to zero will disabled the edge length feature.
///
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
///
/// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig
bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
const float maxError, const int maxEdgeLen,
@@ -615,7 +831,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
const int h = chf.height;
const int borderSize = chf.borderSize;
ctx->startTimer(RC_TIMER_BUILD_CONTOURS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_CONTOURS);
rcVcopy(cset.bmin, chf.bmin);
rcVcopy(cset.bmax, chf.bmax);
@@ -633,6 +849,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
cset.width = chf.width - chf.borderSize*2;
cset.height = chf.height - chf.borderSize*2;
cset.borderSize = chf.borderSize;
cset.maxError = maxError;
int maxContours = rcMax((int)chf.maxRegions, 8);
cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
@@ -640,7 +857,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
return false;
cset.nconts = 0;
rcScopedDelete<unsigned char> flags = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
rcScopedDelete<unsigned char> flags((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
if (!flags)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount);
@@ -706,17 +923,17 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
verts.resize(0);
simplified.resize(0);
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
walkContour(x, y, i, chf, flags, verts);
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags);
removeDegenerateSegments(simplified);
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
// Store region->contour remap info.
// Create contour.
if (simplified.size()/4 >= 3)
@@ -724,7 +941,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
if (cset.nconts >= maxContours)
{
// Allocate more contours.
// This can happen when there are tiny holes in the heightfield.
// This happens when a region has holes.
const int oldMax = maxContours;
maxContours *= 2;
rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
@@ -737,10 +954,10 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
}
rcFree(cset.conts);
cset.conts = newConts;
ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours);
}
rcContour* cont = &cset.conts[cset.nconts++];
cont->nverts = simplified.size()/4;
@@ -754,9 +971,9 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
if (borderSize > 0)
{
// If the heightfield was build with bordersize, remove the offset.
for (int i = 0; i < cont->nverts; ++i)
for (int j = 0; j < cont->nverts; ++j)
{
int* v = &cont->verts[i*4];
int* v = &cont->verts[j*4];
v[0] -= borderSize;
v[2] -= borderSize;
}
@@ -773,25 +990,14 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
if (borderSize > 0)
{
// If the heightfield was build with bordersize, remove the offset.
for (int i = 0; i < cont->nrverts; ++i)
for (int j = 0; j < cont->nrverts; ++j)
{
int* v = &cont->rverts[i*4];
int* v = &cont->rverts[j*4];
v[0] -= borderSize;
v[2] -= borderSize;
}
}
/* cont->cx = cont->cy = cont->cz = 0;
for (int i = 0; i < cont->nverts; ++i)
{
cont->cx += cont->verts[i*4+0];
cont->cy += cont->verts[i*4+1];
cont->cz += cont->verts[i*4+2];
}
cont->cx /= cont->nverts;
cont->cy /= cont->nverts;
cont->cz /= cont->nverts;*/
cont->reg = reg;
cont->area = area;
}
@@ -799,55 +1005,101 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
}
}
// Check and merge droppings.
// Sometimes the previous algorithms can fail and create several contours
// per area. This pass will try to merge the holes into the main region.
for (int i = 0; i < cset.nconts; ++i)
// Merge holes if needed.
if (cset.nconts > 0)
{
rcContour& cont = cset.conts[i];
// Check if the contour is would backwards.
if (calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0)
// Calculate winding of all polygons.
rcScopedDelete<char> winding((char*)rcAlloc(sizeof(char)*cset.nconts, RC_ALLOC_TEMP));
if (!winding)
{
// Find another contour which has the same region ID.
int mergeIdx = -1;
for (int j = 0; j < cset.nconts; ++j)
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'hole' (%d).", cset.nconts);
return false;
}
int nholes = 0;
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
// If the contour is wound backwards, it is a hole.
winding[i] = calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0 ? -1 : 1;
if (winding[i] < 0)
nholes++;
}
if (nholes > 0)
{
// Collect outline contour and holes contours per region.
// We assume that there is one outline and multiple holes.
const int nregions = chf.maxRegions+1;
rcScopedDelete<rcContourRegion> regions((rcContourRegion*)rcAlloc(sizeof(rcContourRegion)*nregions, RC_ALLOC_TEMP));
if (!regions)
{
if (i == j) continue;
if (cset.conts[j].nverts && cset.conts[j].reg == cont.reg)
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'regions' (%d).", nregions);
return false;
}
memset(regions, 0, sizeof(rcContourRegion)*nregions);
rcScopedDelete<rcContourHole> holes((rcContourHole*)rcAlloc(sizeof(rcContourHole)*cset.nconts, RC_ALLOC_TEMP));
if (!holes)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'holes' (%d).", cset.nconts);
return false;
}
memset(holes, 0, sizeof(rcContourHole)*cset.nconts);
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
// Positively would contours are outlines, negative holes.
if (winding[i] > 0)
{
// Make sure the polygon is correctly oriented.
if (calcAreaOfPolygon2D(cset.conts[j].verts, cset.conts[j].nverts))
{
mergeIdx = j;
break;
}
if (regions[cont.reg].outline)
ctx->log(RC_LOG_ERROR, "rcBuildContours: Multiple outlines for region %d.", cont.reg);
regions[cont.reg].outline = &cont;
}
else
{
regions[cont.reg].nholes++;
}
}
if (mergeIdx == -1)
int index = 0;
for (int i = 0; i < nregions; i++)
{
ctx->log(RC_LOG_WARNING, "rcBuildContours: Could not find merge target for bad contour %d.", i);
}
else
{
rcContour& mcont = cset.conts[mergeIdx];
// Merge by closest points.
int ia = 0, ib = 0;
getClosestIndices(mcont.verts, mcont.nverts, cont.verts, cont.nverts, ia, ib);
if (ia == -1 || ib == -1)
if (regions[i].nholes > 0)
{
ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to find merge points for %d and %d.", i, mergeIdx);
continue;
regions[i].holes = &holes[index];
index += regions[i].nholes;
regions[i].nholes = 0;
}
if (!mergeContours(mcont, cont, ia, ib))
}
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
rcContourRegion& reg = regions[cont.reg];
if (winding[i] < 0)
reg.holes[reg.nholes++].contour = &cont;
}
// Finally merge each regions holes into the outline.
for (int i = 0; i < nregions; i++)
{
rcContourRegion& reg = regions[i];
if (!reg.nholes) continue;
if (reg.outline)
{
ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to merge contours %d and %d.", i, mergeIdx);
continue;
mergeRegionHoles(ctx, reg);
}
else
{
// The region does not have an outline.
// This can happen if the contour becaomes selfoverlapping because of
// too aggressive simplification settings.
ctx->log(RC_LOG_ERROR, "rcBuildContours: Bad outline for region %d, contour simplification is likely too aggressive.", i);
}
}
}
}
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS);
return true;
}

View File

@@ -37,7 +37,7 @@ void rcFilterLowHangingWalkableObstacles(rcContext* ctx, const int walkableClimb
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_FILTER_LOW_OBSTACLES);
rcScopedTimer timer(ctx, RC_TIMER_FILTER_LOW_OBSTACLES);
const int w = solid.width;
const int h = solid.height;
@@ -67,8 +67,6 @@ void rcFilterLowHangingWalkableObstacles(rcContext* ctx, const int walkableClimb
}
}
}
ctx->stopTimer(RC_TIMER_FILTER_LOW_OBSTACLES);
}
/// @par
@@ -86,7 +84,7 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_FILTER_BORDER);
rcScopedTimer timer(ctx, RC_TIMER_FILTER_BORDER);
const int w = solid.width;
const int h = solid.height;
@@ -128,7 +126,7 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
rcSpan* ns = solid.spans[dx + dy*w];
int nbot = -walkableClimb;
int ntop = ns ? (int)ns->smin : MAX_HEIGHT;
// Skip neighbor if the gap between the spans is too small.
// Skip neightbour if the gap between the spans is too small.
if (rcMin(top,ntop) - rcMax(bot,nbot) > walkableHeight)
minh = rcMin(minh, nbot - bot);
@@ -137,7 +135,7 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
{
nbot = (int)ns->smax;
ntop = ns->next ? (int)ns->next->smin : MAX_HEIGHT;
// Skip neighbor if the gap between the spans is too small.
// Skip neightbour if the gap between the spans is too small.
if (rcMin(top,ntop) - rcMax(bot,nbot) > walkableHeight)
{
minh = rcMin(minh, nbot - bot);
@@ -156,20 +154,19 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
// The current span is close to a ledge if the drop to any
// neighbour span is less than the walkableClimb.
if (minh < -walkableClimb)
{
s->area = RC_NULL_AREA;
}
// If the difference between all neighbours is too large,
// we are at steep slope, mark the span as ledge.
if ((asmax - asmin) > walkableClimb)
else if ((asmax - asmin) > walkableClimb)
{
s->area = RC_NULL_AREA;
}
}
}
}
ctx->stopTimer(RC_TIMER_FILTER_BORDER);
}
}
/// @par
///
@@ -181,7 +178,7 @@ void rcFilterWalkableLowHeightSpans(rcContext* ctx, int walkableHeight, rcHeight
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_FILTER_WALKABLE);
rcScopedTimer timer(ctx, RC_TIMER_FILTER_WALKABLE);
const int w = solid.width;
const int h = solid.height;
@@ -202,6 +199,4 @@ void rcFilterWalkableLowHeightSpans(rcContext* ctx, int walkableHeight, rcHeight
}
}
}
ctx->stopTimer(RC_TIMER_FILTER_WALKABLE);
}

View File

@@ -38,7 +38,7 @@ struct rcLayerRegion
unsigned char layerId; // Layer ID
unsigned char nlayers; // Layer count
unsigned char nneis; // Neighbour count
unsigned char base; // Flag indicating if the region is hte base of merged regions.
unsigned char base; // Flag indicating if the region is the base of merged regions.
};
@@ -87,12 +87,12 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_LAYERS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_LAYERS);
const int w = chf.width;
const int h = chf.height;
rcScopedDelete<unsigned char> srcReg = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
rcScopedDelete<unsigned char> srcReg((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
if (!srcReg)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount);
@@ -101,7 +101,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);
const int nsweeps = chf.width;
rcScopedDelete<rcLayerSweepSpan> sweeps = (rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP);
rcScopedDelete<rcLayerSweepSpan> sweeps((rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP));
if (!sweeps)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps);
@@ -212,7 +212,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// Allocate and init layer regions.
const int nregs = (int)regId;
rcScopedDelete<rcLayerRegion> regs = (rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP);
rcScopedDelete<rcLayerRegion> regs((rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP));
if (!regs)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs);
@@ -258,7 +258,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
const unsigned char rai = srcReg[ai];
if (rai != 0xff && rai != ri)
if (rai != 0xff && rai != ri && regs[ri].nneis < RC_MAX_NEIS)
addUnique(regs[ri].neis, regs[ri].nneis, rai);
}
}
@@ -293,7 +293,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
for (int i = 0; i < nregs; ++i)
{
rcLayerRegion& root = regs[i];
// Skip alreadu visited.
// Skip already visited.
if (root.layerId != 0xff)
continue;
@@ -325,7 +325,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
continue;
// Skip if the height range would become too large.
const int ymin = rcMin(root.ymin, regn.ymin);
const int ymax = rcMin(root.ymax, regn.ymax);
const int ymax = rcMax(root.ymax, regn.ymax);
if ((ymax - ymin) >= 255)
continue;
@@ -373,11 +373,11 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
continue;
// Skip if the height range would become too large.
const int ymin = rcMin(ri.ymin, rj.ymin);
const int ymax = rcMin(ri.ymax, rj.ymax);
const int ymax = rcMax(ri.ymax, rj.ymax);
if ((ymax - ymin) >= 255)
continue;
// Make sure that there is no overlap when mergin 'ri' and 'rj'.
// Make sure that there is no overlap when merging 'ri' and 'rj'.
bool overlap = false;
// Iterate over all regions which have the same layerId as 'rj'
for (int k = 0; k < nregs; ++k)
@@ -417,7 +417,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// Add overlaid layers from 'rj' to 'ri'.
for (int k = 0; k < rj.nlayers; ++k)
addUnique(ri.layers, ri.nlayers, rj.layers[k]);
// Update heigh bounds.
// Update height bounds.
ri.ymin = rcMin(ri.ymin, rj.ymin);
ri.ymax = rcMax(ri.ymax, rj.ymax);
}
@@ -446,10 +446,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// No layers, return empty.
if (layerId == 0)
{
ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
return true;
}
// Create layers.
rcAssert(lset.layers == 0);
@@ -481,10 +478,8 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
for (int i = 0; i < lset.nlayers; ++i)
{
unsigned char curId = (unsigned char)i;
// Allocate memory for the current layer.
rcHeightfieldLayer* layer = &lset.layers[i];
memset(layer, 0, sizeof(rcHeightfieldLayer));
const int gridSize = sizeof(unsigned char)*lw*lh;
@@ -528,7 +523,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
layer->cs = chf.cs;
layer->ch = chf.ch;
// Adjust the bbox to fit the heighfield.
// Adjust the bbox to fit the heightfield.
rcVcopy(layer->bmin, bmin);
rcVcopy(layer->bmax, bmax);
layer->bmin[1] = bmin[1] + hmin*chf.ch;
@@ -542,7 +537,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
layer->miny = layer->height;
layer->maxy = 0;
// Copy height and area from compact heighfield.
// Copy height and area from compact heightfield.
for (int y = 0; y < lh; ++y)
{
for (int x = 0; x < lw; ++x)
@@ -550,14 +545,14 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
const int cx = borderSize+x;
const int cy = borderSize+y;
const rcCompactCell& c = chf.cells[cx+cy*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j)
{
const rcCompactSpan& s = chf.spans[i];
const rcCompactSpan& s = chf.spans[j];
// Skip unassigned regions.
if (srcReg[i] == 0xff)
if (srcReg[j] == 0xff)
continue;
// Skip of does nto belong to current layer.
unsigned char lid = regs[srcReg[i]].layerId;
unsigned char lid = regs[srcReg[j]].layerId;
if (lid != curId)
continue;
@@ -570,7 +565,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// Store height and area type.
const int idx = x+y*lw;
layer->heights[idx] = (unsigned char)(s.y - hmin);
layer->areas[idx] = chf.areas[i];
layer->areas[idx] = chf.areas[j];
// Check connection.
unsigned char portal = 0;
@@ -614,7 +609,5 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
layer->miny = layer->maxy = 0;
}
ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
return true;
}

View File

@@ -1,77 +0,0 @@
//
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include "RecastLog.h"
#include <stdio.h>
#include <stdarg.h>
static rcLog* g_log = 0;
static rcBuildTimes* g_btimes = 0;
rcLog::rcLog() :
m_messageCount(0),
m_textPoolSize(0)
{
}
rcLog::~rcLog()
{
if (g_log == this)
g_log = 0;
}
void rcLog::log(rcLogCategory category, const char* format, ...)
{
if (m_messageCount >= MAX_MESSAGES)
return;
char* dst = &m_textPool[m_textPoolSize];
int n = TEXT_POOL_SIZE - m_textPoolSize;
if (n < 2)
return;
// Store category
*dst = (char)category;
n--;
// Store message
va_list ap;
va_start(ap, format);
int ret = vsnprintf(dst+1, n-1, format, ap);
va_end(ap);
if (ret > 0)
m_textPoolSize += ret+2;
m_messages[m_messageCount++] = dst;
}
void rcSetLog(rcLog* log)
{
g_log = log;
}
rcLog* rcGetLog()
{
return g_log;
}
void rcSetBuildTimes(rcBuildTimes* btimes)
{
g_btimes = btimes;
}
rcBuildTimes* rcGetBuildTimes()
{
return g_btimes;
}

View File

@@ -160,6 +160,7 @@ static unsigned short addVertex(unsigned short x, unsigned short y, unsigned sho
return (unsigned short)i;
}
// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
@@ -288,6 +289,53 @@ static bool diagonal(int i, int j, int n, const int* verts, int* indices)
return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
}
static bool diagonalieLoose(int i, int j, int n, const int* verts, int* indices)
{
const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
// For each edge (k,k+1) of P
for (int k = 0; k < n; k++)
{
int k1 = next(k, n);
// Skip edges incident to i or j
if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
{
const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
continue;
if (intersectProp(d0, d1, p0, p1))
return false;
}
}
return true;
}
static bool inConeLoose(int i, int j, int n, const int* verts, int* indices)
{
const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
// If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
if (leftOn(pin1, pi, pi1))
return leftOn(pi, pj, pin1) && leftOn(pj, pi, pi1);
// Assume (i-1,i,i+1) not collinear.
// else P[i] is reflex.
return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
}
static bool diagonalLoose(int i, int j, int n, const int* verts, int* indices)
{
return inConeLoose(i, j, n, verts, indices) && diagonalieLoose(i, j, n, verts, indices);
}
static int triangulate(int n, const int* verts, int* indices, int* tris)
{
int ntris = 0;
@@ -305,7 +353,7 @@ static int triangulate(int n, const int* verts, int* indices, int* tris)
while (n > 3)
{
int minLen = -1;
int i_min = -1;
int mini = -1;
for (int i = 0; i < n; i++)
{
int i1 = next(i, n);
@@ -321,24 +369,51 @@ static int triangulate(int n, const int* verts, int* indices, int* tris)
if (minLen < 0 || len < minLen)
{
minLen = len;
i_min = i;
mini = i;
}
}
}
if (i_min == -1)
if (mini == -1)
{
// Should not happen.
/* printf("mini == -1 ntris=%d n=%d\n", ntris, n);
// We might get here because the contour has overlapping segments, like this:
//
// A o-o=====o---o B
// / |C D| \
// o o o o
// : : : :
// We'll try to recover by loosing up the inCone test a bit so that a diagonal
// like A-B or C-D can be found and we can continue.
minLen = -1;
mini = -1;
for (int i = 0; i < n; i++)
{
printf("%d ", indices[i] & 0x0fffffff);
int i1 = next(i, n);
int i2 = next(i1, n);
if (diagonalLoose(i, i2, n, verts, indices))
{
const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4];
int dx = p2[0] - p0[0];
int dy = p2[2] - p0[2];
int len = dx*dx + dy*dy;
if (minLen < 0 || len < minLen)
{
minLen = len;
mini = i;
}
}
}
if (mini == -1)
{
// The contour is messed up. This sometimes happens
// if the contour simplification is too aggressive.
return -ntris;
}
printf("\n");*/
return -ntris;
}
int i = i_min;
int i = mini;
int i1 = next(i, n);
int i2 = next(i1, n);
@@ -453,8 +528,8 @@ static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
return dx*dx + dy*dy;
}
static void mergePolys(unsigned short* pa, unsigned short* pb, int ea, int eb,
unsigned short* tmp, const int nvp)
static void mergePolyVerts(unsigned short* pa, unsigned short* pb, int ea, int eb,
unsigned short* tmp, const int nvp)
{
const int na = countPolyVerts(pa, nvp);
const int nb = countPolyVerts(pb, nvp);
@@ -526,7 +601,7 @@ static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned sho
// Find edges which share the removed vertex.
const int maxEdges = numTouchedVerts*2;
int nedges = 0;
rcScopedDelete<int> edges = (int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP);
rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP));
if (!edges)
{
ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3);
@@ -550,9 +625,9 @@ static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned sho
// Check if the edge exists
bool exists = false;
for (int k = 0; k < nedges; ++k)
for (int m = 0; m < nedges; ++m)
{
int* e = &edges[k*3];
int* e = &edges[m*3];
if (e[1] == b)
{
// Exists, increment vertex share count.
@@ -606,7 +681,7 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
int nedges = 0;
rcScopedDelete<int> edges = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP);
rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP));
if (!edges)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4);
@@ -614,15 +689,15 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
int nhole = 0;
rcScopedDelete<int> hole = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP);
rcScopedDelete<int> hole((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
if (!hole)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp);
return false;
}
int nhreg = 0;
rcScopedDelete<int> hreg = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP);
rcScopedDelete<int> hreg((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
if (!hreg)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp);
@@ -630,7 +705,7 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
int nharea = 0;
rcScopedDelete<int> harea = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP);
rcScopedDelete<int> harea((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
if (!harea)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp);
@@ -661,7 +736,8 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
// Remove the polygon.
unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2];
memcpy(p,p2,sizeof(unsigned short)*nvp);
if (p != p2)
memcpy(p,p2,sizeof(unsigned short)*nvp);
memset(p+nvp,0xff,sizeof(unsigned short)*nvp);
mesh.regs[i] = mesh.regs[mesh.npolys-1];
mesh.areas[i] = mesh.areas[mesh.npolys-1];
@@ -671,7 +747,7 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
// Remove vertex.
for (int i = (int)rem; i < mesh.nverts; ++i)
for (int i = (int)rem; i < mesh.nverts - 1; ++i)
{
mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
@@ -746,22 +822,22 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
break;
}
rcScopedDelete<int> tris = (int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP);
rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP));
if (!tris)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3);
return false;
}
rcScopedDelete<int> tverts = (int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP);
rcScopedDelete<int> tverts((int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP));
if (!tverts)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4);
return false;
}
rcScopedDelete<int> thole = (int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP);
if (!tverts)
rcScopedDelete<int> thole((int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP));
if (!thole)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole);
return false;
@@ -787,20 +863,20 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
// Merge the hole triangles back to polygons.
rcScopedDelete<unsigned short> polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP));
if (!polys)
{
ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp);
return false;
}
rcScopedDelete<unsigned short> pregs = (unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> pregs((unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP));
if (!pregs)
{
ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris);
return false;
}
rcScopedDelete<unsigned char> pareas = (unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP);
if (!pregs)
rcScopedDelete<unsigned char> pareas((unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP));
if (!pareas)
{
ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris);
return false;
@@ -819,7 +895,14 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
polys[npolys*nvp+0] = (unsigned short)hole[t[0]];
polys[npolys*nvp+1] = (unsigned short)hole[t[1]];
polys[npolys*nvp+2] = (unsigned short)hole[t[2]];
pregs[npolys] = (unsigned short)hreg[t[0]];
// If this polygon covers multiple region types then
// mark it as such
if (hreg[t[0]] != hreg[t[1]] || hreg[t[1]] != hreg[t[2]])
pregs[npolys] = RC_MULTIPLE_REGS;
else
pregs[npolys] = (unsigned short)hreg[t[0]];
pareas[npolys] = (unsigned char)harea[t[0]];
npolys++;
}
@@ -860,8 +943,13 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
// Found best, merge.
unsigned short* pa = &polys[bestPa*nvp];
unsigned short* pb = &polys[bestPb*nvp];
mergePolys(pa, pb, bestEa, bestEb, tmpPoly, nvp);
memcpy(pb, &polys[(npolys-1)*nvp], sizeof(unsigned short)*nvp);
mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
if (pregs[bestPa] != pregs[bestPb])
pregs[bestPa] = RC_MULTIPLE_REGS;
unsigned short* last = &polys[(npolys-1)*nvp];
if (pb != last)
memcpy(pb, last, sizeof(unsigned short)*nvp);
pregs[bestPb] = pregs[npolys-1];
pareas[bestPb] = pareas[npolys-1];
npolys--;
@@ -905,13 +993,14 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_POLYMESH);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESH);
rcVcopy(mesh.bmin, cset.bmin);
rcVcopy(mesh.bmax, cset.bmax);
mesh.cs = cset.cs;
mesh.ch = cset.ch;
mesh.borderSize = cset.borderSize;
mesh.maxEdgeError = cset.maxError;
int maxVertices = 0;
int maxTris = 0;
@@ -931,10 +1020,10 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
return false;
}
rcScopedDelete<unsigned char> vflags = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP);
rcScopedDelete<unsigned char> vflags((unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP));
if (!vflags)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices);
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices);
return false;
}
memset(vflags, 0, maxVertices);
@@ -974,7 +1063,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
memset(mesh.regs, 0, sizeof(unsigned short)*maxTris);
memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
rcScopedDelete<int> nextVert = (int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP);
rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP));
if (!nextVert)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices);
@@ -982,7 +1071,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
}
memset(nextVert, 0, sizeof(int)*maxVertices);
rcScopedDelete<int> firstVert = (int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP);
rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
if (!firstVert)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
@@ -991,19 +1080,19 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
firstVert[i] = -1;
rcScopedDelete<int> indices = (int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP);
rcScopedDelete<int> indices((int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP));
if (!indices)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont);
return false;
}
rcScopedDelete<int> tris = (int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP);
rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP));
if (!tris)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3);
return false;
}
rcScopedDelete<unsigned short> polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP));
if (!polys)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp);
@@ -1053,7 +1142,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
vflags[indices[j]] = 1;
}
}
// Build initial polygons.
int npolys = 0;
memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short));
@@ -1104,8 +1193,10 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
// Found best, merge.
unsigned short* pa = &polys[bestPa*nvp];
unsigned short* pb = &polys[bestPb*nvp];
mergePolys(pa, pb, bestEa, bestEb, tmpPoly, nvp);
memcpy(pb, &polys[(npolys-1)*nvp], sizeof(unsigned short)*nvp);
mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
unsigned short* lastPoly = &polys[(npolys-1)*nvp];
if (pb != lastPoly)
memcpy(pb, lastPoly, sizeof(unsigned short)*nvp);
npolys--;
}
else
@@ -1150,6 +1241,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
}
// Remove vertex
// Note: mesh.nverts is already decremented inside removeVertex()!
// Fixup vertex flags
for (int j = i; j < mesh.nverts; ++j)
vflags[j] = vflags[j+1];
--i;
@@ -1212,8 +1304,6 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
}
ctx->stopTimer(RC_TIMER_BUILD_POLYMESH);
return true;
}
@@ -1225,7 +1315,7 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
if (!nmeshes || !meshes)
return true;
ctx->startTimer(RC_TIMER_MERGE_POLYMESH);
rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESH);
mesh.nvp = meshes[0]->nvp;
mesh.cs = meshes[0]->cs;
@@ -1286,7 +1376,7 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
}
memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys);
rcScopedDelete<int> nextVert = (int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP);
rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP));
if (!nextVert)
{
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts);
@@ -1294,7 +1384,7 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
}
memset(nextVert, 0, sizeof(int)*maxVerts);
rcScopedDelete<int> firstVert = (int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP);
rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
if (!firstVert)
{
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
@@ -1303,13 +1393,13 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
firstVert[i] = -1;
rcScopedDelete<unsigned short> vremap = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM);
rcScopedDelete<unsigned short> vremap((unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM));
if (!vremap)
{
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh);
return false;
}
memset(nextVert, 0, sizeof(int)*maxVerts);
memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh);
for (int i = 0; i < nmeshes; ++i)
{
@@ -1318,6 +1408,12 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f);
const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f);
bool isMinX = (ox == 0);
bool isMinZ = (oz == 0);
bool isMaxX = ((unsigned short)floorf((mesh.bmax[0] - pmesh->bmax[0]) / mesh.cs + 0.5f)) == 0;
bool isMaxZ = ((unsigned short)floorf((mesh.bmax[2] - pmesh->bmax[2]) / mesh.cs + 0.5f)) == 0;
bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ);
for (int j = 0; j < pmesh->nverts; ++j)
{
unsigned short* v = &pmesh->verts[j*3];
@@ -1338,6 +1434,36 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
if (src[k] == RC_MESH_NULL_IDX) break;
tgt[k] = vremap[src[k]];
}
if (isOnBorder)
{
for (int k = mesh.nvp; k < mesh.nvp * 2; ++k)
{
if (src[k] & 0x8000 && src[k] != 0xffff)
{
unsigned short dir = src[k] & 0xf;
switch (dir)
{
case 0: // Portal x-
if (isMinX)
tgt[k] = src[k];
break;
case 1: // Portal z+
if (isMaxZ)
tgt[k] = src[k];
break;
case 2: // Portal x+
if (isMaxX)
tgt[k] = src[k];
break;
case 3: // Portal z-
if (isMinZ)
tgt[k] = src[k];
break;
}
}
}
}
}
}
@@ -1357,7 +1483,70 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
}
ctx->stopTimer(RC_TIMER_MERGE_POLYMESH);
return true;
}
bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst)
{
rcAssert(ctx);
// Destination must be empty.
rcAssert(dst.verts == 0);
rcAssert(dst.polys == 0);
rcAssert(dst.regs == 0);
rcAssert(dst.areas == 0);
rcAssert(dst.flags == 0);
dst.nverts = src.nverts;
dst.npolys = src.npolys;
dst.maxpolys = src.npolys;
dst.nvp = src.nvp;
rcVcopy(dst.bmin, src.bmin);
rcVcopy(dst.bmax, src.bmax);
dst.cs = src.cs;
dst.ch = src.ch;
dst.borderSize = src.borderSize;
dst.maxEdgeError = src.maxEdgeError;
dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM);
if (!dst.verts)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3);
return false;
}
memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3);
dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM);
if (!dst.polys)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp);
return false;
}
memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp);
dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
if (!dst.regs)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys);
return false;
}
memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys);
dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM);
if (!dst.areas)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys);
return false;
}
memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys);
dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
if (!dst.flags)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys);
return false;
}
memcpy(dst.flags, src.flags, sizeof(unsigned short)*src.npolys);
return true;
}

File diff suppressed because it is too large Load Diff

View File

@@ -50,7 +50,7 @@ static rcSpan* allocSpan(rcHeightfield& hf)
// Allocate memory for the new pool.
rcSpanPool* pool = (rcSpanPool*)rcAlloc(sizeof(rcSpanPool), RC_ALLOC_PERM);
if (!pool) return 0;
pool->next = 0;
// Add the pool into the list of pools.
pool->next = hf.pools;
hf.pools = pool;
@@ -82,7 +82,7 @@ static void freeSpan(rcHeightfield& hf, rcSpan* ptr)
hf.freelist = ptr;
}
static void addSpan(rcHeightfield& hf, const int x, const int y,
static bool addSpan(rcHeightfield& hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr)
{
@@ -90,16 +90,18 @@ static void addSpan(rcHeightfield& hf, const int x, const int y,
int idx = x + y*hf.width;
rcSpan* s = allocSpan(hf);
if (!s)
return false;
s->smin = smin;
s->smax = smax;
s->area = area;
s->next = 0;
// Empty cell, add he first span.
// Empty cell, add the first span.
if (!hf.spans[idx])
{
hf.spans[idx] = s;
return;
return true;
}
rcSpan* prev = 0;
rcSpan* cur = hf.spans[idx];
@@ -152,6 +154,8 @@ static void addSpan(rcHeightfield& hf, const int x, const int y,
s->next = hf.spans[idx];
hf.spans[idx] = s;
}
return true;
}
/// @par
@@ -161,45 +165,80 @@ static void addSpan(rcHeightfield& hf, const int x, const int y,
/// from the existing span, the span flags are merged.
///
/// @see rcHeightfield, rcSpan.
void rcAddSpan(rcContext* /*ctx*/, rcHeightfield& hf, const int x, const int y,
bool rcAddSpan(rcContext* ctx, rcHeightfield& hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr)
{
// rcAssert(ctx);
addSpan(hf, x,y, smin, smax, area, flagMergeThr);
rcAssert(ctx);
if (!addSpan(hf, x, y, smin, smax, area, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcAddSpan: Out of memory.");
return false;
}
return true;
}
static int clipPoly(const float* in, int n, float* out, float pnx, float pnz, float pd)
// divides a convex polygons into two convex polygons on both sides of a line
static void dividePoly(const float* in, int nin,
float* out1, int* nout1,
float* out2, int* nout2,
float x, int axis)
{
float d[12];
for (int i = 0; i < n; ++i)
d[i] = pnx*in[i*3+0] + pnz*in[i*3+2] + pd;
int m = 0;
for (int i = 0, j = n-1; i < n; j=i, ++i)
for (int i = 0; i < nin; ++i)
d[i] = x - in[i*3+axis];
int m = 0, n = 0;
for (int i = 0, j = nin-1; i < nin; j=i, ++i)
{
bool ina = d[j] >= 0;
bool inb = d[i] >= 0;
if (ina != inb)
{
float s = d[j] / (d[j] - d[i]);
out[m*3+0] = in[j*3+0] + (in[i*3+0] - in[j*3+0])*s;
out[m*3+1] = in[j*3+1] + (in[i*3+1] - in[j*3+1])*s;
out[m*3+2] = in[j*3+2] + (in[i*3+2] - in[j*3+2])*s;
out1[m*3+0] = in[j*3+0] + (in[i*3+0] - in[j*3+0])*s;
out1[m*3+1] = in[j*3+1] + (in[i*3+1] - in[j*3+1])*s;
out1[m*3+2] = in[j*3+2] + (in[i*3+2] - in[j*3+2])*s;
rcVcopy(out2 + n*3, out1 + m*3);
m++;
n++;
// add the i'th point to the right polygon. Do NOT add points that are on the dividing line
// since these were already added above
if (d[i] > 0)
{
rcVcopy(out1 + m*3, in + i*3);
m++;
}
else if (d[i] < 0)
{
rcVcopy(out2 + n*3, in + i*3);
n++;
}
}
if (inb)
else // same side
{
out[m*3+0] = in[i*3+0];
out[m*3+1] = in[i*3+1];
out[m*3+2] = in[i*3+2];
m++;
// add the i'th point to the right polygon. Addition is done even for points on the dividing line
if (d[i] >= 0)
{
rcVcopy(out1 + m*3, in + i*3);
m++;
if (d[i] != 0)
continue;
}
rcVcopy(out2 + n*3, in + i*3);
n++;
}
}
return m;
*nout1 = m;
*nout2 = n;
}
static void rasterizeTri(const float* v0, const float* v1, const float* v2,
static bool rasterizeTri(const float* v0, const float* v1, const float* v2,
const unsigned char area, rcHeightfield& hf,
const float* bmin, const float* bmax,
const float cs, const float ics, const float ich,
@@ -220,50 +259,59 @@ static void rasterizeTri(const float* v0, const float* v1, const float* v2,
// If the triangle does not touch the bbox of the heightfield, skip the triagle.
if (!overlapBounds(bmin, bmax, tmin, tmax))
return;
return true;
// Calculate the footpring of the triangle on the grid.
int x0 = (int)((tmin[0] - bmin[0])*ics);
// Calculate the footprint of the triangle on the grid's y-axis
int y0 = (int)((tmin[2] - bmin[2])*ics);
int x1 = (int)((tmax[0] - bmin[0])*ics);
int y1 = (int)((tmax[2] - bmin[2])*ics);
x0 = rcClamp(x0, 0, w-1);
y0 = rcClamp(y0, 0, h-1);
x1 = rcClamp(x1, 0, w-1);
y1 = rcClamp(y1, 0, h-1);
// Clip the triangle into all grid cells it touches.
float in[7*3], out[7*3], inrow[7*3];
float buf[7*3*4];
float *in = buf, *inrow = buf+7*3, *p1 = inrow+7*3, *p2 = p1+7*3;
rcVcopy(&in[0], v0);
rcVcopy(&in[1*3], v1);
rcVcopy(&in[2*3], v2);
int nvrow, nvIn = 3;
for (int y = y0; y <= y1; ++y)
{
// Clip polygon to row.
rcVcopy(&in[0], v0);
rcVcopy(&in[1*3], v1);
rcVcopy(&in[2*3], v2);
int nvrow = 3;
// Clip polygon to row. Store the remaining polygon as well
const float cz = bmin[2] + y*cs;
nvrow = clipPoly(in, nvrow, out, 0, 1, -cz);
if (nvrow < 3) continue;
nvrow = clipPoly(out, nvrow, inrow, 0, -1, cz+cs);
dividePoly(in, nvIn, inrow, &nvrow, p1, &nvIn, cz+cs, 2);
rcSwap(in, p1);
if (nvrow < 3) continue;
// find the horizontal bounds in the row
float minX = inrow[0], maxX = inrow[0];
for (int i=1; i<nvrow; ++i)
{
if (minX > inrow[i*3]) minX = inrow[i*3];
if (maxX < inrow[i*3]) maxX = inrow[i*3];
}
int x0 = (int)((minX - bmin[0])*ics);
int x1 = (int)((maxX - bmin[0])*ics);
x0 = rcClamp(x0, 0, w-1);
x1 = rcClamp(x1, 0, w-1);
int nv, nv2 = nvrow;
for (int x = x0; x <= x1; ++x)
{
// Clip polygon to column.
int nv = nvrow;
// Clip polygon to column. store the remaining polygon as well
const float cx = bmin[0] + x*cs;
nv = clipPoly(inrow, nv, out, 1, 0, -cx);
if (nv < 3) continue;
nv = clipPoly(out, nv, in, -1, 0, cx+cs);
dividePoly(inrow, nv2, p1, &nv, p2, &nv2, cx+cs, 0);
rcSwap(inrow, p2);
if (nv < 3) continue;
// Calculate min and max of the span.
float smin = in[1], smax = in[1];
float smin = p1[1], smax = p1[1];
for (int i = 1; i < nv; ++i)
{
smin = rcMin(smin, in[i*3+1]);
smax = rcMax(smax, in[i*3+1]);
smin = rcMin(smin, p1[i*3+1]);
smax = rcMax(smax, p1[i*3+1]);
}
smin -= bmin[1];
smax -= bmin[1];
@@ -278,9 +326,12 @@ static void rasterizeTri(const float* v0, const float* v1, const float* v2,
unsigned short ismin = (unsigned short)rcClamp((int)floorf(smin * ich), 0, RC_SPAN_MAX_HEIGHT);
unsigned short ismax = (unsigned short)rcClamp((int)ceilf(smax * ich), (int)ismin+1, RC_SPAN_MAX_HEIGHT);
addSpan(hf, x, y, ismin, ismax, area, flagMergeThr);
if (!addSpan(hf, x, y, ismin, ismax, area, flagMergeThr))
return false;
}
}
return true;
}
/// @par
@@ -288,19 +339,23 @@ static void rasterizeTri(const float* v0, const float* v1, const float* v2,
/// No spans will be added if the triangle does not overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangle(rcContext* ctx, const float* v0, const float* v1, const float* v2,
bool rcRasterizeTriangle(rcContext* ctx, const float* v0, const float* v1, const float* v2,
const unsigned char area, rcHeightfield& solid,
const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
rasterizeTri(v0, v1, v2, area, solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, area, solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangle: Out of memory.");
return false;
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}
/// @par
@@ -308,13 +363,13 @@ void rcRasterizeTriangle(rcContext* ctx, const float* v0, const float* v1, const
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const int* tris, const unsigned char* areas, const int nt,
rcHeightfield& solid, const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
@@ -325,10 +380,14 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const float* v1 = &verts[tris[i*3+1]*3];
const float* v2 = &verts[tris[i*3+2]*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
return false;
}
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}
/// @par
@@ -336,13 +395,13 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const unsigned short* tris, const unsigned char* areas, const int nt,
rcHeightfield& solid, const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
@@ -353,10 +412,14 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const float* v1 = &verts[tris[i*3+1]*3];
const float* v2 = &verts[tris[i*3+2]*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
return false;
}
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}
/// @par
@@ -364,12 +427,12 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangles(rcContext* ctx, const float* verts, const unsigned char* areas, const int nt,
bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const unsigned char* areas, const int nt,
rcHeightfield& solid, const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
@@ -380,8 +443,12 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const unsigned cha
const float* v1 = &verts[(i*3+1)*3];
const float* v2 = &verts[(i*3+2)*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
return false;
}
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}

View File

@@ -286,7 +286,10 @@ static bool floodRegion(int x, int y, int i,
if (nr & RC_BORDER_REG) // Do not take borders into account.
continue;
if (nr != 0 && nr != r)
{
ar = nr;
break;
}
const rcCompactSpan& as = chf.spans[ai];
@@ -298,9 +301,12 @@ static bool floodRegion(int x, int y, int i,
const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
if (chf.areas[ai2] != area)
continue;
unsigned short nr = srcReg[ai2];
if (nr != 0 && nr != r)
ar = nr;
unsigned short nr2 = srcReg[ai2];
if (nr2 != 0 && nr2 != r)
{
ar = nr2;
break;
}
}
}
}
@@ -309,6 +315,7 @@ static bool floodRegion(int x, int y, int i,
srcReg[ci] = 0;
continue;
}
count++;
// Expand neighbours.
@@ -340,30 +347,44 @@ static unsigned short* expandRegions(int maxIter, unsigned short level,
rcCompactHeightfield& chf,
unsigned short* srcReg, unsigned short* srcDist,
unsigned short* dstReg, unsigned short* dstDist,
rcIntArray& stack)
rcIntArray& stack,
bool fillStack)
{
const int w = chf.width;
const int h = chf.height;
// Find cells revealed by the raised level.
stack.resize(0);
for (int y = 0; y < h; ++y)
if (fillStack)
{
for (int x = 0; x < w; ++x)
// Find cells revealed by the raised level.
stack.resize(0);
for (int y = 0; y < h; ++y)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
for (int x = 0; x < w; ++x)
{
if (chf.dist[i] >= level && srcReg[i] == 0 && chf.areas[i] != RC_NULL_AREA)
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
stack.push(x);
stack.push(y);
stack.push(i);
if (chf.dist[i] >= level && srcReg[i] == 0 && chf.areas[i] != RC_NULL_AREA)
{
stack.push(x);
stack.push(y);
stack.push(i);
}
}
}
}
}
else // use cells in the input stack
{
// mark all cells which already have a region
for (int j=0; j<stack.size(); j+=3)
{
int i = stack[j+2];
if (srcReg[i] != 0)
stack[j+2] = -1;
}
}
int iter = 0;
while (stack.size() > 0)
{
@@ -434,6 +455,61 @@ static unsigned short* expandRegions(int maxIter, unsigned short level,
}
static void sortCellsByLevel(unsigned short startLevel,
rcCompactHeightfield& chf,
unsigned short* srcReg,
unsigned int nbStacks, rcIntArray* stacks,
unsigned short loglevelsPerStack) // the levels per stack (2 in our case) as a bit shift
{
const int w = chf.width;
const int h = chf.height;
startLevel = startLevel >> loglevelsPerStack;
for (unsigned int j=0; j<nbStacks; ++j)
stacks[j].resize(0);
// put all cells in the level range into the appropriate stacks
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (chf.areas[i] == RC_NULL_AREA || srcReg[i] != 0)
continue;
int level = chf.dist[i] >> loglevelsPerStack;
int sId = startLevel - level;
if (sId >= (int)nbStacks)
continue;
if (sId < 0)
sId = 0;
stacks[sId].push(x);
stacks[sId].push(y);
stacks[sId].push(i);
}
}
}
}
static void appendStacks(rcIntArray& srcStack, rcIntArray& dstStack,
unsigned short* srcReg)
{
for (int j=0; j<srcStack.size(); j+=3)
{
int i = srcStack[j+2];
if ((i < 0) || (srcReg[i] != 0))
continue;
dstStack.push(srcStack[j]);
dstStack.push(srcStack[j+1]);
dstStack.push(srcStack[j+2]);
}
}
struct rcRegion
{
inline rcRegion(unsigned short i) :
@@ -441,7 +517,11 @@ struct rcRegion
id(i),
areaType(0),
remap(false),
visited(false)
visited(false),
overlap(false),
connectsToBorder(false),
ymin(0xffff),
ymax(0)
{}
int spanCount; // Number of spans belonging to this region
@@ -449,6 +529,9 @@ struct rcRegion
unsigned char areaType; // Are type.
bool remap;
bool visited;
bool overlap;
bool connectsToBorder;
unsigned short ymin, ymax;
rcIntArray connections;
rcIntArray floors;
};
@@ -678,25 +761,26 @@ static void walkContour(int x, int y, int i, int dir,
// Remove adjacent duplicates.
if (cont.size() > 1)
{
for (int i = 0; i < cont.size(); )
for (int j = 0; j < cont.size(); )
{
int ni = (i+1) % cont.size();
if (cont[i] == cont[ni])
int nj = (j+1) % cont.size();
if (cont[j] == cont[nj])
{
for (int j = i; j < cont.size()-1; ++j)
cont[j] = cont[j+1];
for (int k = j; k < cont.size()-1; ++k)
cont[k] = cont[k+1];
cont.pop();
}
else
++i;
++j;
}
}
}
static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegionSize,
unsigned short& maxRegionId,
rcCompactHeightfield& chf,
unsigned short* srcReg)
static bool mergeAndFilterRegions(rcContext* ctx, int minRegionArea, int mergeRegionSize,
unsigned short& maxRegionId,
rcCompactHeightfield& chf,
unsigned short* srcReg, rcIntArray& overlaps)
{
const int w = chf.width;
const int h = chf.height;
@@ -705,7 +789,7 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
rcRegion* regions = (rcRegion*)rcAlloc(sizeof(rcRegion)*nreg, RC_ALLOC_TEMP);
if (!regions)
{
ctx->log(RC_LOG_ERROR, "filterSmallRegions: Out of memory 'regions' (%d).", nreg);
ctx->log(RC_LOG_ERROR, "mergeAndFilterRegions: Out of memory 'regions' (%d).", nreg);
return false;
}
@@ -728,7 +812,6 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
rcRegion& reg = regions[r];
reg.spanCount++;
// Update floors.
for (int j = (int)c.index; j < ni; ++j)
{
@@ -736,6 +819,8 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
unsigned short floorId = srcReg[j];
if (floorId == 0 || floorId >= nreg)
continue;
if (floorId == r)
reg.overlap = true;
addUniqueFloorRegion(reg, floorId);
}
@@ -806,14 +891,14 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
connectsToBorder = true;
continue;
}
rcRegion& nreg = regions[creg.connections[j]];
if (nreg.visited)
rcRegion& neireg = regions[creg.connections[j]];
if (neireg.visited)
continue;
if (nreg.id == 0 || (nreg.id & RC_BORDER_REG))
if (neireg.id == 0 || (neireg.id & RC_BORDER_REG))
continue;
// Visit
stack.push(nreg.id);
nreg.visited = true;
stack.push(neireg.id);
neireg.visited = true;
}
}
@@ -831,7 +916,7 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
}
}
}
// Merge too small regions to neighbour regions.
int mergeCount = 0 ;
do
@@ -841,7 +926,9 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
{
rcRegion& reg = regions[i];
if (reg.id == 0 || (reg.id & RC_BORDER_REG))
continue;
continue;
if (reg.overlap)
continue;
if (reg.spanCount == 0)
continue;
@@ -858,7 +945,7 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
{
if (reg.connections[j] & RC_BORDER_REG) continue;
rcRegion& mreg = regions[reg.connections[j]];
if (mreg.id == 0 || (mreg.id & RC_BORDER_REG)) continue;
if (mreg.id == 0 || (mreg.id & RC_BORDER_REG) || mreg.overlap) continue;
if (mreg.spanCount < smallest &&
canMergeWithRegion(reg, mreg) &&
canMergeWithRegion(mreg, reg))
@@ -922,6 +1009,224 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
}
maxRegionId = regIdGen;
// Remap regions.
for (int i = 0; i < chf.spanCount; ++i)
{
if ((srcReg[i] & RC_BORDER_REG) == 0)
srcReg[i] = regions[srcReg[i]].id;
}
// Return regions that we found to be overlapping.
for (int i = 0; i < nreg; ++i)
if (regions[i].overlap)
overlaps.push(regions[i].id);
for (int i = 0; i < nreg; ++i)
regions[i].~rcRegion();
rcFree(regions);
return true;
}
static void addUniqueConnection(rcRegion& reg, int n)
{
for (int i = 0; i < reg.connections.size(); ++i)
if (reg.connections[i] == n)
return;
reg.connections.push(n);
}
static bool mergeAndFilterLayerRegions(rcContext* ctx, int minRegionArea,
unsigned short& maxRegionId,
rcCompactHeightfield& chf,
unsigned short* srcReg, rcIntArray& /*overlaps*/)
{
const int w = chf.width;
const int h = chf.height;
const int nreg = maxRegionId+1;
rcRegion* regions = (rcRegion*)rcAlloc(sizeof(rcRegion)*nreg, RC_ALLOC_TEMP);
if (!regions)
{
ctx->log(RC_LOG_ERROR, "mergeAndFilterLayerRegions: Out of memory 'regions' (%d).", nreg);
return false;
}
// Construct regions
for (int i = 0; i < nreg; ++i)
new(&regions[i]) rcRegion((unsigned short)i);
// Find region neighbours and overlapping regions.
rcIntArray lregs(32);
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
lregs.resize(0);
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
const unsigned short ri = srcReg[i];
if (ri == 0 || ri >= nreg) continue;
rcRegion& reg = regions[ri];
reg.spanCount++;
reg.ymin = rcMin(reg.ymin, s.y);
reg.ymax = rcMax(reg.ymax, s.y);
// Collect all region layers.
lregs.push(ri);
// Update neighbours
for (int dir = 0; dir < 4; ++dir)
{
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dir);
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
const unsigned short rai = srcReg[ai];
if (rai > 0 && rai < nreg && rai != ri)
addUniqueConnection(reg, rai);
if (rai & RC_BORDER_REG)
reg.connectsToBorder = true;
}
}
}
// Update overlapping regions.
for (int i = 0; i < lregs.size()-1; ++i)
{
for (int j = i+1; j < lregs.size(); ++j)
{
if (lregs[i] != lregs[j])
{
rcRegion& ri = regions[lregs[i]];
rcRegion& rj = regions[lregs[j]];
addUniqueFloorRegion(ri, lregs[j]);
addUniqueFloorRegion(rj, lregs[i]);
}
}
}
}
}
// Create 2D layers from regions.
unsigned short layerId = 1;
for (int i = 0; i < nreg; ++i)
regions[i].id = 0;
// Merge montone regions to create non-overlapping areas.
rcIntArray stack(32);
for (int i = 1; i < nreg; ++i)
{
rcRegion& root = regions[i];
// Skip already visited.
if (root.id != 0)
continue;
// Start search.
root.id = layerId;
stack.resize(0);
stack.push(i);
while (stack.size() > 0)
{
// Pop front
rcRegion& reg = regions[stack[0]];
for (int j = 0; j < stack.size()-1; ++j)
stack[j] = stack[j+1];
stack.resize(stack.size()-1);
const int ncons = (int)reg.connections.size();
for (int j = 0; j < ncons; ++j)
{
const int nei = reg.connections[j];
rcRegion& regn = regions[nei];
// Skip already visited.
if (regn.id != 0)
continue;
// Skip if the neighbour is overlapping root region.
bool overlap = false;
for (int k = 0; k < root.floors.size(); k++)
{
if (root.floors[k] == nei)
{
overlap = true;
break;
}
}
if (overlap)
continue;
// Deepen
stack.push(nei);
// Mark layer id
regn.id = layerId;
// Merge current layers to root.
for (int k = 0; k < regn.floors.size(); ++k)
addUniqueFloorRegion(root, regn.floors[k]);
root.ymin = rcMin(root.ymin, regn.ymin);
root.ymax = rcMax(root.ymax, regn.ymax);
root.spanCount += regn.spanCount;
regn.spanCount = 0;
root.connectsToBorder = root.connectsToBorder || regn.connectsToBorder;
}
}
layerId++;
}
// Remove small regions
for (int i = 0; i < nreg; ++i)
{
if (regions[i].spanCount > 0 && regions[i].spanCount < minRegionArea && !regions[i].connectsToBorder)
{
unsigned short reg = regions[i].id;
for (int j = 0; j < nreg; ++j)
if (regions[j].id == reg)
regions[j].id = 0;
}
}
// Compress region Ids.
for (int i = 0; i < nreg; ++i)
{
regions[i].remap = false;
if (regions[i].id == 0) continue; // Skip nil regions.
if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions.
regions[i].remap = true;
}
unsigned short regIdGen = 0;
for (int i = 0; i < nreg; ++i)
{
if (!regions[i].remap)
continue;
unsigned short oldId = regions[i].id;
unsigned short newId = ++regIdGen;
for (int j = i; j < nreg; ++j)
{
if (regions[j].id == oldId)
{
regions[j].id = newId;
regions[j].remap = false;
}
}
}
maxRegionId = regIdGen;
// Remap regions.
for (int i = 0; i < chf.spanCount; ++i)
{
@@ -936,6 +1241,8 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
return true;
}
/// @par
///
/// This is usually the second to the last step in creating a fully built
@@ -950,7 +1257,7 @@ bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_DISTANCEFIELD);
if (chf.dist)
{
@@ -974,25 +1281,23 @@ bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf)
unsigned short maxDist = 0;
ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
calculateDistanceField(chf, src, maxDist);
chf.maxDistance = maxDist;
ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
// Blur
if (boxBlur(chf, 1, src, dst) != src)
rcSwap(src, dst);
// Store distance.
chf.dist = src;
ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
{
rcScopedTimer timerDist(ctx, RC_TIMER_BUILD_DISTANCEFIELD_DIST);
ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD);
calculateDistanceField(chf, src, maxDist);
chf.maxDistance = maxDist;
}
{
rcScopedTimer timerBlur(ctx, RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
// Blur
if (boxBlur(chf, 1, src, dst) != src)
rcSwap(src, dst);
// Store distance.
chf.dist = src;
}
rcFree(dst);
@@ -1052,13 +1357,13 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_REGIONS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
const int w = chf.width;
const int h = chf.height;
unsigned short id = 1;
rcScopedDelete<unsigned short> srcReg = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP));
if (!srcReg)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount);
@@ -1067,7 +1372,7 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
const int nsweeps = rcMax(chf.width,chf.height);
rcScopedDelete<rcSweepSpan> sweeps = (rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP);
rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
if (!sweeps)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps);
@@ -1181,20 +1486,22 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
}
}
ctx->startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Filter out small regions.
chf.maxRegions = id;
if (!filterSmallRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg))
return false;
{
rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Merge regions and filter out small regions.
rcIntArray overlaps;
chf.maxRegions = id;
if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps))
return false;
// Monotone partitioning does not generate overlapping regions.
}
// Store the result out.
for (int i = 0; i < chf.spanCount; ++i)
chf.spans[i].reg = srcReg[i];
ctx->stopTimer(RC_TIMER_BUILD_REGIONS);
return true;
}
@@ -1223,12 +1530,12 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_REGIONS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
const int w = chf.width;
const int h = chf.height;
rcScopedDelete<unsigned short> buf = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount*4, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> buf((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount*4, RC_ALLOC_TEMP));
if (!buf)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: Out of memory 'tmp' (%d).", chf.spanCount*4);
@@ -1236,7 +1543,13 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
}
ctx->startTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
const int LOG_NB_STACKS = 3;
const int NB_STACKS = 1 << LOG_NB_STACKS;
rcIntArray lvlStacks[NB_STACKS];
for (int i=0; i<NB_STACKS; ++i)
lvlStacks[i].resize(1024);
rcIntArray stack(1024);
rcIntArray visited(1024);
@@ -1262,6 +1575,13 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
// Make sure border will not overflow.
const int bw = rcMin(w, borderSize);
const int bh = rcMin(h, borderSize);
if (regionId > 0xFFFB)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: Region ID overflow");
return false;
}
// Paint regions
paintRectRegion(0, bw, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
paintRectRegion(w-bw, w, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
@@ -1271,44 +1591,60 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
chf.borderSize = borderSize;
}
int sId = -1;
while (level > 0)
{
level = level >= 2 ? level-2 : 0;
ctx->startTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters, level, chf, srcReg, srcDist, dstReg, dstDist, stack) != srcReg)
sId = (sId+1) & (NB_STACKS-1);
// ctx->startTimer(RC_TIMER_DIVIDE_TO_LEVELS);
if (sId == 0)
sortCellsByLevel(level, chf, srcReg, NB_STACKS, lvlStacks, 1);
else
appendStacks(lvlStacks[sId-1], lvlStacks[sId], srcReg); // copy left overs from last level
// ctx->stopTimer(RC_TIMER_DIVIDE_TO_LEVELS);
{
rcSwap(srcReg, dstReg);
rcSwap(srcDist, dstDist);
}
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
ctx->startTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
// Mark new regions with IDs.
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
rcScopedTimer timerExpand(ctx, RC_TIMER_BUILD_REGIONS_EXPAND);
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters, level, chf, srcReg, srcDist, dstReg, dstDist, lvlStacks[sId], false) != srcReg)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (chf.dist[i] < level || srcReg[i] != 0 || chf.areas[i] == RC_NULL_AREA)
continue;
if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, stack))
regionId++;
}
rcSwap(srcReg, dstReg);
rcSwap(srcDist, dstDist);
}
}
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
{
rcScopedTimer timerFloor(ctx, RC_TIMER_BUILD_REGIONS_FLOOD);
// Mark new regions with IDs.
for (int j = 0; j<lvlStacks[sId].size(); j += 3)
{
int x = lvlStacks[sId][j];
int y = lvlStacks[sId][j+1];
int i = lvlStacks[sId][j+2];
if (i >= 0 && srcReg[i] == 0)
{
if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, stack))
{
if (regionId == 0xFFFF)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: Region ID overflow");
return false;
}
regionId++;
}
}
}
}
}
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters*8, 0, chf, srcReg, srcDist, dstReg, dstDist, stack) != srcReg)
if (expandRegions(expandIters*8, 0, chf, srcReg, srcDist, dstReg, dstDist, stack, true) != srcReg)
{
rcSwap(srcReg, dstReg);
rcSwap(srcDist, dstDist);
@@ -1316,22 +1652,179 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
ctx->startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Filter out small regions.
chf.maxRegions = regionId;
if (!filterSmallRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg))
return false;
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
{
rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
// Merge regions and filter out smalle regions.
rcIntArray overlaps;
chf.maxRegions = regionId;
if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps))
return false;
// If overlapping regions were found during merging, split those regions.
if (overlaps.size() > 0)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: %d overlapping regions.", overlaps.size());
}
}
// Write the result out.
for (int i = 0; i < chf.spanCount; ++i)
chf.spans[i].reg = srcReg[i];
ctx->stopTimer(RC_TIMER_BUILD_REGIONS);
return true;
}
bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf,
const int borderSize, const int minRegionArea)
{
rcAssert(ctx);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
const int w = chf.width;
const int h = chf.height;
unsigned short id = 1;
rcScopedDelete<unsigned short> srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP));
if (!srcReg)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount);
return false;
}
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
const int nsweeps = rcMax(chf.width,chf.height);
rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
if (!sweeps)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps);
return false;
}
// Mark border regions.
if (borderSize > 0)
{
// Make sure border will not overflow.
const int bw = rcMin(w, borderSize);
const int bh = rcMin(h, borderSize);
// Paint regions
paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
chf.borderSize = borderSize;
}
rcIntArray prev(256);
// Sweep one line at a time.
for (int y = borderSize; y < h-borderSize; ++y)
{
// Collect spans from this row.
prev.resize(id+1);
memset(&prev[0],0,sizeof(int)*id);
unsigned short rid = 1;
for (int x = borderSize; x < w-borderSize; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] == RC_NULL_AREA) continue;
// -x
unsigned short previd = 0;
if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(0);
const int ay = y + rcGetDirOffsetY(0);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
previd = srcReg[ai];
}
if (!previd)
{
previd = rid++;
sweeps[previd].rid = previd;
sweeps[previd].ns = 0;
sweeps[previd].nei = 0;
}
// -y
if (rcGetCon(s,3) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(3);
const int ay = y + rcGetDirOffsetY(3);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
{
unsigned short nr = srcReg[ai];
if (!sweeps[previd].nei || sweeps[previd].nei == nr)
{
sweeps[previd].nei = nr;
sweeps[previd].ns++;
prev[nr]++;
}
else
{
sweeps[previd].nei = RC_NULL_NEI;
}
}
}
srcReg[i] = previd;
}
}
// Create unique ID.
for (int i = 1; i < rid; ++i)
{
if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 &&
prev[sweeps[i].nei] == (int)sweeps[i].ns)
{
sweeps[i].id = sweeps[i].nei;
}
else
{
sweeps[i].id = id++;
}
}
// Remap IDs
for (int x = borderSize; x < w-borderSize; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (srcReg[i] > 0 && srcReg[i] < rid)
srcReg[i] = sweeps[srcReg[i]].id;
}
}
}
{
rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
// Merge monotone regions to layers and remove small regions.
rcIntArray overlaps;
chf.maxRegions = id;
if (!mergeAndFilterLayerRegions(ctx, minRegionArea, chf.maxRegions, chf, srcReg, overlaps))
return false;
}
// Store the result out.
for (int i = 0; i < chf.spanCount; ++i)
chf.spans[i].reg = srcReg[i];
return true;
}

View File

@@ -1,58 +0,0 @@
#include "RecastTimer.h"
#if defined(WIN32)
// Win32
#include <windows.h>
rcTimeVal rcGetPerformanceTimer()
{
__int64 count;
QueryPerformanceCounter((LARGE_INTEGER*)&count);
return count;
}
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end)
{
static __int64 freq = 0;
if (freq == 0)
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
__int64 elapsed = end - start;
return (int)(elapsed*1000000 / freq);
}
#elif defined(__MACH__)
// OSX
#include <mach/mach_time.h>
rcTimeVal rcGetPerformanceTimer()
{
return mach_absolute_time();
}
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end)
{
static mach_timebase_info_data_t timebaseInfo;
if (timebaseInfo.denom == 0)
mach_timebase_info(&timebaseInfo);
uint64_t elapsed = end - start;
uint64_t nanosec = elapsed * timebaseInfo.numer / timebaseInfo.denom;
return (int)(nanosec / 1000);
}
#else
// TODO: Linux, etc
rcTimeVal rcGetPerformanceTimer()
{
return 0;
}
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end)
{
return 0;
}
#endif

View File

@@ -0,0 +1,22 @@
The version of Recast is 1.5.0, from:
https://github.com/recastnavigation/recastnavigation
Changes made:
* Recast/Source/RecastMesh.cpp: made buildMeshAdjacency() non-static so it can be used with recast-capi
* Recast/Include/Recast.h: Added forward declaration for buildMeshAdjacency()
The following additional files were added:
* recast-capi.cpp
* recast-capi.h
These expose a C interface to the Recast library, which has only C++ headers.
The version of Detour is 1.4, from:
https://code.google.com/archive/p/recastnavigation/downloads
Changes made:
* DetourStatNavMesh.h: use more portable definition of DT_STAT_NAVMESH_MAGIC
* DetourStatNavMesh.cpp: comment out some unused variables to avoid compiler warnings
* DetourStatNavMeshBuilder.h: add forward declaration for createBVTree
* DetourStatNavMeshBuilder.cpp: made createBVTree non-static for use with recast-capi
The CMakeLists.txt file has been added, since the original software does not include build files for the libraries.
~rdb

View File

@@ -68,17 +68,41 @@ int recast_createHeightfield(struct recast_heightfield *hf, int width, int heigh
}
void recast_markWalkableTriangles(const float walkableSlopeAngle,const float *verts, int nv,
const int *tris, int nt, unsigned char *flags)
const int *tris, int nt, unsigned char *areas)
{
INIT_SCTX();
rcMarkWalkableTriangles(sctx, walkableSlopeAngle, verts, nv, tris, nt, flags);
rcMarkWalkableTriangles(sctx, walkableSlopeAngle, verts, nv, tris, nt, areas);
}
void recast_rasterizeTriangles(const float *verts, int nv, const int *tris,
const unsigned char *flags, int nt, struct recast_heightfield *solid)
void recast_clearUnwalkableTriangles(const float walkableSlopeAngle, const float* verts, int nv,
const int* tris, int nt, unsigned char* areas)
{
INIT_SCTX();
rcRasterizeTriangles(sctx, verts, nv, tris, flags, nt, *(rcHeightfield *) solid);
rcClearUnwalkableTriangles(sctx, walkableSlopeAngle, verts, nv, tris, nt, areas);
}
int recast_addSpan(struct recast_heightfield *hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr)
{
INIT_SCTX();
return rcAddSpan(sctx, *(rcHeightfield *) hf, x, y, smin, smax, area, flagMergeThr);
}
int recast_rasterizeTriangle(const float *v0, const float *v1, const float *v2,
const unsigned char area, struct recast_heightfield *solid,
const int flagMergeThr)
{
INIT_SCTX();
return rcRasterizeTriangle(sctx, v0, v1, v2, area, *(rcHeightfield *) solid, flagMergeThr);
}
int recast_rasterizeTriangles(const float *verts, const int nv, const int *tris,
const unsigned char *areas, const int nt, struct recast_heightfield *solid,
const int flagMergeThr)
{
INIT_SCTX();
return rcRasterizeTriangles(sctx, verts, nv, tris, areas, nt, *(rcHeightfield *) solid, flagMergeThr);
}
void recast_filterLedgeSpans(const int walkableHeight, const int walkableClimb,
@@ -100,6 +124,22 @@ void recast_filterLowHangingWalkableObstacles(const int walkableClimb, struct re
rcFilterLowHangingWalkableObstacles(sctx, walkableClimb, *(rcHeightfield *) solid);
}
int recast_getHeightFieldSpanCount(struct recast_heightfield *hf)
{
INIT_SCTX();
return rcGetHeightFieldSpanCount(sctx, *(rcHeightfield *) hf);
}
struct recast_heightfieldLayerSet *recast_newHeightfieldLayerSet(void)
{
return (struct recast_heightfieldLayerSet *) rcAllocHeightfieldLayerSet();
}
void recast_destroyHeightfieldLayerSet(struct recast_heightfieldLayerSet *lset)
{
rcFreeHeightfieldLayerSet( (rcHeightfieldLayerSet *) lset);
}
struct recast_compactHeightfield *recast_newCompactHeightfield(void)
{
return (struct recast_compactHeightfield *) rcAllocCompactHeightfield();
@@ -124,18 +164,68 @@ int recast_erodeWalkableArea(int radius, struct recast_compactHeightfield *chf)
return rcErodeWalkableArea(sctx, radius, *(rcCompactHeightfield *) chf);
}
int recast_medianFilterWalkableArea(struct recast_compactHeightfield *chf)
{
INIT_SCTX();
return rcMedianFilterWalkableArea(sctx, *(rcCompactHeightfield *) chf);
}
void recast_markBoxArea(const float *bmin, const float *bmax, unsigned char areaId,
struct recast_compactHeightfield *chf)
{
INIT_SCTX();
rcMarkBoxArea(sctx, bmin, bmax, areaId, *(rcCompactHeightfield *) chf);
}
void recast_markConvexPolyArea(const float* verts, const int nverts,
const float hmin, const float hmax, unsigned char areaId,
struct recast_compactHeightfield *chf)
{
INIT_SCTX();
rcMarkConvexPolyArea(sctx, verts, nverts, hmin, hmax, areaId, *(rcCompactHeightfield *) chf);
}
int recast_offsetPoly(const float* verts, const int nverts,
const float offset, float *outVerts, const int maxOutVerts)
{
return rcOffsetPoly(verts, nverts, offset, outVerts, maxOutVerts);
}
void recast_markCylinderArea(const float* pos, const float r, const float h,
unsigned char areaId, struct recast_compactHeightfield *chf)
{
INIT_SCTX();
rcMarkCylinderArea(sctx, pos, r, h, areaId, *(rcCompactHeightfield *) chf);
}
int recast_buildDistanceField(struct recast_compactHeightfield *chf)
{
INIT_SCTX();
return rcBuildDistanceField(sctx, *(rcCompactHeightfield *) chf);
}
int recast_buildRegions(struct recast_compactHeightfield *chf, int borderSize,
int minRegionSize, int mergeRegionSize)
int recast_buildRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea)
{
INIT_SCTX();
return rcBuildRegions(sctx, *(rcCompactHeightfield *) chf, borderSize,
minRegionSize, mergeRegionSize);
minRegionArea, mergeRegionArea);
}
int recast_buildLayerRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea)
{
INIT_SCTX();
return rcBuildLayerRegions(sctx, *(rcCompactHeightfield *) chf, borderSize,
minRegionArea);
}
int recast_buildRegionsMonotone(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea)
{
INIT_SCTX();
return rcBuildRegionsMonotone(sctx, *(rcCompactHeightfield *) chf, borderSize,
minRegionArea, mergeRegionArea);
}
struct recast_contourSet *recast_newContourSet(void)
@@ -149,10 +239,11 @@ void recast_destroyContourSet(struct recast_contourSet *contourSet)
}
int recast_buildContours(struct recast_compactHeightfield *chf,
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset)
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset,
const int buildFlags)
{
INIT_SCTX();
return rcBuildContours(sctx, *(rcCompactHeightfield *) chf, maxError, maxEdgeLen, *(rcContourSet *) cset);
return rcBuildContours(sctx, *(rcCompactHeightfield *) chf, maxError, maxEdgeLen, *(rcContourSet *) cset, buildFlags);
}
struct recast_polyMesh *recast_newPolyMesh(void)
@@ -165,10 +256,22 @@ void recast_destroyPolyMesh(struct recast_polyMesh *polyMesh)
rcFreePolyMesh((rcPolyMesh *) polyMesh);
}
int recast_buildPolyMesh(struct recast_contourSet *cset, int nvp, struct recast_polyMesh *mesh)
int recast_buildPolyMesh(struct recast_contourSet *cset, const int nvp, struct recast_polyMesh *mesh)
{
INIT_SCTX();
return rcBuildPolyMesh(sctx, *(rcContourSet *) cset, nvp, * (rcPolyMesh *) mesh);
return rcBuildPolyMesh(sctx, *(rcContourSet *) cset, nvp, *(rcPolyMesh *) mesh);
}
int recast_mergePolyMeshes(struct recast_polyMesh **meshes, const int nmeshes, struct recast_polyMesh *mesh)
{
INIT_SCTX();
return rcMergePolyMeshes(sctx, (rcPolyMesh **) meshes, nmeshes, *(rcPolyMesh *) mesh);
}
int recast_copyPolyMesh(const struct recast_polyMesh *src, struct recast_polyMesh *dst)
{
INIT_SCTX();
return rcCopyPolyMesh(sctx, *(const rcPolyMesh *) src, *(rcPolyMesh *) dst);
}
unsigned short *recast_polyMeshGetVerts(struct recast_polyMesh *mesh, int *nverts)
@@ -240,6 +343,12 @@ int recast_buildPolyMeshDetail(const struct recast_polyMesh *mesh, const struct
sampleDist, sampleMaxError, *(rcPolyMeshDetail *) dmesh);
}
int recast_mergePolyMeshDetails(struct recast_polyMeshDetail **meshes, const int nmeshes, struct recast_polyMeshDetail *mesh)
{
INIT_SCTX();
return rcMergePolyMeshDetails(sctx, (rcPolyMeshDetail **) meshes, nmeshes, *(rcPolyMeshDetail *) mesh);
}
float *recast_polyMeshDetailGetVerts(struct recast_polyMeshDetail *mesh, int *nverts)
{
rcPolyMeshDetail *dmesh = (rcPolyMeshDetail *)mesh;

View File

@@ -38,12 +38,13 @@ struct recast_polyMesh;
struct recast_polyMeshDetail;
struct recast_heightfield;
struct recast_compactHeightfield;
struct recast_heightfieldLayerSet;
struct recast_contourSet;
enum recast_SpanFlags
enum recast_BuildContoursFlags
{
RECAST_WALKABLE = 0x01,
RECAST_REACHABLE = 0x02
RECAST_CONTOUR_TESS_WALL_EDGES = 0x01,
RECAST_CONTOUR_TESS_AREA_EDGES = 0x02,
};
int recast_buildMeshAdjacency(unsigned short* polys, const int npolys,
@@ -61,10 +62,22 @@ int recast_createHeightfield(struct recast_heightfield *hf, int width, int heigh
const float *bmin, const float* bmax, float cs, float ch);
void recast_markWalkableTriangles(const float walkableSlopeAngle,const float *verts, int nv,
const int *tris, int nt, unsigned char *flags);
const int *tris, int nt, unsigned char *areas);
void recast_rasterizeTriangles(const float *verts, int nv, const int *tris,
const unsigned char *flags, int nt, struct recast_heightfield *solid);
void recast_clearUnwalkableTriangles(const float walkableSlopeAngle, const float* verts, int nv,
const int* tris, int nt, unsigned char* areas);
int recast_addSpan(struct recast_heightfield *hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr);
int recast_rasterizeTriangle(const float* v0, const float* v1, const float* v2,
const unsigned char area, struct recast_heightfield *solid,
const int flagMergeThr);
int recast_rasterizeTriangles(const float *verts, const int nv, const int *tris,
const unsigned char *areas, const int nt, struct recast_heightfield *solid,
const int flagMergeThr);
void recast_filterLedgeSpans(const int walkableHeight, const int walkableClimb,
struct recast_heightfield *solid);
@@ -73,6 +86,12 @@ void recast_filterWalkableLowHeightSpans(int walkableHeight, struct recast_heigh
void recast_filterLowHangingWalkableObstacles(const int walkableClimb, struct recast_heightfield *solid);
int recast_getHeightFieldSpanCount(struct recast_heightfield *hf);
struct recast_heightfieldLayerSet *recast_newHeightfieldLayerSet(void);
void recast_destroyHeightfieldLayerSet(struct recast_heightfieldLayerSet *lset);
struct recast_compactHeightfield *recast_newCompactHeightfield(void);
void recast_destroyCompactHeightfield(struct recast_compactHeightfield *compactHeightfield);
@@ -82,10 +101,31 @@ int recast_buildCompactHeightfield(const int walkableHeight, const int walkableC
int recast_erodeWalkableArea(int radius, struct recast_compactHeightfield *chf);
int recast_medianFilterWalkableArea(struct recast_compactHeightfield *chf);
void recast_markBoxArea(const float *bmin, const float *bmax, unsigned char areaId,
struct recast_compactHeightfield *chf);
void recast_markConvexPolyArea(const float* verts, const int nverts,
const float hmin, const float hmax, unsigned char areaId,
struct recast_compactHeightfield *chf);
int recast_offsetPoly(const float* verts, const int nverts,
const float offset, float *outVerts, const int maxOutVerts);
void recast_markCylinderArea(const float* pos, const float r, const float h,
unsigned char areaId, struct recast_compactHeightfield *chf);
int recast_buildDistanceField(struct recast_compactHeightfield *chf);
int recast_buildRegions(struct recast_compactHeightfield *chf, int borderSize,
int minRegionSize, int mergeRegionSize);
int recast_buildRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea);
int recast_buildLayerRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea);
int recast_buildRegionsMonotone(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea);
/* Contour set */
@@ -94,7 +134,8 @@ struct recast_contourSet *recast_newContourSet(void);
void recast_destroyContourSet(struct recast_contourSet *contourSet);
int recast_buildContours(struct recast_compactHeightfield *chf,
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset);
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset,
const int buildFlags);
/* Poly mesh */
@@ -102,7 +143,11 @@ struct recast_polyMesh *recast_newPolyMesh(void);
void recast_destroyPolyMesh(struct recast_polyMesh *polyMesh);
int recast_buildPolyMesh(struct recast_contourSet *cset, int nvp, struct recast_polyMesh *mesh);
int recast_buildPolyMesh(struct recast_contourSet *cset, const int nvp, struct recast_polyMesh *mesh);
int recast_mergePolyMeshes(struct recast_polyMesh **meshes, const int nmeshes, struct recast_polyMesh *mesh);
int recast_copyPolyMesh(const struct recast_polyMesh *src, struct recast_polyMesh *dst);
unsigned short *recast_polyMeshGetVerts(struct recast_polyMesh *mesh, int *nverts);
@@ -121,6 +166,8 @@ void recast_destroyPolyMeshDetail(struct recast_polyMeshDetail *polyMeshDetail);
int recast_buildPolyMeshDetail(const struct recast_polyMesh *mesh, const struct recast_compactHeightfield *chf,
const float sampleDist, const float sampleMaxError, struct recast_polyMeshDetail *dmesh);
int recast_mergePolyMeshDetails(struct recast_polyMeshDetail **meshes, const int nmeshes, struct recast_polyMeshDetail *mesh);
float *recast_polyMeshDetailGetVerts(struct recast_polyMeshDetail *mesh, int *nverts);
unsigned char *recast_polyMeshDetailGetTris(struct recast_polyMeshDetail *mesh, int *ntris);

View File

@@ -1,250 +0,0 @@
#!/bin/bash
SDL="SDL2"
INCLUDE_DIR="/usr/include/${SDL}"
SCRIPT=`realpath -s $0`
DIR=`dirname $SCRIPT`
DIR=`dirname $DIR`
mkdir -p $DIR/include/${SDL}
mkdir -p $DIR/src
rm -rf $DIR/include/${SDL}/*.h
rm -rf $DIR/src/sdlew.c
echo "Generating sdlew headers..."
UNSUPPORTED="SDL_MemoryBarrierRelease SDL_MemoryBarrierAcquire SDL_AtomicCAS SDL_AtomicCASPtr \
SDL_iPhoneSetAnimationCallback SDL_iPhoneSetEventPump SDL_AndroidGetJNIEnv SDL_AndroidGetActivity \
SDL_AndroidGetActivity SDL_AndroidGetInternalStoragePath SDL_AndroidGetExternalStorageState \
SDL_AndroidGetExternalStoragePath SDL_CreateShapedWindow SDL_IsShapedWindow tSDL_SetWindowShape \
SDL_GetShapedWindowMode"
for header in $INCLUDE_DIR/*; do
filename=`basename $header`
cat $header \
| sed -r 's/extern DECLSPEC ((const )?[a-z0-9_]+(\s\*)?)\s?SDLCALL /typedef \1 SDLCALL t/i' \
> $DIR/include/${SDL}/$filename
line_num=`cat $DIR/include/${SDL}/$filename | grep -n "Ends C function" | cut -d : -f 1`
if [ ! -z "$line_num" ]; then
functions=`grep -E 'typedef [A-Za-z0-9_ \*]+ SDLCALL' $DIR/include/${SDL}/$filename \
| sed -r 's/typedef [A-Za-z0-9_ \*]+ SDLCALL t([a-z0-9_]+).*/extern t\1 *\1;/i'`
functions=`echo "${functions}" | sed -e 's/[\/&]/\\\&/g'`
echo "$functions" | while read function; do
if [ -z "$function" ]; then
continue;
fi
func_name=`echo $function | cut -d '*' -f 2 | sed -r 's/;//'`
if [ ! -z "`echo "$UNSUPPORTED" | grep $func_name`" ]; then
continue;
fi
if [ "$func_name" == "SDL_memcpy" ]; then
line_num=`cat $DIR/include/${SDL}/$filename | grep -n "SDL_memcpy4" | cut -d : -f 1`
sed -ri "${line_num}s/(.*)/${function}\n\1/" $DIR/include/${SDL}/$filename
else
sed -ri "${line_num}s/(.*)/${function}\n\1/" $DIR/include/${SDL}/$filename
fi
line_num=`cat $DIR/include/${SDL}/$filename | grep -n "Ends C function" | cut -d : -f 1`
done
line_num=`cat $DIR/include/${SDL}/$filename | grep -n "Ends C function" | cut -d : -f 1`
sed -ri "${line_num}s/(.*)/\n\1/" $DIR/include/${SDL}/$filename
fi
if [ $filename == "SDL_stdinc.h" ]; then
cat $header | grep -E '#if(def)? (defined\()?HAVE_' | sed -r 's/#if(def)? //' | while read check; do
func_names=`cat $DIR/include/${SDL}/$filename \
| grep -A 8 "$check\$" \
| grep -v struct \
| grep 'typedef' \
| sed -r 's/typedef [a-z0-9_ \*]+ SDLCALL ([a-z0-9_]+).*/\1/i'`
full_check=`echo "${check}" | sed -e 's/[\/&]/\\\&/g'`
if [ ! -z "`echo $full_check | grep defined`" ]; then
full_check="#if !($full_check)"
else
full_check="#ifndef $full_check"
fi
for func_name in $func_names; do
line_num=`grep -n "extern ${func_name} \*" $DIR/include/${SDL}/$filename | cut -d : -f 1`
let prev_num=line_num-1
if [ -z "`cat $DIR/include/${SDL}/$filename | head -n $prev_num | tail -n 1 | grep '#if'`" ]; then
sed -ri "${line_num}s/(.*)/$full_check \/* GEN_CHECK_MARKER *\/\n\1\n#endif \/* GEN_CHECK_MARKER *\//" $DIR/include/${SDL}/$filename
fi
done
done
fi
done
cat << EOF > $DIR/include/sdlew.h
/*
* Copyright 2014 Blender Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
#ifndef __SDL_EW_H__
#define __SDL_EW_H__
#ifdef __cplusplus
extern "C" {
#endif
enum {
SDLEW_SUCCESS = 0,
SDLEW_ERROR_OPEN_FAILED = -1,
SDLEW_ERROR_ATEXIT_FAILED = -2,
SDLEW_ERROR_VERSION = -3,
};
int sdlewInit(void);
#ifdef __cplusplus
}
#endif
#endif /* __SDL_EW_H__ */
EOF
echo "Generating sdlew sources..."
cat << EOF > $DIR/src/sdlew.c
/*
* Copyright 2014 Blender Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
#ifdef _MSC_VER
# define snprintf _snprintf
# define popen _popen
# define pclose _pclose
# define _CRT_SECURE_NO_WARNINGS
#endif
#include "sdlew.h"
#include "${SDL}/SDL.h"
#include "${SDL}/SDL_syswm.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# include <windows.h>
/* Utility macros. */
typedef HMODULE DynamicLibrary;
# define dynamic_library_open(path) LoadLibrary(path)
# define dynamic_library_close(lib) FreeLibrary(lib)
# define dynamic_library_find(lib, symbol) GetProcAddress(lib, symbol)
#else
# include <dlfcn.h>
typedef void* DynamicLibrary;
# define dynamic_library_open(path) dlopen(path, RTLD_NOW)
# define dynamic_library_close(lib) dlclose(lib)
# define dynamic_library_find(lib, symbol) dlsym(lib, symbol)
#endif
#define SDL_LIBRARY_FIND_CHECKED(name) \
name = (t##name *)dynamic_library_find(lib, #name); \
assert(name);
#define SDL_LIBRARY_FIND(name) \
name = (t##name *)dynamic_library_find(lib, #name);
static DynamicLibrary lib;
EOF
content=`grep --no-filename -ER "extern tSDL|GEN_CHECK_MARKER" $DIR/include/${SDL}/`
echo "$content" | sed -r 's/extern t([a-z0-9_]+).*/t\1 *\1;/gi' >> $DIR/src/sdlew.c
cat << EOF >> $DIR/src/sdlew.c
static void sdlewExit(void) {
if(lib != NULL) {
/* Ignore errors. */
dynamic_library_close(lib);
lib = NULL;
}
}
/* Implementation function. */
int sdlewInit(void) {
/* Library paths. */
#ifdef _WIN32
/* Expected in c:/windows/system or similar, no path needed. */
const char *path = "SDL2.dll";
#elif defined(__APPLE__)
/* Default installation path. */
const char *path = "/usr/local/cuda/lib/libSDL2.dylib";
#else
const char *path = "libSDL2.so";
#endif
static int initialized = 0;
static int result = 0;
int error;
if (initialized) {
return result;
}
initialized = 1;
error = atexit(sdlewExit);
if (error) {
result = SDLEW_ERROR_ATEXIT_FAILED;
return result;
}
/* Load library. */
lib = dynamic_library_open(path);
if (lib == NULL) {
result = SDLEW_ERROR_OPEN_FAILED;
return result;
}
EOF
echo "$content" | sed -r 's/extern t([a-z0-9_]+).*/ SDL_LIBRARY_FIND(\1);/gi' >> $DIR/src/sdlew.c
cat << EOF >> $DIR/src/sdlew.c
result = SDLEW_SUCCESS;
return result;
}
EOF
sed -i 's/\s\/\* GEN_CHECK_MARKER \*\///g' $DIR/src/sdlew.c
sed -i 's/\s\/\* GEN_CHECK_MARKER \*\///g' $DIR/include/${SDL}/SDL_stdinc.h

View File

@@ -1,15 +0,0 @@
#!/bin/bash
SDL="SDL2"
INCLUDE_DIR="/usr/include/${SDL}"
SCRIPT=`realpath -s $0`
DIR=`dirname $SCRIPT`
DIR=`dirname $DIR`
for f in $DIR/include/${SDL}/*.h; do
file_name=`basename $f`
echo "Striping $file_name..."
sed -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' -i $f
sed 's/[ \t]*$//' -i $f
sed '/^$/N;/^\n$/D' -i $f
done

View File

@@ -1,11 +1,11 @@
/*
* Adopted from jemalloc with this license:
* Original code from jemalloc with this license:
*
* Copyright (C) 2002-2013 Jason Evans <jasone@canonware.com>.
* All rights reserved.
* Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
* Copyright (C) 2009-2013 Facebook, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice(s),
@@ -13,7 +13,7 @@
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
@@ -24,63 +24,59 @@
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2016 Blender Foundation.
* All rights reserved.
*
* The Original Code is: adapted from jemalloc.
*
* ***** END GPL LICENSE BLOCK *****
*/
/**
* \file atomic_ops.h
* \ingroup Atomic
*
* \author Copyright (C) 2016 Blender Foundation, adapted from jemalloc.
* \brief Provides wrapper around system-specific atomic primitives, and some extensions (faked-atomic operations
* over float numbers).
*/
#ifndef __ATOMIC_OPS_H__
#define __ATOMIC_OPS_H__
#include <assert.h>
#if defined (__APPLE__)
# include <libkern/OSAtomic.h>
#elif defined(_MSC_VER)
# define NOGDI
# ifndef NOMINMAX
# define NOMINMAX
# endif
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#elif defined(__arm__)
#if defined(__arm__)
/* Attempt to fix compilation error on Debian armel kernel.
* arm7 architecture does have both 32 and 64bit atomics, however
* it's gcc doesn't have __GCC_HAVE_SYNC_COMPARE_AND_SWAP_n defined.
*/
# define JE_FORCE_SYNC_COMPARE_AND_SWAP_8
# define JE_FORCE_SYNC_COMPARE_AND_SWAP_1
# define JE_FORCE_SYNC_COMPARE_AND_SWAP_4
# define JE_FORCE_SYNC_COMPARE_AND_SWAP_8
#endif
/* needed for int types */
#include "../../source/blender/blenlib/BLI_sys_types.h"
#include <stdlib.h>
#include <stddef.h>
#include "intern/atomic_ops_utils.h"
/* little macro so inline keyword works */
#if defined(_MSC_VER)
# define ATOMIC_INLINE static __forceinline
#else
# if (defined(__APPLE__) && defined(__ppc__))
/* static inline __attribute__ here breaks osx ppc gcc42 build */
# define ATOMIC_INLINE static __attribute__((always_inline))
# else
# define ATOMIC_INLINE static inline __attribute__((always_inline))
# endif
#endif
/* This is becoming a bit nastier that it was originally foreseen,
* consider using autoconfig detection instead.
*/
#if defined(_M_X64) || defined(__amd64__) || defined(__x86_64__) || defined(__s390x__) || defined(__powerpc64__) || defined(__aarch64__) || (defined(__sparc__) && defined(__arch64__)) || defined(__alpha__) || defined(__mips64)
# define LG_SIZEOF_PTR 3
# define LG_SIZEOF_INT 2
#else
# define LG_SIZEOF_PTR 2
# define LG_SIZEOF_INT 2
#endif
/************************/
/******************************************************************************/
/* Function prototypes. */
#if (LG_SIZEOF_PTR == 3 || LG_SIZEOF_INT == 3)
#if (LG_SIZEOF_PTR == 8 || LG_SIZEOF_INT == 8)
ATOMIC_INLINE uint64_t atomic_add_uint64(uint64_t *p, uint64_t x);
ATOMIC_INLINE uint64_t atomic_sub_uint64(uint64_t *p, uint64_t x);
ATOMIC_INLINE uint64_t atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new);
@@ -90,6 +86,9 @@ ATOMIC_INLINE uint32_t atomic_add_uint32(uint32_t *p, uint32_t x);
ATOMIC_INLINE uint32_t atomic_sub_uint32(uint32_t *p, uint32_t x);
ATOMIC_INLINE uint32_t atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new);
ATOMIC_INLINE uint32_t atomic_fetch_and_add_uint32(uint32_t *p, uint32_t x);
ATOMIC_INLINE uint8_t atomic_fetch_and_or_uint8(uint8_t *p, uint8_t b);
ATOMIC_INLINE uint8_t atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b);
ATOMIC_INLINE size_t atomic_add_z(size_t *p, size_t x);
@@ -100,395 +99,22 @@ ATOMIC_INLINE unsigned atomic_add_u(unsigned *p, unsigned x);
ATOMIC_INLINE unsigned atomic_sub_u(unsigned *p, unsigned x);
ATOMIC_INLINE unsigned atomic_cas_u(unsigned *v, unsigned old, unsigned _new);
/******************************************************************************/
/* 64-bit operations. */
#if (LG_SIZEOF_PTR == 3 || LG_SIZEOF_INT == 3)
# ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8
ATOMIC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
return __sync_add_and_fetch(p, x);
}
ATOMIC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return __sync_sub_and_fetch(p, x);
}
ATOMIC_INLINE uint64_t
atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
return __sync_val_compare_and_swap(v, old, _new);
}
#elif (defined(_MSC_VER))
ATOMIC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
return InterlockedExchangeAdd64((int64_t *)p, (int64_t)x) + x;
}
ATOMIC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return InterlockedExchangeAdd64((int64_t *)p, -((int64_t)x)) - x;
}
ATOMIC_INLINE uint64_t
atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
return InterlockedCompareExchange64((int64_t *)v, _new, old);
}
#elif (defined(__APPLE__))
ATOMIC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
return (uint64_t)OSAtomicAdd64((int64_t)x, (int64_t *)p);
}
ATOMIC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return (uint64_t)OSAtomicAdd64(-((int64_t)x), (int64_t *)p);
}
ATOMIC_INLINE uint64_t
atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
uint64_t init_val = *v;
OSAtomicCompareAndSwap64((int64_t)old, (int64_t)_new, (int64_t *)v);
return init_val;
}
# elif (defined(__amd64__) || defined(__x86_64__))
ATOMIC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
asm volatile (
"lock; xaddq %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
x = (uint64_t)(-(int64_t)x);
asm volatile (
"lock; xaddq %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint64_t
atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
uint64_t ret;
asm volatile (
"lock; cmpxchgq %2,%1"
: "=a" (ret), "+m" (*v)
: "r" (_new), "0" (old)
: "memory");
return ret;
}
# elif (defined(JEMALLOC_ATOMIC9))
ATOMIC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
/*
* atomic_fetchadd_64() doesn't exist, but we only ever use this
* function on LP64 systems, so atomic_fetchadd_long() will do.
*/
assert(sizeof(uint64_t) == sizeof(unsigned long));
return atomic_fetchadd_long(p, (unsigned long)x) + x;
}
ATOMIC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
assert(sizeof(uint64_t) == sizeof(unsigned long));
return atomic_fetchadd_long(p, (unsigned long)(-(long)x)) - x;
}
ATOMIC_INLINE uint64_t
atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
assert(sizeof(uint64_t) == sizeof(unsigned long));
return atomic_cmpset_long(v, old, _new);
}
# elif (defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_8))
ATOMIC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
return __sync_add_and_fetch(p, x);
}
ATOMIC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return __sync_sub_and_fetch(p, x);
}
ATOMIC_INLINE uint64_t
atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
return __sync_val_compare_and_swap(v, old, _new);
}
# else
# error "Missing implementation for 64-bit atomic operations"
# endif
#endif
/* WARNING! Float 'atomics' are really faked ones, those are actually closer to some kind of spinlock-sync'ed operation,
* which means they are only efficient if collisions are highly unlikely (i.e. if probability of two threads
* working on the same pointer at the same time is very low). */
ATOMIC_INLINE float atomic_add_fl(float *p, const float x);
/******************************************************************************/
/* 32-bit operations. */
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
ATOMIC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return __sync_add_and_fetch(p, x);
}
/* Include system-dependent implementations. */
ATOMIC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return __sync_sub_and_fetch(p, x);
}
ATOMIC_INLINE uint32_t
atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
return __sync_val_compare_and_swap(v, old, _new);
}
#elif (defined(_MSC_VER))
ATOMIC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return InterlockedExchangeAdd(p, x) + x;
}
ATOMIC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return InterlockedExchangeAdd(p, -((int32_t)x)) - x;
}
ATOMIC_INLINE uint32_t
atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
return InterlockedCompareExchange((long *)v, _new, old);
}
#elif (defined(__APPLE__))
ATOMIC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return (uint32_t)OSAtomicAdd32((int32_t)x, (int32_t *)p);
}
ATOMIC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return (uint32_t)OSAtomicAdd32(-((int32_t)x), (int32_t *)p);
}
ATOMIC_INLINE uint32_t
atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
uint32_t init_val = *v;
OSAtomicCompareAndSwap32((int32_t)old, (int32_t)_new, (int32_t *)v);
return init_val;
}
#elif (defined(__i386__) || defined(__amd64__) || defined(__x86_64__))
ATOMIC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
asm volatile (
"lock; xaddl %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
x = (uint32_t)(-(int32_t)x);
asm volatile (
"lock; xaddl %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint32_t
atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
uint32_t ret;
asm volatile (
"lock; cmpxchgl %2,%1"
: "=a" (ret), "+m" (*v)
: "r" (_new), "0" (old)
: "memory");
return ret;
}
#elif (defined(JEMALLOC_ATOMIC9))
ATOMIC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return atomic_fetchadd_32(p, x) + x;
}
ATOMIC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return atomic_fetchadd_32(p, (uint32_t)(-(int32_t)x)) - x;
}
ATOMIC_INLINE uint32_t
atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
return atomic_cmpset_32(v, old, _new);
}
#elif defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_4)
ATOMIC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return __sync_add_and_fetch(p, x);
}
ATOMIC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return __sync_sub_and_fetch(p, x);
}
ATOMIC_INLINE uint32_t
atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
return __sync_val_compare_and_swap(v, old, _new);
}
/* Note that we are using _unix flavor as fallback here (it will raise precompiler errors as needed). */
#if defined(_MSC_VER)
# include "intern/atomic_ops_msvc.h"
#else
# error "Missing implementation for 32-bit atomic operations"
# include "intern/atomic_ops_unix.h"
#endif
/******************************************************************************/
/* 8-bit operations. */
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1
ATOMIC_INLINE uint8_t
atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b)
{
return __sync_fetch_and_and(p, b);
}
#elif (defined(_MSC_VER))
#include <intrin.h>
#pragma intrinsic(_InterlockedAnd8)
ATOMIC_INLINE uint8_t
atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b)
{
#if (LG_SIZEOF_PTR == 3 || LG_SIZEOF_INT == 3)
return InterlockedAnd8((char *)p, (char)b);
#else
return _InterlockedAnd8((char *)p, (char)b);
#endif
}
#else
# error "Missing implementation for 8-bit atomic operations"
#endif
/******************************************************************************/
/* size_t operations. */
ATOMIC_INLINE size_t
atomic_add_z(size_t *p, size_t x)
{
assert(sizeof(size_t) == 1 << LG_SIZEOF_PTR);
#if (LG_SIZEOF_PTR == 3)
return (size_t)atomic_add_uint64((uint64_t *)p, (uint64_t)x);
#elif (LG_SIZEOF_PTR == 2)
return (size_t)atomic_add_uint32((uint32_t *)p, (uint32_t)x);
#endif
}
ATOMIC_INLINE size_t
atomic_sub_z(size_t *p, size_t x)
{
assert(sizeof(size_t) == 1 << LG_SIZEOF_PTR);
#if (LG_SIZEOF_PTR == 3)
return (size_t)atomic_add_uint64((uint64_t *)p,
(uint64_t)-((int64_t)x));
#elif (LG_SIZEOF_PTR == 2)
return (size_t)atomic_add_uint32((uint32_t *)p,
(uint32_t)-((int32_t)x));
#endif
}
ATOMIC_INLINE size_t
atomic_cas_z(size_t *v, size_t old, size_t _new)
{
assert(sizeof(size_t) == 1 << LG_SIZEOF_PTR);
#if (LG_SIZEOF_PTR == 3)
return (size_t)atomic_cas_uint64((uint64_t *)v,
(uint64_t)old,
(uint64_t)_new);
#elif (LG_SIZEOF_PTR == 2)
return (size_t)atomic_cas_uint32((uint32_t *)v,
(uint32_t)old,
(uint32_t)_new);
#endif
}
/******************************************************************************/
/* unsigned operations. */
ATOMIC_INLINE unsigned
atomic_add_u(unsigned *p, unsigned x)
{
assert(sizeof(unsigned) == 1 << LG_SIZEOF_INT);
#if (LG_SIZEOF_INT == 3)
return (unsigned)atomic_add_uint64((uint64_t *)p, (uint64_t)x);
#elif (LG_SIZEOF_INT == 2)
return (unsigned)atomic_add_uint32((uint32_t *)p, (uint32_t)x);
#endif
}
ATOMIC_INLINE unsigned
atomic_sub_u(unsigned *p, unsigned x)
{
assert(sizeof(unsigned) == 1 << LG_SIZEOF_INT);
#if (LG_SIZEOF_INT == 3)
return (unsigned)atomic_add_uint64((uint64_t *)p,
(uint64_t)-((int64_t)x));
#elif (LG_SIZEOF_INT == 2)
return (unsigned)atomic_add_uint32((uint32_t *)p,
(uint32_t)-((int32_t)x));
#endif
}
ATOMIC_INLINE unsigned
atomic_cas_u(unsigned *v, unsigned old, unsigned _new)
{
assert(sizeof(unsigned) == 1 << LG_SIZEOF_INT);
#if (LG_SIZEOF_PTR == 3)
return (unsigned)atomic_cas_uint64((uint64_t *)v,
(uint64_t)old,
(uint64_t)_new);
#elif (LG_SIZEOF_PTR == 2)
return (unsigned)atomic_cas_uint32((uint32_t *)v,
(uint32_t)old,
(uint32_t)_new);
#endif
}
/* Include 'fake' atomic extensions, built over real atomic primitives. */
#include "intern/atomic_ops_ext.h"
#endif /* __ATOMIC_OPS_H__ */

View File

@@ -0,0 +1,146 @@
/*
* Original code from jemalloc with this license:
*
* Copyright (C) 2002-2013 Jason Evans <jasone@canonware.com>.
* All rights reserved.
* Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
* Copyright (C) 2009-2013 Facebook, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2016 Blender Foundation.
* All rights reserved.
*
* The Original Code is: adapted from jemalloc.
*
* ***** END GPL LICENSE BLOCK *****
*/
#ifndef __ATOMIC_OPS_EXT_H__
#define __ATOMIC_OPS_EXT_H__
#include "atomic_ops_utils.h"
/******************************************************************************/
/* size_t operations. */
ATOMIC_INLINE size_t atomic_add_z(size_t *p, size_t x)
{
assert(sizeof(size_t) == LG_SIZEOF_PTR);
#if (LG_SIZEOF_PTR == 8)
return (size_t)atomic_add_uint64((uint64_t *)p, (uint64_t)x);
#elif (LG_SIZEOF_PTR == 4)
return (size_t)atomic_add_uint32((uint32_t *)p, (uint32_t)x);
#endif
}
ATOMIC_INLINE size_t atomic_sub_z(size_t *p, size_t x)
{
assert(sizeof(size_t) == LG_SIZEOF_PTR);
#if (LG_SIZEOF_PTR == 8)
return (size_t)atomic_add_uint64((uint64_t *)p, (uint64_t)-((int64_t)x));
#elif (LG_SIZEOF_PTR == 4)
return (size_t)atomic_add_uint32((uint32_t *)p, (uint32_t)-((int32_t)x));
#endif
}
ATOMIC_INLINE size_t atomic_cas_z(size_t *v, size_t old, size_t _new)
{
assert(sizeof(size_t) == LG_SIZEOF_PTR);
#if (LG_SIZEOF_PTR == 8)
return (size_t)atomic_cas_uint64((uint64_t *)v, (uint64_t)old, (uint64_t)_new);
#elif (LG_SIZEOF_PTR == 4)
return (size_t)atomic_cas_uint32((uint32_t *)v, (uint32_t)old, (uint32_t)_new);
#endif
}
/******************************************************************************/
/* unsigned operations. */
ATOMIC_INLINE unsigned atomic_add_u(unsigned *p, unsigned x)
{
assert(sizeof(unsigned) == LG_SIZEOF_INT);
#if (LG_SIZEOF_INT == 8)
return (unsigned)atomic_add_uint64((uint64_t *)p, (uint64_t)x);
#elif (LG_SIZEOF_INT == 4)
return (unsigned)atomic_add_uint32((uint32_t *)p, (uint32_t)x);
#endif
}
ATOMIC_INLINE unsigned atomic_sub_u(unsigned *p, unsigned x)
{
assert(sizeof(unsigned) == LG_SIZEOF_INT);
#if (LG_SIZEOF_INT == 8)
return (unsigned)atomic_add_uint64((uint64_t *)p, (uint64_t)-((int64_t)x));
#elif (LG_SIZEOF_INT == 4)
return (unsigned)atomic_add_uint32((uint32_t *)p, (uint32_t)-((int32_t)x));
#endif
}
ATOMIC_INLINE unsigned atomic_cas_u(unsigned *v, unsigned old, unsigned _new)
{
assert(sizeof(unsigned) == LG_SIZEOF_INT);
#if (LG_SIZEOF_INT == 8)
return (unsigned)atomic_cas_uint64((uint64_t *)v, (uint64_t)old, (uint64_t)_new);
#elif (LG_SIZEOF_INT == 4)
return (unsigned)atomic_cas_uint32((uint32_t *)v, (uint32_t)old, (uint32_t)_new);
#endif
}
/******************************************************************************/
/* float operations. */
ATOMIC_INLINE float atomic_add_fl(float *p, const float x)
{
assert(sizeof(float) == sizeof(uint32_t));
float oldval, newval;
uint32_t prevval;
do { /* Note that since collisions are unlikely, loop will nearly always run once. */
oldval = *p;
newval = oldval + x;
prevval = atomic_cas_uint32((uint32_t *)p, *(uint32_t *)(&oldval), *(uint32_t *)(&newval));
} while (UNLIKELY(prevval != *(uint32_t *)(&oldval)));
return newval;
}
#endif /* __ATOMIC_OPS_EXT_H__ */

View File

@@ -0,0 +1,107 @@
/*
* Adopted from jemalloc with this license:
*
* Copyright (C) 2002-2013 Jason Evans <jasone@canonware.com>.
* All rights reserved.
* Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
* Copyright (C) 2009-2013 Facebook, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ATOMIC_OPS_MSVC_H__
#define __ATOMIC_OPS_MSVC_H__
#include "atomic_ops_utils.h"
#define NOGDI
#ifndef NOMINMAX
# define NOMINMAX
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <intrin.h>
/******************************************************************************/
/* 64-bit operations. */
#if (LG_SIZEOF_PTR == 8 || LG_SIZEOF_INT == 8)
ATOMIC_INLINE uint64_t atomic_add_uint64(uint64_t *p, uint64_t x)
{
return InterlockedExchangeAdd64((int64_t *)p, (int64_t)x) + x;
}
ATOMIC_INLINE uint64_t atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return InterlockedExchangeAdd64((int64_t *)p, -((int64_t)x)) - x;
}
ATOMIC_INLINE uint64_t atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
return InterlockedCompareExchange64((int64_t *)v, _new, old);
}
#endif
/******************************************************************************/
/* 32-bit operations. */
ATOMIC_INLINE uint32_t atomic_add_uint32(uint32_t *p, uint32_t x)
{
return InterlockedExchangeAdd(p, x) + x;
}
ATOMIC_INLINE uint32_t atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return InterlockedExchangeAdd(p, -((int32_t)x)) - x;
}
ATOMIC_INLINE uint32_t atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
return InterlockedCompareExchange((long *)v, _new, old);
}
ATOMIC_INLINE uint32_t atomic_fetch_and_add_uint32(uint32_t *p, uint32_t x)
{
return InterlockedExchangeAdd(p, x);
}
/******************************************************************************/
/* 8-bit operations. */
#pragma intrinsic(_InterlockedAnd8)
ATOMIC_INLINE uint8_t atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b)
{
#if (LG_SIZEOF_PTR == 8 || LG_SIZEOF_INT == 8)
return InterlockedAnd8((char *)p, (char)b);
#else
return _InterlockedAnd8((char *)p, (char)b);
#endif
}
#pragma intrinsic(_InterlockedOr8)
ATOMIC_INLINE uint8_t atomic_fetch_and_or_uint8(uint8_t *p, uint8_t b)
{
#if (LG_SIZEOF_PTR == 8 || LG_SIZEOF_INT == 8)
return InterlockedOr8((char *)p, (char)b);
#else
return _InterlockedOr8((char *)p, (char)b);
#endif
}
#endif /* __ATOMIC_OPS_MSVC_H__ */

View File

@@ -0,0 +1,190 @@
/*
* Original code from jemalloc with this license:
*
* Copyright (C) 2002-2013 Jason Evans <jasone@canonware.com>.
* All rights reserved.
* Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
* Copyright (C) 2009-2013 Facebook, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2016 Blender Foundation.
* All rights reserved.
*
* The Original Code is: adapted from jemalloc.
*
* ***** END GPL LICENSE BLOCK *****
*/
#ifndef __ATOMIC_OPS_UNIX_H__
#define __ATOMIC_OPS_UNIX_H__
#include "atomic_ops_utils.h"
/******************************************************************************/
/* 64-bit operations. */
#if (LG_SIZEOF_PTR == 8 || LG_SIZEOF_INT == 8)
# if (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) || defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_8))
ATOMIC_INLINE uint64_t atomic_add_uint64(uint64_t *p, uint64_t x)
{
return __sync_add_and_fetch(p, x);
}
ATOMIC_INLINE uint64_t atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return __sync_sub_and_fetch(p, x);
}
ATOMIC_INLINE uint64_t atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
return __sync_val_compare_and_swap(v, old, _new);
}
# elif (defined(__amd64__) || defined(__x86_64__))
ATOMIC_INLINE uint64_t atomic_add_uint64(uint64_t *p, uint64_t x)
{
asm volatile (
"lock; xaddq %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint64_t atomic_sub_uint64(uint64_t *p, uint64_t x)
{
x = (uint64_t)(-(int64_t)x);
asm volatile (
"lock; xaddq %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint64_t atomic_cas_uint64(uint64_t *v, uint64_t old, uint64_t _new)
{
uint64_t ret;
asm volatile (
"lock; cmpxchgq %2,%1"
: "=a" (ret), "+m" (*v)
: "r" (_new), "0" (old)
: "memory");
return ret;
}
# else
# error "Missing implementation for 64-bit atomic operations"
# endif
#endif
/******************************************************************************/
/* 32-bit operations. */
#if (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_4))
ATOMIC_INLINE uint32_t atomic_add_uint32(uint32_t *p, uint32_t x)
{
return __sync_add_and_fetch(p, x);
}
ATOMIC_INLINE uint32_t atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return __sync_sub_and_fetch(p, x);
}
ATOMIC_INLINE uint32_t atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
return __sync_val_compare_and_swap(v, old, _new);
}
#elif (defined(__i386__) || defined(__amd64__) || defined(__x86_64__))
ATOMIC_INLINE uint32_t atomic_add_uint32(uint32_t *p, uint32_t x)
{
asm volatile (
"lock; xaddl %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint32_t atomic_sub_uint32(uint32_t *p, uint32_t x)
{
x = (uint32_t)(-(int32_t)x);
asm volatile (
"lock; xaddl %0, %1;"
: "+r" (x), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return x;
}
ATOMIC_INLINE uint32_t atomic_cas_uint32(uint32_t *v, uint32_t old, uint32_t _new)
{
uint32_t ret;
asm volatile (
"lock; cmpxchgl %2,%1"
: "=a" (ret), "+m" (*v)
: "r" (_new), "0" (old)
: "memory");
return ret;
}
#else
# error "Missing implementation for 32-bit atomic operations"
#endif
#if (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_4))
ATOMIC_INLINE uint32_t atomic_fetch_and_add_uint32(uint32_t *p, uint32_t x)
{
return __sync_fetch_and_add(p, x);
}
#else
# error "Missing implementation for 32-bit atomic operations"
#endif
/******************************************************************************/
/* 8-bit operations. */
#if (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1) || defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_1))
ATOMIC_INLINE uint8_t atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b)
{
return __sync_fetch_and_and(p, b);
}
ATOMIC_INLINE uint8_t atomic_fetch_and_or_uint8(uint8_t *p, uint8_t b)
{
return __sync_fetch_and_or(p, b);
}
#else
# error "Missing implementation for 8-bit atomic operations"
#endif
#endif /* __ATOMIC_OPS_UNIX_H__ */

View File

@@ -0,0 +1,110 @@
/*
* Original code from jemalloc with this license:
*
* Copyright (C) 2002-2013 Jason Evans <jasone@canonware.com>.
* All rights reserved.
* Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
* Copyright (C) 2009-2013 Facebook, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2016 Blender Foundation.
* All rights reserved.
*
* The Original Code is: adapted from jemalloc.
*
* ***** END GPL LICENSE BLOCK *****
*/
#ifndef __ATOMIC_OPS_UTILS_H__
#define __ATOMIC_OPS_UTILS_H__
/* needed for int types */
#include "../../../source/blender/blenlib/BLI_sys_types.h"
#include <stdlib.h>
#include <limits.h>
#include <assert.h>
/* little macro so inline keyword works */
#if defined(_MSC_VER)
# define ATOMIC_INLINE static __forceinline
#else
# if (defined(__APPLE__) && defined(__ppc__))
/* static inline __attribute__ here breaks osx ppc gcc42 build */
# define ATOMIC_INLINE static __attribute__((always_inline))
# else
# define ATOMIC_INLINE static inline __attribute__((always_inline))
# endif
#endif
#ifndef LIKELY
# ifdef __GNUC__
# define LIKELY(x) __builtin_expect(!!(x), 1)
# define UNLIKELY(x) __builtin_expect(!!(x), 0)
# else
# define LIKELY(x) (x)
# define UNLIKELY(x) (x)
# endif
#endif
#ifdef UINTPTR_MAX
# if (UINTPTR_MAX == 0xFFFFFFFF)
# define LG_SIZEOF_PTR 4
# elif (UINTPTR_MAX == 0xFFFFFFFFFFFFFFFF)
# define LG_SIZEOF_PTR 8
# endif
#elif defined(__WORDSIZE) /* Fallback for older glibc and cpp */
# if (__WORDSIZE == 32)
# define LG_SIZEOF_PTR 4
# elif (__WORDSIZE == 64)
# define LG_SIZEOF_PTR 8
# endif
#endif
#ifndef LG_SIZEOF_PTR
# error "Cannot find pointer size"
#endif
#if (UINT_MAX == 0xFFFFFFFF)
# define LG_SIZEOF_INT 4
#elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF)
# define LG_SIZEOF_INT 8
#else
# error "Cannot find int size"
#endif
#endif /* __ATOMIC_OPS_UTILS_H__ */

View File

@@ -14,7 +14,15 @@ include(cmake/external_libs.cmake)
# todo: this code could be refactored a bit to avoid duplication
# note: CXX_HAS_SSE is needed in case passing SSE flags fails altogether (gcc-arm)
if(NOT WITH_CPU_SSE)
if(WITH_CYCLES_NATIVE_ONLY)
set(CXX_HAS_SSE FALSE)
set(CXX_HAS_AVX FALSE)
set(CXX_HAS_AVX2 FALSE)
add_definitions(
-DWITH_KERNEL_NATIVE
)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
elseif(NOT WITH_CPU_SSE)
set(CXX_HAS_SSE FALSE)
set(CXX_HAS_AVX FALSE)
set(CXX_HAS_AVX2 FALSE)
@@ -145,7 +153,9 @@ set(WITH_CYCLES_DEVICE_MULTI TRUE)
if(CYCLES_STANDALONE_REPOSITORY)
TEST_UNORDERED_MAP_SUPPORT()
endif()
if(HAVE_STD_UNORDERED_MAP_HEADER)
if(WITH_CXX11)
add_definitions(-DCYCLES_STD_UNORDERED_MAP)
elseif(HAVE_STD_UNORDERED_MAP_HEADER)
if(HAVE_UNORDERED_MAP_IN_STD_NAMESPACE)
add_definitions(-DCYCLES_STD_UNORDERED_MAP)
else()

View File

@@ -84,18 +84,12 @@ include_directories(SYSTEM ${INC_SYS})
macro(cycles_target_link_libraries target)
target_link_libraries(${target} ${LIBRARIES})
if(WITH_CYCLES_OSL)
target_link_libraries_decoupled(${target} OSL_LIBRARIES)
if(MSVC)
target_link_libraries_debug(${target} "${LLVM_LIBRARIES_DEBUG}")
target_link_libraries_optimized(${target} "${LLVM_LIBRARIES}")
else()
target_link_libraries(${target} ${LLVM_LIBRARIES})
endif()
target_link_libraries(${target} ${OSL_LIBRARIES} ${LLVM_LIBRARIES})
endif()
target_link_libraries_decoupled(${target} OPENIMAGEIO_LIBRARIES)
target_link_libraries_decoupled(${target} OPENEXR_LIBRARIES)
target_link_libraries(
${target}
${OPENIMAGEIO_LIBRARIES}
${OPENEXR_LIBRARIES}
${PUGIXML_LIBRARIES}
${BOOST_LIBRARIES}
${CMAKE_DL_LIBS}

View File

@@ -32,6 +32,7 @@
#include "util_string.h"
#include "util_time.h"
#include "util_transform.h"
#include "util_version.h"
#ifdef WITH_CYCLES_STANDALONE_GUI
#include "util_view.h"
@@ -358,7 +359,7 @@ static void options_parse(int argc, const char **argv)
/* parse options */
ArgParse ap;
bool help = false, debug = false;
bool help = false, debug = false, version = false;
int verbosity = 1;
ap.options ("Usage: cycles [options] file.xml",
@@ -380,6 +381,7 @@ static void options_parse(int argc, const char **argv)
"--verbose %d", &verbosity, "Set verbosity of the logger",
#endif
"--help", &help, "Print help message",
"--version", &version, "Print version number",
NULL);
if(ap.parse(argc, argv) < 0) {
@@ -406,6 +408,10 @@ static void options_parse(int argc, const char **argv)
exit(EXIT_SUCCESS);
}
else if(version) {
printf("%s\n", CYCLES_VERSION_STRING);
exit(EXIT_SUCCESS);
}
else if(help || options.filepath == "") {
ap.usage();
exit(EXIT_SUCCESS);

View File

@@ -52,7 +52,7 @@ struct XMLReadState {
Scene *scene; /* scene pointer */
Transform tfm; /* current transform state */
bool smooth; /* smooth normal state */
int shader; /* current shader */
Shader *shader; /* current shader */
string base; /* base path to current file*/
float dicing_rate; /* current dicing rate */
Mesh::DisplacementMethod displacement_method;
@@ -60,7 +60,7 @@ struct XMLReadState {
XMLReadState()
: scene(NULL),
smooth(false),
shader(0),
shader(NULL),
dicing_rate(0.0f),
displacement_method(Mesh::DISPLACE_BUMP)
{
@@ -230,6 +230,24 @@ static bool xml_read_enum(ustring *str, ShaderEnum& enm, pugi::xml_node node, co
return false;
}
static bool xml_read_enum_value(int *value, ShaderEnum& enm, pugi::xml_node node, const char *name)
{
pugi::xml_attribute attr = node.attribute(name);
if(attr) {
ustring ustr(attr.value());
if(enm.exists(ustr)) {
*value = enm[ustr];
return true;
}
else
fprintf(stderr, "Unknown value \"%s\" for attribute \"%s\".\n", ustr.c_str(), name);
}
return false;
}
static ShaderSocketType xml_read_socket_type(pugi::xml_node node, const char *name)
{
pugi::xml_attribute attr = node.attribute(name);
@@ -437,7 +455,7 @@ static void xml_read_shader_graph(const XMLReadState& state, Shader *shader, pug
/* Generate inputs/outputs from node sockets
*
* Note: ShaderInput/ShaderOutput store shallow string copies only!
* Socket names must be stored in the extra lists instead. */
* So we register them as ustring to ensure the pointer stays valid. */
/* read input values */
for(pugi::xml_node param = node.first_child(); param; param = param.next_sibling()) {
if(string_iequals(param.name(), "input")) {
@@ -449,8 +467,7 @@ static void xml_read_shader_graph(const XMLReadState& state, Shader *shader, pug
if(type == SHADER_SOCKET_UNDEFINED)
continue;
osl->input_names.push_back(ustring(name));
osl->add_input(osl->input_names.back().c_str(), type);
osl->add_input(ustring(name).c_str(), type);
}
else if(string_iequals(param.name(), "output")) {
string name;
@@ -461,8 +478,7 @@ static void xml_read_shader_graph(const XMLReadState& state, Shader *shader, pug
if(type == SHADER_SOCKET_UNDEFINED)
continue;
osl->output_names.push_back(ustring(name));
osl->add_output(osl->output_names.back().c_str(), type);
osl->add_output(ustring(name).c_str(), type);
}
}
@@ -531,7 +547,24 @@ static void xml_read_shader_graph(const XMLReadState& state, Shader *shader, pug
snode = bump;
}
else if(string_iequals(node.name(), "mapping")) {
snode = new MappingNode();
MappingNode *map = new MappingNode();
TextureMapping *texmap = &map->tex_mapping;
xml_read_enum_value((int*) &texmap->type, TextureMapping::type_enum, node, "type");
xml_read_enum_value((int*) &texmap->projection, TextureMapping::projection_enum, node, "projection");
xml_read_enum_value((int*) &texmap->x_mapping, TextureMapping::mapping_enum, node, "x_mapping");
xml_read_enum_value((int*) &texmap->y_mapping, TextureMapping::mapping_enum, node, "y_mapping");
xml_read_enum_value((int*) &texmap->z_mapping, TextureMapping::mapping_enum, node, "z_mapping");
xml_read_bool(&texmap->use_minmax, node, "use_minmax");
if(texmap->use_minmax) {
xml_read_float3(&texmap->min, node, "min");
xml_read_float3(&texmap->max, node, "max");
}
xml_read_float3(&texmap->translation, node, "translation");
xml_read_float3(&texmap->rotation, node, "rotation");
xml_read_float3(&texmap->scale, node, "scale");
snode = map;
}
else if(string_iequals(node.name(), "anisotropic_bsdf")) {
AnisotropicBsdfNode *aniso = new AnisotropicBsdfNode();
@@ -867,7 +900,7 @@ static void xml_read_background(const XMLReadState& state, pugi::xml_node node)
xml_read_bool(&bg->transparent, node, "transparent");
/* Background Shader */
Shader *shader = state.scene->shaders[state.scene->default_background];
Shader *shader = state.scene->default_background;
xml_read_bool(&shader->heterogeneous_volume, node, "heterogeneous_volume");
xml_read_int(&shader->volume_interpolation_method, node, "volume_interpolation_method");
@@ -906,7 +939,7 @@ static void xml_read_mesh(const XMLReadState& state, pugi::xml_node node)
mesh->used_shaders.push_back(state.shader);
/* read state */
int shader = state.shader;
int shader = 0;
bool smooth = state.smooth;
mesh->displacement_method = state.displacement_method;
@@ -1008,6 +1041,8 @@ static void xml_read_mesh(const XMLReadState& state, pugi::xml_node node)
fdata[2] = make_float3(UV[v2*2], UV[v2*2+1], 0.0);
fdata += 3;
}
index_offset += nverts[i];
}
}
}
@@ -1064,7 +1099,7 @@ static void xml_read_patch(const XMLReadState& state, pugi::xml_node node)
mesh->used_shaders.push_back(state.shader);
/* split */
SubdParams sdparams(mesh, state.shader, state.smooth);
SubdParams sdparams(mesh, 0, state.smooth);
xml_read_float(&sdparams.dicing_rate, node, "dicing_rate");
DiagSplit dsplit(sdparams);
@@ -1161,17 +1196,14 @@ static void xml_read_state(XMLReadState& state, pugi::xml_node node)
string shadername;
if(xml_read_string(&shadername, node, "shader")) {
int i = 0;
bool found = false;
foreach(Shader *shader, state.scene->shaders) {
if(shader->name == shadername) {
state.shader = i;
state.shader = shader;
found = true;
break;
}
i++;
}
if(!found)

View File

@@ -50,10 +50,39 @@ def _workaround_buggy_drivers():
_cycles.opencl_disable()
def _parse_command_line():
import sys
argv = sys.argv
if "--" not in argv:
return
argv = argv[argv.index("--") + 1:]
num_resumable_chunks = None
current_resumable_chunk = None
# TODO(sergey): Add some nice error ptins if argument is not used properly.
idx = 0
while idx < len(argv) - 1:
arg = argv[idx]
if arg == '--cycles-resumable-num-chunks':
num_resumable_chunks = int(argv[idx + 1])
elif arg == '--cycles-resumable-current-chunk':
current_resumable_chunk = int(argv[idx + 1])
idx += 1
if num_resumable_chunks is not None and current_resumable_chunk is not None:
import _cycles
_cycles.set_resumable_chunks(num_resumable_chunks,
current_resumable_chunk)
def init():
import bpy
import _cycles
import os.path
import sys
# Workaround possibly buggy legacy drivers which crashes on the OpenCL
# device enumeration.
@@ -72,7 +101,7 @@ def init():
user_path = os.path.dirname(os.path.abspath(bpy.utils.user_resource('CONFIG', '')))
_cycles.init(path, user_path, bpy.app.background)
_parse_command_line()
def exit():
import _cycles

View File

@@ -46,6 +46,12 @@ enum_displacement_methods = (
('BOTH', "Both", "Combination of displacement and bump mapping"),
)
enum_subdivision_types = (
('NONE', "None", "No subdivision"),
('LINEAR', "Linear", "Use linear subdivision"),
('CATMULL_CLARK', "CatmullClark", "Use Catmull-Clark subdivision"),
)
enum_bvh_types = (
('DYNAMIC_BVH', "Dynamic BVH", "Objects can be individually updated, at the cost of slower render time"),
('STATIC_BVH', "Static BVH", "Any object modification requires a complete BVH rebuild, but renders faster"),
@@ -187,57 +193,57 @@ class CyclesRenderSettings(bpy.types.PropertyGroup):
cls.aa_samples = IntProperty(
name="AA Samples",
description="Number of antialiasing samples to render for each pixel",
min=1, max=10000,
min=1, max=2097151,
default=4,
)
cls.preview_aa_samples = IntProperty(
name="AA Samples",
description="Number of antialiasing samples to render in the viewport, unlimited if 0",
min=0, max=10000,
min=0, max=2097151,
default=4,
)
cls.diffuse_samples = IntProperty(
name="Diffuse Samples",
description="Number of diffuse bounce samples to render for each AA sample",
min=1, max=10000,
min=1, max=1024,
default=1,
)
cls.glossy_samples = IntProperty(
name="Glossy Samples",
description="Number of glossy bounce samples to render for each AA sample",
min=1, max=10000,
min=1, max=1024,
default=1,
)
cls.transmission_samples = IntProperty(
name="Transmission Samples",
description="Number of transmission bounce samples to render for each AA sample",
min=1, max=10000,
min=1, max=1024,
default=1,
)
cls.ao_samples = IntProperty(
name="Ambient Occlusion Samples",
description="Number of ambient occlusion samples to render for each AA sample",
min=1, max=10000,
min=1, max=1024,
default=1,
)
cls.mesh_light_samples = IntProperty(
name="Mesh Light Samples",
description="Number of mesh emission light samples to render for each AA sample",
min=1, max=10000,
min=1, max=1024,
default=1,
)
cls.subsurface_samples = IntProperty(
name="Subsurface Samples",
description="Number of subsurface scattering samples to render for each AA sample",
min=1, max=10000,
min=1, max=1024,
default=1,
)
cls.volume_samples = IntProperty(
name="Volume Samples",
description="Number of volume scattering samples to render for each AA sample",
min=1, max=10000,
min=1, max=1024,
default=1,
)
@@ -364,6 +370,26 @@ class CyclesRenderSettings(bpy.types.PropertyGroup):
min=2, max=65536
)
cls.dicing_rate = FloatProperty(
name="Dicing Rate",
description="Size of a micropolygon in pixels",
min=0.1, max=1000.0,
default=1.0,
)
cls.preview_dicing_rate = FloatProperty(
name="Preview Dicing Rate",
description="Size of a micropolygon in pixels during preview render",
min=0.1, max=1000.0,
default=8.0,
)
cls.max_subdivisions = IntProperty(
name="Max Subdivisions",
description="Stop subdividing when this level is reached even if the dice rate would produce finer tessellation",
min=0, max=16,
default=12,
)
cls.film_exposure = FloatProperty(
name="Exposure",
description="Image brightness scale",
@@ -568,6 +594,8 @@ class CyclesRenderSettings(bpy.types.PropertyGroup):
cls.debug_use_cpu_sse2 = BoolProperty(name="SSE2", default=True)
cls.debug_use_qbvh = BoolProperty(name="QBVH", default=True)
cls.debug_use_cuda_adaptive_compile = BoolProperty(name="Adaptive Compile", default=False)
cls.debug_opencl_kernel_type = EnumProperty(
name="OpenCL Kernel Type",
default='DEFAULT',
@@ -931,15 +959,16 @@ class CyclesMeshSettings(bpy.types.PropertyGroup):
items=enum_displacement_methods,
default='BUMP',
)
cls.use_subdivision = BoolProperty(
name="Use Subdivision",
description="Subdivide mesh for rendering",
default=False,
cls.subdivision_type = EnumProperty(
name="Subdivision Type",
description="Type of subdivision to use",
items=enum_subdivision_types,
default='NONE',
)
cls.dicing_rate = FloatProperty(
name="Dicing Rate",
description="",
min=0.001, max=1000.0,
description="Multiplier for scene dicing rate",
min=0.1, max=1000.0,
default=1.0,
)

View File

@@ -209,8 +209,8 @@ class CyclesRender_PT_sampling(CyclesButtonsPanel, Panel):
draw_samples_info(layout, context)
class CyclesRender_PT_volume_sampling(CyclesButtonsPanel, Panel):
bl_label = "Volume Sampling"
class CyclesRender_PT_geometery(CyclesButtonsPanel, Panel):
bl_label = "Geometry"
bl_options = {'DEFAULT_CLOSED'}
def draw(self, context):
@@ -219,11 +219,30 @@ class CyclesRender_PT_volume_sampling(CyclesButtonsPanel, Panel):
scene = context.scene
cscene = scene.cycles
row = layout.row()
row.label("Heterogeneous:")
row = layout.row()
row.prop(cscene, "volume_step_size")
row.prop(cscene, "volume_max_steps")
if cscene.feature_set == 'EXPERIMENTAL':
split = layout.split()
col = split.column()
sub = col.column(align=True)
sub.label("Volume Sampling:")
sub.prop(cscene, "volume_step_size")
sub.prop(cscene, "volume_max_steps")
col = split.column()
sub = col.column(align=True)
sub.label("Subdivision Rate:")
sub.prop(cscene, "dicing_rate", text="Render")
sub.prop(cscene, "preview_dicing_rate", text="Preview")
sub.separator()
sub.prop(cscene, "max_subdivisions")
else:
row = layout.row()
row.label("Volume Sampling:")
row = layout.row()
row.prop(cscene, "volume_step_size")
row.prop(cscene, "volume_max_steps")
class CyclesRender_PT_light_paths(CyclesButtonsPanel, Panel):
@@ -681,10 +700,20 @@ class Cycles_PT_mesh_displacement(CyclesButtonsPanel, Panel):
elif mball:
cdata = mball.cycles
layout.prop(cdata, "displacement_method", text="Method")
layout.prop(cdata, "use_subdivision")
layout.prop(cdata, "dicing_rate")
split = layout.split()
col = split.column()
sub = col.column(align=True)
sub.label(text="Displacment:")
sub.prop(cdata, "displacement_method", text="")
col = split.column()
sub = col.column(align=True)
sub.label(text="Subdivision:")
sub.prop(cdata, "subdivision_type", text="")
if cdata.subdivision_type != 'NONE':
sub.prop(cdata, "dicing_rate")
class CyclesObject_PT_motion_blur(CyclesButtonsPanel, Panel):
bl_label = "Motion Blur"
@@ -1505,7 +1534,7 @@ class CyclesRender_PT_debug(CyclesButtonsPanel, Panel):
@classmethod
def poll(cls, context):
return bpy.app.debug_value == 256
return CyclesButtonsPanel.poll(context) and bpy.app.debug_value == 256
def draw(self, context):
layout = self.layout
@@ -1524,6 +1553,10 @@ class CyclesRender_PT_debug(CyclesButtonsPanel, Panel):
row.prop(cscene, "debug_use_cpu_avx2", toggle=True)
col.prop(cscene, "debug_use_qbvh")
col = layout.column()
col.label('CUDA Flags:')
col.prop(cscene, "debug_use_cuda_adaptive_compile")
col = layout.column()
col.label('OpenCL Flags:')
col.prop(cscene, "debug_opencl_kernel_type", text="Kernel")

View File

@@ -65,6 +65,9 @@ struct BlenderCamera {
bool use_spherical_stereo;
float interocular_distance;
float convergence_distance;
bool use_pole_merge;
float pole_merge_angle_from;
float pole_merge_angle_to;
enum { AUTO, HORIZONTAL, VERTICAL } sensor_fit;
float sensor_width;
@@ -183,6 +186,10 @@ static void blender_camera_from_object(BlenderCamera *bcam,
}
bcam->use_spherical_stereo = b_engine.use_spherical_stereo(b_ob);
bcam->use_pole_merge = b_camera.stereo().use_pole_merge();
bcam->pole_merge_angle_from = b_camera.stereo().pole_merge_angle_from();
bcam->pole_merge_angle_to = b_camera.stereo().pole_merge_angle_to();
bcam->ortho_scale = b_camera.ortho_scale();
bcam->lens = b_camera.lens();
@@ -360,6 +367,12 @@ static void blender_camera_sync(Camera *cam, BlenderCamera *bcam, int width, int
blender_camera_viewplane(bcam, width, height,
&cam->viewplane, &aspectratio, &sensor_size);
cam->width = bcam->full_width;
cam->height = bcam->full_height;
cam->full_width = width;
cam->full_height = height;
/* panorama sensor */
if(bcam->type == CAMERA_PANORAMA && bcam->panorama_type == PANORAMA_FISHEYE_EQUISOLID) {
float fit_xratio = (float)bcam->full_width*bcam->pixelaspect.x;
@@ -421,6 +434,10 @@ static void blender_camera_sync(Camera *cam, BlenderCamera *bcam, int width, int
cam->stereo_eye = Camera::STEREO_NONE;
}
cam->use_pole_merge = bcam->use_pole_merge;
cam->pole_merge_angle_from = bcam->pole_merge_angle_from;
cam->pole_merge_angle_to = bcam->pole_merge_angle_to;
/* anamorphic lens bokeh */
cam->aperture_ratio = bcam->aperture_ratio;

View File

@@ -138,8 +138,7 @@ bool ObtainCacheParticleData(Mesh *mesh, BL::Mesh *b_mesh, BL::Object *b_ob, Par
BL::ParticleSettings b_part((const PointerRNA)b_psys.settings().ptr);
if((b_part.render_type() == BL::ParticleSettings::render_type_PATH) && (b_part.type() == BL::ParticleSettings::type_HAIR)) {
int mi = clamp(b_part.material()-1, 0, mesh->used_shaders.size()-1);
int shader = mesh->used_shaders[mi];
int shader = clamp(b_part.material()-1, 0, mesh->used_shaders.size()-1);
int draw_step = background ? b_part.render_step() : b_part.draw_step();
int totparts = b_psys.particles.length();
int totchild = background ? b_psys.child_particles.length() : (int)((float)b_psys.child_particles.length() * (float)b_part.draw_percentage() / 100.0f);

Some files were not shown because too many files have changed in this diff Show More