Compare commits
56
Commits
step_misc
...
editchecks
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2923050080 | ||
|
|
9dd4023aa5 | ||
|
|
d39ca30602 | ||
|
|
b714d88185 | ||
|
|
eff3fea479 | ||
|
|
7358e90b54 | ||
|
|
3c2b0de9d2 | ||
|
|
a384f838fb | ||
|
|
1053594e9a | ||
|
|
72cde263cc | ||
|
|
b670a19aba | ||
|
|
2d9fa5c033 | ||
|
|
8be0f0ae85 | ||
|
|
00ffa4bd80 | ||
|
|
e5e0905d03 | ||
|
|
10d13793b0 | ||
|
|
70d5180438 | ||
|
|
50fe626694 | ||
|
|
ca403c92ed | ||
|
|
bab959474f | ||
|
|
27b522c155 | ||
|
|
875231c335 | ||
|
|
89810b06ca | ||
|
|
90e512b5d6 | ||
|
|
19fe382208 | ||
|
|
994c56b05f | ||
|
|
db76164ea8 | ||
|
|
58c5ed3681 | ||
|
|
05bd5c7470 | ||
|
|
2276f4ef8c | ||
|
|
188e72eb32 | ||
|
|
03306043ea | ||
|
|
28038fe0ea | ||
|
|
5b5cb8c538 | ||
|
|
1c20d18156 | ||
|
|
97920fbc90 | ||
|
|
37fb7d928a | ||
|
|
2056b359bd | ||
|
|
b4cf00292a | ||
|
|
6748dd37ab | ||
|
|
ef35c1dca1 | ||
|
|
8cdedd8752 | ||
|
|
e4ba0b166c | ||
|
|
586ac06c7e | ||
|
|
0d745fca35 | ||
|
|
5270e67abe | ||
|
|
14051845a3 | ||
|
|
d6fa937212 | ||
|
|
37aee260c1 | ||
|
|
56d64428ae | ||
|
|
0f6db7016d | ||
|
|
cbffc1171b | ||
|
|
21e034ee34 | ||
|
|
8f81f27d92 | ||
|
|
d729a7d3f2 | ||
|
|
17601916f4 |
+31
-16
@@ -678,8 +678,13 @@ endif(MSVC)
|
||||
# before use so platforms without GNU/LLVM-style linker options are skipped.
|
||||
brlcad_check_linker_flag(C "LINKER:--no-undefined" BRLCAD_LINKER_NO_UNDEFINED_C_FLAG_FOUND)
|
||||
brlcad_check_linker_flag(CXX "LINKER:--no-undefined" BRLCAD_LINKER_NO_UNDEFINED_CXX_FLAG_FOUND)
|
||||
if(BRLCAD_LINKER_NO_UNDEFINED_C_FLAG_FOUND AND BRLCAD_LINKER_NO_UNDEFINED_CXX_FLAG_FOUND)
|
||||
if(BRLCAD_LINKER_NO_UNDEFINED_C_FLAG_FOUND AND BRLCAD_LINKER_NO_UNDEFINED_CXX_FLAG_FOUND
|
||||
AND NOT BRLCAD_ENABLE_ADDRESS_SANITIZER)
|
||||
set(BRLCAD_LINKER_NO_UNDEFINED_FLAG "LINKER:--no-undefined" CACHE STRING "Linker flag requiring resolved shared library symbols" FORCE)
|
||||
else()
|
||||
# Clang links the AddressSanitizer runtime into executables, leaving its
|
||||
# shared-library instrumentation symbols unresolved until then.
|
||||
set(BRLCAD_LINKER_NO_UNDEFINED_FLAG "" CACHE STRING "Linker flag requiring resolved shared library symbols" FORCE)
|
||||
endif()
|
||||
brlcad_check_linker_flags(C BRLCAD_LINKER_WHOLE_ARCHIVE_GROUP_C_FLAG_FOUND "LINKER:--whole-archive" "LINKER:--no-whole-archive")
|
||||
brlcad_check_linker_flags(CXX BRLCAD_LINKER_WHOLE_ARCHIVE_GROUP_CXX_FLAG_FOUND "LINKER:--whole-archive" "LINKER:--no-whole-archive")
|
||||
@@ -1642,21 +1647,31 @@ if(NOT MSVC)
|
||||
endif(BRLCAD_WARNINGS OR BRLCAD_ENABLE_STRICT)
|
||||
|
||||
if(BRLCAD_ENABLE_COVERAGE)
|
||||
# TODO: These seem to GCC specific flags - should probably set up for clang
|
||||
# as well if that's our compiler...
|
||||
# https://clang.llvm.org/docs/SourceBasedCodeCoverage.html
|
||||
# If we need different settings for different tools, should
|
||||
# encapsulate each tool's setup in a function
|
||||
check_c_flag(ftest-coverage)
|
||||
check_cxx_flag(ftest-coverage)
|
||||
if(FTEST_COVERAGE_C_FLAG_FOUND)
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -lgcov -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lgcov -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
else(FTEST_COVERAGE_C_FLAG_FOUND)
|
||||
message(SEND_ERROR "Building with coverage is not supported by BRL-CAD on this platform.")
|
||||
endif(FTEST_COVERAGE_C_FLAG_FOUND)
|
||||
if(CMAKE_C_COMPILER_ID MATCHES "Clang" AND CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
check_c_flag(fprofile-instr-generate)
|
||||
check_cxx_flag(fprofile-instr-generate)
|
||||
check_c_flag(fcoverage-mapping)
|
||||
check_cxx_flag(fcoverage-mapping)
|
||||
if(NOT FPROFILE_INSTR_GENERATE_C_FLAG_FOUND OR
|
||||
NOT FPROFILE_INSTR_GENERATE_CXX_FLAG_FOUND OR
|
||||
NOT FCOVERAGE_MAPPING_C_FLAG_FOUND OR
|
||||
NOT FCOVERAGE_MAPPING_CXX_FLAG_FOUND)
|
||||
message(FATAL_ERROR "Clang source-based coverage is not supported by this toolchain.")
|
||||
endif()
|
||||
add_compile_options(-fprofile-instr-generate -fcoverage-mapping)
|
||||
add_link_options(-fprofile-instr-generate)
|
||||
else()
|
||||
check_c_flag(ftest-coverage)
|
||||
check_cxx_flag(ftest-coverage)
|
||||
if(FTEST_COVERAGE_C_FLAG_FOUND AND FTEST_COVERAGE_CXX_FLAG_FOUND)
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -lgcov -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lgcov -ftest-coverage -fprofile-arcs -fprofile-update=atomic")
|
||||
else()
|
||||
message(FATAL_ERROR "GCC coverage is not supported by this toolchain.")
|
||||
endif()
|
||||
endif()
|
||||
endif(BRLCAD_ENABLE_COVERAGE)
|
||||
|
||||
if(BRLCAD_ENABLE_STRICT)
|
||||
|
||||
@@ -13,6 +13,8 @@ changes made. See document footer for additional details.
|
||||
--- 20XX-XX-XX Release 7.46.0 ---
|
||||
----------------------------------------------------------------------
|
||||
|
||||
* improved pixscale & bwscale scaling and image piping - Sean Morrison
|
||||
* restored pixdiff behavior on .pix, added -b for .bw - Sean Morrison
|
||||
* updated MGED and Archer for Tcl 8.6.18 and Itcl/Itk 4 - Cliff Yapp
|
||||
* fixed writes to fileless geometry databases - Cliff Yapp
|
||||
* fixed nastran-g handling of large property IDs - Rupesh, Cliff Yapp
|
||||
|
||||
@@ -4,38 +4,54 @@
|
||||
:manmanual: BRL-CAD
|
||||
|
||||
== NAME
|
||||
pixdiff - highlight samples which differ between two pix or bw files
|
||||
pixdiff - highlight differences between two pix or bw images
|
||||
|
||||
== SYNOPSIS
|
||||
|
||||
[source]
|
||||
----
|
||||
pixdiff _file1.pix_ _file2.pix_ > _out.pix_
|
||||
pixdiff _file1.bw_ _file2.bw_ > _out.bw_
|
||||
pixdiff -b _file1.bw_ _file2.bw_ > _out.bw_
|
||||
----
|
||||
|
||||
|
||||
[[description]]
|
||||
== DESCRIPTION
|
||||
|
||||
*pixdiff* compares two raw *pix*(5) or *bw*(5) images byte by byte and
|
||||
writes a difference image of the same size to standard output. Bytes that
|
||||
differ by +/-1 are written at intensity 192, while larger differences are
|
||||
written at full intensity 255. Matching bytes are written at half their
|
||||
original intensity, providing visual context for locating differences.
|
||||
By default, *pixdiff* compares raw *pix*(5) images as RGB pixels and writes
|
||||
a PIX difference image to standard output. When all three channels of a
|
||||
pixel match, it writes a dim grayscale version of that pixel to all three
|
||||
output channels. When any channel differs, each matching channel is written
|
||||
as zero, each channel differing by one is written as 192, and each channel
|
||||
differing by more than one is written as 255.
|
||||
|
||||
Because the comparison does not interpret pixel structure, no format option
|
||||
is needed and *pixdiff* is independent of image resolution. The two inputs
|
||||
must be the same size in bytes; otherwise the program reports the mismatch
|
||||
and exits. Either input file may be given as
|
||||
With *-b*, *pixdiff* compares raw *bw*(5) images one byte at a time and
|
||||
writes a BW difference image. Differing samples use the same 192 and 255
|
||||
intensities; matching samples are written at half their original intensity.
|
||||
|
||||
No image dimensions are needed. The two inputs must be the same size in
|
||||
bytes, and PIX input must contain complete three-byte pixels. Otherwise,
|
||||
*pixdiff* reports an error. Either input file may be given as
|
||||
*-* to read from standard input. Output must be redirected; *pixdiff*
|
||||
refuses to write a raw image stream to a terminal.
|
||||
|
||||
Upon completion, the count of bytes that matched, that were off by 1, and
|
||||
that were off by many is reported on standard error.
|
||||
Upon completion, *pixdiff* reports matching, off-by-one, and larger-difference
|
||||
channel or sample counts on standard error.
|
||||
|
||||
Also see *bwdiff*(1), which can also operate on *pix*(5) files and can
|
||||
produce other kinds of difference output.
|
||||
*bwdiff -n -b* produces a similar BW highlight image, but writes 255 rather
|
||||
than 192 for off-by-one differences. The default *bwdiff*(1) output instead
|
||||
shows signed differences around a neutral gray.
|
||||
|
||||
|
||||
[[options]]
|
||||
== OPTIONS
|
||||
|
||||
*-b*::
|
||||
Treat both inputs and the output as one-byte-per-pixel BW images. Without
|
||||
this option, use three-byte-per-pixel PIX images.
|
||||
|
||||
*-h*::
|
||||
Show usage information.
|
||||
|
||||
|
||||
[[examples]]
|
||||
@@ -59,10 +75,10 @@ on standard error give a quick quantitative sense of how much changed.
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
pixdiff depth_a.bw depth_b.bw > depth_diff.bw
|
||||
pixdiff -b depth_a.bw depth_b.bw > depth_diff.bw
|
||||
----
|
||||
Writes a grayscale highlight image using the same byte comparison and
|
||||
statistics as the color example; no format option is needed.
|
||||
Writes a grayscale highlight image using byte-wise comparison. Matching
|
||||
samples retain half their input intensity as context.
|
||||
====
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ Link with *-lanalyze*.
|
||||
The public interface is organized across the headers included by
|
||||
_analyze.h_, including _analyze/diff.h_, _analyze/density.h_,
|
||||
_analyze/grid.h_, _analyze/heal.h_, _analyze/info.h_, _analyze/pnts.h_,
|
||||
_analyze/polygonize.h_, _analyze/nirt.h_, _analyze/voxelize.h_, and
|
||||
_analyze/contour.h_, _analyze/polygonize.h_, _analyze/nirt.h_,
|
||||
_analyze/voxelize.h_, and
|
||||
_analyze/worker.h_.
|
||||
|
||||
== DESCRIPTION
|
||||
@@ -32,7 +33,7 @@ to gather the information they need.
|
||||
Facilities provided by the library include model differencing, material
|
||||
density and mass property analysis, ray-based gridding and sampling,
|
||||
geometry healing, model information queries, point-cloud generation and
|
||||
processing, polygonization and voxelization of geometry, and the
|
||||
processing, manifold dual contouring and voxelization of geometry, and the
|
||||
interactive ray-tracing engine used by the *nirt*(1) command. A parallel
|
||||
worker interface supports distributing analysis work across multiple
|
||||
threads.
|
||||
|
||||
@@ -200,6 +200,18 @@ ____
|
||||
|
||||
The LIBRT_DEBUG environment variable may be set to the hexadecimal bit vector as described by the DEBUG_* flags listed in the raytrace.h header. Similarly, many LIBRT applications provide a "-x #" command-line option which will take precedence over the environment variable.
|
||||
|
||||
The RT_DEBUG_RTCMP flag (0x10000000) (set with LIBRT_DEBUG=10000000) appends
|
||||
one high-precision rtcmp JSON record per ray with final hit partitions to the
|
||||
file named by LIBRT_RTCMP_FILE. Misses produce no record. librt never clears
|
||||
the file; the caller must clear or rotate it before a new comparison as needed.
|
||||
Separate processes must not write to the same file concurrently. Pending
|
||||
records are flushed within two seconds under normal operation and during normal
|
||||
process shutdown. A process terminated abnormally may lose pending records.
|
||||
rtcmp comparison files should use the same hit-only capture mode on both sides;
|
||||
its generation mode also includes misses. The output can be expanded to also
|
||||
include primitive segments if the environment variable LIBRT_RTCMP_PRIMITIVES
|
||||
is set to 1.
|
||||
|
||||
The LIBRT_V4FLIP environment variable may be set to a true or false value to respectively force or disable endianness interpretation of v4 geometry database files. The default behavior is to automatically detect whether flipping the endian interpretation will help LIBRT read a binary-incompatible v4 geometry database file. Setting LIBRT_V4FLIP will override automatic detection.
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ facetize - Creates __new_object__ using __old_object__ as a guide, creating an e
|
||||
|
||||
[source]
|
||||
----
|
||||
facetize [-h] [-v] [-q] [-n] [-r] [-s suffix] [-p prefix] [--in-place] [--max-time #] [--max-pnts #] [--resume] [--methods m1,m2,...] [--method-opts METHOD opt1=val opt2=val...] [--no-empty] [--log-file filename] [--nmg-booleval] [--disable-fixup] [--perturb] [--no-perturb] [--perturb-sa-tol #] [--perturb-vol-tol #] [--tolerate-failures] [-B -t threshold] {old_object new_object}
|
||||
facetize [-h] [-v] [-q] [-n] [-r] [-j jobs] [-s suffix] [-p prefix] [--in-place] [--max-time #] [--max-pnts #] [--resume] [--methods m1,m2,...] [--method-opts METHOD opt1=val opt2=val...] [--no-empty] [--log-file filename] [--nmg-booleval] [--disable-fixup] [--perturb] [--no-perturb] [--perturb-sa-tol #] [--perturb-vol-tol #] [--tolerate-failures] [-B -t threshold] {old_object new_object}
|
||||
----
|
||||
|
||||
|
||||
@@ -45,6 +45,8 @@ By default, the Manifold BoT path can make use of a coplanarity-avoidance pertur
|
||||
|
||||
When the perturbation step is active, per-region *facetize* validates the initial Boolean output against the original CSG geometry using a Crofton stochastic raytrace. The default tolerance thresholds that trigger a perturb retry are 10% for both surface area and volume; these can be adjusted with *--perturb-sa-tol* and *--perturb-vol-tol*. At the end of a per-region facetization run *facetize* prints a concise validation summary listing how many regions passed, triggered a perturb retry, or encountered one of the following noteworthy conditions:
|
||||
|
||||
_Unbounded halfspace (validation unavailable)_: Crofton surface-area and volume comparisons require a finite sampling domain. A standalone halfspace, or another CSG result without finite bounds, is therefore not sampled and is counted as having validation unavailable. A bounded object intersected with or subtracted by a halfspace can still be validated because its finite operand supplies the sampling bounds.
|
||||
|
||||
_Sub-mm / few-hit bypass (accepted with note)_: When the Crofton sampler finds only a very small number of ray-surface intersections (below an internal threshold of 50 crossings), the sampling noise alone would exceed 14% relative error, making any SA comparison meaningless. Geometry in this category is typically sub-millimetre in cross-section (e.g., a TGC with a radius under 0.2 mm) but the stochastic sampler has confirmed that some geometry is present. The BoT conversion is accepted and the region is counted separately in the summary. Users should verify that such extreme geometry reflects actual modeling intent rather than an accidental near-degenerate primitive.
|
||||
|
||||
_Zero-hit replacement_: When the Crofton sampler fires rays but records zero intersections with the CSG geometry while the corresponding BoT is non-empty, *facetize* concludes that the Boolean evaluation most likely produces empty geometry (for example, a subtractor that fully engulfs the base object). In this case the non-empty BoT is discarded and replaced with an empty BoT to match the expected raytrace behavior. If this replacement appears unexpected for a given region, the *lint* command can be used to inspect the result.
|
||||
@@ -61,13 +63,21 @@ Different tolerance settings will create finer or coarser meshes. See the *tol*
|
||||
|
||||
Primitive tessellation is performed in a child process against a private working copy of the database in the BRL-CAD cache. The original database is not modified as individual primitive meshes are generated. Only after the conversion succeeds are the requested results transferred from the working database. This separation also permits an interrupted conversion to retain its intermediate state for use with *--resume*.
|
||||
|
||||
The parent command sends primitive names to a persistent tessellation process one at a time. The child reports a result for each name, so a timeout, conversion failure, or child-process crash that occurs before a database write can be associated directly with the affected primitive. The child is restarted when necessary and processing continues with the next name; the parent does not subdivide and retry the whole group to discover which object failed. Unless output is suppressed with *--quiet*, long tessellation batches also report their current object and completed-object count at approximately five-second intervals.
|
||||
The parent command sends primitive names to a small pool of persistent tessellation processes. Each child reports a result for every name, so a timeout, conversion failure, or child-process crash can be associated directly with the affected primitive. A child is restarted when necessary and processing continues with the next name; the parent does not subdivide and retry the whole group to discover which object failed. Unless output is suppressed with *--quiet*, long tessellation batches also report their completed-object count and active-worker state at approximately five-second intervals.
|
||||
|
||||
Database updates use a separate write handshake. After preparing a mesh in memory, the child announces that it is ready to write and reports the approximate mesh size, then waits. The parent acknowledges that it is waiting for the write before the child may update the working database. The child explicitly reports when the update is complete. Consequently, the normal per-object tessellation limit, including *--max-time* and method-specific limits, applies to mesh preparation and does not interrupt an acknowledged database write.
|
||||
By default, *facetize* uses at most two worker processes and only enables the second when both CPU and memory information indicate it is safe. It reserves the larger of one GiB or one quarter of total physical memory for the rest of the system. Starting another job also requires at least 512 MiB beyond that reserve, or the largest worker resident-memory measurement seen so far if that is greater. If the platform cannot report the required memory information, *facetize* falls back to one worker. The available CPU count is divided among worker processes and is also imposed as the thread limit inside each worker, preventing nested algorithms from independently using all CPUs. *--jobs* changes the maximum process count; it does not bypass the memory admission checks.
|
||||
|
||||
Per-region BoT conversion uses this worker policy for both independent CSG validation and initial Manifold Boolean evaluation. When more than one worker is available, persistent validation processes each open their own read-only handle to the original database and compute Crofton surface-area and volume references for different regions. Persistent Boolean processes then evaluate different region trees using independent read-only handles to one shared snapshot of the tessellated working database. That snapshot also serves as the rollback checkpoint, so increasing *--jobs* does not create additional full database copies. This process isolation avoids sharing mutable raytrace preparation or database state between concurrent evaluations. Each result remains associated with the requested region name. The parent commits completed BoTs through one writer and continues to perform hierarchy changes, validation decisions, and any perturb retries serially. A one-worker run retains the established in-process order and avoids the snapshot phase.
|
||||
|
||||
Validation and Boolean workers report their completed-region count and active-worker state approximately every five seconds. When *--max-time* is specified, it also bounds each parallel CSG reference or Boolean request; a timed-out process is terminated, and the failure is associated with that region. Failure or timeout of supplementary CSG validation does not cause unrelated regions to be retried.
|
||||
|
||||
Database updates use a separate write handshake. After preparing a mesh in memory, a child announces that it is ready to write and reports the approximate mesh size and its current resident memory, then waits. The parent grants write permission, the child acknowledges when it is starting the write, and the child explicitly reports when the update is complete. Consequently, the normal per-object tessellation limit, including *--max-time* and method-specific limits, applies to mesh preparation and does not interrupt an acknowledged write.
|
||||
|
||||
With multiple workers, primitive tessellation children write to small staging databases rather than modifying the shared working database. Region Boolean children read one immutable cache-local snapshot while completed results are committed to the working database. The snapshot doubles as the recovery checkpoint and is opened independently by each worker; it is not duplicated per worker. For very large files, snapshot preparation reports the amount copied and elapsed time at five-second intervals. A region result is first completed in memory and enters the write handshake only when it is ready to replace the prior staged result. After a child reports a completed staging write, the parent submits that result to a single persistent writer process. The writer announces that it is ready, waits for the parent's permission, acknowledges that it is starting the write, transfers the result through one persistent working-database handle, and reports completion. This permits tessellation and initial region Boolean evaluation to proceed in parallel without concurrent database allocation updates or repeated full directory scans, while allowing the parent to supervise the canonical database write itself. With one worker, the established direct path avoids the extra staging I/O and database snapshot.
|
||||
|
||||
Before the first primitive conversion, the parent measures write throughput on the same cache filesystem as the working database. It writes a temporary file in 1 MiB chunks until approximately one second has elapsed or 128 MiB has been written, then removes the file immediately. Successful mesh writes of at least 1 MiB subsequently refine this profile. For each database update, the parent allows ten times the projected write time, with a minimum of five seconds and a maximum of five minutes. This measured allowance protects legitimate long writes on slow storage while still detecting a genuinely stalled update.
|
||||
|
||||
If a child fails before write permission is granted, the working database is known to be unchanged and no rollback is needed. A failure, crash, or write-deadline expiration after permission is granted but before completion is ambiguous: the working database may contain a partial update. In that case *facetize* restores its cache-local checkpoint and replays only the primitive conversions already known to have succeeded. The original database remains untouched during this recovery.
|
||||
If a child fails before acknowledging that its write has started, the working database is known to be unchanged and no rollback is needed. In parallel mode, a failure during a child write affects only that worker's disposable staging database, so the failed object is reported and the worker can be restarted without replaying unrelated objects. A serial child failure during a direct write, or a writer-process failure after acknowledging write start, is ambiguous because the working database may contain a partial update. In those cases *facetize* restores its cache-local checkpoint and replays only the conversions not already tied to a specific failure. The original database remains untouched during this recovery.
|
||||
|
||||
|
||||
[[facetize_options]]
|
||||
@@ -94,6 +104,10 @@ Instructs *facetize* to produce NMG solids rather than BoT solids.
|
||||
Rather than converting all specified inputs to one top level object, walk specified trees and individually convert regions to facetized objects. This mode is useful when wanting to display models in shaded mode while preserving color and region ID properties. If no regions are present a normal conversion is performed instead.
|
||||
|
||||
|
||||
*-j, --jobs #*::
|
||||
Set the maximum number of facetize worker processes. A value of 1 forces serial processing. The default value of 0 selects a conservative automatic limit based on available CPUs and memory. Memory checks may delay or reduce parallel work even when a larger value is requested. In per-region BoT mode the same limit controls parallel CSG reference sampling and initial Manifold Boolean evaluation.
|
||||
|
||||
|
||||
*-s, --suffix*::
|
||||
User specified suffix to use avoiding naming conflicts (naming conflict avoidance is needed when creating objects in *-r* mode.)
|
||||
|
||||
@@ -119,7 +133,7 @@ Resume an incomplete facetization process (will utilize cached data from a previ
|
||||
|
||||
|
||||
*--methods*::
|
||||
Accepts a comma separated list of one or more facetization methods to use. The default is to try all algorithms available as needed, but if a user knows they want to try a specific methodology they can call it out using this option.
|
||||
Accepts a comma separated list of one or more facetization methods to use. The default tries NMG tessellation first, Manifold Dual Contouring (MDC) second, and SPSR as a final fallback. Other listed methods may be selected explicitly if a user wants to try a specific methodology.
|
||||
|
||||
|
||||
*--method-opts*::
|
||||
@@ -231,21 +245,15 @@ mged>**facetize --tolerate-failures large_model large_model.partial.bot**
|
||||
|
||||
====
|
||||
|
||||
.Increase Decimation in CM Mode
|
||||
.Refine a Manifold Dual Contouring conversion
|
||||
[example]
|
||||
====
|
||||
mged>**facetize --methods CM --method-opts feature_size=0.06 d_feature_size=2.0 ellipse.r ell.bot**
|
||||
This selects MDC directly and requests a finer cell size with a larger ray
|
||||
budget than the default:
|
||||
|
||||
The default settings on this object in CM mode will produce a little over 8000 faces in the final bot, but the addition of the *d_feature_size* option with a >1.5 value has dramatically reduced the count to 104.
|
||||
mged>**facetize --methods MDC --method-opts "MDC feature_size=0.1 max_rays=400000" ellipse.r ell.bot**
|
||||
|
||||
====
|
||||
|
||||
.Decrease Decimation in CM Mode
|
||||
[example]
|
||||
====
|
||||
mged>**facetize --methods CM --method-opts feature_size=0.06 d_feature_size=0.01 ellipse.r ell.bot**
|
||||
|
||||
If the intent is preserve a more detailed mesh, reducing *decimation-feature-size* will keep more of the original triangles - in the above example, almost 250 thousand of the original 6.9 million faces were retained. NOTE: use lower values here cautiously, as extremely large meshes can be very difficult for many tools to deal with.
|
||||
Smaller feature sizes increase mesh detail, ray count, memory use, and runtime.
|
||||
|
||||
====
|
||||
|
||||
|
||||
+13
-16
@@ -679,23 +679,21 @@ Convert CSG geometry to a 3D voxel grid by:
|
||||
fill fraction
|
||||
* Level-of-detail parameter controls sub-voxel sampling
|
||||
|
||||
==== 7.5 Implicit Surface Polygonizer (Marching Cubes / Tetrahedral)
|
||||
==== 7.5 Manifold Dual Contouring
|
||||
|
||||
An implicit surface polygonizer (Bloomenthal tetrahedral marching) for
|
||||
converting any inside/outside function to a triangle mesh.
|
||||
`contour.cpp` evaluates CSG geometry directly with `librt` and constructs
|
||||
closed, oriented triangle meshes:
|
||||
|
||||
`polygonizer.c` (based on Jules Bloomenthal’s "`An Implicit Surface
|
||||
Polygonizer,`" Graphics Gems IV, 1994) converts any implicit function
|
||||
(inside/outside test) to a triangle mesh:
|
||||
|
||||
* Maintains a hash table of evaluated lattice corners and edges
|
||||
* Expanding front: starts at a seed point and spreads outward, testing
|
||||
adjacent cube faces
|
||||
* Each transitive cube is optionally decomposed into 6 tetrahedra for
|
||||
sub-cube accuracy
|
||||
* Edge-surface crossing is found by bisection (`converge`) then the
|
||||
vertex normal is estimated from finite differences
|
||||
* Used in `libanalyze` for converting CSG regions to faceted form
|
||||
* Recursively refines an implicit octree using cached axis-aligned rays along
|
||||
node box edges and interior quarter- and center-lines
|
||||
* Reuses complete ray partitions at the conforming finest grid and retains
|
||||
evaluated boundary points with analytic surface normals
|
||||
* Resolves ambiguous faces consistently and permits multiple vertices in a
|
||||
cell to preserve local topology
|
||||
* Places vertices with bounded quadratic-error minimization
|
||||
* Validates the resulting indexed mesh before returning it
|
||||
* Backs the legacy `analyze_polygonize` interface without retaining the old
|
||||
seed-driven marching-tetrahedra implementation
|
||||
|
||||
==== 7.6 Geometry Differencing (raydiff)
|
||||
|
||||
@@ -1712,7 +1710,6 @@ import
|
||||
runtime
|
||||
* *MT19937*: Mersenne Twister PRNG
|
||||
* *pbrt-v3* (derived): HLBVH construction algorithm
|
||||
* *Bloomenthal polygonizer*: implicit surface polygonization
|
||||
* *Screened Poisson Reconstruction* (Michael Kazhdan): surface
|
||||
reconstruction from point clouds
|
||||
* *Ball Pivoting Algorithm*: surface reconstruction
|
||||
|
||||
@@ -55,7 +55,6 @@ brlcad_manage_files(pbrt.txt ${DOC_DIR}/legal/embedded TRIGGER
|
||||
brlcad_manage_files(picohash.txt ${DOC_DIR}/legal/embedded TRIGGER gist)
|
||||
brlcad_manage_files(pixcii.txt ${DOC_DIR}/legal/embedded TRIGGER libicv)
|
||||
brlcad_manage_files(point_in_polygon.txt ${DOC_DIR}/legal/embedded TRIGGER libbg)
|
||||
brlcad_manage_files(polygonizer.txt ${DOC_DIR}/legal/embedded TRIGGER libanalyze)
|
||||
brlcad_manage_files(predicates.txt ${DOC_DIR}/legal/embedded TRIGGER libbg)
|
||||
brlcad_manage_files(profont.txt ${DOC_DIR}/legal/embedded TRIGGER libbu)
|
||||
brlcad_manage_files(pstdint.txt ${DOC_DIR}/legal/embedded TRIGGER libbu)
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
https://www.bloomenthal.com/JBloom/code/polygonizer.c
|
||||
|
||||
Authored by Jules Bloomenthal, Xerox PARC.
|
||||
Copyright (c) Xerox Corporation, 1991. All rights reserved.
|
||||
Permission is granted to reproduce, use and distribute this code for
|
||||
any and all purposes, provided that this notice appears in all copies.
|
||||
|
||||
file:/src/libanalyze/polygonizer.c
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
#include "common.h"
|
||||
|
||||
#include "analyze/defines.h"
|
||||
#include "analyze/contour.h"
|
||||
#include "analyze/debug.h"
|
||||
#include "analyze/diff.h"
|
||||
#include "analyze/density.h"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
set(
|
||||
analyze_headers
|
||||
contour.h
|
||||
debug.h
|
||||
defines.h
|
||||
density.h
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/* C O N T O U R . H
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this file; see the file named COPYING for more
|
||||
* information.
|
||||
*/
|
||||
/** @addtogroup libanalyze
|
||||
* @{ */
|
||||
/** @file analyze/contour.h
|
||||
*
|
||||
* Ray-driven manifold dual contouring of evaluated BRL-CAD geometry.
|
||||
*/
|
||||
|
||||
#ifndef ANALYZE_CONTOUR_H
|
||||
#define ANALYZE_CONTOUR_H
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "vmath.h"
|
||||
#include "analyze/defines.h"
|
||||
|
||||
__BEGIN_DECLS
|
||||
|
||||
#define ANALYZE_MDC_DEFAULT_MAX_RAYS 0
|
||||
#define ANALYZE_MDC_DEFAULT_MINIMUM_FREE_MEM 150000000
|
||||
#define ANALYZE_MDC_DEFAULT_MIN_DEPTH 2
|
||||
#define ANALYZE_MDC_DEFAULT_MAX_DEPTH 10
|
||||
#define ANALYZE_MDC_MAX_DEPTH 20
|
||||
#define ANALYZE_MDC_DEFAULT_MAX_TIME 600
|
||||
|
||||
struct db_i;
|
||||
/** Resource and accuracy controls for analyze_mdc(). */
|
||||
struct analyze_mdc_params {
|
||||
/** Requested maximum finest-cell edge length. Zero selects an
|
||||
* implementation default based on the model bounds. */
|
||||
fastf_t feature_size;
|
||||
|
||||
/** Optional user ceiling for the automatically derived ray budget.
|
||||
* Zero applies only geometry, depth, time, and memory limits. */
|
||||
size_t max_rays;
|
||||
|
||||
/** Abort before available memory drops below this many bytes. */
|
||||
size_t minimum_free_mem;
|
||||
|
||||
/** Minimum and maximum power-of-two grid depths. */
|
||||
int min_depth;
|
||||
int max_depth;
|
||||
|
||||
/** Maximum wall-clock processing time in seconds. Zero is unlimited. */
|
||||
int max_time;
|
||||
|
||||
/** Emit progress diagnostics when non-zero. */
|
||||
int verbosity;
|
||||
};
|
||||
|
||||
#define ANALYZE_MDC_PARAMS_DEFAULT { \
|
||||
0.0, \
|
||||
ANALYZE_MDC_DEFAULT_MAX_RAYS, \
|
||||
ANALYZE_MDC_DEFAULT_MINIMUM_FREE_MEM, \
|
||||
ANALYZE_MDC_DEFAULT_MIN_DEPTH, \
|
||||
ANALYZE_MDC_DEFAULT_MAX_DEPTH, \
|
||||
ANALYZE_MDC_DEFAULT_MAX_TIME, \
|
||||
0 \
|
||||
}
|
||||
|
||||
enum analyze_mdc_status {
|
||||
ANALYZE_MDC_OK = 0,
|
||||
ANALYZE_MDC_INVALID_INPUT = 1,
|
||||
ANALYZE_MDC_PREP_FAILED = 2,
|
||||
ANALYZE_MDC_NO_SURFACE = 3,
|
||||
ANALYZE_MDC_RAY_LIMIT = 4,
|
||||
ANALYZE_MDC_TIMEOUT = 5,
|
||||
ANALYZE_MDC_MEMORY_LIMIT = 6,
|
||||
ANALYZE_MDC_AMBIGUOUS = 7,
|
||||
ANALYZE_MDC_NOT_MANIFOLD = 8
|
||||
};
|
||||
|
||||
/**
|
||||
* Evaluate @p object with librt and construct an indexed triangle mesh.
|
||||
*
|
||||
* On success, the caller owns @p faces and @p vertices and must release them
|
||||
* with bu_free(). Failure leaves all outputs empty.
|
||||
*/
|
||||
ANALYZE_EXPORT extern enum analyze_mdc_status
|
||||
analyze_mdc(int **faces, size_t *num_faces, point_t **vertices,
|
||||
size_t *num_vertices, const char *object, struct db_i *dbip,
|
||||
const struct analyze_mdc_params *params);
|
||||
|
||||
__END_DECLS
|
||||
|
||||
#endif /* ANALYZE_CONTOUR_H */
|
||||
|
||||
/** @} */
|
||||
|
||||
/*
|
||||
* Local Variables:
|
||||
* mode: C
|
||||
* tab-width: 8
|
||||
* indent-tabs-mode: t
|
||||
* c-file-style: "stroustrup"
|
||||
* End:
|
||||
* ex: shiftwidth=4 tabstop=8
|
||||
*/
|
||||
@@ -43,9 +43,29 @@ struct analyze_polygonize_params {
|
||||
size_t minimum_free_mem;
|
||||
int verbosity;
|
||||
};
|
||||
#define ANALYZE_POLYGONIZE_PARAMS_DEFAULT { 0, 0, 30, 150000000, 0 }
|
||||
#define ANALYZE_POLYGONIZE_DEFAULT_MAX_CYCLE_TIME 30
|
||||
#define ANALYZE_POLYGONIZE_DEFAULT_MINIMUM_FREE_MEM 150000000
|
||||
#define ANALYZE_POLYGONIZE_PARAMS_DEFAULT { 0, 0, \
|
||||
ANALYZE_POLYGONIZE_DEFAULT_MAX_CYCLE_TIME, \
|
||||
ANALYZE_POLYGONIZE_DEFAULT_MINIMUM_FREE_MEM, 0 }
|
||||
|
||||
/**
|
||||
* Legacy polygonization interface, implemented by analyze_mdc().
|
||||
*
|
||||
* @p size is the requested maximum cell edge length. @p p_s is retained for
|
||||
* source and binary compatibility but is no longer used as a starting seed.
|
||||
* The caller owns successful output arrays and must release them with
|
||||
* bu_free(). Failure leaves all outputs empty.
|
||||
*
|
||||
* @return 0 on success
|
||||
* @return -1 on invalid input or polygonization failure
|
||||
* @return 2 when a time limit is reached
|
||||
* @return 3 when the minimum-free-memory limit is reached
|
||||
*/
|
||||
ANALYZE_EXPORT extern int
|
||||
analyze_polygonize(int **faces, int *num_faces, point_t **vertices, int *num_vertices, fastf_t size, point_t p_s, const char *obj, struct db_i *dbip, struct analyze_polygonize_params *p);
|
||||
analyze_polygonize(int **faces, int *num_faces, point_t **vertices,
|
||||
int *num_vertices, fastf_t size, point_t p_s, const char *obj,
|
||||
struct db_i *dbip, struct analyze_polygonize_params *p);
|
||||
|
||||
__END_DECLS
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@
|
||||
#include "bg/clip.h"
|
||||
#include "bg/lseg.h"
|
||||
#include "bg/obr.h"
|
||||
#include "bg/pca.h"
|
||||
#include "bg/plane.h"
|
||||
#include "bg/polygon.h"
|
||||
#include "bg/sat.h"
|
||||
|
||||
+4
-4
@@ -50,12 +50,12 @@ BG_EXPORT extern int bg_lseg_clip(fastf_t *xp1, fastf_t *yp1, fastf_t *xp2, fast
|
||||
* The RPP has faces parallel to the coordinate planes and is defined
|
||||
* by a minimum point and a maximum point.
|
||||
*
|
||||
* FIXME: the function name implies this takes a point,dir for a,b but
|
||||
* it actually takes a line segment going from points a to b!
|
||||
* Despite its historical name, this function clips the finite line segment
|
||||
* from a to b.
|
||||
*
|
||||
* Returns -
|
||||
* 0 if ray does not hit RPP,
|
||||
* !0 if ray hits RPP.
|
||||
* 0 if the segment does not hit the RPP,
|
||||
* !0 if the segment hits the RPP.
|
||||
*
|
||||
* Implicit Return -
|
||||
* if !0 was returned, "a" and "b" have been clipped to the RPP.
|
||||
|
||||
+6
-3
@@ -126,9 +126,12 @@ BG_EXPORT extern int bg_3d_coplanar_obr(point_t *center,
|
||||
* \endverbatim
|
||||
*
|
||||
*
|
||||
* @param[out] pnts eight points of oriented bounding box
|
||||
* @param points_3d array of 3D points
|
||||
* @param pnt_cnt number of points in pnts array
|
||||
* @param[out] pnts eight non-NULL, caller-provided point_t storage
|
||||
* locations for the oriented bounding box vertices
|
||||
* @param[in] points_3d flat array containing 3 * pnt_cnt coordinate values
|
||||
* @param[in] pnt_cnt number of points in points_3d
|
||||
*
|
||||
* @return 0 on success and -1 for invalid input or when no box can be fit
|
||||
*/
|
||||
BG_EXPORT extern int bg_3d_obb(point_t **pnts,
|
||||
const fastf_t *points_3d,
|
||||
|
||||
+4
-4
@@ -21,7 +21,7 @@
|
||||
/*----------------------------------------------------------------------*/
|
||||
/** @addtogroup bg_pca
|
||||
*
|
||||
* Principle Component Analysis
|
||||
* Principal Component Analysis
|
||||
*
|
||||
* Calculates an XYZ coordinate system such that it aligns with the largest
|
||||
* variations in the supplied data. Intuitively, it "aligns" with the
|
||||
@@ -50,7 +50,7 @@
|
||||
* point_t p;
|
||||
* for (size_t i = 0; i < pntcnt; i++) {
|
||||
* MAT4X3PNT(p, RT, pnts[i]);
|
||||
* VMOVE(pnts[i], v);
|
||||
* VMOVE(pnts[i], p);
|
||||
* }
|
||||
* @endcode
|
||||
*/
|
||||
@@ -69,7 +69,7 @@ __BEGIN_DECLS
|
||||
|
||||
/**
|
||||
* @brief
|
||||
* Perform a Principle Component Analysis on a set of points.
|
||||
* Perform a Principal Component Analysis on a set of points.
|
||||
*
|
||||
* Outputs are a center point and XYZ vectors for the coordinate system.
|
||||
*
|
||||
@@ -88,7 +88,7 @@ BG_EXPORT extern int bg_pca(point_t *c, vect_t *xaxis, vect_t *yaxis, vect_t *za
|
||||
|
||||
__END_DECLS
|
||||
|
||||
#endif /* BG_PLANE_H */
|
||||
#endif /* BG_PCA_H */
|
||||
/** @} */
|
||||
/*
|
||||
* Local Variables:
|
||||
|
||||
+7
-4
@@ -1171,9 +1171,10 @@ BG_EXPORT extern int bg_isect_planes(point_t pt,
|
||||
|
||||
/**
|
||||
* @brief
|
||||
* Given an origin and a normal, create a plane_t.
|
||||
* Given an origin and a normal, create a plane_t with a unit normal.
|
||||
* The input point and normal are not modified. A zero-length normal fails.
|
||||
*/
|
||||
BG_EXPORT extern int bg_plane_pt_nrml(plane_t *p, point_t pt, vect_t nrml);
|
||||
BG_EXPORT extern int bg_plane_pt_nrml(plane_t *p, const point_t pt, const vect_t nrml);
|
||||
|
||||
/**
|
||||
* @brief
|
||||
@@ -1188,13 +1189,15 @@ BG_EXPORT extern int bg_fit_plane(point_t *c, vect_t *n, size_t npnts, point_t *
|
||||
|
||||
/**
|
||||
* @brief
|
||||
* Find the closest U,V point on the plane p to 3d point pt.
|
||||
* Find the closest U,V point on the plane p to 3d point pt. The plane normal
|
||||
* need not be unit length.
|
||||
*/
|
||||
BG_EXPORT extern int bg_plane_closest_pt(fastf_t *u, fastf_t *v, plane_t *p, point_t *pt);
|
||||
|
||||
/**
|
||||
* @brief
|
||||
* Return the 3D point on the plane at parametric coordinates u, v.
|
||||
* Return the 3D point on the plane at parametric coordinates u, v. The plane
|
||||
* normal need not be unit length.
|
||||
*/
|
||||
BG_EXPORT extern int bg_plane_pt_at(point_t *pt, plane_t *p, fastf_t u, fastf_t v);
|
||||
|
||||
|
||||
@@ -293,6 +293,7 @@ BG_EXPORT extern int bg_3d_polygon_area(fastf_t *area, size_t npts, const point_
|
||||
* @param[in] npts Number of point_ts, stored in pts
|
||||
* @param[in] pts all points of the polygon, sorted counter-clockwise.
|
||||
* The array mustn't contain duplicated points or non-coplanar points.
|
||||
* A zero-area polygon fails.
|
||||
*
|
||||
* @return 0 if calculation was successful
|
||||
* @return 1 if calculation failed, e.g. because one in-parameter is a NULL-pointer
|
||||
@@ -307,7 +308,7 @@ BG_EXPORT extern int bg_3d_polygon_centroid(point_t *cent, size_t npts, const po
|
||||
*@param[in] npts Number of points, pts contains
|
||||
*@param pts Array of point_ts, building a convex polygon. Duplicated points
|
||||
*aren't allowed. The points in the array will be sorted counter-clockwise.
|
||||
*@param[in] cmp Plane equation of the polygon
|
||||
*@param[in] cmp Plane equation of the polygon. Its normal must be nonzero.
|
||||
*
|
||||
*@return 0 if calculation was successful
|
||||
*@return 1 if calculation failed, e.g. because pts is a NULL-pointer
|
||||
|
||||
+20
-8
@@ -39,7 +39,9 @@
|
||||
__BEGIN_DECLS
|
||||
|
||||
/**
|
||||
* Test for an intersection between a line and an Axis-Aligned Bounding Box (AABB).
|
||||
* Test for an intersection between an infinite line and an Axis-Aligned
|
||||
* Bounding Box (AABB). ldir need not be unit length, but must be nonzero.
|
||||
* aabb_extent supplies the positive half extents along the coordinate axes.
|
||||
*
|
||||
* Returns 1 if they intersect, 0 otherwise.
|
||||
*/
|
||||
@@ -50,7 +52,10 @@ bg_sat_line_aabb(
|
||||
);
|
||||
|
||||
/**
|
||||
* Test for an intersection between a line and an Oriented Bounding Box (OBB).
|
||||
* Test for an intersection between an infinite line and an Oriented Bounding
|
||||
* Box (OBB). ldir need not be unit length, but must be nonzero. Each OBB
|
||||
* extent vector points from the center to a face center; nonzero vectors must
|
||||
* be mutually perpendicular, and a zero vector represents a degenerate axis.
|
||||
*
|
||||
* Returns 1 if they intersect, 0 otherwise.
|
||||
*/
|
||||
@@ -61,7 +66,9 @@ bg_sat_line_obb(
|
||||
);
|
||||
|
||||
/**
|
||||
* Test for an intersection between a triangle and an Axis-Aligned Bounding Box (AABB).
|
||||
* Test for an intersection between a triangle and an Axis-Aligned Bounding
|
||||
* Box (AABB). extent supplies the positive half extents along the coordinate
|
||||
* axes.
|
||||
*
|
||||
* Returns 1 if they intersect, 0 otherwise.
|
||||
*/
|
||||
@@ -72,7 +79,10 @@ bg_sat_tri_aabb(
|
||||
);
|
||||
|
||||
/**
|
||||
* Test for an intersection between a triangle and an Oriented Bounding Box (OBB).
|
||||
* Test for an intersection between a triangle and an Oriented Bounding Box
|
||||
* (OBB). Each extent vector points from the center to a face center; nonzero
|
||||
* vectors must be mutually perpendicular, and a zero vector represents a
|
||||
* degenerate axis.
|
||||
*
|
||||
* Returns 1 if they intersect, 0 otherwise.
|
||||
*/
|
||||
@@ -85,8 +95,9 @@ bg_sat_tri_obb(
|
||||
/**
|
||||
* Test for an intersection between an Axis-Aligned Bounding Box (AABB) and an
|
||||
* Oriented Bounding Box (OBB). The latter is defined by a center point and
|
||||
* three perpendicular vectors from the center to the centers of the various
|
||||
* faces.
|
||||
* three extent vectors from the center to the centers of the various faces.
|
||||
* Nonzero extent vectors must be mutually perpendicular; a zero vector
|
||||
* represents a degenerate axis.
|
||||
*
|
||||
* Returns 1 if they intersect, 0 otherwise.
|
||||
*/
|
||||
@@ -98,8 +109,9 @@ bg_sat_aabb_obb(
|
||||
|
||||
/**
|
||||
* Test for an intersection between two Oriented Bounding Boxes (OBBs). The
|
||||
* boxes are defined by a center point and three perpendicular vectors from the
|
||||
* center to the centers of the various faces.
|
||||
* boxes are defined by a center point and three extent vectors from the center
|
||||
* to the centers of the various faces. Nonzero extent vectors must be
|
||||
* mutually perpendicular; a zero vector represents a degenerate axis.
|
||||
*
|
||||
* Returns 1 if they intersect, 0 otherwise.
|
||||
*/
|
||||
|
||||
+127
-5
@@ -67,6 +67,7 @@
|
||||
#define BG_SPSR_H
|
||||
|
||||
#include "common.h"
|
||||
#include <stdint.h>
|
||||
#include "vmath.h"
|
||||
#include "bg/defines.h"
|
||||
|
||||
@@ -109,7 +110,7 @@ struct bg_3d_spsr_opts {
|
||||
#define BG_3D_SPSR_BOUNDARY_DIRICHLET 3
|
||||
|
||||
#define BG_3D_SPSR_DEFAULT_DEGREE 1 /* DEFAULT_FEM_DEGREE */
|
||||
#define BG_3D_SPSR_DEFAULT_DEPTH 11
|
||||
#define BG_3D_SPSR_DEFAULT_DEPTH 8
|
||||
#define BG_3D_SPSR_DEFAULT_KERNELDEPTH 0
|
||||
#define BG_3D_SPSR_DEFAULT_ITERATIONS 0
|
||||
#define BG_3D_SPSR_DEFAULT_FULL_DEPTH 0
|
||||
@@ -117,13 +118,13 @@ struct bg_3d_spsr_opts {
|
||||
#define BG_3D_SPSR_DEFAULT_BASEVCYCLES 0
|
||||
#define BG_3D_SPSR_DEFAULT_MAX_MEM 0
|
||||
#define BG_3D_SPSR_DEFAULT_THREADS 0
|
||||
#define BG_3D_SPSR_DEFAULT_SAMPLES_PER_NODE 1.1
|
||||
#define BG_3D_SPSR_DEFAULT_SCALE 1.0
|
||||
#define BG_3D_SPSR_DEFAULT_SAMPLES_PER_NODE 1.5
|
||||
#define BG_3D_SPSR_DEFAULT_SCALE 1.1
|
||||
#define BG_3D_SPSR_DEFAULT_WIDTH 0.0
|
||||
#define BG_3D_SPSR_DEFAULT_CONFIDENCE 0.0
|
||||
#define BG_3D_SPSR_DEFAULT_CONFIDENCE_BIAS 0.0
|
||||
#define BG_3D_SPSR_DEFAULT_CGSOLVER_ACCURACY 1.0e-3
|
||||
#define BG_3D_SPSR_DEFAULT_POINT_WEIGHT 8.0 /* DefaultPointWeightMultiplier * Degree */
|
||||
#define BG_3D_SPSR_DEFAULT_POINT_WEIGHT 2.0
|
||||
#define BG_3D_SPSR_DEFAULT_NONMANIFOLD 0
|
||||
#define BG_3D_SPSR_DEFAULT_LINEARFIT 0
|
||||
#define BG_3D_SPSR_DEFAULT_EXACT 1
|
||||
@@ -167,10 +168,131 @@ struct bg_3d_spsr_opts {
|
||||
* @return 0 if successful, else error
|
||||
*
|
||||
*/
|
||||
BG_EXPORT int bg_3d_spsr(int **faces, int *num_faces, point_t **vertices, int *num_vertices,
|
||||
DEPRECATED BG_EXPORT int bg_3d_spsr(int **faces, int *num_faces, point_t **vertices, int *num_vertices,
|
||||
const point_t *input_points_3d, const vect_t *input_normals_3d,
|
||||
int num_input_pnts, struct bg_3d_spsr_opts *opts);
|
||||
|
||||
/** Reasons the SPSR solver may request additional source samples. */
|
||||
#define BG_3D_SPSR_REFINE_RESIDUAL 0x01u
|
||||
#define BG_3D_SPSR_REFINE_NORMAL 0x02u
|
||||
#define BG_3D_SPSR_REFINE_DENSITY 0x04u
|
||||
#define BG_3D_SPSR_REFINE_SURFACE_VARIATION 0x08u
|
||||
|
||||
/** Adaptive SPSR termination states. */
|
||||
#define BG_3D_SPSR_COMPLETE 0
|
||||
#define BG_3D_SPSR_CALLBACK_STOP 1
|
||||
#define BG_3D_SPSR_POINT_LIMIT 2
|
||||
#define BG_3D_SPSR_TIME_LIMIT 3
|
||||
#define BG_3D_SPSR_NO_NEW_SAMPLES 4
|
||||
#define BG_3D_SPSR_SOLVER_ERROR 5
|
||||
|
||||
/**
|
||||
* One oriented source sample. A positive @p thickness records the length of
|
||||
* the solid ray partition that supplied the sample. Non-zero equal pair IDs
|
||||
* identify the entry and exit samples of the same partition.
|
||||
*/
|
||||
struct bg_3d_spsr_sample {
|
||||
point_t point;
|
||||
vect_t normal;
|
||||
fastf_t thickness;
|
||||
uint64_t pair_id;
|
||||
};
|
||||
|
||||
/** A spatial location at which the solver would benefit from more samples. */
|
||||
struct bg_3d_spsr_refinement_hint {
|
||||
point_t point;
|
||||
vect_t normal;
|
||||
fastf_t error;
|
||||
unsigned int reasons;
|
||||
};
|
||||
|
||||
/** Source-to-candidate measurements supplied by an adaptive callback. */
|
||||
struct bg_3d_spsr_validation {
|
||||
size_t ray_count;
|
||||
size_t source_hit_rays;
|
||||
size_t partition_mismatch_rays;
|
||||
size_t thin_partition_count;
|
||||
size_t thin_partition_mismatches;
|
||||
fastf_t endpoint_error_p95;
|
||||
fastf_t endpoint_error_p99;
|
||||
fastf_t chord_error_fraction;
|
||||
fastf_t surface_area_error_fraction;
|
||||
fastf_t volume_error_fraction;
|
||||
int passed;
|
||||
};
|
||||
|
||||
/** Information passed to an adaptive source-sampling callback. */
|
||||
struct bg_3d_spsr_refinement_request {
|
||||
size_t pass;
|
||||
fastf_t target_feature_size;
|
||||
double remaining_time;
|
||||
const point_t *vertices;
|
||||
size_t vertex_count;
|
||||
const int *faces;
|
||||
size_t face_count;
|
||||
const struct bg_3d_spsr_refinement_hint *hints;
|
||||
size_t hint_count;
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback response. Sample storage remains owned by the callback and need
|
||||
* only remain valid until the callback returns; libbg copies it immediately.
|
||||
*/
|
||||
struct bg_3d_spsr_refinement_response {
|
||||
const struct bg_3d_spsr_sample *samples;
|
||||
size_t sample_count;
|
||||
struct bg_3d_spsr_validation validation;
|
||||
/** Non-zero asks the adaptive driver to stop after this candidate. */
|
||||
int stop_refinement;
|
||||
};
|
||||
|
||||
typedef int (*bg_3d_spsr_refinement_func_t)(
|
||||
struct bg_3d_spsr_refinement_response *response,
|
||||
const struct bg_3d_spsr_refinement_request *request,
|
||||
void *client_data);
|
||||
|
||||
/** Options controlling a bounded adaptive SPSR reconstruction. */
|
||||
struct bg_3d_spsr_adaptive_opts {
|
||||
struct bg_3d_spsr_opts solver;
|
||||
size_t max_refinement_passes;
|
||||
size_t max_points;
|
||||
fastf_t target_feature_size;
|
||||
double max_time;
|
||||
};
|
||||
|
||||
/** Last-resort solve budget; callbacks may stop earlier when progress stalls. */
|
||||
#define BG_3D_SPSR_DEFAULT_REFINEMENT_PASSES 8
|
||||
#define BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT { \
|
||||
BG_3D_SPSR_OPTS_DEFAULT, \
|
||||
BG_3D_SPSR_DEFAULT_REFINEMENT_PASSES, \
|
||||
0, \
|
||||
0.0, \
|
||||
0.0 }
|
||||
|
||||
/** Summary of an adaptive SPSR attempt. */
|
||||
struct bg_3d_spsr_report {
|
||||
size_t solve_count;
|
||||
size_t initial_sample_count;
|
||||
size_t final_sample_count;
|
||||
size_t requested_sample_count;
|
||||
size_t accepted_sample_count;
|
||||
double elapsed_time;
|
||||
int termination;
|
||||
struct bg_3d_spsr_validation validation;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reconstruct a surface and, when requested, obtain targeted additional
|
||||
* samples from @p refine. A callback is required when refinement passes are
|
||||
* enabled. The final candidate must be marked as passed by the callback.
|
||||
*/
|
||||
BG_EXPORT int bg_3d_spsr_adaptive(int **faces, int *num_faces,
|
||||
point_t **vertices, int *num_vertices,
|
||||
const struct bg_3d_spsr_sample *input_samples, size_t sample_count,
|
||||
const struct bg_3d_spsr_adaptive_opts *opts,
|
||||
bg_3d_spsr_refinement_func_t refine, void *client_data,
|
||||
struct bg_3d_spsr_report *report);
|
||||
|
||||
__END_DECLS
|
||||
|
||||
#endif /* BG_SPSR_H */
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ BG_EXPORT extern double bg_tri_closest_pt(
|
||||
|
||||
__END_DECLS
|
||||
|
||||
#endif /* BG_TRI_TRI_H */
|
||||
#endif /* BG_TRI_PT_H */
|
||||
/** @} */
|
||||
/*
|
||||
* Local Variables:
|
||||
|
||||
@@ -54,7 +54,7 @@ BG_EXPORT extern int bg_isect_tri_line(point_t *isect,
|
||||
* If isect is non-NULL, it is written only when an intersection is found.
|
||||
*/
|
||||
BG_EXPORT extern int bg_isect_tri_ray(const point_t orig,
|
||||
const point_t dir,
|
||||
const vect_t dir,
|
||||
const point_t vert0,
|
||||
const point_t vert1,
|
||||
const point_t vert2,
|
||||
|
||||
@@ -87,7 +87,11 @@ BG_EXPORT extern int bg_trimesh_oriented(int vcnt, int fcnt, fastf_t *v, int *f)
|
||||
/**
|
||||
* Check if a mesh is topologically solid. Returns 1 if the mesh is NOT SOLID
|
||||
* and 0 if the mesh is SOLID. A SOLID (0) outcome indicates the mesh satisfies
|
||||
* all three criteria: Closed, Manifold, Oriented
|
||||
* all three criteria: Closed, Manifold, Oriented. If @p bedges is non-NULL,
|
||||
* it is set to NULL when no edge diagnostics are present, or to a bu_calloc()
|
||||
* allocated array of vertex-index pairs for unmatched, misoriented, and excess
|
||||
* edges. The caller must bu_free() a non-NULL result. Use
|
||||
* bg_trimesh_solid2() when structured diagnostics and their counts are needed.
|
||||
*/
|
||||
BG_EXPORT extern int bg_trimesh_solid(int vcnt, int fcnt, fastf_t *v, int *f, int **bedges);
|
||||
|
||||
|
||||
+15
-12
@@ -214,8 +214,8 @@ BN_EXPORT extern void bn_mat_ae(mat_t m,
|
||||
double elev);
|
||||
|
||||
/**
|
||||
* Find the azimuth and elevation angles that correspond to the
|
||||
* direction (not including twist) given by a direction vector.
|
||||
* Find the azimuth and elevation angles, in degrees, that correspond
|
||||
* to the direction (not including twist) given by a direction vector.
|
||||
*/
|
||||
BN_EXPORT extern void bn_ae_vec(fastf_t *azp,
|
||||
fastf_t *elp,
|
||||
@@ -236,14 +236,16 @@ BN_EXPORT extern void bn_aet_vec(fastf_t *az,
|
||||
fastf_t accuracy);
|
||||
|
||||
/**
|
||||
* Find a unit vector from the origin given azimuth and elevation.
|
||||
* Find a unit vector from the origin given azimuth and elevation in
|
||||
* radians.
|
||||
*/
|
||||
BN_EXPORT extern void bn_vec_ae(vect_t vec,
|
||||
fastf_t az,
|
||||
fastf_t el);
|
||||
|
||||
/**
|
||||
* Find a vector from the origin given azimuth, elevation, and distance.
|
||||
* Find a vector from the origin given azimuth and elevation in radians,
|
||||
* and distance.
|
||||
*/
|
||||
BN_EXPORT extern void bn_vec_aed(vect_t vec,
|
||||
fastf_t az,
|
||||
@@ -310,8 +312,10 @@ BN_EXPORT extern void bn_vec_perp(vect_t new_vec,
|
||||
* space by the angle between the two. There are many candidate
|
||||
* matrices.
|
||||
*
|
||||
* The input 'from' and 'to' vectors need not be unit length.
|
||||
* MAT4X3VEC(to, m, from) is the identity that is created.
|
||||
* The input 'from' and 'to' vectors need not be unit length. They are
|
||||
* normalized internally. Near-parallel inputs are handled using the
|
||||
* angular tolerance in 'tol'. If either input cannot be normalized,
|
||||
* the result is the identity matrix.
|
||||
*
|
||||
*/
|
||||
BN_EXPORT extern void bn_mat_fromto(mat_t m,
|
||||
@@ -344,12 +348,11 @@ BN_EXPORT extern void bn_mat_zrot(mat_t m,
|
||||
double cosz);
|
||||
|
||||
/**
|
||||
* Given a direction vector D of unit length, product a matrix which
|
||||
* rotates that vector D onto the -Z axis. This matrix will be
|
||||
* suitable for use as a "model2view" matrix.
|
||||
*
|
||||
* XXX This routine will fail if the vector is already more or less
|
||||
* aligned with the Z axis.
|
||||
* Given a nonzero direction vector D, produce a matrix which
|
||||
* rotates D onto the -Z axis. D is normalized internally. Z-axis
|
||||
* directions use a deterministic roll, and a zero direction produces
|
||||
* the identity matrix. This matrix will be suitable for use as a
|
||||
* model2view matrix.
|
||||
*
|
||||
* This is done in several steps.
|
||||
*
|
||||
|
||||
@@ -37,11 +37,42 @@ __BEGIN_DECLS
|
||||
|
||||
typedef struct bn_multipoly {
|
||||
uint32_t magic;
|
||||
/**< Number of coefficients in the first polynomial variable. */
|
||||
int dgrs;
|
||||
/**< Number of coefficients in the second polynomial variable. */
|
||||
int dgrt;
|
||||
/**< Coefficient of S^s * T^t is cf[s][t]. */
|
||||
double **cf;
|
||||
} bn_multipoly_t;
|
||||
|
||||
/**
|
||||
* Allocate a zero-valued bivariate polynomial with the specified
|
||||
* coefficient counts. Both counts must be positive.
|
||||
*/
|
||||
BN_EXPORT extern struct bn_multipoly *bn_multipoly_new(int dgrs, int dgrt);
|
||||
|
||||
/** Release a bivariate polynomial allocated by bn_multipoly_new(). */
|
||||
BN_EXPORT extern void bn_multipoly_free(struct bn_multipoly *poly);
|
||||
|
||||
/** Grow a polynomial to at least the specified coefficient counts. */
|
||||
BN_EXPORT extern struct bn_multipoly *bn_multipoly_grow(struct bn_multipoly *poly,
|
||||
int dgrs,
|
||||
int dgrt);
|
||||
|
||||
/** Set the coefficient of S^s * T^t, growing the polynomial as needed. */
|
||||
BN_EXPORT extern struct bn_multipoly *bn_multipoly_set(struct bn_multipoly *poly,
|
||||
int s,
|
||||
int t,
|
||||
double value);
|
||||
|
||||
/** Return the sum of two bivariate polynomials. */
|
||||
BN_EXPORT extern struct bn_multipoly *bn_multipoly_add(const struct bn_multipoly *p1,
|
||||
const struct bn_multipoly *p2);
|
||||
|
||||
/** Return the product of two bivariate polynomials. */
|
||||
BN_EXPORT extern struct bn_multipoly *bn_multipoly_mul(const struct bn_multipoly *p1,
|
||||
const struct bn_multipoly *p2);
|
||||
|
||||
__END_DECLS
|
||||
|
||||
#endif /* BN_MULTIPOLY_H */
|
||||
|
||||
+20
-4
@@ -45,7 +45,10 @@ __BEGIN_DECLS
|
||||
|
||||
/**
|
||||
* Polynomial data type
|
||||
* bn_poly->cf[n] corresponds to X^n
|
||||
*
|
||||
* Coefficients are stored from the highest to the lowest degree:
|
||||
* `cf[0]` is the coefficient of `X^dgr` and `cf[dgr]` is the
|
||||
* constant coefficient.
|
||||
*/
|
||||
typedef struct bn_poly {
|
||||
uint32_t magic;
|
||||
@@ -63,6 +66,9 @@ typedef struct bn_poly {
|
||||
*
|
||||
* @brief
|
||||
* multiply two polynomials
|
||||
*
|
||||
* The output may alias either input. If the result exceeds
|
||||
* BN_MAX_POLY_DEGREE, returns BN_POLY_NULL without modifying product.
|
||||
*/
|
||||
BN_EXPORT extern struct bn_poly *bn_poly_mul(struct bn_poly *product,
|
||||
const struct bn_poly *m1,
|
||||
@@ -81,6 +87,8 @@ BN_EXPORT extern struct bn_poly *bn_poly_scale(struct bn_poly *eqn,
|
||||
* bn_poly_add
|
||||
* @brief
|
||||
* add two polynomials
|
||||
*
|
||||
* The output may alias either input.
|
||||
*/
|
||||
BN_EXPORT extern struct bn_poly *bn_poly_add(struct bn_poly *sum,
|
||||
const struct bn_poly *poly1,
|
||||
@@ -90,6 +98,8 @@ BN_EXPORT extern struct bn_poly *bn_poly_add(struct bn_poly *sum,
|
||||
* bn_poly_sub
|
||||
* @brief
|
||||
* subtract two polynomials
|
||||
*
|
||||
* The output may alias either input.
|
||||
*/
|
||||
BN_EXPORT extern struct bn_poly *bn_poly_sub(struct bn_poly *diff,
|
||||
const struct bn_poly *poly1,
|
||||
@@ -98,7 +108,10 @@ BN_EXPORT extern struct bn_poly *bn_poly_sub(struct bn_poly *diff,
|
||||
/**
|
||||
* @brief
|
||||
* Divides any polynomial into any other polynomial using synthetic
|
||||
* division. Both polynomials must have real coefficients.
|
||||
* division. Both polynomials must have real coefficients and the
|
||||
* divisor's leading coefficient must be nonzero. The quotient and
|
||||
* remainder outputs must be distinct; the quotient may alias the
|
||||
* dividend. All other output/input pairs must be distinct.
|
||||
*/
|
||||
BN_EXPORT extern void bn_poly_synthetic_division(struct bn_poly *quo,
|
||||
struct bn_poly *rem,
|
||||
@@ -108,7 +121,8 @@ BN_EXPORT extern void bn_poly_synthetic_division(struct bn_poly *quo,
|
||||
/**
|
||||
*@brief
|
||||
* Uses the quadratic formula to find the roots (in `complex' form) of
|
||||
* any quadratic equation with real coefficients.
|
||||
* any quadratic equation with real coefficients. A nonzero leading
|
||||
* coefficient need not be one.
|
||||
*
|
||||
* @return 1 for success
|
||||
* @return 0 for fail.
|
||||
@@ -144,6 +158,7 @@ BN_EXPORT extern int bn_poly_quadratic_roots(struct bn_complex roots[],
|
||||
* If D < 0, there will be three unequal real roots.
|
||||
*
|
||||
* Returns 1 for success, 0 for fail.
|
||||
* A nonzero leading coefficient need not be one.
|
||||
*/
|
||||
BN_EXPORT extern int bn_poly_cubic_roots(struct bn_complex roots[],
|
||||
const struct bn_poly *eqn);
|
||||
@@ -151,7 +166,8 @@ BN_EXPORT extern int bn_poly_cubic_roots(struct bn_complex roots[],
|
||||
/**
|
||||
*@brief
|
||||
* Uses the quartic formula to find the roots (in `complex' form)
|
||||
* of any quartic equation with real coefficients.
|
||||
* of any quartic equation with real coefficients. A nonzero leading
|
||||
* coefficient need not be one.
|
||||
*
|
||||
* @return 1 for success
|
||||
* @return 0 for fail.
|
||||
|
||||
+4
-3
@@ -100,8 +100,8 @@ BN_EXPORT extern void quat_double(quat_t qout,
|
||||
/**
|
||||
*@brief Gives the bisector of quaternions q1 and q2.
|
||||
*
|
||||
* (Could be done with quat_slerp and factor 0.5)
|
||||
* [I believe they must be unit quaternions this to work]
|
||||
* Inputs must be unit quaternions. Antipodal inputs use a valid
|
||||
* great-circle midpoint.
|
||||
*/
|
||||
BN_EXPORT extern void quat_bisect(quat_t qout,
|
||||
const quat_t q1,
|
||||
@@ -161,7 +161,8 @@ BN_EXPORT extern void quat_exp(quat_t out,
|
||||
|
||||
/**
|
||||
*@brief
|
||||
* Take the natural logarithm of a unit quaternion.
|
||||
* Take the natural logarithm of a unit quaternion. The identity
|
||||
* quaternion maps to the zero quaternion.
|
||||
* Code by Ken Shoemake.
|
||||
*/
|
||||
BN_EXPORT extern void quat_log(quat_t out,
|
||||
|
||||
+16
-9
@@ -205,23 +205,30 @@ BU_EXPORT extern int bu_sscanf(const char *src, const char *fmt, ...) _BU_ATTR_S
|
||||
/** Routines for scanning certain kinds of data. */
|
||||
|
||||
/**
|
||||
* Scans a sequence of fastf_t numbers from a string or stdin
|
||||
* Scans a sequence of fastf_t numbers from a string or stdin.
|
||||
*
|
||||
* Scanning fastf_t numbers with bu_sscanf() is difficult, because
|
||||
* doing so requires scanning to some intermediate type like double
|
||||
* and then assigning to the fastf_t variable to convert the value to
|
||||
* whatever type fastf_t really is. This function makes it possible
|
||||
* to scan a series of fastf_t numbers separated by some character(s)
|
||||
* easily, by doing the required conversion internally to the
|
||||
* functions. As series of delimiter characters will be skipped,
|
||||
* empty scan fields are not supported (e.g., "0.0,,0.0,1.0" will scan
|
||||
* as 3 fields, not 4 with the 2nd skipped).
|
||||
* to scan a series of fastf_t numbers easily, by doing the required
|
||||
* conversion internally. Delimiters form a non-empty character set:
|
||||
* one or more delimiter characters must separate values, and repeated
|
||||
* delimiters are skipped. Empty scan fields are therefore not
|
||||
* supported (e.g., "0.0,,0.0,1.0" scans as 3 fields, not 4 with the
|
||||
* second skipped). A trailing delimiter is not consumed after the
|
||||
* final requested value.
|
||||
*
|
||||
* @param[out] c Returns number of characters scanned by the function
|
||||
* @param[out] c Optional destination for the number of input characters
|
||||
* consumed. It is set to zero before scanning and remains zero for
|
||||
* invalid arguments or when no value is scanned.
|
||||
* @param[in] src A source string to scan from, or NULL to read from stdin
|
||||
* @param[in] delim Any delimiter character(s) to skip between scan values
|
||||
* @param[in] delim Non-empty set of delimiter characters to skip between
|
||||
* scan values
|
||||
* @param[in] n Number of fastf_t values to scan from the src input string
|
||||
* @param[out] ... Pointers to fastf_t for storing scanned values (optional)
|
||||
* @param[out] ... Exactly n fastf_t pointers for storing scanned values;
|
||||
* individual pointers may be NULL
|
||||
* @return Number of values scanned
|
||||
*
|
||||
*/
|
||||
BU_EXPORT extern int bu_scan_fastf_t(int *c, const char *src, const char *delim, size_t n, ...);
|
||||
|
||||
+14
-1
@@ -103,10 +103,23 @@ BU_EXPORT extern void bu_nice_set(int newnice);
|
||||
|
||||
/**
|
||||
* Return the maximum number of physical CPUs that are considered to
|
||||
* be available to this process now.
|
||||
* be available to this process now, subject to any process-local limit set by
|
||||
* bu_avail_cpus_set().
|
||||
*/
|
||||
BU_EXPORT extern size_t bu_avail_cpus(void);
|
||||
|
||||
/**
|
||||
* Limit the CPU count reported by bu_avail_cpus() and honored by subsequent
|
||||
* bu_parallel() calls in this process. A value of zero removes the limit.
|
||||
* Call this before starting worker threads; changing the limit does not resize
|
||||
* work that is already running.
|
||||
*
|
||||
* This is useful when several independent processes share one machine and
|
||||
* each process contains code that selects its own parallelism with
|
||||
* bu_avail_cpus().
|
||||
*/
|
||||
BU_EXPORT extern void bu_avail_cpus_set(size_t ncpu);
|
||||
|
||||
|
||||
/**
|
||||
* Create parallel threads of execution.
|
||||
|
||||
+2
-2
@@ -84,7 +84,7 @@ __BEGIN_DECLS
|
||||
#define RT_DEBUG_HF 0x04000000 /**< @brief 27 Height Field solids */
|
||||
|
||||
#define RT_DEBUG_MESHING 0x08000000 /**< @brief 28 Print meshing/triangulation details */
|
||||
#define RT_DEBUG_UNUSED_3 0x10000000 /**< @brief 29 Unassigned */
|
||||
#define RT_DEBUG_RTCMP 0x10000000 /**< @brief 29 Append rays to LIBRT_RTCMP_FILE; LIBRT_RTCMP_PRIMITIVES=1 includes primitive segments */
|
||||
#define RT_DEBUG_UNUSED_4 0x20000000 /**< @brief 30 Unassigned */
|
||||
|
||||
/* Options which will cause the library to write binary debugging output */
|
||||
@@ -96,7 +96,7 @@ __BEGIN_DECLS
|
||||
"\040PL_BOX" \
|
||||
"\037PL_SOLIDS" \
|
||||
"\036UNUSED_4" \
|
||||
"\035UNUSED_3" \
|
||||
"\035RTCMP" \
|
||||
"\034UNUSED_2" \
|
||||
"\033HF" \
|
||||
"\032EBM" \
|
||||
|
||||
+23
-6
@@ -465,6 +465,17 @@ rt_get_solid_keypoint(struct rt_edit *s, point_t *pt, const char **strp, fastf_t
|
||||
RT_EXPORT extern void
|
||||
rt_edit_set_edflag(struct rt_edit *s, int edflag);
|
||||
|
||||
/**
|
||||
* Set a parameter-edit translation target expressed in model base units.
|
||||
*
|
||||
* rt_edit's parameter-edit handlers consume e_para in database local units,
|
||||
* while keypoints and edit axes are maintained in model base units. This
|
||||
* helper performs the boundary conversion for callers that have computed a
|
||||
* target from a keypoint, axis, or view transform.
|
||||
*/
|
||||
RT_EXPORT extern void
|
||||
rt_edit_set_translation_target(struct rt_edit *s, const point_t target);
|
||||
|
||||
RT_EXPORT extern int
|
||||
rt_edit_knob_cmd_process(
|
||||
struct rt_edit *s,
|
||||
@@ -499,8 +510,10 @@ rt_knob_edit_sca(
|
||||
int matrix_edit);
|
||||
|
||||
/* Equivalent to sedit - run editing logic after input data is set in
|
||||
* rt_edit container */
|
||||
RT_EXPORT extern void
|
||||
* rt_edit container. Transient input flags are consumed whether the edit
|
||||
* succeeds or fails; parameter values remain available to the caller.
|
||||
* Returns BRLCAD_ERROR if the primitive edit fails. */
|
||||
RT_EXPORT extern int
|
||||
rt_edit_process(struct rt_edit *s);
|
||||
|
||||
/**
|
||||
@@ -521,7 +534,7 @@ rt_edit_snap_point(point2d_t pt, const struct rt_edit *s);
|
||||
* restored later with rt_edit_revert().
|
||||
*
|
||||
* The snapshot is stored inside the rt_edit struct. Calling this
|
||||
* function again overwrites any previous snapshot (single-level undo).
|
||||
* function again replaces the previous snapshot only on success.
|
||||
*
|
||||
* @return BRLCAD_OK on success, BRLCAD_ERROR if the export failed.
|
||||
*/
|
||||
@@ -532,8 +545,8 @@ rt_edit_checkpoint(struct rt_edit *s);
|
||||
* Restore primitive parameters from the snapshot saved by
|
||||
* rt_edit_checkpoint().
|
||||
*
|
||||
* If no snapshot has been saved (or the last snapshot was already
|
||||
* consumed) this function logs a message and returns BRLCAD_ERROR.
|
||||
* The snapshot remains available for repeated restores. If none has
|
||||
* been saved, this function logs a message and returns BRLCAD_ERROR.
|
||||
*
|
||||
* @return BRLCAD_OK on success, BRLCAD_ERROR otherwise.
|
||||
*/
|
||||
@@ -697,7 +710,11 @@ enum rt_constraint_edit_op_kind {
|
||||
RT_CONSTRAINT_EDIT_OP_SET_BEND,
|
||||
RT_CONSTRAINT_EDIT_OP_SCALE_OD,
|
||||
RT_CONSTRAINT_EDIT_OP_SCALE_ID,
|
||||
RT_CONSTRAINT_EDIT_OP_SCALE_BEND
|
||||
RT_CONSTRAINT_EDIT_OP_SCALE_BEND,
|
||||
/* Set every point when an all-zero dimension has no scale reference. */
|
||||
RT_CONSTRAINT_EDIT_OP_SET_ALL_OD,
|
||||
RT_CONSTRAINT_EDIT_OP_SET_ALL_ID,
|
||||
RT_CONSTRAINT_EDIT_OP_SET_ALL_BEND
|
||||
};
|
||||
|
||||
struct rt_constraint_edit_param_ref {
|
||||
|
||||
@@ -227,6 +227,32 @@ struct rt_crofton_params {
|
||||
double time_ms; /**< wall-clock time budget (ms); 0 = disabled */
|
||||
};
|
||||
|
||||
/** One solid partition observed by a Crofton ray. */
|
||||
struct rt_crofton_segment {
|
||||
point_t in_point;
|
||||
vect_t in_normal;
|
||||
point_t out_point;
|
||||
vect_t out_normal;
|
||||
fastf_t thickness;
|
||||
size_t ray_id;
|
||||
};
|
||||
|
||||
/**
|
||||
* Structured samples and estimates produced by rt_crofton_collect().
|
||||
* Release @p segments with rt_crofton_result_free().
|
||||
*/
|
||||
struct rt_crofton_result {
|
||||
struct rt_crofton_segment *segments;
|
||||
size_t segment_count;
|
||||
size_t ray_count;
|
||||
size_t crossing_count;
|
||||
double surface_area;
|
||||
double volume;
|
||||
};
|
||||
|
||||
/** Initialize an rt_crofton_result before first use. */
|
||||
#define RT_CROFTON_RESULT_INIT { NULL, 0, 0, 0, 0.0, 0.0 }
|
||||
|
||||
|
||||
/**
|
||||
* Run the Cauchy-Crofton ray-sampling estimator on an already-prepared
|
||||
@@ -337,6 +363,26 @@ struct rt_crofton_params {
|
||||
*/
|
||||
RT_EXPORT extern int rt_crofton_shoot(double *out_surf_area, double *out_volume, point_t *out_aabb_min, point_t *out_aabb_max, point_t out_obb[8], point_t **out_points, size_t *out_point_count, struct rt_i *rtip, const struct rt_crofton_params *params, const fastf_t *bbox_min, const fastf_t *bbox_max);
|
||||
|
||||
/**
|
||||
* Run Crofton sampling while preserving oriented entry/exit pairs.
|
||||
*
|
||||
* @p result must be initialized with RT_CROFTON_RESULT_INIT. On success it
|
||||
* owns the returned segment array. @p rtip must already be prepared.
|
||||
* @p ray_offset skips that many samples in the deterministic sequence and
|
||||
* labels the returned rays starting at that value. This lets successive
|
||||
* calls use disjoint validation streams.
|
||||
*/
|
||||
RT_EXPORT extern int rt_crofton_collect(struct rt_crofton_result *result,
|
||||
struct rt_i *rtip,
|
||||
const struct rt_crofton_params *params,
|
||||
size_t ray_offset,
|
||||
const fastf_t *bbox_min,
|
||||
const fastf_t *bbox_max);
|
||||
|
||||
/** Release storage owned by a structured Crofton result. */
|
||||
RT_EXPORT extern void rt_crofton_result_free(
|
||||
struct rt_crofton_result *result);
|
||||
|
||||
|
||||
/**
|
||||
* Cauchy-Crofton surface-area and/or volume estimator for a primitive.
|
||||
|
||||
@@ -55,14 +55,11 @@ struct clt_tri_specific {
|
||||
};
|
||||
#endif
|
||||
|
||||
#define RT_BOT_SURFNO_INTERIOR (-1)
|
||||
|
||||
/* Shared between bot and ars at the moment */
|
||||
struct bot_specific {
|
||||
unsigned char bot_mode;
|
||||
unsigned char bot_orientation;
|
||||
unsigned char bot_flags;
|
||||
unsigned char bot_parity_shot;
|
||||
size_t bot_ntri;
|
||||
fastf_t *bot_thickness;
|
||||
struct bu_bitv *bot_facemode;
|
||||
|
||||
@@ -41,6 +41,7 @@ struct rt_nmg_edit {
|
||||
struct loopuse *lu_copy; /* copy of loop to be extruded */
|
||||
plane_t lu_pl; /* plane equation for loop to be extruded */
|
||||
struct shell *es_s; /* Shell where extrusion is to end up */
|
||||
int es_s_from_extrusion; /* Replace this edit's prior preview */
|
||||
point_t lu_keypoint; /* keypoint of lu_copy for extrusion */
|
||||
struct vertex *es_v; /* Currently selected NMG vertex (ECMD_NMG_VPICK) */
|
||||
struct faceuse *es_fu; /* Currently selected NMG faceuse (ECMD_NMG_FPICK) */
|
||||
|
||||
@@ -55,6 +55,9 @@
|
||||
|
||||
__BEGIN_DECLS
|
||||
|
||||
/** Wait until pending RT_DEBUG_RTCMP records have reached the output file. */
|
||||
RT_EXPORT extern int rt_rtcmp_capture_flush(void);
|
||||
|
||||
/**
|
||||
* @brief
|
||||
* Shoot a ray
|
||||
|
||||
@@ -2200,7 +2200,11 @@ macro(find_package_opencv)
|
||||
set(OpenCV_DIR_TMP "${OpenCV_DIR}")
|
||||
set(OpenCV_DIR "${CMAKE_BINARY_DIR}/${LIB_DIR}/cmake/opencv4")
|
||||
set(OpenCV_ROOT ${CMAKE_BINARY_DIR})
|
||||
find_package(OpenCV COMPONENTS core features2d imgproc highgui)
|
||||
find_package(OpenCV CONFIG COMPONENTS core imgproc imgcodecs highgui)
|
||||
if(OpenCV_FOUND AND OpenCV_VERSION_MAJOR GREATER_EQUAL 5)
|
||||
# OpenCV 5 moved boundingRect from imgproc to geometry.
|
||||
find_package(OpenCV CONFIG COMPONENTS geometry)
|
||||
endif()
|
||||
unset(OpenCV_ROOT)
|
||||
|
||||
# If no bundled copy, see what the system has
|
||||
|
||||
@@ -117,6 +117,20 @@ if(TARGET libged)
|
||||
|
||||
endif(TARGET libged)
|
||||
|
||||
if(TARGET librt AND FUZZER_SUPPORTED)
|
||||
set(RT_EDIT_FUZZ_DIR "${CMAKE_SOURCE_DIR}/src/librt/tests/edit")
|
||||
brlcad_addexec(
|
||||
fuzz_rt_edit_test
|
||||
"${RT_EDIT_FUZZ_DIR}/fuzz.cpp;${RT_EDIT_FUZZ_DIR}/ars.cpp;${RT_EDIT_FUZZ_DIR}/bot.cpp"
|
||||
"libbu;librt;libnmg;libwdb;libbrep"
|
||||
TEST
|
||||
)
|
||||
set_target_properties(fuzz_rt_edit_test PROPERTIES UNITY_BUILD OFF)
|
||||
target_compile_options(fuzz_rt_edit_test PRIVATE ${FUZZER_EXE_COMPILE_OPTIONS})
|
||||
target_link_options(fuzz_rt_edit_test PRIVATE ${FUZZER_LINK_OPTIONS})
|
||||
BRLCAD_ADD_TEST(NAME fuzz_rt_edit_smoke COMMAND fuzz_rt_edit_test -runs=1 -max_total_time=5)
|
||||
endif()
|
||||
|
||||
cmakefiles(
|
||||
CMakeLists.txt
|
||||
fuzz_ged.cpp
|
||||
|
||||
@@ -68,6 +68,13 @@
|
||||
* ("/tc6_reg.c/sub6.s#sub"), so the lookup missed and no variant was
|
||||
* applied, leaving the phantom face. After the fix the plan is built
|
||||
* from region roots so keys match and the phantom face is eliminated.
|
||||
*
|
||||
* TC7 - NMG Boolean isolation and output modes: verifies that an interrupted
|
||||
* worker cannot commit output, then exercises BoT, NMG, region, and
|
||||
* in-place output paths.
|
||||
*
|
||||
* TC8 - implicit solid roots survive the working-database close and remain
|
||||
* valid members of the imported output hierarchy.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
@@ -78,7 +85,9 @@
|
||||
#include <string>
|
||||
|
||||
#include "bu/app.h"
|
||||
#include "bu/env.h"
|
||||
#include "bu/file.h"
|
||||
#include "bu/log.h"
|
||||
#include "bu/malloc.h"
|
||||
#include "bu/str.h"
|
||||
#include "bu/vls.h"
|
||||
@@ -142,6 +151,36 @@ write_comb2(struct rt_wdb *wdbp,
|
||||
0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
static int
|
||||
write_comb1(struct rt_wdb *wdbp, const char *comb_name, const char *member, int is_region)
|
||||
{
|
||||
struct bu_list head;
|
||||
BU_LIST_INIT(&head);
|
||||
mk_addmember(member, &head, NULL, WMOP_UNION);
|
||||
return mk_comb(wdbp, comb_name, &head, is_region, NULL, NULL, NULL,
|
||||
0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
static int
|
||||
run_facetize_command(const char *gfile, int argc, const char **argv, int verbose)
|
||||
{
|
||||
struct ged *gedp = ged_open("db", gfile, 1);
|
||||
if (!gedp) {
|
||||
bu_log("[regress_facetize] ged_open(%s) failed\n", gfile);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
int ret = ged_exec(gedp, argc, argv);
|
||||
if (verbose || ret != BRLCAD_OK) {
|
||||
const char *log = bu_vls_cstr(gedp->ged_result_str);
|
||||
if (log && log[0])
|
||||
bu_log("[facetize] %s\n", log);
|
||||
}
|
||||
|
||||
ged_close(gedp);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open @a gfile with ged_open and run "facetize @a input @a output".
|
||||
* Returns BRLCAD_OK on success, BRLCAD_ERROR otherwise.
|
||||
@@ -149,23 +188,8 @@ write_comb2(struct rt_wdb *wdbp,
|
||||
static int
|
||||
run_facetize(const char *gfile, const char *input, const char *output, int verbose)
|
||||
{
|
||||
struct ged *gedp = ged_open("db", gfile, 1);
|
||||
if (!gedp) {
|
||||
bu_log("[regress_facetize] ged_open(%s) failed\n", gfile);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
const char *av[4] = {"facetize", input, output, NULL};
|
||||
int ret = ged_exec(gedp, 3, av);
|
||||
|
||||
if (verbose || ret != BRLCAD_OK) {
|
||||
const char *log = bu_vls_cstr(gedp->ged_result_str);
|
||||
if (log && log[0])
|
||||
bu_log("[facetize] %s\n", log);
|
||||
}
|
||||
|
||||
ged_close(gedp);
|
||||
return ret;
|
||||
return run_facetize_command(gfile, 3, av, verbose);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -212,6 +236,46 @@ bu_log("[regress_facetize] check_bot: '%s' type %d is not a BoT\n",
|
||||
return ok;
|
||||
}
|
||||
|
||||
static int
|
||||
check_object_type(const char *gfile, const char *object_name, int expected_type)
|
||||
{
|
||||
struct db_i *dbip = db_open(gfile, DB_OPEN_READONLY);
|
||||
if (!dbip || db_dirbuild(dbip) < 0) {
|
||||
if (dbip)
|
||||
db_close(dbip);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
struct directory *dp = db_lookup(dbip, object_name, LOOKUP_QUIET);
|
||||
if (!dp) {
|
||||
bu_log("[regress_facetize] '%s' does not exist\n", object_name);
|
||||
db_close(dbip);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
struct rt_db_internal intern;
|
||||
RT_DB_INTERNAL_INIT(&intern);
|
||||
if (rt_db_get_internal(&intern, dp, dbip, NULL) < 0) {
|
||||
db_close(dbip);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
int ret = (intern.idb_minor_type == expected_type) ? BRLCAD_OK : BRLCAD_ERROR;
|
||||
if (ret != BRLCAD_OK)
|
||||
bu_log("[regress_facetize] '%s' type %d, expected %d\n",
|
||||
object_name, intern.idb_minor_type, expected_type);
|
||||
rt_db_free_internal(&intern);
|
||||
db_close(dbip);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int
|
||||
count_log_hook(void *data, void *UNUSED(message))
|
||||
{
|
||||
int *count = (int *)data;
|
||||
(*count)++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run rt_crofton_shoot on @a obj_name in @a gfile.
|
||||
* Stores SA (mm2) and VOL (mm3) in *sa / *vol.
|
||||
@@ -1120,6 +1184,183 @@ tc6_havoc_wind9_pattern(const char *tmpdir, int verbose)
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
|
||||
static int
|
||||
tc7_nmg_modes(const char *tmpdir, int verbose)
|
||||
{
|
||||
bu_log("[regress_facetize] TC7: NMG Boolean and output modes...\n");
|
||||
|
||||
struct bu_vls gpath = BU_VLS_INIT_ZERO;
|
||||
bu_vls_printf(&gpath, "%s/tc7_nmg.g", tmpdir);
|
||||
const char *gfile = bu_vls_cstr(&gpath);
|
||||
if (bu_file_exists(gfile, NULL))
|
||||
bu_file_delete(gfile);
|
||||
|
||||
struct db_i *dbip = db_create(gfile, 5);
|
||||
if (!dbip) {
|
||||
bu_vls_free(&gpath);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
|
||||
point_t box_pts[8] = {
|
||||
{0.0, 0.0, 0.0}, {10.0, 0.0, 0.0},
|
||||
{10.0, 10.0, 0.0}, {0.0, 10.0, 0.0},
|
||||
{0.0, 0.0, 10.0}, {10.0, 0.0, 10.0},
|
||||
{10.0, 10.0, 10.0}, {0.0, 10.0, 10.0}
|
||||
};
|
||||
if (write_arb8(wdbp, "box.s", box_pts) < 0 ||
|
||||
write_comb1(wdbp, "box.r", "box.s", 1) < 0 ||
|
||||
write_comb1(wdbp, "box.c", "box.s", 0) < 0) {
|
||||
wdb_close(wdbp);
|
||||
bu_vls_free(&gpath);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
wdb_close(wdbp);
|
||||
|
||||
const char *bot_av[] = {"facetize", "--nmg-booleval", "box.r", "box.bot", NULL};
|
||||
const char *fault_av[] = {"facetize", "--nmg-booleval", "box.r", "fault.bot", NULL};
|
||||
const char *nmg_av[] = {"facetize", "-n", "box.r", "box.nmg", NULL};
|
||||
const char *regions_av[] = {"facetize", "-r", "--nmg-booleval", "box.r", "box.regions", NULL};
|
||||
const char *fallback_av[] = {"facetize", "-r", "--nmg-booleval", "box.c", "box-fallback.bot", NULL};
|
||||
const char *object_in_place_av[] = {"facetize", "--in-place", "--nmg-booleval", "box.c", NULL};
|
||||
const char *in_place_av[] = {"facetize", "-r", "--in-place", "--nmg-booleval", "box.r", NULL};
|
||||
|
||||
int ret = BRLCAD_OK;
|
||||
auto check_tc7 = [&ret](bool passed, const char *description) {
|
||||
if (passed)
|
||||
return;
|
||||
bu_log("[regress_facetize] TC7: FAIL - %s\n", description);
|
||||
ret = BRLCAD_ERROR;
|
||||
};
|
||||
|
||||
struct bu_vls fault_path = BU_VLS_INIT_ZERO;
|
||||
bu_vls_printf(&fault_path, "%s/tc7_nmg_worker.fault", tmpdir);
|
||||
(void)bu_file_delete(bu_vls_cstr(&fault_path));
|
||||
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT",
|
||||
"nmg-before-ready:fault.bot", 1);
|
||||
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT_FILE",
|
||||
bu_vls_cstr(&fault_path), 1);
|
||||
int fault_ret = run_facetize_command(gfile, 4, fault_av, verbose);
|
||||
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT", "", 1);
|
||||
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT_FILE", "", 1);
|
||||
check_tc7(fault_ret == BRLCAD_ERROR,
|
||||
"an interrupted NMG Boolean worker did not report failure");
|
||||
check_tc7(bu_file_exists(bu_vls_cstr(&fault_path), NULL),
|
||||
"NMG Boolean worker fault did not trigger");
|
||||
check_tc7(check_object_type(gfile, "fault.bot", ID_BOT) != BRLCAD_OK,
|
||||
"an interrupted NMG Boolean worker committed an output");
|
||||
(void)bu_file_delete(bu_vls_cstr(&fault_path));
|
||||
bu_vls_free(&fault_path);
|
||||
|
||||
int hook_calls = 0;
|
||||
bu_log_add_hook(count_log_hook, &hook_calls);
|
||||
int bot_ret = run_facetize_command(gfile, 4, bot_av, verbose);
|
||||
int hook_calls_before_probe = hook_calls;
|
||||
bu_log("facetize NMG hook restoration probe\n");
|
||||
bu_log_delete_hook(count_log_hook, &hook_calls);
|
||||
|
||||
check_tc7(bot_ret == BRLCAD_OK, "NMG Boolean BoT command failed");
|
||||
check_tc7(hook_calls == hook_calls_before_probe + 1,
|
||||
"temporary log hook was not restored");
|
||||
check_tc7(check_bot_exists(gfile, "box.bot") == BRLCAD_OK,
|
||||
"NMG Boolean BoT output is missing");
|
||||
|
||||
int nmg_ret = run_facetize_command(gfile, 4, nmg_av, verbose);
|
||||
check_tc7(nmg_ret == BRLCAD_OK, "NMG output command failed");
|
||||
check_tc7(check_object_type(gfile, "box.nmg", ID_NMG) == BRLCAD_OK,
|
||||
"NMG output has the wrong type");
|
||||
|
||||
int regions_ret = run_facetize_command(gfile, 5, regions_av, verbose);
|
||||
check_tc7(regions_ret == BRLCAD_OK, "NMG Boolean region command failed");
|
||||
check_tc7(check_object_type(gfile, "box.regions", ID_COMBINATION) == BRLCAD_OK,
|
||||
"NMG Boolean region output is missing");
|
||||
|
||||
int fallback_ret = run_facetize_command(gfile, 5, fallback_av, verbose);
|
||||
check_tc7(fallback_ret == BRLCAD_OK,
|
||||
"region mode object fallback command failed");
|
||||
check_tc7(check_bot_exists(gfile, "box-fallback.bot") == BRLCAD_OK,
|
||||
"region mode object fallback output is missing");
|
||||
|
||||
int object_in_place_ret = run_facetize_command(gfile, 4,
|
||||
object_in_place_av, verbose);
|
||||
check_tc7(object_in_place_ret == BRLCAD_OK,
|
||||
"in-place NMG Boolean object command failed");
|
||||
check_tc7(check_object_type(gfile, "box.c", ID_BOT) == BRLCAD_OK,
|
||||
"in-place NMG Boolean object has the wrong type");
|
||||
|
||||
int in_place_ret = run_facetize_command(gfile, 5, in_place_av, verbose);
|
||||
check_tc7(in_place_ret == BRLCAD_OK,
|
||||
"in-place NMG Boolean region command failed");
|
||||
check_tc7(check_object_type(gfile, "box.r", ID_COMBINATION) == BRLCAD_OK,
|
||||
"in-place region root has the wrong type");
|
||||
check_tc7(check_bot_exists(gfile, "box.r.bot") == BRLCAD_OK,
|
||||
"in-place region BoT output is missing");
|
||||
|
||||
bu_log("[regress_facetize] TC7: %s\n", ret == BRLCAD_OK ? "PASS" : "FAIL");
|
||||
bu_vls_free(&gpath);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* TC8: implicit root replacement persists across database reopen */
|
||||
/* ------------------------------------------------------------------ */
|
||||
static int
|
||||
tc8_implicit_root_persistence(const char *tmpdir, int verbose)
|
||||
{
|
||||
bu_log("[regress_facetize] TC8: implicit root persistence...\n");
|
||||
|
||||
struct bu_vls gpath = BU_VLS_INIT_ZERO;
|
||||
bu_vls_printf(&gpath, "%s/tc8_implicit_root.g", tmpdir);
|
||||
const char *gfile = bu_vls_cstr(&gpath);
|
||||
if (bu_file_exists(gfile, NULL))
|
||||
bu_file_delete(gfile);
|
||||
|
||||
struct db_i *dbip = db_create(gfile, 5);
|
||||
if (!dbip) {
|
||||
bu_vls_free(&gpath);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
|
||||
point_t region_points[8] = {
|
||||
{0.0, 0.0, 0.0}, {10.0, 0.0, 0.0},
|
||||
{10.0, 10.0, 0.0}, {0.0, 10.0, 0.0},
|
||||
{0.0, 0.0, 10.0}, {10.0, 0.0, 10.0},
|
||||
{10.0, 10.0, 10.0}, {0.0, 10.0, 10.0}
|
||||
};
|
||||
point_t loose_points[8] = {
|
||||
{20.0, 0.0, 0.0}, {30.0, 0.0, 0.0},
|
||||
{30.0, 10.0, 0.0}, {20.0, 10.0, 0.0},
|
||||
{20.0, 0.0, 10.0}, {30.0, 0.0, 10.0},
|
||||
{30.0, 10.0, 10.0}, {20.0, 10.0, 10.0}
|
||||
};
|
||||
if (!wdbp || write_arb8(wdbp, "region.s", region_points) < 0 ||
|
||||
write_arb8(wdbp, "loose.s", loose_points) < 0 ||
|
||||
write_comb1(wdbp, "box.r", "region.s", 1) < 0 ||
|
||||
write_comb2(wdbp, "assembly.c", "box.r", 'u',
|
||||
"loose.s", 'u') < 0) {
|
||||
if (wdbp)
|
||||
wdb_close(wdbp);
|
||||
bu_vls_free(&gpath);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
wdb_close(wdbp);
|
||||
|
||||
const char *facetize_args[] = {
|
||||
"facetize", "-r", "assembly.c", "assembly.regions", NULL
|
||||
};
|
||||
int ret = run_facetize_command(gfile, 4, facetize_args, verbose);
|
||||
if (ret == BRLCAD_OK &&
|
||||
(check_object_type(gfile, "assembly.regions", ID_COMBINATION) != BRLCAD_OK ||
|
||||
check_object_type(gfile, "facetize_assembly.c", ID_COMBINATION) != BRLCAD_OK ||
|
||||
check_bot_exists(gfile, "box.r.bot") != BRLCAD_OK ||
|
||||
check_bot_exists(gfile, "facetize_loose.s") != BRLCAD_OK))
|
||||
ret = BRLCAD_ERROR;
|
||||
|
||||
bu_log("[regress_facetize] TC8: %s\n",
|
||||
ret == BRLCAD_OK ? "PASS" : "FAIL");
|
||||
bu_vls_free(&gpath);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* main */
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -1151,6 +1392,8 @@ return 1;
|
||||
if (tc4_havoc_reuse(tmpdir, verbose) != BRLCAD_OK) ret = 1;
|
||||
if (tc5_near_coplanar_subTOL(tmpdir, verbose) != BRLCAD_OK) ret = 1;
|
||||
if (tc6_havoc_wind9_pattern(tmpdir, verbose) != BRLCAD_OK) ret = 1;
|
||||
if (tc7_nmg_modes(tmpdir, verbose) != BRLCAD_OK) ret = 1;
|
||||
if (tc8_implicit_root_persistence(tmpdir, verbose) != BRLCAD_OK) ret = 1;
|
||||
|
||||
if (ret == 0)
|
||||
bu_log("[regress_facetize] All tests PASSED\n");
|
||||
|
||||
@@ -100,6 +100,7 @@ if(TARGET mged)
|
||||
continue()
|
||||
endif(TNAME STREQUAL "")
|
||||
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${testfile}")
|
||||
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/${testfile}" TEST_CONTENTS)
|
||||
if(TNAME STREQUAL "search_exec")
|
||||
string(CONFIGURE "${TEST_CONTENTS}" TEST_CONTENTS @ONLY)
|
||||
@@ -126,6 +127,12 @@ if(TARGET mged)
|
||||
elseif(TNAME STREQUAL "arb")
|
||||
set(TEST_EXPECT "'arb' testing completed")
|
||||
set(TEST_SOURCE "${CMAKE_CURRENT_BINARY_DIR}/regress_${testfile}")
|
||||
elseif(TNAME MATCHES "^(extrude|facedef|mirface|permute)$")
|
||||
set(TEST_EXPECT "'${TNAME}' testing completed")
|
||||
set(TEST_SOURCE "${CMAKE_CURRENT_BINARY_DIR}/regress_${testfile}")
|
||||
elseif(TNAME STREQUAL "edgedir")
|
||||
set(TEST_EXPECT "'edarb edgedir' testing completed")
|
||||
set(TEST_SOURCE "${CMAKE_CURRENT_BINARY_DIR}/regress_${testfile}")
|
||||
elseif(TNAME STREQUAL "killtree")
|
||||
set(TEST_EXPECT "KILL Solid: killtree_dup.s")
|
||||
set(TEST_REJECT "db_lookup(killtree_dup.s) failed")
|
||||
@@ -187,6 +194,7 @@ distclean(${mged_outfiles})
|
||||
|
||||
cmakefiles(
|
||||
CMakeLists.txt
|
||||
csg_edit.mged
|
||||
mged.tcl
|
||||
regression_resources.tcl
|
||||
search_exec_procs.tcl
|
||||
|
||||
@@ -43,4 +43,37 @@ foreach {arb_type face expected_type} $arb_extrude_cases {
|
||||
arb_standard_storage_check $expected_type $prim
|
||||
}
|
||||
|
||||
# A one-inch extrusion must extend a face by 25.4 base millimeters through
|
||||
# both the direct libged command and MGED's interactive solid editor.
|
||||
set inch_in_mm 25.4
|
||||
set tolerance 0.001
|
||||
foreach mode {direct interactive} {
|
||||
set suffix "_inch_$mode"
|
||||
in_arb8 extrude $suffix
|
||||
set prim "extrude_arb8${suffix}.s"
|
||||
set base_x [lindex [db get $prim V1] 0]
|
||||
|
||||
units in
|
||||
if {$mode eq "direct"} {
|
||||
if {[catch {edarb extrude $prim 1234 1} result]} {
|
||||
error "inch edarb extrusion failed: $result"
|
||||
}
|
||||
} else {
|
||||
Z
|
||||
e $prim
|
||||
sed $prim
|
||||
if {[catch {extrude 1234 1} result]} {
|
||||
error "inch MGED extrusion failed: $result"
|
||||
}
|
||||
accept
|
||||
Z
|
||||
}
|
||||
units mm
|
||||
|
||||
set new_x [lindex [db get $prim V5] 0]
|
||||
if {abs($new_x - $base_x - $inch_in_mm) > $tolerance} {
|
||||
error "inch $mode extrusion moved V5 by [expr {$new_x - $base_x}] mm"
|
||||
}
|
||||
}
|
||||
|
||||
puts "*** 'extrude' testing completed ***"
|
||||
|
||||
@@ -53,12 +53,23 @@ endif(BRLCAD_ENABLE_TCL)
|
||||
# Archer plugins
|
||||
set(
|
||||
archer_utility_FILES
|
||||
plugins/Utility/attrGroupsDisplayUtilityP.tcl
|
||||
plugins/Utility/botUtilityP.tcl
|
||||
plugins/Utility/lodUtilityP.tcl
|
||||
plugins/Utility/README
|
||||
plugins/Utility/attrGroupsDisplayUtilityP.tcl
|
||||
plugins/Utility/attrGroupsDisplayUtilityP/AttrGroupsDisplayUtilityP.tcl
|
||||
plugins/Utility/botUtilityP.tcl
|
||||
plugins/Utility/botUtilityP/BotUtilityP.tcl
|
||||
plugins/Utility/lodUtilityP.tcl
|
||||
plugins/Utility/lodUtilityP/LODUtilityP.tcl
|
||||
)
|
||||
set(archer_wizard_FILES
|
||||
plugins/Wizards/humanwizard.tcl
|
||||
plugins/Wizards/humanwizard/HumanWizard.tcl
|
||||
plugins/Wizards/tankwizard.tcl
|
||||
plugins/Wizards/tankwizard/TankWizard.tcl
|
||||
plugins/Wizards/tankwizard/images/tank.png
|
||||
plugins/Wizards/tirewizard.tcl
|
||||
plugins/Wizards/tirewizard/TireWizard.tcl
|
||||
)
|
||||
set(archer_wizard_FILES plugins/Wizards/humanwizard.tcl plugins/Wizards/tankwizard.tcl plugins/Wizards/tirewizard.tcl)
|
||||
|
||||
if(BRLCAD_ENABLE_TCL)
|
||||
brlcad_adddata(archer_utility_FILES plugins/archer/Utility)
|
||||
@@ -77,6 +88,8 @@ endif(BRLCAD_ENABLE_TCL)
|
||||
set(
|
||||
archer_ignore_files
|
||||
CMakeLists.txt
|
||||
plugins/Commands/README
|
||||
plugins/Core/README
|
||||
${archer_utility_FILES}
|
||||
${archer_wizard_FILES}
|
||||
${archer_txt}
|
||||
|
||||
Vendored
+1
-1
@@ -752,7 +752,7 @@ tessellate_part(struct creo_conv_info *cinfo, ProMdl model, struct bu_vls **snam
|
||||
}
|
||||
|
||||
/* Check solidity */
|
||||
success = bg_trimesh_solid((int)vert_tree->curr_vert, (size_t)faces.size() / 3,
|
||||
success = !bg_trimesh_solid((int)vert_tree->curr_vert, (size_t)faces.size() / 3,
|
||||
vert_tree->the_array, &faces[0], NULL);
|
||||
|
||||
/* If it's not solid and we're testing solidity, keep trying... */
|
||||
|
||||
@@ -34,6 +34,9 @@
|
||||
|
||||
// OpenCV header files
|
||||
#include <opencv2/opencv.hpp>
|
||||
#if CV_VERSION_MAJOR >= 5
|
||||
#include <opencv2/geometry.hpp>
|
||||
#endif
|
||||
#include <opencv2/core/core.hpp>
|
||||
#include "opencv2/highgui/highgui.hpp"
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ set(
|
||||
api.c
|
||||
centroid.c
|
||||
check_options.c
|
||||
contour.cpp
|
||||
density.cpp
|
||||
globals.c
|
||||
inside.c
|
||||
@@ -68,7 +69,7 @@ set(
|
||||
cmakefiles(${libanalyze_ignored_files})
|
||||
|
||||
# Note - libanalyze_deps is defined by ${BRLCAD_SOURCE_DIR}/src/source_dirs.cmake
|
||||
brlcad_addlib(libanalyze "${LIBANALYZE_SOURCES}" "" "${CMAKE_CURRENT_BINARY_DIR}"
|
||||
brlcad_addlib(libanalyze "${LIBANALYZE_SOURCES}" "" "${CMAKE_CURRENT_BINARY_DIR};${EIGEN3_INCLUDE_DIR}"
|
||||
PUBLIC_LIBS ${libanalyze_deps}
|
||||
)
|
||||
set_target_properties(libanalyze PROPERTIES VERSION 20.0.1 SOVERSION 20)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+78
-908
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,6 @@
|
||||
brlcad_addexec(analyze_contour contour.cpp "libanalyze;libwdb;librt;libbg;libbu" TEST)
|
||||
brlcad_add_test(NAME analyze_contour COMMAND analyze_contour)
|
||||
|
||||
brlcad_addexec(analyze_raydiff raydiff.c "libanalyze;librt;libbu" TEST)
|
||||
brlcad_addexec(analyze_sp solid_partitions.c "libanalyze;librt;libbu" TEST)
|
||||
brlcad_addexec(analyze_nhit nhit.cpp "libanalyze;librt;libbu" TEST_USESDATA)
|
||||
@@ -13,6 +16,7 @@ brlcad_add_test(NAME analyze_densities_std COMMAND analyze_densities std)
|
||||
cmakefiles(
|
||||
CMakeLists.txt
|
||||
arbs.g
|
||||
contour.cpp
|
||||
raydiff.g
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
/* A N A L Y Z E _ C O N T O U R . C P P
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* 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,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* 2. 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.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED.
|
||||
*/
|
||||
/** @file contour.cpp
|
||||
*
|
||||
* Basic topology and resource-limit tests for analyze_mdc().
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
|
||||
#include "bu/app.h"
|
||||
#include "bu/malloc.h"
|
||||
#include "bg/trimesh.h"
|
||||
#include "analyze/contour.h"
|
||||
#include "analyze/polygonize.h"
|
||||
#include "raytrace.h"
|
||||
#include "wdb.h"
|
||||
|
||||
static constexpr double METRIC_RELATIVE_TOLERANCE = 0.10;
|
||||
|
||||
static int failures = 0;
|
||||
|
||||
|
||||
static void
|
||||
expect(bool condition, const char *message)
|
||||
{
|
||||
if (condition)
|
||||
return;
|
||||
|
||||
std::fprintf(stderr, "FAIL: %s\n", message);
|
||||
failures++;
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
expect_metric(double actual, double expected, const char *object,
|
||||
const char *metric)
|
||||
{
|
||||
double relative_error = std::fabs(actual - expected) / expected;
|
||||
if (actual >= 0.0 && relative_error <= METRIC_RELATIVE_TOLERANCE)
|
||||
return;
|
||||
|
||||
std::fprintf(stderr,
|
||||
"FAIL: %s %s is %.17g, expected %.17g (relative error %.2f%%)\n",
|
||||
object, metric, actual, expected, 100.0 * relative_error);
|
||||
failures++;
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
check_mesh(struct db_i *dbip, const char *object, int expected_components = 1,
|
||||
double expected_area = 0.0, double expected_volume = 0.0,
|
||||
size_t minimum_faces = 4, int expected_euler = INT_MAX)
|
||||
{
|
||||
int *faces = NULL;
|
||||
point_t *vertices = NULL;
|
||||
size_t face_count = 0;
|
||||
size_t vertex_count = 0;
|
||||
struct analyze_mdc_params params = ANALYZE_MDC_PARAMS_DEFAULT;
|
||||
params.min_depth = 4;
|
||||
params.max_depth = 8;
|
||||
params.max_rays = 0;
|
||||
params.minimum_free_mem = 0;
|
||||
params.max_time = 0;
|
||||
params.verbosity = 0;
|
||||
|
||||
enum analyze_mdc_status status = analyze_mdc(&faces, &face_count,
|
||||
&vertices, &vertex_count, object, dbip, ¶ms);
|
||||
expect(status == ANALYZE_MDC_OK, object);
|
||||
if (status == ANALYZE_MDC_OK) {
|
||||
expect(vertex_count >= 4, "contour has vertices");
|
||||
expect(face_count >= minimum_faces, "contour has expected resolution");
|
||||
expect(bg_trimesh_solid2(static_cast<int>(vertex_count),
|
||||
static_cast<int>(face_count),
|
||||
reinterpret_cast<fastf_t *>(vertices), faces, NULL) == 0,
|
||||
"contour is a closed oriented manifold");
|
||||
if (expected_euler != INT_MAX) {
|
||||
std::set<std::pair<int, int>> edges;
|
||||
for (size_t face = 0; face < face_count; face++) {
|
||||
for (size_t corner = 0; corner < 3; corner++) {
|
||||
int a = faces[3 * face + corner];
|
||||
int b = faces[3 * face + (corner + 1) % 3];
|
||||
edges.insert(std::minmax(a, b));
|
||||
}
|
||||
}
|
||||
long long euler = static_cast<long long>(vertex_count) -
|
||||
static_cast<long long>(edges.size()) +
|
||||
static_cast<long long>(face_count);
|
||||
expect(euler == expected_euler,
|
||||
"contour has the expected Euler characteristic");
|
||||
}
|
||||
if (expected_area > 0.0)
|
||||
expect_metric(bg_trimesh_area(faces, face_count, vertices,
|
||||
vertex_count), expected_area, object, "surface area");
|
||||
if (expected_volume > 0.0)
|
||||
expect_metric(bg_trimesh_volume(faces, face_count, vertices,
|
||||
vertex_count), expected_volume, object, "volume");
|
||||
|
||||
int *face_indices = NULL;
|
||||
int *component_offsets = NULL;
|
||||
int components = bg_trimesh_separate(&face_indices,
|
||||
&component_offsets, faces, static_cast<int>(face_count));
|
||||
expect(components == expected_components,
|
||||
"contour has the expected connected components");
|
||||
if (face_indices)
|
||||
bu_free(face_indices, "MDC test component faces");
|
||||
if (component_offsets)
|
||||
bu_free(component_offsets, "MDC test component offsets");
|
||||
}
|
||||
|
||||
if (faces)
|
||||
bu_free(faces, "MDC test faces");
|
||||
if (vertices)
|
||||
bu_free(vertices, "MDC test vertices");
|
||||
}
|
||||
|
||||
|
||||
static bool
|
||||
make_region(struct rt_wdb *wdbp, const char *region, const char *solid)
|
||||
{
|
||||
struct wmember member;
|
||||
BU_LIST_INIT(&member.l);
|
||||
if (!mk_addmember(solid, &member.l, NULL, WMOP_UNION))
|
||||
return false;
|
||||
return mk_lcomb(wdbp, region, &member, 1, NULL, NULL, NULL, 0) == 0;
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
main(int UNUSED(argc), const char **argv)
|
||||
{
|
||||
bu_setprogname(argv[0]);
|
||||
|
||||
struct db_i *dbip = db_create_inmem();
|
||||
expect(dbip != NULL, "create in-memory database");
|
||||
if (!dbip)
|
||||
return 1;
|
||||
|
||||
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_INMEM);
|
||||
expect(wdbp != NULL, "open in-memory database");
|
||||
if (!wdbp) {
|
||||
db_close(dbip);
|
||||
return 1;
|
||||
}
|
||||
|
||||
constexpr double sphere_radius = 10.0;
|
||||
constexpr double torus_major_radius = 10.0;
|
||||
constexpr double torus_minor_radius = 2.5;
|
||||
constexpr double slender_torus_major_radius = 100.0;
|
||||
constexpr double slender_torus_minor_radius = 2.0;
|
||||
constexpr double lower_radius = 1.5;
|
||||
constexpr double upper_radius = 1.0;
|
||||
|
||||
point_t center = VINIT_ZERO;
|
||||
point_t minimum = {-8.0, -6.0, -4.0};
|
||||
point_t maximum = {8.0, 6.0, 4.0};
|
||||
expect(mk_sph(wdbp, "sphere.s", center, sphere_radius) == 0,
|
||||
"create test sphere");
|
||||
expect(mk_rpp(wdbp, "box.s", minimum, maximum) == 0,
|
||||
"create test box");
|
||||
point_t thin_minimum = {-5.0, -2.5, -0.05};
|
||||
point_t thin_maximum = {5.0, 2.5, 0.05};
|
||||
expect(mk_rpp(wdbp, "thin.s", thin_minimum, thin_maximum) == 0,
|
||||
"create thin-wall test box");
|
||||
|
||||
point_t tunnel_minimum = {-10.0, -10.0, -10.0};
|
||||
point_t tunnel_maximum = {10.0, 10.0, 10.0};
|
||||
point_t tunnel_base = {0.0, 0.0, -11.0};
|
||||
vect_t tunnel_height = {0.0, 0.0, 22.0};
|
||||
expect(mk_rpp(wdbp, "tunnel_outer.s", tunnel_minimum,
|
||||
tunnel_maximum) == 0, "create tunnel test outer box");
|
||||
expect(mk_rcc(wdbp, "tunnel_void.s", tunnel_base, tunnel_height,
|
||||
1.0) == 0, "create tunnel test void");
|
||||
struct wmember tunnel_members;
|
||||
BU_LIST_INIT(&tunnel_members.l);
|
||||
expect(mk_addmember("tunnel_outer.s", &tunnel_members.l, NULL,
|
||||
WMOP_UNION) != NULL, "add tunnel outer box");
|
||||
expect(mk_addmember("tunnel_void.s", &tunnel_members.l, NULL,
|
||||
WMOP_SUBTRACT) != NULL, "subtract tunnel void");
|
||||
expect(mk_lcomb(wdbp, "tunnel.r", &tunnel_members, 1, NULL, NULL,
|
||||
NULL, 0) == 0, "create tunnel test region");
|
||||
vect_t normal = {0.0, 0.0, 1.0};
|
||||
expect(mk_tor(wdbp, "torus.s", center, normal, torus_major_radius,
|
||||
torus_minor_radius) == 0,
|
||||
"create test torus");
|
||||
expect(mk_tor(wdbp, "slender_torus.s", center, normal,
|
||||
slender_torus_major_radius, slender_torus_minor_radius) == 0,
|
||||
"create high-aspect torus");
|
||||
|
||||
point_t tgc_base = {-4.0, -3.0, -6.0};
|
||||
vect_t tgc_height = {2.0, 1.0, 12.0};
|
||||
vect_t tgc_a = {5.0, 0.0, 0.0};
|
||||
vect_t tgc_b = {0.0, 3.0, 0.0};
|
||||
vect_t tgc_c = {2.5, 0.0, 0.0};
|
||||
vect_t tgc_d = {0.0, 1.5, 0.0};
|
||||
expect(mk_tgc(wdbp, "tgc.s", tgc_base, tgc_height, tgc_a, tgc_b,
|
||||
tgc_c, tgc_d) == 0, "create test TGC");
|
||||
|
||||
point_t concave_arb[8] = {
|
||||
{500.0, -500.0, -500.0},
|
||||
{500.0, 500.0, -500.0},
|
||||
{500.0, -169.922, -304.688},
|
||||
{500.0, -500.0, 500.0},
|
||||
{400.0, -500.0, -500.0},
|
||||
{400.0, 500.0, -500.0},
|
||||
{400.0, -169.922, -304.688},
|
||||
{400.0, -500.0, 500.0}
|
||||
};
|
||||
expect(mk_arb8(wdbp, "concave.s",
|
||||
reinterpret_cast<const fastf_t *>(concave_arb)) == 0,
|
||||
"create sharp concave ARB");
|
||||
|
||||
point_t lower_center = {-8.0, -5.0, -3.0};
|
||||
point_t upper_center = {9.0, 4.0, 6.0};
|
||||
expect(mk_sph(wdbp, "lower.s", lower_center, lower_radius) == 0,
|
||||
"create lower disconnected sphere");
|
||||
expect(mk_sph(wdbp, "upper.s", upper_center, upper_radius) == 0,
|
||||
"create upper disconnected sphere");
|
||||
struct wmember members;
|
||||
BU_LIST_INIT(&members.l);
|
||||
expect(mk_addmember("lower.s", &members.l, NULL, WMOP_UNION) != NULL,
|
||||
"add lower disconnected sphere");
|
||||
expect(mk_addmember("upper.s", &members.l, NULL, WMOP_UNION) != NULL,
|
||||
"add upper disconnected sphere");
|
||||
expect(mk_lcomb(wdbp, "disconnected.r", &members, 1, NULL, NULL, NULL,
|
||||
0) == 0, "create disconnected region");
|
||||
|
||||
constexpr double overlap_radius = 5.0;
|
||||
constexpr double overlap_offset = 3.0;
|
||||
point_t overlap_left_center = {-overlap_offset, 0.0, 0.0};
|
||||
point_t overlap_right_center = {overlap_offset, 0.0, 0.0};
|
||||
expect(mk_sph(wdbp, "overlap_left.s", overlap_left_center,
|
||||
overlap_radius) == 0, "create left overlapping sphere");
|
||||
expect(mk_sph(wdbp, "overlap_right.s", overlap_right_center,
|
||||
overlap_radius) == 0, "create right overlapping sphere");
|
||||
expect(make_region(wdbp, "overlap_left.r", "overlap_left.s"),
|
||||
"create left overlapping region");
|
||||
expect(make_region(wdbp, "overlap_right.r", "overlap_right.s"),
|
||||
"create right overlapping region");
|
||||
struct wmember overlap_members;
|
||||
BU_LIST_INIT(&overlap_members.l);
|
||||
expect(mk_addmember("overlap_left.r", &overlap_members.l, NULL,
|
||||
WMOP_UNION) != NULL, "add left overlapping region");
|
||||
expect(mk_addmember("overlap_right.r", &overlap_members.l, NULL,
|
||||
WMOP_UNION) != NULL, "add right overlapping region");
|
||||
expect(mk_lcomb(wdbp, "overlap.c", &overlap_members, 0, NULL, NULL,
|
||||
NULL, 0) == 0, "create overlapping-region combination");
|
||||
|
||||
vect_t box_size;
|
||||
VSUB2(box_size, maximum, minimum);
|
||||
|
||||
const double sphere_area = 4.0 * M_PI * sphere_radius * sphere_radius;
|
||||
const double sphere_volume = 4.0 * M_PI * sphere_radius * sphere_radius *
|
||||
sphere_radius / 3.0;
|
||||
const double box_area = 2.0 * (box_size[X] * box_size[Y] +
|
||||
box_size[X] * box_size[Z] + box_size[Y] * box_size[Z]);
|
||||
const double box_volume = box_size[X] * box_size[Y] * box_size[Z];
|
||||
vect_t thin_size;
|
||||
VSUB2(thin_size, thin_maximum, thin_minimum);
|
||||
const double thin_area = 2.0 * (thin_size[X] * thin_size[Y] +
|
||||
thin_size[X] * thin_size[Z] + thin_size[Y] * thin_size[Z]);
|
||||
const double thin_volume =
|
||||
thin_size[X] * thin_size[Y] * thin_size[Z];
|
||||
const double torus_area = 4.0 * M_PI * M_PI * torus_major_radius *
|
||||
torus_minor_radius;
|
||||
const double torus_volume = 2.0 * M_PI * M_PI * torus_major_radius *
|
||||
torus_minor_radius * torus_minor_radius;
|
||||
const double slender_torus_area = 4.0 * M_PI * M_PI *
|
||||
slender_torus_major_radius * slender_torus_minor_radius;
|
||||
const double disconnected_area = 4.0 * M_PI *
|
||||
(lower_radius * lower_radius + upper_radius * upper_radius);
|
||||
const double disconnected_volume = 4.0 * M_PI *
|
||||
(lower_radius * lower_radius * lower_radius +
|
||||
upper_radius * upper_radius * upper_radius) / 3.0;
|
||||
const double overlap_distance = 2.0 * overlap_offset;
|
||||
const double overlap_cap_height = overlap_radius -
|
||||
0.5 * overlap_distance;
|
||||
const double overlap_intersection_volume = M_PI *
|
||||
(4.0 * overlap_radius + overlap_distance) *
|
||||
std::pow(2.0 * overlap_radius - overlap_distance, 2.0) / 12.0;
|
||||
const double overlap_area = 8.0 * M_PI * overlap_radius *
|
||||
overlap_radius - 4.0 * M_PI * overlap_radius * overlap_cap_height;
|
||||
const double overlap_volume = 8.0 * M_PI * overlap_radius *
|
||||
overlap_radius * overlap_radius / 3.0 -
|
||||
overlap_intersection_volume;
|
||||
|
||||
check_mesh(dbip, "sphere.s", 1, sphere_area, sphere_volume);
|
||||
check_mesh(dbip, "box.s", 1, box_area, box_volume);
|
||||
check_mesh(dbip, "thin.s", 1, thin_area, thin_volume, 10000);
|
||||
check_mesh(dbip, "torus.s", 1, torus_area, torus_volume, 4, 0);
|
||||
check_mesh(dbip, "slender_torus.s", 1, slender_torus_area,
|
||||
0.0, 4, 0);
|
||||
check_mesh(dbip, "tunnel.r", 1, 0.0, 0.0, 4, 0);
|
||||
check_mesh(dbip, "tgc.s");
|
||||
check_mesh(dbip, "concave.s");
|
||||
check_mesh(dbip, "disconnected.r", 2, disconnected_area,
|
||||
disconnected_volume);
|
||||
check_mesh(dbip, "overlap.c", 1, overlap_area, overlap_volume);
|
||||
|
||||
{
|
||||
int *coarse_faces = NULL;
|
||||
point_t *coarse_vertices = NULL;
|
||||
size_t coarse_face_count = 0;
|
||||
size_t coarse_vertex_count = 0;
|
||||
struct analyze_mdc_params coarse = ANALYZE_MDC_PARAMS_DEFAULT;
|
||||
coarse.min_depth = 3;
|
||||
coarse.max_depth = 3;
|
||||
coarse.max_rays = 50000;
|
||||
coarse.minimum_free_mem = 0;
|
||||
coarse.max_time = 0;
|
||||
enum analyze_mdc_status coarse_status = analyze_mdc(&coarse_faces,
|
||||
&coarse_face_count, &coarse_vertices, &coarse_vertex_count,
|
||||
"tunnel.r", dbip, &coarse);
|
||||
expect(coarse_status == ANALYZE_MDC_AMBIGUOUS,
|
||||
"under-resolved tunnel requests refinement");
|
||||
expect(!coarse_faces && !coarse_vertices && !coarse_face_count &&
|
||||
coarse_vertex_count == 0,
|
||||
"under-resolved tunnel leaves outputs empty");
|
||||
if (coarse_faces)
|
||||
bu_free(coarse_faces, "coarse MDC test faces");
|
||||
if (coarse_vertices)
|
||||
bu_free(coarse_vertices, "coarse MDC test vertices");
|
||||
}
|
||||
|
||||
{
|
||||
int *compatibility_faces = NULL;
|
||||
point_t *compatibility_vertices = NULL;
|
||||
int compatibility_face_count = 0;
|
||||
int compatibility_vertex_count = 0;
|
||||
point_t unused_seed = VINIT_ZERO;
|
||||
struct analyze_polygonize_params compatibility =
|
||||
ANALYZE_POLYGONIZE_PARAMS_DEFAULT;
|
||||
compatibility.max_time = 0;
|
||||
compatibility.max_cycle_time = 0;
|
||||
compatibility.minimum_free_mem = 0;
|
||||
|
||||
int status = analyze_polygonize(&compatibility_faces,
|
||||
&compatibility_face_count, &compatibility_vertices,
|
||||
&compatibility_vertex_count, 1.0, unused_seed, "sphere.s",
|
||||
dbip, &compatibility);
|
||||
expect(status == 0, "polygonize compatibility interface");
|
||||
if (status == 0) {
|
||||
expect(compatibility_face_count >= 4,
|
||||
"compatibility contour has faces");
|
||||
expect(compatibility_vertex_count >= 4,
|
||||
"compatibility contour has vertices");
|
||||
expect(bg_trimesh_solid2(compatibility_vertex_count,
|
||||
compatibility_face_count,
|
||||
reinterpret_cast<fastf_t *>(compatibility_vertices),
|
||||
compatibility_faces, NULL) == 0,
|
||||
"compatibility contour is a closed oriented manifold");
|
||||
}
|
||||
if (compatibility_faces)
|
||||
bu_free(compatibility_faces, "compatibility test faces");
|
||||
if (compatibility_vertices)
|
||||
bu_free(compatibility_vertices, "compatibility test vertices");
|
||||
|
||||
compatibility.max_time = 1;
|
||||
compatibility.time_offset = 1;
|
||||
expect(analyze_polygonize(&compatibility_faces,
|
||||
&compatibility_face_count, &compatibility_vertices,
|
||||
&compatibility_vertex_count, 1.0, unused_seed, "sphere.s",
|
||||
dbip, &compatibility) == 2,
|
||||
"compatibility interface preserves timeout status");
|
||||
expect(!compatibility_faces && !compatibility_vertices &&
|
||||
!compatibility_face_count && !compatibility_vertex_count,
|
||||
"compatibility timeout leaves outputs empty");
|
||||
}
|
||||
|
||||
int *faces = NULL;
|
||||
point_t *vertices = NULL;
|
||||
size_t face_count = 0;
|
||||
size_t vertex_count = 0;
|
||||
struct analyze_mdc_params limited = ANALYZE_MDC_PARAMS_DEFAULT;
|
||||
limited.min_depth = 4;
|
||||
limited.max_depth = 4;
|
||||
limited.max_rays = 1;
|
||||
limited.minimum_free_mem = 0;
|
||||
expect(analyze_mdc(&faces, &face_count, &vertices, &vertex_count,
|
||||
"sphere.s", dbip, &limited) == ANALYZE_MDC_RAY_LIMIT,
|
||||
"ray limit is enforced during sampling");
|
||||
expect(!faces && !vertices && !face_count && !vertex_count,
|
||||
"failure leaves outputs empty");
|
||||
|
||||
expect(analyze_mdc(NULL, &face_count, &vertices, &vertex_count,
|
||||
"sphere.s", dbip, NULL) == ANALYZE_MDC_INVALID_INPUT,
|
||||
"invalid output pointer is rejected");
|
||||
|
||||
db_close(dbip);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Local Variables:
|
||||
* mode: C++
|
||||
* tab-width: 8
|
||||
* c-basic-offset: 4
|
||||
* indent-tabs-mode: t
|
||||
* c-file-style: "stroustrup"
|
||||
* End:
|
||||
* ex: shiftwidth=4 tabstop=8
|
||||
*/
|
||||
+4
-4
@@ -113,10 +113,10 @@ bg_lseg_clip(fastf_t *xp1, fastf_t *yp1, fastf_t *xp2, fastf_t *yp2, fastf_t cli
|
||||
int
|
||||
bg_ray_vclip(point_t a, point_t b, const fastf_t *min_pt, const fastf_t *max_pt)
|
||||
{
|
||||
static vect_t diff;
|
||||
static double sv;
|
||||
static double st;
|
||||
static double mindist, maxdist;
|
||||
vect_t diff;
|
||||
double sv;
|
||||
double st;
|
||||
double mindist, maxdist;
|
||||
fastf_t *pt = &a[0];
|
||||
fastf_t *dir = &diff[0];
|
||||
int i;
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@
|
||||
/** @file libbg/pca.cpp
|
||||
*
|
||||
* @brief
|
||||
* Principle Component Analysis.
|
||||
* Principal Component Analysis.
|
||||
*
|
||||
*/
|
||||
|
||||
@@ -74,7 +74,7 @@ bg_pca(point_t *c, vect_t *xa, vect_t *ya, vect_t *za, size_t npnts, const point
|
||||
}
|
||||
|
||||
// 3. Perform SVD
|
||||
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU);
|
||||
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU);
|
||||
|
||||
// 4. Extract the vectors from the U matrix
|
||||
vect_t xaxis, yaxis, zaxis;
|
||||
|
||||
+44
-73
@@ -2620,20 +2620,50 @@ bg_lseg3_lseg3_parallel(const point_t sg1pt1, const point_t sg1pt2,
|
||||
}
|
||||
|
||||
extern "C" int
|
||||
bg_plane_pt_nrml(plane_t *p, point_t pt, vect_t nrml)
|
||||
bg_plane_pt_nrml(plane_t *p, const point_t pt, const vect_t nrml)
|
||||
{
|
||||
if (!p)
|
||||
vect_t normal;
|
||||
fastf_t normal_length;
|
||||
|
||||
if (!p || !pt || !nrml)
|
||||
return -1;
|
||||
vect_t unrml;
|
||||
VMOVE(unrml, nrml);
|
||||
VUNITIZE(nrml);
|
||||
(*p)[0] = unrml[0];
|
||||
(*p)[1] = unrml[1];
|
||||
(*p)[2] = unrml[2];
|
||||
(*p)[3] = unrml[0]*pt[0] + unrml[1]*pt[1] + unrml[2]*pt[2];
|
||||
|
||||
VMOVE(normal, nrml);
|
||||
normal_length = MAGNITUDE(normal);
|
||||
if (normal_length <= SMALL_FASTF)
|
||||
return -1;
|
||||
|
||||
VSCALE(normal, normal, 1.0 / normal_length);
|
||||
(*p)[X] = normal[X];
|
||||
(*p)[Y] = normal[Y];
|
||||
(*p)[Z] = normal[Z];
|
||||
(*p)[H] = VDOT(normal, pt);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
plane_coordinate_frame(point_t origin, vect_t xaxis, vect_t yaxis, const plane_t *p)
|
||||
{
|
||||
vect_t normal;
|
||||
fastf_t normal_length;
|
||||
|
||||
VSET(normal, (*p)[X], (*p)[Y], (*p)[Z]);
|
||||
normal_length = MAGNITUDE(normal);
|
||||
if (normal_length <= SMALL_FASTF)
|
||||
return -1;
|
||||
|
||||
VSCALE(normal, normal, 1.0 / normal_length);
|
||||
VSCALE(origin, normal, (*p)[H] / normal_length);
|
||||
bn_vec_perp(xaxis, normal);
|
||||
VUNITIZE(xaxis);
|
||||
VCROSS(yaxis, normal, xaxis);
|
||||
VUNITIZE(yaxis);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
// Use PCA fit a plane to vertex points
|
||||
extern "C" int
|
||||
bg_fit_plane(point_t *c, vect_t *n, size_t npnts, point_t *pnts)
|
||||
@@ -2664,40 +2694,11 @@ bg_plane_closest_pt(fastf_t *u, fastf_t *v, plane_t *p, point_t *pt)
|
||||
return -1;
|
||||
|
||||
point_t origin;
|
||||
vect_t xaxis, yaxis, zaxis;
|
||||
VSET(zaxis, (*p)[0], (*p)[1], (*p)[2]);
|
||||
fastf_t x, y, z, d;
|
||||
x = fabs((*p)[0]);
|
||||
y = fabs((*p)[1]);
|
||||
z = fabs((*p)[2]);
|
||||
d = 0.0;
|
||||
if ( y >= x && y >= z ) {
|
||||
d = x;
|
||||
x = y;
|
||||
y = d;
|
||||
} else if ( z >= x && z >= y ) {
|
||||
d = x;
|
||||
x = z;
|
||||
z = d;
|
||||
}
|
||||
if ( x > SMALL_FASTF ) {
|
||||
y /= x;
|
||||
z /= x;
|
||||
d = x*sqrt(1.0 + y*y + z*z);
|
||||
} else if ( x > 0.0 && x < MAX_FASTF ) {
|
||||
d = x;
|
||||
}
|
||||
vect_t xaxis, yaxis;
|
||||
|
||||
if (d < 0 || NEAR_ZERO(d, SMALL_FASTF))
|
||||
if (plane_coordinate_frame(origin, xaxis, yaxis, p))
|
||||
return -1;
|
||||
|
||||
VMOVE(origin, zaxis);
|
||||
VSCALE(origin, origin, 1/d*(*p)[3]);
|
||||
VUNITIZE(zaxis);
|
||||
bn_vec_perp(xaxis, zaxis);
|
||||
VUNITIZE(xaxis);
|
||||
VCROSS(yaxis, zaxis, xaxis);
|
||||
VUNITIZE(yaxis);
|
||||
vect_t vc;
|
||||
VSUB2(vc, *pt, origin);
|
||||
|
||||
@@ -2711,45 +2712,15 @@ bg_plane_closest_pt(fastf_t *u, fastf_t *v, plane_t *p, point_t *pt)
|
||||
extern "C" int
|
||||
bg_plane_pt_at(point_t *pt, plane_t *p, fastf_t u, fastf_t v)
|
||||
{
|
||||
if (!pt)
|
||||
if (!pt || !p)
|
||||
return -1;
|
||||
|
||||
point_t origin;
|
||||
vect_t xaxis, yaxis, zaxis;
|
||||
VSET(zaxis, (*p)[0], (*p)[1], (*p)[2]);
|
||||
fastf_t x, y, z, d;
|
||||
x = fabs((*p)[0]);
|
||||
y = fabs((*p)[1]);
|
||||
z = fabs((*p)[2]);
|
||||
d = 0.0;
|
||||
if ( y >= x && y >= z ) {
|
||||
d = x;
|
||||
x = y;
|
||||
y = d;
|
||||
} else if ( z >= x && z >= y ) {
|
||||
d = x;
|
||||
x = z;
|
||||
z = d;
|
||||
}
|
||||
if ( x > SMALL_FASTF ) {
|
||||
y /= x;
|
||||
z /= x;
|
||||
d = x*sqrt(1.0 + y*y + z*z);
|
||||
} else if ( x > 0.0 && x < MAX_FASTF ) {
|
||||
d = x;
|
||||
}
|
||||
vect_t xaxis, yaxis;
|
||||
|
||||
if (d < 0 || NEAR_ZERO(d, SMALL_FASTF))
|
||||
if (plane_coordinate_frame(origin, xaxis, yaxis, p))
|
||||
return -1;
|
||||
|
||||
VMOVE(origin, zaxis);
|
||||
VSCALE(origin, origin, 1/d*(*p)[3]);
|
||||
VUNITIZE(zaxis);
|
||||
bn_vec_perp(xaxis, zaxis);
|
||||
VUNITIZE(xaxis);
|
||||
VCROSS(yaxis, zaxis, xaxis);
|
||||
VUNITIZE(yaxis);
|
||||
|
||||
VSCALE(xaxis, xaxis, u);
|
||||
VSCALE(yaxis, yaxis, v);
|
||||
VADD2(origin, origin, xaxis);
|
||||
|
||||
+51
-72
@@ -83,7 +83,7 @@ bg_polygon_view_bbox(point2d_t *bmin, point2d_t *bmax, struct bg_polygon *p, mat
|
||||
// contours. ONLY considering positive contour points.
|
||||
for (size_t i = 0; i < p->num_contours; i++) {
|
||||
struct bg_poly_contour *c = &p->contour[i];
|
||||
if (!c->num_points)
|
||||
if ((p->hole && p->hole[i]) || !c->num_points)
|
||||
continue;
|
||||
for (size_t j = 0; j < c->num_points; j++) {
|
||||
point_t vpoint;
|
||||
@@ -143,64 +143,45 @@ bg_3d_polygon_area(fastf_t *area, size_t npts, const point_t *pts)
|
||||
int
|
||||
bg_3d_polygon_centroid(point_t *cent, size_t npts, const point_t *pts)
|
||||
{
|
||||
size_t i;
|
||||
fastf_t x_0 = 0.0;
|
||||
fastf_t x_1 = 0.0;
|
||||
fastf_t y_0 = 0.0;
|
||||
fastf_t y_1 = 0.0;
|
||||
fastf_t z_0 = 0.0;
|
||||
fastf_t z_1 = 0.0;
|
||||
fastf_t a = 0.0;
|
||||
fastf_t signedArea = 0.0;
|
||||
point_t centroid = VINIT_ZERO;
|
||||
vect_t normal = VINIT_ZERO;
|
||||
vect_t edge0, edge1, cross;
|
||||
fastf_t signed_area = 0.0;
|
||||
|
||||
if (!pts || !cent || npts < 3)
|
||||
return 1;
|
||||
/* Calculate Centroid projection for face for x-y-plane */
|
||||
for (i = 0; i < npts-1; i++) {
|
||||
x_0 = pts[i][0];
|
||||
y_0 = pts[i][1];
|
||||
x_1 = pts[i+1][0];
|
||||
y_1 = pts[i+1][1];
|
||||
a = x_0 *y_1 - x_1*y_0;
|
||||
signedArea += a;
|
||||
*cent[0] += (x_0 + x_1)*a;
|
||||
*cent[1] += (y_0 + y_1)*a;
|
||||
|
||||
for (size_t i = 1; i + 1 < npts; i++) {
|
||||
VSUB2(edge0, pts[i], pts[0]);
|
||||
VSUB2(edge1, pts[i + 1], pts[0]);
|
||||
VCROSS(cross, edge0, edge1);
|
||||
VADD2(normal, normal, cross);
|
||||
}
|
||||
x_0 = pts[i][0];
|
||||
y_0 = pts[i][1];
|
||||
x_1 = pts[0][0];
|
||||
y_1 = pts[0][1];
|
||||
a = x_0 *y_1 - x_1*y_0;
|
||||
signedArea += a;
|
||||
*cent[0] += (x_0 + x_1)*a;
|
||||
*cent[1] += (y_0 + y_1)*a;
|
||||
if (MAGNITUDE(normal) <= SMALL_FASTF)
|
||||
return 1;
|
||||
VUNITIZE(normal);
|
||||
|
||||
signedArea *= 0.5;
|
||||
*cent[0] /= (6.0*signedArea);
|
||||
*cent[1] /= (6.0*signedArea);
|
||||
for (size_t i = 1; i + 1 < npts; i++) {
|
||||
point_t triangle_centroid;
|
||||
fastf_t triangle_area;
|
||||
|
||||
/* calculate Centroid projection for face for x-z-plane */
|
||||
|
||||
signedArea = 0.0;
|
||||
for (i = 0; i < npts-1; i++) {
|
||||
x_0 = pts[i][0];
|
||||
z_0 = pts[i][2];
|
||||
x_1 = pts[i+1][0];
|
||||
z_1 = pts[i+1][2];
|
||||
a = x_0 *z_1 - x_1*z_0;
|
||||
signedArea += a;
|
||||
*cent[2] += (z_0 + z_1)*a;
|
||||
VSUB2(edge0, pts[i], pts[0]);
|
||||
VSUB2(edge1, pts[i + 1], pts[0]);
|
||||
VCROSS(cross, edge0, edge1);
|
||||
triangle_area = VDOT(cross, normal);
|
||||
signed_area += triangle_area;
|
||||
VADD2(triangle_centroid, pts[0], pts[i]);
|
||||
VADD2(triangle_centroid, triangle_centroid, pts[i + 1]);
|
||||
VSCALE(triangle_centroid, triangle_centroid, triangle_area / 3.0);
|
||||
VADD2(centroid, centroid, triangle_centroid);
|
||||
}
|
||||
x_0 = pts[i][0];
|
||||
z_0 = pts[i][2];
|
||||
x_1 = pts[0][0];
|
||||
z_1 = pts[0][2];
|
||||
a = x_0 *z_1 - x_1*z_0;
|
||||
signedArea += a;
|
||||
*cent[2] += (z_0 + z_1)*a;
|
||||
|
||||
signedArea *= 0.5;
|
||||
*cent[2] /= (6.0*signedArea);
|
||||
if (NEAR_ZERO(signed_area, SMALL_FASTF))
|
||||
return 1;
|
||||
|
||||
VSCALE(centroid, centroid, 1.0 / signed_area);
|
||||
VMOVE(*cent, centroid);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -263,6 +244,7 @@ bg_3d_polygon_make_pnts_planes(size_t *npts, point_t **pts, size_t neqs, const p
|
||||
|
||||
|
||||
struct sort_ccw_data {
|
||||
point_t centroid;
|
||||
vect_t x_axis;
|
||||
vect_t y_axis;
|
||||
};
|
||||
@@ -272,20 +254,26 @@ static int
|
||||
sort_ccw_3d(const void *left, const void *right, void *context)
|
||||
{
|
||||
const struct sort_ccw_data *data = (const struct sort_ccw_data *)context;
|
||||
const fastf_t *left_point = (const fastf_t *)left;
|
||||
const fastf_t *right_point = (const fastf_t *)right;
|
||||
double left_angle = atan2(VDOT(left_point, data->y_axis),
|
||||
VDOT(left_point, data->x_axis));
|
||||
double right_angle = atan2(VDOT(right_point, data->y_axis),
|
||||
VDOT(right_point, data->x_axis));
|
||||
const point_t *left_point = (const point_t *)left;
|
||||
const point_t *right_point = (const point_t *)right;
|
||||
vect_t left_offset, right_offset;
|
||||
double left_angle, right_angle;
|
||||
double left_radius, right_radius;
|
||||
|
||||
VSUB2(left_offset, *left_point, data->centroid);
|
||||
VSUB2(right_offset, *right_point, data->centroid);
|
||||
left_angle = atan2(VDOT(left_offset, data->y_axis),
|
||||
VDOT(left_offset, data->x_axis));
|
||||
right_angle = atan2(VDOT(right_offset, data->y_axis),
|
||||
VDOT(right_offset, data->x_axis));
|
||||
|
||||
if (left_angle < right_angle)
|
||||
return -1;
|
||||
if (left_angle > right_angle)
|
||||
return 1;
|
||||
|
||||
double left_radius = MAGSQ(left_point);
|
||||
double right_radius = MAGSQ(right_point);
|
||||
left_radius = MAGSQ(left_offset);
|
||||
right_radius = MAGSQ(right_offset);
|
||||
if (left_radius < right_radius)
|
||||
return -1;
|
||||
if (left_radius > right_radius)
|
||||
@@ -298,11 +286,10 @@ int
|
||||
bg_3d_polygon_sort_ccw(size_t npts, point_t *pts, plane_t cmp)
|
||||
{
|
||||
size_t i;
|
||||
point_t centroid;
|
||||
vect_t normal;
|
||||
struct sort_ccw_data data;
|
||||
|
||||
if (!pts || npts < 3)
|
||||
if (!pts || !cmp || npts < 3)
|
||||
return 1;
|
||||
if (MAGNITUDE(cmp) < VDIVIDE_TOL)
|
||||
return 1;
|
||||
@@ -312,21 +299,13 @@ bg_3d_polygon_sort_ccw(size_t npts, point_t *pts, plane_t cmp)
|
||||
bn_vec_ortho(data.x_axis, normal);
|
||||
VCROSS(data.y_axis, normal, data.x_axis);
|
||||
|
||||
/* Angular ordering is about the polygon center, not the model origin.
|
||||
* Translate temporarily so the comparator only needs the plane axes. */
|
||||
VSETALL(centroid, 0.0);
|
||||
VSETALL(data.centroid, 0.0);
|
||||
for (i = 0; i < npts; i++)
|
||||
VADD2(centroid, centroid, pts[i]);
|
||||
VSCALE(centroid, centroid, 1.0 / (double)npts);
|
||||
|
||||
for (i = 0; i < npts; i++)
|
||||
VSUB2(pts[i], pts[i], centroid);
|
||||
VADD2(data.centroid, data.centroid, pts[i]);
|
||||
VSCALE(data.centroid, data.centroid, 1.0 / (fastf_t)npts);
|
||||
|
||||
bu_sort(pts, npts, sizeof(point_t), sort_ccw_3d, &data);
|
||||
|
||||
for (i = 0; i < npts; i++)
|
||||
VADD2(pts[i], pts[i], centroid);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
+796
-134
@@ -8,8 +8,8 @@
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
@@ -19,170 +19,832 @@
|
||||
*/
|
||||
/** @file spsr.cpp
|
||||
*
|
||||
* Interface to Adaptive Multigrid Solvers for Screened Poisson Surface Reconstruction
|
||||
* Compatible with mkazhdan/PoissonRecon API (v18.x+).
|
||||
*
|
||||
* Screened Poisson surface reconstruction for fixed and adaptive oriented
|
||||
* point sets.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "vmath.h"
|
||||
#include "bu/log.h"
|
||||
#include "bu/malloc.h"
|
||||
#include "bg/spsr.h"
|
||||
#include "RTree.h"
|
||||
|
||||
#if defined(__GNUC__) && !defined(__clang__)
|
||||
# pragma GCC diagnostic push /* start new diagnostic pragma */
|
||||
# pragma GCC diagnostic push
|
||||
# pragma GCC diagnostic ignored "-Wall"
|
||||
#elif defined(__clang__)
|
||||
# pragma clang diagnostic push /* start new diagnostic pragma */
|
||||
# pragma clang diagnostic push
|
||||
# pragma clang diagnostic ignored "-Weverything"
|
||||
#endif
|
||||
#include "SPSR/Reconstructors.h"
|
||||
#if defined(__GNUC__) && !defined(__clang__)
|
||||
# pragma GCC diagnostic pop /* end ignoring warnings */
|
||||
# pragma GCC diagnostic pop
|
||||
#elif defined(__clang__)
|
||||
# pragma clang diagnostic pop /* end ignoring warnings */
|
||||
# pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
using namespace PoissonRecon;
|
||||
|
||||
// Input stream for oriented samples: implements `read` for coordinates and normals
|
||||
template<typename Real, unsigned int Dim>
|
||||
struct PtStream : public Reconstructor::InputOrientedSampleStream<Real, Dim>
|
||||
{
|
||||
PtStream(const point_t *ipnts, const vect_t *inorms, int cnt)
|
||||
: _size(cnt), _current(0), _input_pnts(ipnts), _input_nrmls(inorms) {}
|
||||
void reset(void) { _current = 0; }
|
||||
bool read(Point<Real, Dim> &p, Point<Real, Dim> &n)
|
||||
{
|
||||
if (_current < _size) {
|
||||
for (size_t d = 0; d < Dim; d++)
|
||||
p[d] = _input_pnts[_current][d];
|
||||
for (size_t d = 0; d < Dim; d++)
|
||||
n[d] = _input_nrmls[_current][d];
|
||||
_current++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
protected:
|
||||
unsigned int _size, _current;
|
||||
const point_t *_input_pnts;
|
||||
const vect_t *_input_nrmls;
|
||||
namespace {
|
||||
|
||||
using clock_type = std::chrono::steady_clock;
|
||||
using real_type = fastf_t;
|
||||
|
||||
constexpr size_t SPSR_MAX_HINTS = 4096;
|
||||
constexpr size_t SPSR_MIN_NEIGHBORS = 4;
|
||||
constexpr double SPSR_NORMAL_ANGLE_DEGREES = 15.0;
|
||||
constexpr double SPSR_DEDUP_FRACTION = 0.25;
|
||||
constexpr int SPSR_MAX_DEPTH = 30;
|
||||
|
||||
struct spsr_mesh {
|
||||
std::vector<int> faces;
|
||||
std::vector<real_type> vertices;
|
||||
};
|
||||
|
||||
// Output face stream: must implement write() and size()
|
||||
template <typename Index>
|
||||
struct PolygonStream : public Reconstructor::OutputFaceStream<2>
|
||||
template<typename Real, unsigned int Dim>
|
||||
struct point_stream : public Reconstructor::InputOrientedSampleStream<Real, Dim>
|
||||
{
|
||||
PolygonStream(std::vector<std::vector<Index>> &polygonStream) : _polygons(polygonStream) {}
|
||||
size_t size(void) const { return _polygons.size(); }
|
||||
point_stream(const std::vector<struct bg_3d_spsr_sample> &samples)
|
||||
: current(0), input(samples)
|
||||
{
|
||||
}
|
||||
|
||||
void reset(void)
|
||||
{
|
||||
current = 0;
|
||||
}
|
||||
|
||||
bool read(Point<Real, Dim> &point, Point<Real, Dim> &normal)
|
||||
{
|
||||
if (current >= input.size())
|
||||
return false;
|
||||
|
||||
for (size_t dimension = 0; dimension < Dim; dimension++) {
|
||||
point[dimension] = input[current].point[dimension];
|
||||
normal[dimension] = input[current].normal[dimension];
|
||||
}
|
||||
current++;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
size_t current;
|
||||
const std::vector<struct bg_3d_spsr_sample> &input;
|
||||
};
|
||||
|
||||
template<typename Index>
|
||||
struct polygon_stream : public Reconstructor::OutputFaceStream<2>
|
||||
{
|
||||
polygon_stream(std::vector<std::vector<Index>> &output) : polygons(output)
|
||||
{
|
||||
}
|
||||
|
||||
size_t size(void) const
|
||||
{
|
||||
return polygons.size();
|
||||
}
|
||||
|
||||
size_t write(const std::vector<node_index_type> &polygon)
|
||||
{
|
||||
std::vector<Index> poly(polygon.size());
|
||||
for (size_t i = 0; i < polygon.size(); i++) poly[i] = (Index)polygon[i];
|
||||
_polygons.push_back(poly);
|
||||
return _polygons.size() - 1;
|
||||
std::vector<Index> converted(polygon.size());
|
||||
for (size_t i = 0; i < polygon.size(); i++)
|
||||
converted[i] = static_cast<Index>(polygon[i]);
|
||||
polygons.push_back(std::move(converted));
|
||||
return polygons.size() - 1;
|
||||
}
|
||||
protected:
|
||||
std::vector<std::vector<Index>> &_polygons;
|
||||
|
||||
private:
|
||||
std::vector<std::vector<Index>> &polygons;
|
||||
};
|
||||
|
||||
// Output vertex stream: must implement write() and size()
|
||||
template <typename Real, unsigned int Dim>
|
||||
struct VertexStream : public Reconstructor::OutputLevelSetVertexStream<Real, Dim>
|
||||
template<typename Real, unsigned int Dim>
|
||||
struct vertex_stream : public Reconstructor::OutputLevelSetVertexStream<Real, Dim>
|
||||
{
|
||||
VertexStream(std::vector<Real> &vCoordinates) : _vCoordinates(vCoordinates) {}
|
||||
size_t size(void) const { return _vCoordinates.size() / Dim; }
|
||||
size_t write(const Point<Real, Dim> &p, const Point<Real, Dim> &, const Real &)
|
||||
vertex_stream(std::vector<Real> &output) : coordinates(output)
|
||||
{
|
||||
for (unsigned int d = 0; d < Dim; d++) _vCoordinates.push_back(p[d]);
|
||||
return _vCoordinates.size() / Dim - 1;
|
||||
}
|
||||
protected:
|
||||
std::vector<Real> &_vCoordinates;
|
||||
|
||||
size_t size(void) const
|
||||
{
|
||||
return coordinates.size() / Dim;
|
||||
}
|
||||
|
||||
size_t write(const Point<Real, Dim> &point, const Point<Real, Dim> &,
|
||||
const Real &)
|
||||
{
|
||||
for (unsigned int dimension = 0; dimension < Dim; dimension++)
|
||||
coordinates.push_back(point[dimension]);
|
||||
return coordinates.size() / Dim - 1;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<Real> &coordinates;
|
||||
};
|
||||
|
||||
extern "C" int
|
||||
bg_3d_spsr(int **faces, int *num_faces, point_t **points, int *num_pnts,
|
||||
const point_t *input_points_3d, const vect_t *input_normals_3d,
|
||||
int num_input_pnts, struct bg_3d_spsr_opts *spsr_opts)
|
||||
static double
|
||||
elapsed_seconds(const clock_type::time_point &start)
|
||||
{
|
||||
using Real = fastf_t;
|
||||
static const unsigned int FEMSig = FEMDegreeAndBType<Reconstructor::Poisson::DefaultFEMDegree, Reconstructor::Poisson::DefaultFEMBoundary>::Signature;
|
||||
using FEMSigs = IsotropicUIntPack<3, FEMSig>;
|
||||
|
||||
// Set up multithreading
|
||||
PoissonRecon::ThreadPool::ParallelizationType = PoissonRecon::ThreadPool::ASYNC;
|
||||
|
||||
// Solver and extraction parameters
|
||||
Reconstructor::Poisson::SolutionParameters<Real> solverParams;
|
||||
solverParams.verbose = false;
|
||||
solverParams.depth = (spsr_opts) ? spsr_opts->depth : 8;
|
||||
solverParams.fullDepth = (spsr_opts) ? spsr_opts->full_depth : 11;
|
||||
solverParams.samplesPerNode = (spsr_opts) ? spsr_opts->samples_per_node : 1.5;
|
||||
solverParams.exactInterpolation = true;
|
||||
|
||||
Reconstructor::LevelSetExtractionParameters extractionParams;
|
||||
extractionParams.forceManifold = true;
|
||||
extractionParams.linearFit = false;
|
||||
extractionParams.polygonMesh = false;
|
||||
extractionParams.verbose = false;
|
||||
|
||||
PtStream<Real, 3> vstream(input_points_3d, input_normals_3d, num_input_pnts);
|
||||
|
||||
using Implicit = Reconstructor::Implicit<Real, 3, FEMSigs>;
|
||||
using Solver = Reconstructor::Poisson::Solver<Real, 3, FEMSigs>;
|
||||
Implicit *implicit = Solver::Solve(vstream, solverParams);
|
||||
|
||||
if (!implicit) {
|
||||
bu_log("PoissonRecon: Solver::Solve failed\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::vector<std::vector<int>> polygons;
|
||||
std::vector<Real> vCoordinates;
|
||||
PolygonStream<int> pStream(polygons);
|
||||
VertexStream<Real, 3> vStream(vCoordinates);
|
||||
|
||||
implicit->extractLevelSet(vStream, pStream, extractionParams);
|
||||
|
||||
*num_faces = (int)(polygons.size());
|
||||
*num_pnts = (int)(vCoordinates.size() / 3);
|
||||
bu_log("Point cnt: %d\n", *num_pnts);
|
||||
bu_log("Face cnt: %d\n", *num_faces);
|
||||
|
||||
// Allocate output arrays
|
||||
(*faces) = (int *)bu_calloc(*num_faces * 3, sizeof(int), "faces array");
|
||||
(*points) = (point_t *)bu_calloc(*num_pnts, sizeof(point_t), "points array");
|
||||
|
||||
// Copy faces (triangulated output expected)
|
||||
for (int i = 0; i < *num_faces; i++) {
|
||||
if (polygons[i].size() != 3) {
|
||||
bu_log("Warning: polygon %d is not a triangle (has %zu vertices)\n", i, polygons[i].size());
|
||||
// TODO - triangulate if we don't have a triangle.
|
||||
continue;
|
||||
}
|
||||
(*faces)[3*i+0] = polygons[i][0];
|
||||
(*faces)[3*i+1] = polygons[i][1];
|
||||
(*faces)[3*i+2] = polygons[i][2];
|
||||
}
|
||||
// Copy points
|
||||
for (int i = 0; i < *num_pnts; i++) {
|
||||
(*points)[i][X] = vCoordinates[3*i+0];
|
||||
(*points)[i][Y] = vCoordinates[3*i+1];
|
||||
(*points)[i][Z] = vCoordinates[3*i+2];
|
||||
}
|
||||
|
||||
delete implicit;
|
||||
return 0;
|
||||
return std::chrono::duration<double>(clock_type::now() - start).count();
|
||||
}
|
||||
|
||||
static bool
|
||||
finite_vector(const fastf_t *vector)
|
||||
{
|
||||
return std::isfinite(vector[X]) && std::isfinite(vector[Y]) &&
|
||||
std::isfinite(vector[Z]);
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
// tab-width: 8
|
||||
// mode: C++
|
||||
// c-basic-offset: 4
|
||||
// indent-tabs-mode: t
|
||||
// c-file-style: "stroustrup"
|
||||
// End:
|
||||
// ex: shiftwidth=4 tabstop=8 cino=N-s
|
||||
static bool
|
||||
valid_options(const struct bg_3d_spsr_opts &options)
|
||||
{
|
||||
if (options.degree != BG_3D_SPSR_DEFAULT_DEGREE ||
|
||||
options.btype != BG_3D_SPSR_BOUNDARY_NEUMANN ||
|
||||
options.max_memory_GB != BG_3D_SPSR_DEFAULT_MAX_MEM ||
|
||||
options.threads != BG_3D_SPSR_DEFAULT_THREADS ||
|
||||
!NEAR_ZERO(options.confidence, SMALL_FASTF) ||
|
||||
!NEAR_ZERO(options.confidence_bias, SMALL_FASTF))
|
||||
return false;
|
||||
|
||||
if (options.depth < 1 || options.depth > SPSR_MAX_DEPTH ||
|
||||
options.kerneldepth < 0 || options.iterations < 0 ||
|
||||
options.full_depth < 0 || options.base_depth < 0 ||
|
||||
options.baseVcycles < 0 || options.samples_per_node <= 0.0 ||
|
||||
options.scale < 1.0 || options.width < 0.0 ||
|
||||
options.cgsolver_accuracy <= 0.0 || options.point_weight < 0.0)
|
||||
return false;
|
||||
|
||||
return options.nonManifold >= 0 && options.nonManifold <= 1 &&
|
||||
options.linearFit >= 0 && options.linearFit <= 1 &&
|
||||
options.exact >= 0 && options.exact <= 1;
|
||||
}
|
||||
|
||||
static void
|
||||
set_solver_options(
|
||||
Reconstructor::Poisson::SolutionParameters<real_type> &solver,
|
||||
Reconstructor::LevelSetExtractionParameters &extraction,
|
||||
const struct bg_3d_spsr_opts &options)
|
||||
{
|
||||
solver.depth = static_cast<unsigned int>(options.depth);
|
||||
solver.kernelDepth = options.kerneldepth ?
|
||||
static_cast<unsigned int>(options.kerneldepth) :
|
||||
static_cast<unsigned int>(-1);
|
||||
solver.iters = options.iterations ?
|
||||
static_cast<unsigned int>(options.iterations) : 8u;
|
||||
solver.fullDepth = options.full_depth ?
|
||||
static_cast<unsigned int>(options.full_depth) :
|
||||
std::min(5u, solver.depth);
|
||||
solver.baseDepth = options.base_depth ?
|
||||
static_cast<unsigned int>(options.base_depth) :
|
||||
static_cast<unsigned int>(-1);
|
||||
solver.baseVCycles = options.baseVcycles ?
|
||||
static_cast<unsigned int>(options.baseVcycles) : 1u;
|
||||
solver.samplesPerNode = options.samples_per_node;
|
||||
solver.scale = options.scale;
|
||||
solver.width = options.width;
|
||||
solver.cgSolverAccuracy = options.cgsolver_accuracy;
|
||||
solver.pointWeight = options.point_weight;
|
||||
solver.exactInterpolation = options.exact != 0;
|
||||
solver.confidence = false;
|
||||
solver.verbose = false;
|
||||
solver.showResidual = false;
|
||||
|
||||
extraction.forceManifold = options.nonManifold == 0;
|
||||
extraction.linearFit = options.linearFit != 0;
|
||||
extraction.polygonMesh = false;
|
||||
extraction.verbose = false;
|
||||
}
|
||||
|
||||
static fastf_t
|
||||
sample_extent(const std::vector<struct bg_3d_spsr_sample> &samples)
|
||||
{
|
||||
point_t minimum;
|
||||
point_t maximum;
|
||||
VSETALL(minimum, INFINITY);
|
||||
VSETALL(maximum, -INFINITY);
|
||||
for (const auto &sample : samples)
|
||||
VMINMAX(minimum, maximum, sample.point);
|
||||
return DIST_PNT_PNT(minimum, maximum);
|
||||
}
|
||||
|
||||
class sample_set
|
||||
{
|
||||
public:
|
||||
sample_set(fastf_t tolerance, size_t limit) :
|
||||
distance_tolerance(tolerance), distance_tolerance_sq(tolerance * tolerance),
|
||||
point_limit(limit)
|
||||
{
|
||||
}
|
||||
|
||||
bool append(const struct bg_3d_spsr_sample &input)
|
||||
{
|
||||
if (!finite_vector(input.point) || !finite_vector(input.normal))
|
||||
return false;
|
||||
|
||||
struct bg_3d_spsr_sample sample = input;
|
||||
fastf_t normal_length = MAGNITUDE(sample.normal);
|
||||
if (!std::isfinite(normal_length) || normal_length <= VUNITIZE_TOL)
|
||||
return false;
|
||||
VSCALE(sample.normal, sample.normal, 1.0 / normal_length);
|
||||
|
||||
double minimum[3];
|
||||
double maximum[3];
|
||||
for (size_t dimension = 0; dimension < 3; dimension++) {
|
||||
minimum[dimension] = sample.point[dimension] - distance_tolerance;
|
||||
maximum[dimension] = sample.point[dimension] + distance_tolerance;
|
||||
}
|
||||
|
||||
bool duplicate = false;
|
||||
index.Search(minimum, maximum,
|
||||
[&sample, this, &duplicate](const size_t &candidate, void *) {
|
||||
if (DIST_PNT_PNT_SQ(sample.point, values[candidate].point) <=
|
||||
distance_tolerance_sq) {
|
||||
duplicate = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}, NULL);
|
||||
if (duplicate || (point_limit && values.size() >= point_limit))
|
||||
return false;
|
||||
|
||||
size_t sample_index = values.size();
|
||||
values.push_back(sample);
|
||||
double point[3] = {
|
||||
sample.point[X], sample.point[Y], sample.point[Z]
|
||||
};
|
||||
index.Insert(point, point, sample_index);
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::vector<struct bg_3d_spsr_sample> &samples(void) const
|
||||
{
|
||||
return values;
|
||||
}
|
||||
|
||||
bool full(void) const
|
||||
{
|
||||
return point_limit && values.size() >= point_limit;
|
||||
}
|
||||
|
||||
private:
|
||||
fastf_t distance_tolerance;
|
||||
fastf_t distance_tolerance_sq;
|
||||
size_t point_limit;
|
||||
std::vector<struct bg_3d_spsr_sample> values;
|
||||
RTree<size_t, double, 3> index;
|
||||
};
|
||||
|
||||
static void
|
||||
append_hint(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
|
||||
const point_t point, const vect_t normal, fastf_t error,
|
||||
unsigned int reasons)
|
||||
{
|
||||
struct bg_3d_spsr_refinement_hint hint = {};
|
||||
VMOVE(hint.point, point);
|
||||
VMOVE(hint.normal, normal);
|
||||
hint.error = error;
|
||||
hint.reasons = reasons;
|
||||
hints.push_back(hint);
|
||||
}
|
||||
|
||||
template<typename Implicit>
|
||||
static void
|
||||
sample_hints(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
|
||||
const std::vector<struct bg_3d_spsr_sample> &samples,
|
||||
const Implicit &implicit, fastf_t feature_size)
|
||||
{
|
||||
const fastf_t normal_dot_limit =
|
||||
std::cos(SPSR_NORMAL_ANGLE_DEGREES * DEG2RAD);
|
||||
typename Implicit::Evaluator evaluator = implicit.evaluator();
|
||||
|
||||
for (const auto &sample : samples) {
|
||||
Point<real_type, 3> point;
|
||||
for (size_t dimension = 0; dimension < 3; dimension++)
|
||||
point[dimension] = sample.point[dimension];
|
||||
|
||||
try {
|
||||
Point<real_type, 3> gradient = evaluator.grad(point);
|
||||
real_type gradient_length = std::sqrt(
|
||||
gradient[0] * gradient[0] + gradient[1] * gradient[1] +
|
||||
gradient[2] * gradient[2]);
|
||||
unsigned int reasons = 0;
|
||||
fastf_t error = feature_size;
|
||||
vect_t normal;
|
||||
VSET(normal, gradient[0], gradient[1], gradient[2]);
|
||||
|
||||
if (gradient_length <= VUNITIZE_TOL) {
|
||||
reasons = BG_3D_SPSR_REFINE_RESIDUAL |
|
||||
BG_3D_SPSR_REFINE_NORMAL;
|
||||
VSETALL(normal, 0.0);
|
||||
} else {
|
||||
fastf_t residual = std::fabs(
|
||||
evaluator(point) - implicit.isoValue) / gradient_length;
|
||||
fastf_t normal_dot = std::fabs(
|
||||
VDOT(sample.normal, normal) / gradient_length);
|
||||
if (residual > feature_size) {
|
||||
reasons |= BG_3D_SPSR_REFINE_RESIDUAL;
|
||||
error = residual;
|
||||
}
|
||||
if (normal_dot < normal_dot_limit) {
|
||||
reasons |= BG_3D_SPSR_REFINE_NORMAL;
|
||||
error = std::max(error,
|
||||
feature_size * (1.0 + normal_dot_limit - normal_dot));
|
||||
}
|
||||
VSCALE(normal, normal, 1.0 / gradient_length);
|
||||
}
|
||||
|
||||
if (reasons)
|
||||
append_hint(hints, sample.point, normal, error, reasons);
|
||||
} catch (const std::exception &) {
|
||||
append_hint(hints, sample.point, sample.normal,
|
||||
2.0 * feature_size, BG_3D_SPSR_REFINE_RESIDUAL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
density_hints(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
|
||||
const std::vector<struct bg_3d_spsr_sample> &samples,
|
||||
fastf_t feature_size)
|
||||
{
|
||||
RTree<size_t, double, 3> index;
|
||||
for (size_t i = 0; i < samples.size(); i++) {
|
||||
double point[3] = {
|
||||
samples[i].point[X], samples[i].point[Y], samples[i].point[Z]
|
||||
};
|
||||
index.Insert(point, point, i);
|
||||
}
|
||||
|
||||
fastf_t search_distance_sq = feature_size * feature_size;
|
||||
for (size_t i = 0; i < samples.size(); i++) {
|
||||
double minimum[3];
|
||||
double maximum[3];
|
||||
for (size_t dimension = 0; dimension < 3; dimension++) {
|
||||
minimum[dimension] =
|
||||
samples[i].point[dimension] - feature_size;
|
||||
maximum[dimension] =
|
||||
samples[i].point[dimension] + feature_size;
|
||||
}
|
||||
|
||||
size_t neighbor_count = 0;
|
||||
index.Search(minimum, maximum,
|
||||
[&samples, i, search_distance_sq, &neighbor_count](
|
||||
const size_t &candidate, void *) {
|
||||
if (DIST_PNT_PNT_SQ(samples[i].point,
|
||||
samples[candidate].point) <= search_distance_sq)
|
||||
neighbor_count++;
|
||||
return neighbor_count < SPSR_MIN_NEIGHBORS;
|
||||
}, NULL);
|
||||
|
||||
if (neighbor_count < SPSR_MIN_NEIGHBORS)
|
||||
append_hint(hints, samples[i].point, samples[i].normal,
|
||||
feature_size, BG_3D_SPSR_REFINE_DENSITY);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
surface_variation_hints(
|
||||
std::vector<struct bg_3d_spsr_refinement_hint> &hints,
|
||||
const spsr_mesh &mesh, fastf_t feature_size)
|
||||
{
|
||||
size_t vertex_count = mesh.vertices.size() / 3;
|
||||
std::vector<std::array<fastf_t, 3>> first_normal(vertex_count);
|
||||
std::vector<fastf_t> variation(vertex_count, 0.0);
|
||||
std::vector<unsigned char> have_normal(vertex_count, 0);
|
||||
const fastf_t variation_limit =
|
||||
1.0 - std::cos(SPSR_NORMAL_ANGLE_DEGREES * DEG2RAD);
|
||||
|
||||
for (size_t face = 0; face < mesh.faces.size() / 3; face++) {
|
||||
int ia = mesh.faces[3 * face];
|
||||
int ib = mesh.faces[3 * face + 1];
|
||||
int ic = mesh.faces[3 * face + 2];
|
||||
const fastf_t *a = &mesh.vertices[3 * static_cast<size_t>(ia)];
|
||||
const fastf_t *b = &mesh.vertices[3 * static_cast<size_t>(ib)];
|
||||
const fastf_t *c = &mesh.vertices[3 * static_cast<size_t>(ic)];
|
||||
vect_t ab;
|
||||
vect_t ac;
|
||||
vect_t normal;
|
||||
VSUB2(ab, b, a);
|
||||
VSUB2(ac, c, a);
|
||||
VCROSS(normal, ab, ac);
|
||||
fastf_t length = MAGNITUDE(normal);
|
||||
if (length <= VUNITIZE_TOL)
|
||||
continue;
|
||||
VSCALE(normal, normal, 1.0 / length);
|
||||
|
||||
const int vertices[3] = {ia, ib, ic};
|
||||
for (size_t corner = 0; corner < 3; corner++) {
|
||||
size_t vertex = static_cast<size_t>(vertices[corner]);
|
||||
if (!have_normal[vertex]) {
|
||||
VMOVE(first_normal[vertex].data(), normal);
|
||||
have_normal[vertex] = 1;
|
||||
} else {
|
||||
variation[vertex] = std::max(variation[vertex],
|
||||
1.0 - std::fabs(VDOT(first_normal[vertex].data(), normal)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t vertex = 0; vertex < vertex_count; vertex++) {
|
||||
if (variation[vertex] <= variation_limit)
|
||||
continue;
|
||||
const fastf_t *point = &mesh.vertices[3 * vertex];
|
||||
append_hint(hints, point, first_normal[vertex].data(),
|
||||
feature_size * (1.0 + variation[vertex]),
|
||||
BG_3D_SPSR_REFINE_SURFACE_VARIATION);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
limit_hints(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
|
||||
fastf_t feature_size)
|
||||
{
|
||||
std::sort(hints.begin(), hints.end(),
|
||||
[](const struct bg_3d_spsr_refinement_hint &left,
|
||||
const struct bg_3d_spsr_refinement_hint &right) {
|
||||
return left.error > right.error;
|
||||
});
|
||||
|
||||
RTree<size_t, double, 3> locations;
|
||||
std::vector<struct bg_3d_spsr_refinement_hint> selected;
|
||||
selected.reserve(std::min(hints.size(), SPSR_MAX_HINTS));
|
||||
fastf_t separation = feature_size * SPSR_DEDUP_FRACTION;
|
||||
fastf_t separation_sq = separation * separation;
|
||||
|
||||
for (const auto &hint : hints) {
|
||||
double minimum[3];
|
||||
double maximum[3];
|
||||
for (size_t dimension = 0; dimension < 3; dimension++) {
|
||||
minimum[dimension] = hint.point[dimension] - separation;
|
||||
maximum[dimension] = hint.point[dimension] + separation;
|
||||
}
|
||||
|
||||
bool nearby = false;
|
||||
locations.Search(minimum, maximum,
|
||||
[&hint, &selected, separation_sq, &nearby](
|
||||
const size_t &candidate, void *) {
|
||||
if (DIST_PNT_PNT_SQ(hint.point,
|
||||
selected[candidate].point) <= separation_sq) {
|
||||
nearby = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}, NULL);
|
||||
if (nearby)
|
||||
continue;
|
||||
|
||||
size_t hint_index = selected.size();
|
||||
selected.push_back(hint);
|
||||
double point[3] = {hint.point[X], hint.point[Y], hint.point[Z]};
|
||||
locations.Insert(point, point, hint_index);
|
||||
if (selected.size() == SPSR_MAX_HINTS)
|
||||
break;
|
||||
}
|
||||
|
||||
hints.swap(selected);
|
||||
}
|
||||
|
||||
template<typename Implicit>
|
||||
static bool
|
||||
extract_mesh(spsr_mesh &mesh, const Implicit &implicit,
|
||||
const Reconstructor::LevelSetExtractionParameters ¶meters)
|
||||
{
|
||||
std::vector<std::vector<int>> polygons;
|
||||
polygon_stream<int> faces(polygons);
|
||||
vertex_stream<real_type, 3> vertices(mesh.vertices);
|
||||
implicit.extractLevelSet(vertices, faces, parameters);
|
||||
|
||||
if (mesh.vertices.empty() || mesh.vertices.size() % 3 ||
|
||||
mesh.vertices.size() / 3 >
|
||||
static_cast<size_t>(std::numeric_limits<int>::max()) ||
|
||||
polygons.empty() ||
|
||||
polygons.size() > static_cast<size_t>(std::numeric_limits<int>::max()))
|
||||
return false;
|
||||
|
||||
mesh.faces.reserve(polygons.size() * 3);
|
||||
for (const auto &polygon : polygons) {
|
||||
if (polygon.size() != 3)
|
||||
return false;
|
||||
for (int vertex : polygon) {
|
||||
if (vertex < 0 ||
|
||||
static_cast<size_t>(vertex) >= mesh.vertices.size() / 3)
|
||||
return false;
|
||||
mesh.faces.push_back(vertex);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
solve_once(spsr_mesh &mesh,
|
||||
std::vector<struct bg_3d_spsr_refinement_hint> &hints,
|
||||
const std::vector<struct bg_3d_spsr_sample> &samples,
|
||||
const struct bg_3d_spsr_adaptive_opts &options)
|
||||
{
|
||||
static std::mutex solver_mutex;
|
||||
std::lock_guard<std::mutex> guard(solver_mutex);
|
||||
|
||||
static const unsigned int fem_signature =
|
||||
FEMDegreeAndBType<Reconstructor::Poisson::DefaultFEMDegree,
|
||||
Reconstructor::Poisson::DefaultFEMBoundary>::Signature;
|
||||
using fem_signatures = IsotropicUIntPack<3, fem_signature>;
|
||||
using implicit_type =
|
||||
Reconstructor::Implicit<real_type, 3, fem_signatures>;
|
||||
using solver_type =
|
||||
Reconstructor::Poisson::Solver<real_type, 3, fem_signatures>;
|
||||
|
||||
Reconstructor::Poisson::SolutionParameters<real_type> solver_parameters;
|
||||
Reconstructor::LevelSetExtractionParameters extraction_parameters;
|
||||
set_solver_options(solver_parameters, extraction_parameters,
|
||||
options.solver);
|
||||
|
||||
ThreadPool::ParallelizationType = ThreadPool::ASYNC;
|
||||
point_stream<real_type, 3> points(samples);
|
||||
std::unique_ptr<implicit_type> implicit(
|
||||
solver_type::Solve(points, solver_parameters));
|
||||
if (!implicit || !extract_mesh(mesh, *implicit, extraction_parameters))
|
||||
return false;
|
||||
|
||||
if (options.target_feature_size > 0.0) {
|
||||
sample_hints(hints, samples, *implicit,
|
||||
options.target_feature_size);
|
||||
density_hints(hints, samples, options.target_feature_size);
|
||||
surface_variation_hints(hints, mesh,
|
||||
options.target_feature_size);
|
||||
limit_hints(hints, options.target_feature_size);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
copy_mesh(int **faces, int *face_count, point_t **vertices,
|
||||
int *vertex_count, const spsr_mesh &mesh)
|
||||
{
|
||||
size_t faces_size = mesh.faces.size() * sizeof(int);
|
||||
size_t vertices_size = mesh.vertices.size() * sizeof(real_type);
|
||||
int *new_faces = static_cast<int *>(bu_malloc(faces_size,
|
||||
"SPSR face array"));
|
||||
point_t *new_vertices = static_cast<point_t *>(bu_malloc(vertices_size,
|
||||
"SPSR vertex array"));
|
||||
if (!new_faces || !new_vertices) {
|
||||
if (new_faces)
|
||||
bu_free(new_faces, "SPSR face array");
|
||||
if (new_vertices)
|
||||
bu_free(new_vertices, "SPSR vertex array");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::memcpy(new_faces, mesh.faces.data(), faces_size);
|
||||
std::memcpy(new_vertices, mesh.vertices.data(), vertices_size);
|
||||
*faces = new_faces;
|
||||
*face_count = static_cast<int>(mesh.faces.size() / 3);
|
||||
*vertices = new_vertices;
|
||||
*vertex_count = static_cast<int>(mesh.vertices.size() / 3);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void
|
||||
initialize_outputs(int **faces, int *face_count, point_t **vertices,
|
||||
int *vertex_count, struct bg_3d_spsr_report *report)
|
||||
{
|
||||
if (faces)
|
||||
*faces = NULL;
|
||||
if (face_count)
|
||||
*face_count = 0;
|
||||
if (vertices)
|
||||
*vertices = NULL;
|
||||
if (vertex_count)
|
||||
*vertex_count = 0;
|
||||
if (report)
|
||||
std::memset(report, 0, sizeof(*report));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int
|
||||
bg_3d_spsr_adaptive(int **faces, int *num_faces, point_t **vertices,
|
||||
int *num_vertices, const struct bg_3d_spsr_sample *input_samples,
|
||||
size_t sample_count, const struct bg_3d_spsr_adaptive_opts *input_options,
|
||||
bg_3d_spsr_refinement_func_t refine, void *client_data,
|
||||
struct bg_3d_spsr_report *report)
|
||||
{
|
||||
initialize_outputs(faces, num_faces, vertices, num_vertices, report);
|
||||
if (!faces || !num_faces || !vertices || !num_vertices ||
|
||||
!input_samples || !sample_count)
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
struct bg_3d_spsr_adaptive_opts default_options =
|
||||
BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT;
|
||||
const struct bg_3d_spsr_adaptive_opts &options =
|
||||
input_options ? *input_options : default_options;
|
||||
if (!valid_options(options.solver) ||
|
||||
options.target_feature_size < 0.0 || options.max_time < 0.0 ||
|
||||
(options.max_refinement_passes &&
|
||||
(!refine || options.target_feature_size <= 0.0)) ||
|
||||
(options.max_points && options.max_points < sample_count))
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
fastf_t extent = 0.0;
|
||||
{
|
||||
std::vector<struct bg_3d_spsr_sample> initial(
|
||||
input_samples, input_samples + sample_count);
|
||||
extent = sample_extent(initial);
|
||||
}
|
||||
if (!std::isfinite(extent) || extent <= SMALL_FASTF)
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
fastf_t deduplication_distance =
|
||||
options.target_feature_size > 0.0 ?
|
||||
options.target_feature_size * SPSR_DEDUP_FRACTION :
|
||||
std::max(extent * 1.0e-12, static_cast<fastf_t>(SMALL_FASTF));
|
||||
sample_set accumulated(deduplication_distance, options.max_points);
|
||||
for (size_t i = 0; i < sample_count; i++)
|
||||
accumulated.append(input_samples[i]);
|
||||
if (accumulated.samples().empty())
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
const clock_type::time_point start = clock_type::now();
|
||||
if (report)
|
||||
report->initial_sample_count = accumulated.samples().size();
|
||||
|
||||
bool point_limit_reached = accumulated.full();
|
||||
for (size_t pass = 0; ; pass++) {
|
||||
if (options.max_time > 0.0 &&
|
||||
elapsed_seconds(start) >= options.max_time) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_TIME_LIMIT;
|
||||
break;
|
||||
}
|
||||
|
||||
spsr_mesh mesh;
|
||||
std::vector<struct bg_3d_spsr_refinement_hint> hints;
|
||||
try {
|
||||
if (!solve_once(mesh, hints, accumulated.samples(), options)) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_SOLVER_ERROR;
|
||||
break;
|
||||
}
|
||||
} catch (const std::exception &) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_SOLVER_ERROR;
|
||||
break;
|
||||
} catch (...) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_SOLVER_ERROR;
|
||||
break;
|
||||
}
|
||||
|
||||
if (report)
|
||||
report->solve_count++;
|
||||
|
||||
if (!refine) {
|
||||
if (copy_mesh(faces, num_faces, vertices, num_vertices, mesh)) {
|
||||
if (report) {
|
||||
report->termination = BG_3D_SPSR_COMPLETE;
|
||||
report->validation.passed = 1;
|
||||
report->final_sample_count = accumulated.samples().size();
|
||||
report->elapsed_time = elapsed_seconds(start);
|
||||
}
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_SOLVER_ERROR;
|
||||
break;
|
||||
}
|
||||
|
||||
double remaining_time = options.max_time > 0.0 ?
|
||||
std::max(0.0, options.max_time - elapsed_seconds(start)) : 0.0;
|
||||
if (options.max_time > 0.0 && remaining_time <= 0.0) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_TIME_LIMIT;
|
||||
break;
|
||||
}
|
||||
|
||||
struct bg_3d_spsr_refinement_request request = {};
|
||||
request.pass = pass;
|
||||
request.target_feature_size = options.target_feature_size;
|
||||
request.remaining_time = remaining_time;
|
||||
request.vertices =
|
||||
reinterpret_cast<const point_t *>(mesh.vertices.data());
|
||||
request.vertex_count = mesh.vertices.size() / 3;
|
||||
request.faces = mesh.faces.data();
|
||||
request.face_count = mesh.faces.size() / 3;
|
||||
request.hints = hints.data();
|
||||
request.hint_count = hints.size();
|
||||
|
||||
struct bg_3d_spsr_refinement_response response = {};
|
||||
if (refine(&response, &request, client_data) != BRLCAD_OK) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_CALLBACK_STOP;
|
||||
break;
|
||||
}
|
||||
if (report)
|
||||
report->validation = response.validation;
|
||||
|
||||
if (response.validation.passed) {
|
||||
if (copy_mesh(faces, num_faces, vertices, num_vertices, mesh)) {
|
||||
if (report) {
|
||||
report->termination = BG_3D_SPSR_COMPLETE;
|
||||
report->final_sample_count = accumulated.samples().size();
|
||||
report->elapsed_time = elapsed_seconds(start);
|
||||
}
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_SOLVER_ERROR;
|
||||
break;
|
||||
}
|
||||
if (response.stop_refinement) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_CALLBACK_STOP;
|
||||
break;
|
||||
}
|
||||
|
||||
if (pass == options.max_refinement_passes) {
|
||||
if (report)
|
||||
report->termination = point_limit_reached ?
|
||||
BG_3D_SPSR_POINT_LIMIT : BG_3D_SPSR_CALLBACK_STOP;
|
||||
break;
|
||||
}
|
||||
if (response.sample_count && !response.samples) {
|
||||
if (report)
|
||||
report->termination = BG_3D_SPSR_CALLBACK_STOP;
|
||||
break;
|
||||
}
|
||||
|
||||
if (report)
|
||||
report->requested_sample_count += response.sample_count;
|
||||
size_t accepted = 0;
|
||||
for (size_t i = 0; i < response.sample_count; i++) {
|
||||
if (accumulated.append(response.samples[i]))
|
||||
accepted++;
|
||||
}
|
||||
if (report)
|
||||
report->accepted_sample_count += accepted;
|
||||
point_limit_reached = accumulated.full();
|
||||
|
||||
if (!accepted) {
|
||||
if (report)
|
||||
report->termination = point_limit_reached ?
|
||||
BG_3D_SPSR_POINT_LIMIT : BG_3D_SPSR_NO_NEW_SAMPLES;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (report) {
|
||||
report->final_sample_count = accumulated.samples().size();
|
||||
report->elapsed_time = elapsed_seconds(start);
|
||||
}
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
extern "C" int
|
||||
bg_3d_spsr(int **faces, int *num_faces, point_t **vertices, int *num_vertices,
|
||||
const point_t *input_points_3d, const vect_t *input_normals_3d,
|
||||
int num_input_pnts, struct bg_3d_spsr_opts *spsr_opts)
|
||||
{
|
||||
if (!input_points_3d || !input_normals_3d || num_input_pnts <= 0)
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
std::vector<struct bg_3d_spsr_sample> samples(
|
||||
static_cast<size_t>(num_input_pnts));
|
||||
for (size_t i = 0; i < samples.size(); i++) {
|
||||
VMOVE(samples[i].point, input_points_3d[i]);
|
||||
VMOVE(samples[i].normal, input_normals_3d[i]);
|
||||
}
|
||||
|
||||
struct bg_3d_spsr_adaptive_opts options =
|
||||
BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT;
|
||||
options.max_refinement_passes = 0;
|
||||
if (spsr_opts)
|
||||
options.solver = *spsr_opts;
|
||||
|
||||
return bg_3d_spsr_adaptive(faces, num_faces, vertices, num_vertices,
|
||||
samples.data(), samples.size(), &options, NULL, NULL, NULL);
|
||||
}
|
||||
|
||||
/*
|
||||
* Local Variables:
|
||||
* tab-width: 8
|
||||
* mode: C++
|
||||
* c-basic-offset: 4
|
||||
* indent-tabs-mode: t
|
||||
* c-file-style: "stroustrup"
|
||||
* End:
|
||||
* ex: shiftwidth=4 tabstop=8 cino=N-s
|
||||
*/
|
||||
|
||||
@@ -33,6 +33,10 @@ brlcad_addexec(bg_aabb_ray aabb_ray.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_aabb_ray COMMAND bg_aabb_ray)
|
||||
|
||||
brlcad_addexec(bg_spsr spsr.cpp "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_spsr COMMAND bg_spsr)
|
||||
|
||||
brlcad_addexec(bg_polygon_sort polygon_sort.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_polygon_sort COMMAND bg_polygon_sort)
|
||||
@@ -142,7 +146,7 @@ brlcad_add_test(NAME bg_plane_mk_plane_3pts_succeed COMMAND bg_test pla
|
||||
#
|
||||
# A-D are plane equation parameters, and P is the test point.
|
||||
brlcad_add_test(NAME bg_plane_pt_project_1 COMMAND bg_test plane_pt 6 0,0,1,1 2,2,1)
|
||||
brlcad_add_test(NAME bg_plane_pt_project_2 COMMAND bg_test plane_pt 6 0.737397,0.461098,0.493593,236.3 77.526016919831704,185.674010580054585,189.465011325663767)
|
||||
brlcad_add_test(NAME bg_plane_pt_project_2 COMMAND bg_test plane_pt 6 0.737397,0.461098,0.493593,236.3 77.526016919831704,185.674010580054585,189.465070961146)
|
||||
|
||||
# For function #7 (bg_coplanar_pts), the <args> format is as follows:
|
||||
#
|
||||
@@ -306,7 +310,24 @@ brlcad_addexec(bg_line_distance line_distance.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_line_distance COMMAND bg_line_distance)
|
||||
|
||||
# ************ plane coordinate tests ***********
|
||||
|
||||
brlcad_addexec(bg_plane_coordinates plane_coordinates.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_plane_coordinates COMMAND bg_plane_coordinates)
|
||||
|
||||
# ************ pca.c tests ***********
|
||||
|
||||
brlcad_addexec(bg_pca pca.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_pca COMMAND bg_pca)
|
||||
|
||||
# ************ polygon.c tests ***********
|
||||
|
||||
brlcad_addexec(bg_polygon polygon.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_polygon COMMAND bg_polygon)
|
||||
|
||||
brlcad_addexec(bg_polygon_triangulate polygon_triangulate.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_polygon_triangulate COMMAND bg_polygon_triangulate)
|
||||
@@ -448,6 +469,10 @@ brlcad_addexec(bg_trimesh_area trimesh_area.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
#BRLCAD_ADD_TEST(NAME bg_trimesh_area COMMAND bg_trimesh_area)
|
||||
|
||||
brlcad_addexec(bg_trimesh_solid trimesh_solid.c "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
brlcad_add_test(NAME bg_trimesh_solid COMMAND bg_trimesh_solid)
|
||||
|
||||
# ************ trimesh_repair tests ***********
|
||||
|
||||
brlcad_addexec(bg_trimesh_repair trimesh_repair.cpp "${BG_TEST_LIBS}" TEST)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/* P C A . C
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include "bn.h"
|
||||
#include "bu.h"
|
||||
#include "bg.h"
|
||||
|
||||
|
||||
static int
|
||||
orthonormal_axes(const vect_t xaxis, const vect_t yaxis, const vect_t zaxis)
|
||||
{
|
||||
return !NEAR_EQUAL(MAGSQ(xaxis), 1.0, BN_TOL_DIST)
|
||||
|| !NEAR_EQUAL(MAGSQ(yaxis), 1.0, BN_TOL_DIST)
|
||||
|| !NEAR_EQUAL(MAGSQ(zaxis), 1.0, BN_TOL_DIST)
|
||||
|| !NEAR_ZERO(VDOT(xaxis, yaxis), BN_TOL_DIST)
|
||||
|| !NEAR_ZERO(VDOT(xaxis, zaxis), BN_TOL_DIST)
|
||||
|| !NEAR_ZERO(VDOT(yaxis, zaxis), BN_TOL_DIST);
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
const point_t one_point[] = {{1.0, 2.0, 3.0}};
|
||||
const point_t two_points[] = {{1.0, 2.0, 3.0}, {5.0, 2.0, 3.0}};
|
||||
const point_t one_center = {1.0, 2.0, 3.0};
|
||||
const point_t two_center = {3.0, 2.0, 3.0};
|
||||
const vect_t xaxis_expected = {1.0, 0.0, 0.0};
|
||||
point_t center;
|
||||
vect_t xaxis, yaxis, zaxis;
|
||||
fastf_t alignment;
|
||||
int failed = 0;
|
||||
|
||||
bu_setprogname(argv[0]);
|
||||
if (argc != 1)
|
||||
return 1;
|
||||
|
||||
if (bg_pca(¢er, &xaxis, &yaxis, &zaxis, 1, one_point) != BRLCAD_OK ||
|
||||
!VNEAR_EQUAL(center, one_center, BN_TOL_DIST) ||
|
||||
orthonormal_axes(xaxis, yaxis, zaxis)) {
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
if (bg_pca(¢er, &xaxis, &yaxis, &zaxis, 2, two_points) != BRLCAD_OK ||
|
||||
!VNEAR_EQUAL(center, two_center, BN_TOL_DIST) ||
|
||||
orthonormal_axes(xaxis, yaxis, zaxis)) {
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
alignment = VDOT(xaxis, xaxis_expected);
|
||||
if (!NEAR_EQUAL(alignment * alignment, 1.0, BN_TOL_DIST))
|
||||
failed = 1;
|
||||
|
||||
return failed;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/* P L A N E _ C O O R D I N A T E S . C
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include "bn.h"
|
||||
#include "bu.h"
|
||||
#include "bg.h"
|
||||
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
const point_t plane_point = {0.0, 0.0, 3.0};
|
||||
const vect_t original_normal = {0.0, 0.0, 2.0};
|
||||
const vect_t expected_normal = {0.0, 0.0, 1.0};
|
||||
vect_t normal;
|
||||
vect_t zero_normal = VINIT_ZERO;
|
||||
plane_t plane;
|
||||
plane_t unnormalized_plane = {0.0, 0.0, 2.0, 6.0};
|
||||
point_t query = {2.0, 2.0, 3.0};
|
||||
point_t off_plane_query = {2.0, 2.0, 5.0};
|
||||
const point_t expected_projection = {2.0, 2.0, 3.0};
|
||||
point_t reconstructed = VINIT_ZERO;
|
||||
fastf_t u, v;
|
||||
int failed = 0;
|
||||
|
||||
bu_setprogname(argv[0]);
|
||||
if (argc != 1)
|
||||
return 1;
|
||||
|
||||
VMOVE(normal, original_normal);
|
||||
if (bg_plane_pt_nrml(&plane, plane_point, normal) ||
|
||||
!VNEAR_EQUAL(plane, expected_normal, BN_TOL_DIST) ||
|
||||
!NEAR_EQUAL(plane[H], 3.0, BN_TOL_DIST) ||
|
||||
!VNEAR_EQUAL(normal, original_normal, BN_TOL_DIST)) {
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
if (bg_plane_pt_nrml(&plane, plane_point, zero_normal) != -1)
|
||||
failed = 1;
|
||||
|
||||
if (bg_plane_closest_pt(&u, &v, &unnormalized_plane, &query) ||
|
||||
bg_plane_pt_at(&reconstructed, &unnormalized_plane, u, v) ||
|
||||
!VNEAR_EQUAL(reconstructed, query, BN_TOL_DIST)) {
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
if (bg_plane_closest_pt(&u, &v, &unnormalized_plane, &off_plane_query) ||
|
||||
bg_plane_pt_at(&reconstructed, &unnormalized_plane, u, v) ||
|
||||
!VNEAR_EQUAL(reconstructed, expected_projection, BN_TOL_DIST)) {
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
return failed;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/* P O L Y G O N . C
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include "bn.h"
|
||||
#include "bu.h"
|
||||
#include "bg.h"
|
||||
|
||||
|
||||
static int
|
||||
test_view_bbox(void)
|
||||
{
|
||||
point_t outer[] = {
|
||||
{0.0, 0.0, 0.0},
|
||||
{2.0, 0.0, 0.0},
|
||||
{2.0, 2.0, 0.0},
|
||||
{0.0, 2.0, 0.0}
|
||||
};
|
||||
point_t hole[] = {
|
||||
{100.0, 100.0, 0.0},
|
||||
{101.0, 100.0, 0.0},
|
||||
{101.0, 101.0, 0.0},
|
||||
{100.0, 101.0, 0.0}
|
||||
};
|
||||
struct bg_poly_contour contours[] = {
|
||||
{4, outer, 0},
|
||||
{4, hole, 0}
|
||||
};
|
||||
int holes[] = {0, 1};
|
||||
struct bg_polygon polygon = BG_POLYGON_NULL;
|
||||
mat_t model2view;
|
||||
point2d_t bmin, bmax;
|
||||
|
||||
polygon.num_contours = 2;
|
||||
polygon.hole = holes;
|
||||
polygon.contour = contours;
|
||||
MAT_IDN(model2view);
|
||||
bg_polygon_view_bbox(&bmin, &bmax, &polygon, model2view);
|
||||
|
||||
return !NEAR_EQUAL(bmin[X], 0.0, BN_TOL_DIST)
|
||||
|| !NEAR_EQUAL(bmin[Y], 0.0, BN_TOL_DIST)
|
||||
|| !NEAR_EQUAL(bmax[X], 2.0, BN_TOL_DIST)
|
||||
|| !NEAR_EQUAL(bmax[Y], 2.0, BN_TOL_DIST);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_centroid(void)
|
||||
{
|
||||
const point_t rectangle[] = {
|
||||
{5.0, 0.0, 0.0},
|
||||
{5.0, 4.0, 0.0},
|
||||
{5.0, 4.0, 2.0},
|
||||
{5.0, 0.0, 2.0}
|
||||
};
|
||||
const point_t expected = {5.0, 2.0, 1.0};
|
||||
point_t output[] = {
|
||||
{11.0, 12.0, 13.0},
|
||||
{0.0, 0.0, 0.0},
|
||||
{17.0, 18.0, 19.0},
|
||||
{23.0, 24.0, 25.0}
|
||||
};
|
||||
const point_t before = {11.0, 12.0, 13.0};
|
||||
const point_t after = {17.0, 18.0, 19.0};
|
||||
const point_t farther_after = {23.0, 24.0, 25.0};
|
||||
|
||||
return bg_3d_polygon_centroid(&output[1], 4, rectangle)
|
||||
|| !VNEAR_EQUAL(output[1], expected, BN_TOL_DIST)
|
||||
|| !VNEAR_EQUAL(output[0], before, BN_TOL_DIST)
|
||||
|| !VNEAR_EQUAL(output[2], after, BN_TOL_DIST)
|
||||
|| !VNEAR_EQUAL(output[3], farther_after, BN_TOL_DIST);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_ccw_sort(void)
|
||||
{
|
||||
point_t points[] = {
|
||||
{10.0, 10.0, 0.0},
|
||||
{10.1, 10.1, 0.0},
|
||||
{10.1, 10.0, 0.0},
|
||||
{10.0, 10.1, 0.0}
|
||||
};
|
||||
plane_t plane = {0.0, 0.0, 1.0, 0.0};
|
||||
vect_t total = VINIT_ZERO;
|
||||
vect_t cross;
|
||||
|
||||
if (bg_3d_polygon_sort_ccw(4, points, plane))
|
||||
return 1;
|
||||
|
||||
for (size_t i = 0; i < 4; i++) {
|
||||
size_t next = i + 1 == 4 ? 0 : i + 1;
|
||||
VCROSS(cross, points[i], points[next]);
|
||||
VADD2(total, total, cross);
|
||||
}
|
||||
|
||||
return total[Z] <= SMALL_FASTF;
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
bu_setprogname(argv[0]);
|
||||
if (argc != 1)
|
||||
return 1;
|
||||
|
||||
return test_view_bbox() || test_centroid() || test_ccw_sort();
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/* S P S R . C P P
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this file; see the file named COPYING for more
|
||||
* information.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "vmath.h"
|
||||
#include "bu/app.h"
|
||||
#include "bu/log.h"
|
||||
#include "bu/malloc.h"
|
||||
#include "bg/spsr.h"
|
||||
|
||||
static int failures = 0;
|
||||
|
||||
static void
|
||||
expect(bool condition, const char *message)
|
||||
{
|
||||
if (condition)
|
||||
return;
|
||||
bu_log("FAIL: %s\n", message);
|
||||
failures++;
|
||||
}
|
||||
|
||||
static std::vector<struct bg_3d_spsr_sample>
|
||||
sphere_samples(size_t count)
|
||||
{
|
||||
const fastf_t golden_angle = M_PI * (3.0 - std::sqrt(5.0));
|
||||
std::vector<struct bg_3d_spsr_sample> samples(count);
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
fastf_t y = 1.0 - 2.0 *
|
||||
(static_cast<fastf_t>(i) + 0.5) / count;
|
||||
fastf_t radius = std::sqrt(std::max(0.0, 1.0 - y * y));
|
||||
fastf_t angle = golden_angle * i;
|
||||
VSET(samples[i].point, radius * std::cos(angle), y,
|
||||
radius * std::sin(angle));
|
||||
VMOVE(samples[i].normal, samples[i].point);
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
struct callback_state {
|
||||
size_t calls;
|
||||
size_t hints;
|
||||
struct bg_3d_spsr_sample additional_sample;
|
||||
bool refine_once;
|
||||
bool stop;
|
||||
};
|
||||
|
||||
static int
|
||||
accept_candidate(struct bg_3d_spsr_refinement_response *response,
|
||||
const struct bg_3d_spsr_refinement_request *request, void *data)
|
||||
{
|
||||
struct callback_state *state =
|
||||
static_cast<struct callback_state *>(data);
|
||||
state->calls++;
|
||||
state->hints = request->hint_count;
|
||||
response->validation.ray_count = 100;
|
||||
if (state->stop) {
|
||||
response->validation.passed = 0;
|
||||
response->stop_refinement = 1;
|
||||
} else if (state->refine_once && state->calls == 1) {
|
||||
response->samples = &state->additional_sample;
|
||||
response->sample_count = 1;
|
||||
response->validation.passed = 0;
|
||||
} else {
|
||||
response->validation.passed = 1;
|
||||
}
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
|
||||
int
|
||||
main(int UNUSED(argc), const char **argv)
|
||||
{
|
||||
bu_setprogname(argv[0]);
|
||||
|
||||
std::vector<struct bg_3d_spsr_sample> samples = sphere_samples(256);
|
||||
struct bg_3d_spsr_adaptive_opts options =
|
||||
BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT;
|
||||
options.solver.depth = 5;
|
||||
options.max_refinement_passes = 0;
|
||||
|
||||
int *faces = NULL;
|
||||
int face_count = 0;
|
||||
point_t *vertices = NULL;
|
||||
int vertex_count = 0;
|
||||
struct bg_3d_spsr_report report = {};
|
||||
int ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
|
||||
&vertex_count, samples.data(), samples.size(), &options,
|
||||
NULL, NULL, &report);
|
||||
expect(ret == BRLCAD_OK, "fixed structured reconstruction succeeds");
|
||||
expect(face_count > 0 && vertex_count > 0,
|
||||
"fixed structured reconstruction returns a mesh");
|
||||
expect(report.solve_count == 1 && report.validation.passed,
|
||||
"fixed structured reconstruction reports one successful solve");
|
||||
if (faces)
|
||||
bu_free(faces, "SPSR test faces");
|
||||
if (vertices)
|
||||
bu_free(vertices, "SPSR test vertices");
|
||||
|
||||
struct callback_state state = {};
|
||||
options.max_refinement_passes = 3;
|
||||
options.target_feature_size = 0.1;
|
||||
options.max_points = 512;
|
||||
faces = NULL;
|
||||
vertices = NULL;
|
||||
face_count = 0;
|
||||
vertex_count = 0;
|
||||
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
|
||||
&vertex_count, samples.data(), samples.size(), &options,
|
||||
accept_candidate, &state, &report);
|
||||
expect(ret == BRLCAD_OK, "callback can accept an adaptive candidate");
|
||||
expect(state.calls == 1, "accepted candidate stops adaptive solving");
|
||||
expect(report.validation.ray_count == 100,
|
||||
"adaptive report preserves callback validation");
|
||||
if (faces)
|
||||
bu_free(faces, "SPSR test faces");
|
||||
if (vertices)
|
||||
bu_free(vertices, "SPSR test vertices");
|
||||
|
||||
state = {};
|
||||
state.stop = true;
|
||||
faces = NULL;
|
||||
vertices = NULL;
|
||||
face_count = 0;
|
||||
vertex_count = 0;
|
||||
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
|
||||
&vertex_count, samples.data(), samples.size(), &options,
|
||||
accept_candidate, &state, &report);
|
||||
expect(ret == BRLCAD_ERROR,
|
||||
"callback can stop an unproductive adaptive solve");
|
||||
expect(state.calls == 1 && report.solve_count == 1 &&
|
||||
report.termination == BG_3D_SPSR_CALLBACK_STOP,
|
||||
"callback stop preserves the final validation report");
|
||||
|
||||
state = {};
|
||||
state.refine_once = true;
|
||||
VSET(state.additional_sample.point, 1.0, 0.0, 0.0);
|
||||
VSET(state.additional_sample.normal, 1.0, 0.0, 0.0);
|
||||
faces = NULL;
|
||||
vertices = NULL;
|
||||
face_count = 0;
|
||||
vertex_count = 0;
|
||||
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
|
||||
&vertex_count, samples.data(), samples.size(), &options,
|
||||
accept_candidate, &state, &report);
|
||||
expect(ret == BRLCAD_OK, "adaptive refinement can add a source sample");
|
||||
expect(state.calls == 2 && report.solve_count == 2,
|
||||
"new source sample triggers a second solve");
|
||||
expect(report.accepted_sample_count == 1 &&
|
||||
report.final_sample_count == samples.size() + 1,
|
||||
"adaptive report counts incorporated samples");
|
||||
if (faces)
|
||||
bu_free(faces, "SPSR test faces");
|
||||
if (vertices)
|
||||
bu_free(vertices, "SPSR test vertices");
|
||||
|
||||
options.solver.threads = 1;
|
||||
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
|
||||
&vertex_count, samples.data(), samples.size(), &options,
|
||||
accept_candidate, &state, NULL);
|
||||
expect(ret == BRLCAD_ERROR,
|
||||
"unsupported solver settings are rejected");
|
||||
|
||||
expect(bg_3d_spsr_adaptive(NULL, &face_count, &vertices,
|
||||
&vertex_count, samples.data(), samples.size(), &options,
|
||||
accept_candidate, &state, NULL) == BRLCAD_ERROR,
|
||||
"invalid output arguments are rejected");
|
||||
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Local Variables:
|
||||
* tab-width: 8
|
||||
* mode: C++
|
||||
* c-basic-offset: 4
|
||||
* indent-tabs-mode: t
|
||||
* c-file-style: "stroustrup"
|
||||
* End:
|
||||
* ex: shiftwidth=4 tabstop=8 cino=N-s
|
||||
*/
|
||||
@@ -0,0 +1,106 @@
|
||||
/* T R I M E S H _ S O L I D . C
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include "bu.h"
|
||||
#include "bg.h"
|
||||
|
||||
|
||||
static int
|
||||
test_solid_diagnostics(void)
|
||||
{
|
||||
fastf_t vertices[][3] = {
|
||||
{0.0, 0.0, 0.0},
|
||||
{1.0, 0.0, 0.0},
|
||||
{0.0, 1.0, 0.0},
|
||||
{0.0, 0.0, 1.0},
|
||||
{1.0, 1.0, 1.0}
|
||||
};
|
||||
int solid_faces[] = {
|
||||
0, 2, 1,
|
||||
0, 1, 3,
|
||||
0, 3, 2,
|
||||
1, 2, 3
|
||||
};
|
||||
int reversed_faces[] = {
|
||||
0, 1, 2,
|
||||
0, 1, 3,
|
||||
0, 3, 2,
|
||||
1, 2, 3
|
||||
};
|
||||
int mixed_error_faces[] = {
|
||||
0, 1, 2,
|
||||
0, 1, 3,
|
||||
0, 3, 4,
|
||||
1, 2, 3
|
||||
};
|
||||
int *bad_edges = NULL;
|
||||
struct bg_trimesh_solid_errors errors = BG_TRIMESH_SOLID_ERRORS_INIT_NULL;
|
||||
int failed = 0;
|
||||
|
||||
if (bg_trimesh_solid(4, 4, &vertices[0][0], solid_faces, &bad_edges) || bad_edges)
|
||||
failed = 1;
|
||||
|
||||
if (bad_edges) {
|
||||
bu_free(bad_edges, "bad edges");
|
||||
bad_edges = NULL;
|
||||
}
|
||||
|
||||
if (bg_trimesh_solid(4, 4, &vertices[0][0], reversed_faces, &bad_edges) != 1
|
||||
|| !bad_edges) {
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
if (bad_edges)
|
||||
bu_free(bad_edges, "bad edges");
|
||||
|
||||
if (!bg_trimesh_solid2(5, 4, &vertices[0][0], mixed_error_faces, &errors)
|
||||
|| !errors.unmatched.count || !errors.misoriented.count) {
|
||||
failed = 1;
|
||||
}
|
||||
bg_free_trimesh_solid_errors(&errors);
|
||||
|
||||
return failed;
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_free_helpers(void)
|
||||
{
|
||||
struct bg_trimesh_edges edges = BG_TRIMESH_EDGES_INIT_NULL;
|
||||
struct bg_trimesh_faces faces = BG_TRIMESH_FACES_INIT_NULL;
|
||||
|
||||
edges.count = 1;
|
||||
edges.edges = (int *)bu_malloc(2 * sizeof(int), "test edges");
|
||||
faces.count = 1;
|
||||
faces.faces = (int *)bu_malloc(sizeof(int), "test faces");
|
||||
bg_free_trimesh_edges(&edges);
|
||||
bg_free_trimesh_faces(&faces);
|
||||
|
||||
return edges.count != 0 || edges.edges || faces.count != 0 || faces.faces;
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
bu_setprogname(argv[0]);
|
||||
if (argc != 1)
|
||||
return 1;
|
||||
|
||||
return test_solid_diagnostics() || test_free_helpers();
|
||||
}
|
||||
@@ -88,7 +88,7 @@ intersect_triangle(const point_t origin, const vect_t direction,
|
||||
extern "C" {
|
||||
|
||||
int
|
||||
bg_isect_tri_ray(const point_t orig, const point_t dir,
|
||||
bg_isect_tri_ray(const point_t orig, const vect_t dir,
|
||||
const point_t vert0, const point_t vert1, const point_t vert2,
|
||||
point_t *isect)
|
||||
{
|
||||
|
||||
+41
-21
@@ -285,10 +285,20 @@ bg_trimesh_solid2(int vcnt, int fcnt, fastf_t *v, int *f, struct bg_trimesh_soli
|
||||
|
||||
bad_edge_func = errors ? bg_trimesh_edge_continue : bg_trimesh_edge_exit;
|
||||
|
||||
if ((unmatched_edges = bg_trimesh_unmatched_edges(num_edges, edge_list, bad_edge_func, NULL)) ||
|
||||
(misoriented_edges = bg_trimesh_misoriented_edges(num_edges, edge_list, bad_edge_func, NULL)) ||
|
||||
(excess_edges = bg_trimesh_excess_edges(num_edges, edge_list, bad_edge_func, NULL)))
|
||||
{
|
||||
unmatched_edges = bg_trimesh_unmatched_edges(num_edges, edge_list, bad_edge_func, NULL);
|
||||
if (!errors && unmatched_edges) {
|
||||
bu_free(edge_list, "edge_list");
|
||||
return 1;
|
||||
}
|
||||
|
||||
misoriented_edges = bg_trimesh_misoriented_edges(num_edges, edge_list, bad_edge_func, NULL);
|
||||
if (!errors && misoriented_edges) {
|
||||
bu_free(edge_list, "edge_list");
|
||||
return 1;
|
||||
}
|
||||
|
||||
excess_edges = bg_trimesh_excess_edges(num_edges, edge_list, bad_edge_func, NULL);
|
||||
if (unmatched_edges || misoriented_edges || excess_edges) {
|
||||
if (!errors) {
|
||||
bu_free(edge_list, "edge_list");
|
||||
return 1;
|
||||
@@ -329,6 +339,7 @@ bg_free_trimesh_edges(struct bg_trimesh_edges *edges)
|
||||
if (!edges) return;
|
||||
|
||||
bu_free(edges->edges, "bg trimesh edges");
|
||||
edges->edges = NULL;
|
||||
edges->count = 0;
|
||||
}
|
||||
|
||||
@@ -338,6 +349,7 @@ bg_free_trimesh_faces(struct bg_trimesh_faces *faces)
|
||||
if (!faces) return;
|
||||
|
||||
bu_free(faces->faces, "bg trimesh faces");
|
||||
faces->faces = NULL;
|
||||
faces->count = 0;
|
||||
}
|
||||
|
||||
@@ -355,34 +367,42 @@ bg_free_trimesh_solid_errors(struct bg_trimesh_solid_errors *errors)
|
||||
int
|
||||
bg_trimesh_solid(int vcnt, int fcnt, fastf_t *v, int *f, int **bedges)
|
||||
{
|
||||
int bedge_cnt = 0;
|
||||
int not_solid;
|
||||
|
||||
if (bedges) {
|
||||
int copy_cnt = 0;
|
||||
int copy_count = 0;
|
||||
int edge_count;
|
||||
struct bg_trimesh_solid_errors errors = BG_TRIMESH_SOLID_ERRORS_INIT_NULL;
|
||||
|
||||
bedge_cnt = bg_trimesh_solid2(vcnt, fcnt, v, f, &errors);
|
||||
*bedges = NULL;
|
||||
not_solid = bg_trimesh_solid2(vcnt, fcnt, v, f, &errors);
|
||||
edge_count = errors.unmatched.count + errors.misoriented.count + errors.excess.count;
|
||||
if (edge_count) {
|
||||
*bedges = (int *)bu_calloc(edge_count * 2, sizeof(int), "bad edges");
|
||||
|
||||
*bedges = (int *)bu_calloc(bedge_cnt * 2, sizeof(int), "bad edges");
|
||||
|
||||
if (!errors.unmatched.edges || !errors.unmatched.count)
|
||||
return 0;
|
||||
|
||||
memcpy(*bedges, errors.unmatched.edges, errors.unmatched.count * 2 * sizeof(int));
|
||||
copy_cnt += errors.unmatched.count * 2;
|
||||
|
||||
memcpy(*bedges + copy_cnt, errors.misoriented.edges, errors.misoriented.count * 2 * sizeof(int));
|
||||
copy_cnt += errors.misoriented.count * 2;
|
||||
|
||||
memcpy(*bedges + copy_cnt, errors.excess.edges, errors.excess.count * 2 * sizeof(int));
|
||||
if (errors.unmatched.count) {
|
||||
memcpy(*bedges + copy_count, errors.unmatched.edges,
|
||||
errors.unmatched.count * 2 * sizeof(int));
|
||||
copy_count += errors.unmatched.count * 2;
|
||||
}
|
||||
if (errors.misoriented.count) {
|
||||
memcpy(*bedges + copy_count, errors.misoriented.edges,
|
||||
errors.misoriented.count * 2 * sizeof(int));
|
||||
copy_count += errors.misoriented.count * 2;
|
||||
}
|
||||
if (errors.excess.count) {
|
||||
memcpy(*bedges + copy_count, errors.excess.edges,
|
||||
errors.excess.count * 2 * sizeof(int));
|
||||
}
|
||||
}
|
||||
|
||||
bg_free_trimesh_solid_errors(&errors);
|
||||
} else {
|
||||
bedge_cnt = bg_trimesh_solid2(vcnt, fcnt, v, f, NULL);
|
||||
not_solid = bg_trimesh_solid2(vcnt, fcnt, v, f, NULL);
|
||||
}
|
||||
|
||||
/* returns true when not solid */
|
||||
return (bedge_cnt > 0) ? 1 : 0;
|
||||
return not_solid ? 1 : 0;
|
||||
}
|
||||
|
||||
int
|
||||
|
||||
+38
-98
@@ -662,87 +662,6 @@ bn_vec_perp(vect_t new_vec, const vect_t old_vec)
|
||||
VCROSS(new_vec, another_vec, old_vec);
|
||||
}
|
||||
|
||||
static int
|
||||
bn_lseg3_lseg3_parallel(const point_t sg1pt1, const point_t sg1pt2,
|
||||
const point_t sg2pt1, const point_t sg2pt2,
|
||||
const struct bn_tol *tol)
|
||||
{
|
||||
vect_t e_dif[2] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};
|
||||
vect_t e_dif_a[2] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};
|
||||
fastf_t e_rr[2][3] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};
|
||||
char e_sc[2][3] = {{0, 0, 0}, {0, 0, 0}};
|
||||
fastf_t dist = tol->dist;
|
||||
fastf_t tmp;
|
||||
int i, j;
|
||||
|
||||
VSUB2(e_dif[0], sg1pt2, sg1pt1);
|
||||
VSUB2(e_dif[1], sg2pt2, sg2pt1);
|
||||
|
||||
for ( i = 0 ; i < 2 ; i++ ) {
|
||||
for ( j = 0 ; j < 3 ; j++ ) {
|
||||
e_dif_a[i][j] = fabs(e_dif[i][j]);
|
||||
}
|
||||
}
|
||||
|
||||
for ( i = 0 ; i < 2 ; i++ ) {
|
||||
if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Y] > dist)) {
|
||||
e_sc[i][0] = 1;
|
||||
} else if ((e_dif_a[i][X] > dist) && (e_dif_a[i][Y] < dist)) {
|
||||
e_sc[i][0] = 2;
|
||||
} else if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Y] < dist)) {
|
||||
e_sc[i][0] = 3;
|
||||
} else {
|
||||
e_rr[i][0] = e_dif[i][Y] / e_dif[i][X];
|
||||
e_sc[i][0] = 0;
|
||||
}
|
||||
if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Z] > dist)) {
|
||||
e_sc[i][1] = 1;
|
||||
} else if ((e_dif_a[i][X] > dist) && (e_dif_a[i][Z] < dist)) {
|
||||
e_sc[i][1] = 2;
|
||||
} else if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Z] < dist)) {
|
||||
e_sc[i][1] = 3;
|
||||
} else {
|
||||
e_rr[i][1] = e_dif[i][Z] / e_dif[i][X];
|
||||
e_sc[i][1] = 0;
|
||||
}
|
||||
if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Z] > dist)) {
|
||||
e_sc[i][1] = 1;
|
||||
} else if ((e_dif_a[i][X] > dist) && (e_dif_a[i][Z] < dist)) {
|
||||
e_sc[i][1] = 2;
|
||||
} else if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Z] < dist)) {
|
||||
e_sc[i][1] = 3;
|
||||
} else {
|
||||
e_rr[i][1] = e_dif[i][Z] / e_dif[i][X];
|
||||
e_sc[i][1] = 0;
|
||||
}
|
||||
if ((e_dif_a[i][Y] < dist) && (e_dif_a[i][Z] > dist)) {
|
||||
e_sc[i][2] = 1;
|
||||
} else if ((e_dif_a[i][Y] > dist) && (e_dif_a[i][Z] < dist)) {
|
||||
e_sc[i][2] = 2;
|
||||
} else if ((e_dif_a[i][Y] < dist) && (e_dif_a[i][Z] < dist)) {
|
||||
e_sc[i][2] = 3;
|
||||
} else {
|
||||
e_rr[i][2] = e_dif[i][Z] / e_dif[i][Y];
|
||||
e_sc[i][2] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* loop thru (rise/run) ratios from xy, xz and yz planes */
|
||||
for ( i = 0 ; i < 3 ; i++ ) {
|
||||
if (e_sc[0][i] != e_sc[1][i]) {
|
||||
return 0;
|
||||
}
|
||||
if (e_sc[0][i] == 0) {
|
||||
tmp = e_rr[0][i] - e_rr[1][i];
|
||||
if (fabs(tmp) > dist) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
void
|
||||
bn_mat_fromto(
|
||||
mat_t m,
|
||||
@@ -753,7 +672,6 @@ bn_mat_fromto(
|
||||
vect_t test_to;
|
||||
vect_t unit_from, unit_to;
|
||||
fastf_t dot;
|
||||
point_t origin = VINIT_ZERO;
|
||||
|
||||
/**
|
||||
* The method used here is from Graphics Gems, A. Glassner, ed.
|
||||
@@ -767,18 +685,24 @@ bn_mat_fromto(
|
||||
vect_t N, M;
|
||||
vect_t w_prime; /* image of "to" ("w") in Qt */
|
||||
|
||||
BN_CK_TOL(tol);
|
||||
|
||||
VMOVE(unit_from, from);
|
||||
VUNITIZE(unit_from); /* aka "v" */
|
||||
VMOVE(unit_to, to);
|
||||
VUNITIZE(unit_to); /* aka "w" */
|
||||
|
||||
/* If from and to are the same or opposite, special handling is
|
||||
* needed, because the cross product isn't defined. asin(0.00001)
|
||||
* = 0.0005729 degrees (1/2000 degree)
|
||||
if (VZERO(unit_from) || VZERO(unit_to)) {
|
||||
MAT_IDN(m);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Same and opposite directions need special handling because their
|
||||
* cross product does not define a rotation axis.
|
||||
*/
|
||||
if (bn_lseg3_lseg3_parallel(origin, from, origin, to, tol)) {
|
||||
dot = VDOT(from, to);
|
||||
if (dot > SMALL_FASTF) {
|
||||
dot = VDOT(unit_from, unit_to);
|
||||
if (BN_VECT_ARE_PARALLEL(dot, tol)) {
|
||||
if (dot > 0.0) {
|
||||
MAT_IDN(m);
|
||||
return;
|
||||
} else {
|
||||
@@ -812,7 +736,7 @@ bn_mat_fromto(
|
||||
|
||||
/* Verify that it worked */
|
||||
MAT4X3VEC(test_to, m, unit_from);
|
||||
if (UNLIKELY(!bn_lseg3_lseg3_parallel(origin, unit_to, origin, test_to, tol))) {
|
||||
if (UNLIKELY(!BN_VECT_ARE_PARALLEL(VDOT(unit_to, test_to), tol))) {
|
||||
dot = VDOT(unit_to, test_to);
|
||||
bu_log("bn_mat_fromto() ERROR! from (%g, %g, %g) to (%g, %g, %g) went to (%g, %g, %g), dot=%g?\n",
|
||||
V3ARGS(from), V3ARGS(to), V3ARGS(test_to), dot);
|
||||
@@ -899,16 +823,32 @@ bn_mat_lookat(mat_t rot, const vect_t dir, int yflip)
|
||||
vect_t x;
|
||||
vect_t z;
|
||||
vect_t t1;
|
||||
vect_t unit_dir;
|
||||
fastf_t hypot_xy;
|
||||
vect_t xproj;
|
||||
vect_t zproj;
|
||||
|
||||
VMOVE(unit_dir, dir);
|
||||
VUNITIZE(unit_dir);
|
||||
if (VZERO(unit_dir)) {
|
||||
MAT_IDN(rot);
|
||||
return;
|
||||
}
|
||||
|
||||
/* First, rotate D around Z axis to match +X axis (azimuth) */
|
||||
hypot_xy = hypot(dir[X], dir[Y]);
|
||||
bn_mat_zrot(first, -dir[Y] / hypot_xy, dir[X] / hypot_xy);
|
||||
hypot_xy = hypot(unit_dir[X], unit_dir[Y]);
|
||||
if (hypot_xy < VDIVIDE_TOL) {
|
||||
if (unit_dir[Z] < 0.0) {
|
||||
MAT_IDN(rot);
|
||||
} else {
|
||||
bn_mat_yrot(rot, 0.0, -1.0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
bn_mat_zrot(first, -unit_dir[Y] / hypot_xy, unit_dir[X] / hypot_xy);
|
||||
|
||||
/* Next, rotate D around Y axis to match -Z axis (elevation) */
|
||||
bn_mat_yrot(second, -hypot_xy, -dir[Z]);
|
||||
bn_mat_yrot(second, -hypot_xy, -unit_dir[Z]);
|
||||
bn_mat_mul(prod12, second, first);
|
||||
|
||||
/* Produce twist correction, by re-orienting projection of X axis */
|
||||
@@ -937,7 +877,7 @@ bn_mat_lookat(mat_t rot, const vect_t dir, int yflip)
|
||||
}
|
||||
|
||||
/* Check the final results */
|
||||
MAT4X3VEC(t1, rot, dir);
|
||||
MAT4X3VEC(t1, rot, unit_dir);
|
||||
if (t1[Z] > -0.98) {
|
||||
bu_log("Error: bn_mat_lookat final= (%g, %g, %g)\n", V3ARGS(t1));
|
||||
}
|
||||
@@ -1277,10 +1217,10 @@ bn_mat_is_non_unif(const mat_t m)
|
||||
void
|
||||
bn_wrt_point_direc(mat_t out, const mat_t change, const mat_t in, const point_t point, const vect_t direc, const struct bn_tol *tol)
|
||||
{
|
||||
static mat_t t1;
|
||||
static mat_t pt_to_origin, origin_to_pt;
|
||||
static mat_t d_to_zaxis, zaxis_to_d;
|
||||
static vect_t zaxis;
|
||||
mat_t t1;
|
||||
mat_t pt_to_origin, origin_to_pt;
|
||||
mat_t d_to_zaxis, zaxis_to_d;
|
||||
vect_t zaxis;
|
||||
|
||||
/* build "point to origin" matrix */
|
||||
MAT_IDN(pt_to_origin);
|
||||
@@ -1288,7 +1228,7 @@ bn_wrt_point_direc(mat_t out, const mat_t change, const mat_t in, const point_t
|
||||
|
||||
/* build "origin to point" matrix */
|
||||
MAT_IDN(origin_to_pt);
|
||||
MAT_DELTAS_VEC_NEG(origin_to_pt, point);
|
||||
MAT_DELTAS_VEC(origin_to_pt, point);
|
||||
|
||||
/* build "direc to zaxis" matrix */
|
||||
VSET(zaxis, 0.0, 0.0, 1.0);
|
||||
|
||||
+86
-43
@@ -28,21 +28,11 @@
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "bu/interrupt.h"
|
||||
#include "bu/malloc.h"
|
||||
#include "vmath.h"
|
||||
#include "bn/multipoly.h"
|
||||
|
||||
|
||||
#define FAILSTR "failure in multipoly.c"
|
||||
/* the Max and Min macros in vmath.h are destructive and not suited for here, should this be
|
||||
* added somewhere else? */
|
||||
#define Max(a, b) (((a) > (b)) ? (a) : (b))
|
||||
#define Min(a, b) (((a) > (b)) ? (a) : (b))
|
||||
|
||||
/**
|
||||
* bn_multipoly_new
|
||||
*
|
||||
@@ -52,25 +42,41 @@ struct bn_multipoly *
|
||||
bn_multipoly_new(int dgrs, int dgrt)
|
||||
{
|
||||
struct bn_multipoly *newmp;
|
||||
int i, s, t;
|
||||
int i;
|
||||
|
||||
if (dgrs <= 0 || dgrt <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
BU_ALLOC(newmp, struct bn_multipoly);
|
||||
newmp->cf = (double **)bu_malloc(dgrs * sizeof(double *), FAILSTR);
|
||||
newmp->cf = (double **)bu_calloc(dgrs, sizeof(double *), FAILSTR);
|
||||
|
||||
for (i = 0; i < dgrs; i++) {
|
||||
newmp->cf[i] = (double *)bu_malloc(dgrt * sizeof(double), FAILSTR);
|
||||
newmp->cf[i] = (double *)bu_calloc(dgrt, sizeof(double), FAILSTR);
|
||||
}
|
||||
|
||||
newmp->dgrs = dgrs;
|
||||
newmp->dgrt = dgrt;
|
||||
for (s = 0; s < dgrs; s++) {
|
||||
for (t = 0; t < dgrt; t++) {
|
||||
newmp->cf[s][t] = 0;
|
||||
}
|
||||
}
|
||||
return newmp;
|
||||
}
|
||||
|
||||
|
||||
void
|
||||
bn_multipoly_free(struct bn_multipoly *poly)
|
||||
{
|
||||
int s;
|
||||
|
||||
if (!poly) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (s = 0; s < poly->dgrs; s++) {
|
||||
bu_free(poly->cf[s], "bn_multipoly coefficients");
|
||||
}
|
||||
bu_free(poly->cf, "bn_multipoly coefficient rows");
|
||||
bu_free(poly, "bn_multipoly");
|
||||
}
|
||||
|
||||
/**
|
||||
* bn_multipoly_grow
|
||||
*
|
||||
@@ -79,24 +85,35 @@ bn_multipoly_new(int dgrs, int dgrt)
|
||||
struct bn_multipoly *
|
||||
bn_multipoly_grow(register struct bn_multipoly *P, int dgrs, int dgrt)
|
||||
{
|
||||
int i, j;
|
||||
if (dgrs > P->dgrs) {
|
||||
P->cf = (double **)bu_realloc(P->cf, dgrs * sizeof(double *), FAILSTR);
|
||||
for (i = P->dgrs; i < dgrs; i++) {
|
||||
P->cf[i] = (double *)bu_malloc(Max(P->dgrt, dgrt) * sizeof(double), FAILSTR);
|
||||
for (j = 0; j < Max(P->dgrt, dgrt); j++) {
|
||||
P->cf[i][j] = 0;
|
||||
}
|
||||
}
|
||||
double **coefficients;
|
||||
int new_dgrs, new_dgrt;
|
||||
int s, t;
|
||||
|
||||
if (!P) {
|
||||
return NULL;
|
||||
}
|
||||
if (dgrt > P->dgrt) {
|
||||
for (i = 0; i < P->dgrt; i++) {
|
||||
P->cf[i] = (double *)bu_realloc(P->cf, dgrt * sizeof(double *), FAILSTR);
|
||||
for (j = P->dgrt; j < dgrt; j++) {
|
||||
P->cf[i][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
new_dgrs = (dgrs > P->dgrs) ? dgrs : P->dgrs;
|
||||
new_dgrt = (dgrt > P->dgrt) ? dgrt : P->dgrt;
|
||||
if (new_dgrs == P->dgrs && new_dgrt == P->dgrt) {
|
||||
return P;
|
||||
}
|
||||
|
||||
coefficients = (double **)bu_calloc(new_dgrs, sizeof(double *), FAILSTR);
|
||||
for (s = 0; s < new_dgrs; s++) {
|
||||
coefficients[s] = (double *)bu_calloc(new_dgrt, sizeof(double), FAILSTR);
|
||||
}
|
||||
for (s = 0; s < P->dgrs; s++) {
|
||||
for (t = 0; t < P->dgrt; t++) {
|
||||
coefficients[s][t] = P->cf[s][t];
|
||||
}
|
||||
bu_free(P->cf[s], "bn_multipoly coefficients");
|
||||
}
|
||||
bu_free(P->cf, "bn_multipoly coefficient rows");
|
||||
|
||||
P->cf = coefficients;
|
||||
P->dgrs = new_dgrs;
|
||||
P->dgrt = new_dgrt;
|
||||
return P;
|
||||
}
|
||||
|
||||
@@ -108,7 +125,12 @@ bn_multipoly_grow(register struct bn_multipoly *P, int dgrs, int dgrt)
|
||||
struct bn_multipoly *
|
||||
bn_multipoly_set(register struct bn_multipoly *P, int s, int t, double val)
|
||||
{
|
||||
bn_multipoly_grow(P, s + 1, t + 1);
|
||||
if (!P || s < 0 || t < 0) {
|
||||
return NULL;
|
||||
}
|
||||
if (!bn_multipoly_grow(P, s + 1, t + 1)) {
|
||||
return NULL;
|
||||
}
|
||||
P->cf[s][t] = val;
|
||||
return P;
|
||||
}
|
||||
@@ -119,13 +141,26 @@ bn_multipoly_set(register struct bn_multipoly *P, int s, int t, double val)
|
||||
* @brief add two polynomials
|
||||
*/
|
||||
struct bn_multipoly *
|
||||
bn_multipoly_add(register struct bn_multipoly *p1, register struct bn_multipoly *p2)
|
||||
bn_multipoly_add(register const struct bn_multipoly *p1, register const struct bn_multipoly *p2)
|
||||
{
|
||||
struct bn_multipoly *sum = bn_multipoly_new(Max(p1->dgrs, p2->dgrs), Max(p1->dgrt, p2->dgrs));
|
||||
struct bn_multipoly *sum;
|
||||
int s, t;
|
||||
|
||||
if (!p1 || !p2 || p1->dgrs <= 0 || p1->dgrt <= 0 ||
|
||||
p2->dgrs <= 0 || p2->dgrt <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
sum = bn_multipoly_new((p1->dgrs > p2->dgrs) ? p1->dgrs : p2->dgrs,
|
||||
(p1->dgrt > p2->dgrt) ? p1->dgrt : p2->dgrt);
|
||||
for (s = 0; s < sum->dgrs; s++) {
|
||||
for (t = 0; t < sum->dgrt; t++) {
|
||||
sum->cf[s][t] = p1->cf[s][t] + p2->cf[s][t];
|
||||
if (s < p1->dgrs && t < p1->dgrt) {
|
||||
sum->cf[s][t] += p1->cf[s][t];
|
||||
}
|
||||
if (s < p2->dgrs && t < p2->dgrt) {
|
||||
sum->cf[s][t] += p2->cf[s][t];
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
@@ -138,15 +173,23 @@ bn_multipoly_add(register struct bn_multipoly *p1, register struct bn_multipoly
|
||||
*/
|
||||
|
||||
struct bn_multipoly *
|
||||
bn_multipoly_mul(register struct bn_multipoly *p1, register struct bn_multipoly *p2)
|
||||
bn_multipoly_mul(register const struct bn_multipoly *p1, register const struct bn_multipoly *p2)
|
||||
{
|
||||
struct bn_multipoly *product = bn_multipoly_new(p1->dgrs + p2->dgrs, p1->dgrt + p2->dgrt);
|
||||
int s1,s2,t1,t2;
|
||||
struct bn_multipoly *product;
|
||||
int s1, s2, t1, t2;
|
||||
|
||||
if (!p1 || !p2 || p1->dgrs <= 0 || p1->dgrt <= 0 ||
|
||||
p2->dgrs <= 0 || p2->dgrt <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
product = bn_multipoly_new(p1->dgrs + p2->dgrs - 1,
|
||||
p1->dgrt + p2->dgrt - 1);
|
||||
for (s1 = 0; s1 < p1->dgrs; s1++) {
|
||||
for (t1 = 0; t1 < p1->dgrt; t1++) {
|
||||
for (s2 = 0; s2 < p2->dgrs; s2++) {
|
||||
for (t2 = 0; t2 < p2->dgrt; p2++) {
|
||||
product->cf[s1 + s2][t1 + t2] = p1->cf[s1][t1] * p2->cf[s2][t2];
|
||||
for (t2 = 0; t2 < p2->dgrt; t2++) {
|
||||
product->cf[s1 + s2][t1 + t2] += p1->cf[s1][t1] * p2->cf[s2][t2];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+64
-39
@@ -28,7 +28,6 @@
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <stdlib.h> /* for abs */
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
|
||||
@@ -49,7 +48,24 @@ static const struct bn_poly bn_Zero_poly = { BN_POLY_MAGIC, 0, {0.0} };
|
||||
struct bn_poly *
|
||||
bn_poly_mul(register struct bn_poly *product, register const struct bn_poly *m1, register const struct bn_poly *m2)
|
||||
{
|
||||
if (m1->dgr > BN_MAX_POLY_DEGREE ||
|
||||
m2->dgr > BN_MAX_POLY_DEGREE ||
|
||||
m1->dgr > BN_MAX_POLY_DEGREE - m2->dgr) {
|
||||
return BN_POLY_NULL;
|
||||
}
|
||||
|
||||
if (product == m1 || product == m2) {
|
||||
struct bn_poly result;
|
||||
|
||||
if (!bn_poly_mul(&result, m1, m2)) {
|
||||
return BN_POLY_NULL;
|
||||
}
|
||||
*product = result;
|
||||
return product;
|
||||
}
|
||||
|
||||
if (m1->dgr == 1 && m2->dgr == 1) {
|
||||
product->magic = BN_POLY_MAGIC;
|
||||
product->dgr = 2;
|
||||
product->cf[0] = m1->cf[0] * m2->cf[0];
|
||||
product->cf[1] = m1->cf[0] * m2->cf[1] +
|
||||
@@ -58,6 +74,7 @@ bn_poly_mul(register struct bn_poly *product, register const struct bn_poly *m1,
|
||||
return product;
|
||||
}
|
||||
if (m1->dgr == 2 && m2->dgr == 2) {
|
||||
product->magic = BN_POLY_MAGIC;
|
||||
product->dgr = 4;
|
||||
product->cf[0] = m1->cf[0] * m2->cf[0];
|
||||
product->cf[1] = m1->cf[0] * m2->cf[1] +
|
||||
@@ -77,12 +94,7 @@ bn_poly_mul(register struct bn_poly *product, register const struct bn_poly *m1,
|
||||
|
||||
*product = bn_Zero_poly;
|
||||
|
||||
/* If the degree of the product will be larger than the
|
||||
* maximum size allowed in "polyno.h", then return a null
|
||||
* pointer to indicate failure.
|
||||
*/
|
||||
if ((product->dgr = m1->dgr + m2->dgr) > BN_MAX_POLY_DEGREE)
|
||||
return BN_POLY_NULL;
|
||||
product->dgr = m1->dgr + m2->dgr;
|
||||
|
||||
for (ct1=0; ct1 <= m1->dgr; ++ct1) {
|
||||
for (ct2=0; ct2 <= m2->dgr; ++ct2) {
|
||||
@@ -110,28 +122,26 @@ bn_poly_scale(register struct bn_poly *eqn, double factor)
|
||||
struct bn_poly *
|
||||
bn_poly_add(register struct bn_poly *sum, register const struct bn_poly *poly1, register const struct bn_poly *poly2)
|
||||
{
|
||||
struct bn_poly tmp;
|
||||
struct bn_poly result;
|
||||
register size_t i, offset;
|
||||
|
||||
offset = labs((long)poly1->dgr - (long)poly2->dgr);
|
||||
|
||||
tmp = bn_Zero_poly;
|
||||
offset = (poly1->dgr >= poly2->dgr) ?
|
||||
poly1->dgr - poly2->dgr : poly2->dgr - poly1->dgr;
|
||||
|
||||
if (poly1->dgr >= poly2->dgr) {
|
||||
*sum = *poly1;
|
||||
result = *poly1;
|
||||
for (i=0; i <= poly2->dgr; ++i) {
|
||||
tmp.cf[i+offset] = poly2->cf[i];
|
||||
result.cf[i+offset] += poly2->cf[i];
|
||||
}
|
||||
} else {
|
||||
*sum = *poly2;
|
||||
result = *poly2;
|
||||
for (i=0; i <= poly1->dgr; ++i) {
|
||||
tmp.cf[i+offset] = poly1->cf[i];
|
||||
result.cf[i+offset] += poly1->cf[i];
|
||||
}
|
||||
}
|
||||
|
||||
for (i=0; i <= sum->dgr; ++i) {
|
||||
sum->cf[i] += tmp.cf[i];
|
||||
}
|
||||
result.magic = BN_POLY_MAGIC;
|
||||
*sum = result;
|
||||
return sum;
|
||||
}
|
||||
|
||||
@@ -139,30 +149,30 @@ bn_poly_add(register struct bn_poly *sum, register const struct bn_poly *poly1,
|
||||
struct bn_poly *
|
||||
bn_poly_sub(register struct bn_poly *diff, register const struct bn_poly *poly1, register const struct bn_poly *poly2)
|
||||
{
|
||||
struct bn_poly tmp;
|
||||
struct bn_poly result;
|
||||
register size_t i, offset;
|
||||
|
||||
offset = labs((long)poly1->dgr - (long)poly2->dgr);
|
||||
|
||||
*diff = bn_Zero_poly;
|
||||
tmp = bn_Zero_poly;
|
||||
offset = (poly1->dgr >= poly2->dgr) ?
|
||||
poly1->dgr - poly2->dgr : poly2->dgr - poly1->dgr;
|
||||
|
||||
if (poly1->dgr >= poly2->dgr) {
|
||||
*diff = *poly1;
|
||||
result = *poly1;
|
||||
for (i=0; i <= poly2->dgr; ++i) {
|
||||
tmp.cf[i+offset] = poly2->cf[i];
|
||||
result.cf[i+offset] -= poly2->cf[i];
|
||||
}
|
||||
} else {
|
||||
diff->dgr = poly2->dgr;
|
||||
result = bn_Zero_poly;
|
||||
result.dgr = poly2->dgr;
|
||||
for (i=0; i <= poly1->dgr; ++i) {
|
||||
diff->cf[i+offset] = poly1->cf[i];
|
||||
result.cf[i+offset] = poly1->cf[i];
|
||||
}
|
||||
for (i=0; i <= poly2->dgr; ++i) {
|
||||
result.cf[i] -= poly2->cf[i];
|
||||
}
|
||||
tmp = *poly2;
|
||||
}
|
||||
|
||||
for (i=0; i <= diff->dgr; ++i) {
|
||||
diff->cf[i] -= tmp.cf[i];
|
||||
}
|
||||
result.magic = BN_POLY_MAGIC;
|
||||
*diff = result;
|
||||
return diff;
|
||||
}
|
||||
|
||||
@@ -177,12 +187,20 @@ bn_poly_synthetic_division(struct bn_poly *quo, struct bn_poly *rem, const struc
|
||||
*rem = bn_Zero_poly; /* struct copy */
|
||||
|
||||
if (dvsor->dgr > dvdend->dgr) {
|
||||
quo->dgr = -1;
|
||||
} else {
|
||||
quo->dgr = dvdend->dgr - dvsor->dgr;
|
||||
*rem = *dvdend;
|
||||
*quo = bn_Zero_poly;
|
||||
return;
|
||||
}
|
||||
if ((rem->dgr = dvsor->dgr - 1) > dvdend->dgr)
|
||||
rem->dgr = dvdend->dgr;
|
||||
|
||||
if (dvsor->dgr == 0) {
|
||||
for (n=0; n <= quo->dgr; ++n) {
|
||||
quo->cf[n] /= dvsor->cf[0];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
quo->dgr = dvdend->dgr - dvsor->dgr;
|
||||
rem->dgr = dvsor->dgr - 1;
|
||||
|
||||
for (n=0; n <= quo->dgr; ++n) {
|
||||
quo->cf[n] /= dvsor->cf[0];
|
||||
@@ -200,10 +218,11 @@ bn_poly_synthetic_division(struct bn_poly *quo, struct bn_poly *rem, const struc
|
||||
int
|
||||
bn_poly_quadratic_roots(register struct bn_complex *roots, register const struct bn_poly *quadrat)
|
||||
{
|
||||
struct bn_poly monic;
|
||||
fastf_t discrim, denom, rad;
|
||||
const fastf_t small = SMALL_FASTF;
|
||||
|
||||
if (NEAR_ZERO(quadrat->cf[0], small)) {
|
||||
if (ZERO(quadrat->cf[0]) && fpclassify(quadrat->cf[0]) == FP_ZERO) {
|
||||
/* root = -cf[2] / cf[1] */
|
||||
if (NEAR_ZERO(quadrat->cf[1], small)) {
|
||||
/* No solution. Now what? */
|
||||
@@ -216,6 +235,12 @@ bn_poly_quadratic_roots(register struct bn_complex *roots, register const struct
|
||||
return 1; /* OK - repeated root */
|
||||
}
|
||||
|
||||
if (!NEAR_EQUAL(quadrat->cf[0], 1.0, small)) {
|
||||
monic = *quadrat;
|
||||
bn_poly_scale(&monic, 1.0 / monic.cf[0]);
|
||||
quadrat = &monic;
|
||||
}
|
||||
|
||||
discrim = quadrat->cf[1]*quadrat->cf[1] - 4.0* quadrat->cf[0]*quadrat->cf[2];
|
||||
denom = 0.5 / quadrat->cf[0];
|
||||
|
||||
@@ -264,7 +289,7 @@ bn_poly_cubic_roots(register struct bn_complex *roots, register const struct bn_
|
||||
fastf_t a, b, c1, c1_3rd, delta;
|
||||
register int i;
|
||||
|
||||
if (ZERO(eqn->cf[0])) return 0;
|
||||
if (ZERO(eqn->cf[0]) && fpclassify(eqn->cf[0]) == FP_ZERO) return 0;
|
||||
|
||||
/* Cardano's formula below is expressed for a monic polynomial. */
|
||||
if (!NEAR_EQUAL(eqn->cf[0], 1.0, SMALL_FASTF)) {
|
||||
@@ -358,7 +383,7 @@ bn_poly_quartic_roots(register struct bn_complex *roots, register const struct b
|
||||
|
||||
#define Max3(a, b, c) ((c)>((a)>(b)?(a):(b)) ? (c) : ((a)>(b)?(a):(b)))
|
||||
|
||||
if (ZERO(eqn->cf[0])) return 0;
|
||||
if (ZERO(eqn->cf[0]) && fpclassify(eqn->cf[0]) == FP_ZERO) return 0;
|
||||
|
||||
/* Ferrari's formula below is expressed for a monic polynomial. */
|
||||
if (!NEAR_EQUAL(eqn->cf[0], 1.0, SMALL_FASTF)) {
|
||||
|
||||
+12
-2
@@ -174,7 +174,14 @@ quat_double(quat_t qout, const quat_t q1, const quat_t q2)
|
||||
void
|
||||
quat_bisect(quat_t qout, const quat_t q1, const quat_t q2)
|
||||
{
|
||||
QADD2( qout, q1, q2 );
|
||||
quat_t qsum;
|
||||
|
||||
QADD2(qsum, q1, q2);
|
||||
if (QMAGSQ(qsum) < VDIVIDE_TOL * VDIVIDE_TOL) {
|
||||
quat_slerp(qout, q1, q2, 0.5);
|
||||
return;
|
||||
}
|
||||
QMOVE(qout, qsum);
|
||||
QUNITIZE( qout );
|
||||
}
|
||||
|
||||
@@ -302,9 +309,12 @@ quat_log(quat_t out, const quat_t in)
|
||||
fastf_t theta;
|
||||
fastf_t scale;
|
||||
|
||||
if ( (scale = MAGNITUDE(in)) > VDIVIDE_TOL ) {
|
||||
scale = MAGNITUDE(in);
|
||||
if (scale > VDIVIDE_TOL) {
|
||||
theta = atan2( scale, in[W] );
|
||||
scale = theta/scale;
|
||||
} else {
|
||||
scale = 0.0;
|
||||
}
|
||||
|
||||
VSCALE( out, in, scale );
|
||||
|
||||
@@ -33,6 +33,22 @@ vect_close_or_neg(const vect_t a, const vect_t b, double tol)
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
lookat_is_valid(const vect_t direction)
|
||||
{
|
||||
vect_t expected = {0.0, 0.0, -1.0};
|
||||
vect_t output = VINIT_ZERO;
|
||||
mat_t matrix = MAT_INIT_ZERO;
|
||||
|
||||
bn_mat_lookat(matrix, direction, 0);
|
||||
MAT4X3VEC(output, matrix, direction);
|
||||
VUNITIZE(output);
|
||||
|
||||
return finite_vec(output) && vect_close(output, expected, 1.0e-12)
|
||||
&& orthonormal_rotation(matrix, 1.0e-12);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_mat_basic(void)
|
||||
{
|
||||
@@ -799,6 +815,13 @@ test_mat_orientation(void)
|
||||
int failures = 0;
|
||||
const char *test = "mat_orientation";
|
||||
struct bn_tol tol = BN_TOL_INIT_TOL;
|
||||
struct bn_tol angular_tol = BN_TOL_INIT_TOL;
|
||||
static const vect_t lookat_directions[] = {
|
||||
{0.0, 0.0, -1.0},
|
||||
{0.0, 0.0, 1.0},
|
||||
{0.0, 0.0, -5.0},
|
||||
{0.0, 0.0, 5.0}
|
||||
};
|
||||
vect_t input = {1.0, 2.0, 3.0};
|
||||
vect_t perp = VINIT_ZERO;
|
||||
vect_t expected_perp = {0.0, 0.0, 1.0};
|
||||
@@ -806,9 +829,14 @@ test_mat_orientation(void)
|
||||
vect_t to = {0.0, 1.0, 0.0};
|
||||
vect_t opposite = {-1.0, 0.0, 0.0};
|
||||
vect_t dir = {1.0, 1.0, -2.0};
|
||||
vect_t near_from = {1.0, 0.0, 0.0};
|
||||
vect_t near_to = {1.0, 0.1, 0.0};
|
||||
vect_t near_to_unit = VINIT_ZERO;
|
||||
vect_t zero_dir = VINIT_ZERO;
|
||||
vect_t out = VINIT_ZERO;
|
||||
hvect_t homogeneous = HINIT_ZERO;
|
||||
mat_t m = MAT_INIT_ZERO;
|
||||
size_t i;
|
||||
|
||||
if (!HZERO(homogeneous)) {
|
||||
report_failure(test, "HZERO failed for a zero homogeneous vector");
|
||||
@@ -844,6 +872,18 @@ test_mat_orientation(void)
|
||||
failures++;
|
||||
}
|
||||
|
||||
angular_tol.dist = 1.0;
|
||||
angular_tol.dist_sq = 1.0;
|
||||
bn_mat_fromto(m, near_from, near_to, &angular_tol);
|
||||
MAT4X3VEC(out, m, near_from);
|
||||
VUNITIZE(out);
|
||||
VMOVE(near_to_unit, near_to);
|
||||
VUNITIZE(near_to_unit);
|
||||
if (VDOT(out, near_to_unit) < 1.0 - 1.0e-12 || !orthonormal_rotation(m, 1.0e-12)) {
|
||||
report_failure(test, "bn_mat_fromto used distance tolerance for angular classification");
|
||||
failures++;
|
||||
}
|
||||
|
||||
VUNITIZE(dir);
|
||||
bn_mat_lookat(m, dir, 0);
|
||||
MAT4X3VEC(out, m, dir);
|
||||
@@ -854,6 +894,19 @@ test_mat_orientation(void)
|
||||
failures++;
|
||||
}
|
||||
|
||||
for (i = 0; i < sizeof(lookat_directions) / sizeof(lookat_directions[0]); i++) {
|
||||
if (!lookat_is_valid(lookat_directions[i])) {
|
||||
report_failure(test, "bn_mat_lookat failed for an axial direction");
|
||||
failures++;
|
||||
}
|
||||
}
|
||||
|
||||
bn_mat_lookat(m, zero_dir, 0);
|
||||
if (!mat_close(m, bn_mat_identity, 0.0)) {
|
||||
report_failure(test, "bn_mat_lookat did not return identity for a zero direction");
|
||||
failures++;
|
||||
}
|
||||
|
||||
return failures;
|
||||
}
|
||||
|
||||
@@ -864,6 +917,7 @@ test_mat_transform(void)
|
||||
int failures = 0;
|
||||
const char *test = "mat_transform";
|
||||
const double legacy_tol = BN_TOL_DIST;
|
||||
struct bn_tol tol = BN_TOL_INIT_TOL;
|
||||
static const struct {
|
||||
double sinv;
|
||||
double cosv;
|
||||
@@ -919,8 +973,14 @@ test_mat_transform(void)
|
||||
point_t p = {2.0, 2.0, 3.0};
|
||||
point_t axis_point = {1.0, 2.0, 10.0};
|
||||
point_t expected = {1.0, 3.0, 3.0};
|
||||
point_t pivot = {1.0, 2.0, 3.0};
|
||||
point_t pivot_offset = {2.0, 2.0, 3.0};
|
||||
point_t pivot_expected = {1.0, 3.0, 3.0};
|
||||
point_t out = VINIT_ZERO;
|
||||
vect_t pivot_direction = {0.0, 0.0, 1.0};
|
||||
mat_t m = MAT_INIT_ZERO;
|
||||
mat_t change = MAT_INIT_ZERO;
|
||||
mat_t input = MAT_INIT_ZERO;
|
||||
int i;
|
||||
|
||||
bn_mat_arb_rot(m, anchor, axis, M_PI_2);
|
||||
@@ -936,6 +996,20 @@ test_mat_transform(void)
|
||||
failures++;
|
||||
}
|
||||
|
||||
bn_mat_zrot(change, 1.0, 0.0);
|
||||
MAT_IDN(input);
|
||||
bn_wrt_point_direc(m, change, input, pivot, pivot_direction, &tol);
|
||||
MAT4X3PNT(out, m, pivot);
|
||||
if (!vect_close(out, pivot, 1.0e-12)) {
|
||||
report_failure(test, "bn_wrt_point_direc moved its pivot point");
|
||||
failures++;
|
||||
}
|
||||
MAT4X3PNT(out, m, pivot_offset);
|
||||
if (!vect_close(out, pivot_expected, 1.0e-12)) {
|
||||
report_failure(test, "bn_wrt_point_direc did not rotate around its pivot point");
|
||||
failures++;
|
||||
}
|
||||
|
||||
MAT_IDN(m);
|
||||
if (bn_mat_is_non_unif(m) != 0) {
|
||||
report_failure(test, "bn_mat_is_non_unif misclassified the identity matrix");
|
||||
|
||||
@@ -199,6 +199,153 @@ test_poly_ops(void)
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_poly_edge_cases(void)
|
||||
{
|
||||
int failures = 0;
|
||||
const char *test = "poly_edge_cases";
|
||||
const double linear_coeffs[] = {1.0, -1.0};
|
||||
const double quadratic_coeffs[] = {1.0, 0.0, -4.0};
|
||||
const double aliased_sum_coeffs[] = {1.0, 1.0, -5.0};
|
||||
const double aliased_difference_coeffs[] = {-1.0, 1.0, 3.0};
|
||||
const double aliased_product_coeffs[] = {1.0, -1.0, -4.0, 4.0};
|
||||
const double dividend_coeffs[] = {1.0, -3.0, 2.0};
|
||||
const double constant_divisor_coeffs[] = {2.0};
|
||||
const double constant_quotient_coeffs[] = {0.5, -1.5, 1.0};
|
||||
const double higher_divisor_coeffs[] = {1.0, 0.0, 1.0};
|
||||
const double degree_six_coeffs[] = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
|
||||
const double untouched_product_coeffs[] = {42.0};
|
||||
const double zero_coeffs[] = {0.0};
|
||||
const double scaled_quadratic_coeffs[] = {1.0e-12, -5.0e-12, 6.0e-12};
|
||||
const double scaled_cubic_coeffs[] = {1.0e-12, -6.0e-12, 11.0e-12, -6.0e-12};
|
||||
const double scaled_quartic_coeffs[] = {1.0e-12, 0.0, -10.0e-12, 0.0, 9.0e-12};
|
||||
bn_poly_t linear = poly_from_coeffs(1, linear_coeffs);
|
||||
bn_poly_t quadratic = poly_from_coeffs(2, quadratic_coeffs);
|
||||
bn_poly_t dividend = poly_from_coeffs(2, dividend_coeffs);
|
||||
bn_poly_t constant_divisor = poly_from_coeffs(0, constant_divisor_coeffs);
|
||||
bn_poly_t higher_divisor = poly_from_coeffs(2, higher_divisor_coeffs);
|
||||
bn_poly_t degree_six = poly_from_coeffs(6, degree_six_coeffs);
|
||||
bn_poly_t rejected_product = poly_from_coeffs(0, untouched_product_coeffs);
|
||||
bn_poly_t quotient = BN_POLY_INIT_ZERO;
|
||||
bn_poly_t remainder = BN_POLY_INIT_ZERO;
|
||||
bn_poly_t scaled_quadratic = poly_from_coeffs(2, scaled_quadratic_coeffs);
|
||||
bn_poly_t scaled_cubic = poly_from_coeffs(3, scaled_cubic_coeffs);
|
||||
bn_poly_t scaled_quartic = poly_from_coeffs(4, scaled_quartic_coeffs);
|
||||
bn_complex_t roots[4];
|
||||
|
||||
if (!bn_poly_add(&linear, &linear, &quadratic) ||
|
||||
!poly_close(&linear, 2, aliased_sum_coeffs, 0.0)) {
|
||||
report_failure(test, "bn_poly_add did not support output aliasing a lower-degree input");
|
||||
failures++;
|
||||
}
|
||||
|
||||
linear = poly_from_coeffs(1, linear_coeffs);
|
||||
if (!bn_poly_sub(&linear, &linear, &quadratic) ||
|
||||
!poly_close(&linear, 2, aliased_difference_coeffs, 0.0)) {
|
||||
report_failure(test, "bn_poly_sub did not support output aliasing a lower-degree input");
|
||||
failures++;
|
||||
}
|
||||
|
||||
linear = poly_from_coeffs(1, linear_coeffs);
|
||||
if (!bn_poly_mul(&linear, &linear, &quadratic) ||
|
||||
!poly_close(&linear, 3, aliased_product_coeffs, 0.0)) {
|
||||
report_failure(test, "bn_poly_mul did not support output aliasing an input");
|
||||
failures++;
|
||||
}
|
||||
|
||||
if (bn_poly_mul(&rejected_product, °ree_six, &quadratic) ||
|
||||
!poly_close(&rejected_product, 0, untouched_product_coeffs, 0.0)) {
|
||||
report_failure(test, "bn_poly_mul modified its output after a degree-limit failure");
|
||||
failures++;
|
||||
}
|
||||
|
||||
linear = poly_from_coeffs(1, linear_coeffs);
|
||||
bn_poly_synthetic_division("ient, &remainder, ÷nd, &constant_divisor);
|
||||
if (!poly_close("ient, 2, constant_quotient_coeffs, 0.0) ||
|
||||
!poly_close(&remainder, 0, zero_coeffs, 0.0)) {
|
||||
report_failure(test, "bn_poly_synthetic_division failed for a constant divisor");
|
||||
failures++;
|
||||
}
|
||||
|
||||
bn_poly_synthetic_division("ient, &remainder, &linear, &higher_divisor);
|
||||
if (!poly_close("ient, 0, zero_coeffs, 0.0) ||
|
||||
!poly_close(&remainder, 1, linear_coeffs, 0.0)) {
|
||||
report_failure(test, "bn_poly_synthetic_division mishandled a higher-degree divisor");
|
||||
failures++;
|
||||
}
|
||||
|
||||
if (!bn_poly_quadratic_roots(roots, &scaled_quadratic) ||
|
||||
!has_real_root(roots, 2, 2.0, 1.0e-10) ||
|
||||
!has_real_root(roots, 2, 3.0, 1.0e-10)) {
|
||||
report_failure(test, "bn_poly_quadratic_roots rejected a scaled quadratic");
|
||||
failures++;
|
||||
}
|
||||
|
||||
if (!bn_poly_cubic_roots(roots, &scaled_cubic) ||
|
||||
!has_real_root(roots, 3, 1.0, 1.0e-10) ||
|
||||
!has_real_root(roots, 3, 2.0, 1.0e-10) ||
|
||||
!has_real_root(roots, 3, 3.0, 1.0e-10)) {
|
||||
report_failure(test, "bn_poly_cubic_roots rejected a scaled cubic");
|
||||
failures++;
|
||||
}
|
||||
|
||||
if (!bn_poly_quartic_roots(roots, &scaled_quartic) ||
|
||||
!has_real_root(roots, 4, -3.0, 1.0e-8) ||
|
||||
!has_real_root(roots, 4, -1.0, 1.0e-8) ||
|
||||
!has_real_root(roots, 4, 1.0, 1.0e-8) ||
|
||||
!has_real_root(roots, 4, 3.0, 1.0e-8)) {
|
||||
report_failure(test, "bn_poly_quartic_roots rejected a scaled quartic");
|
||||
failures++;
|
||||
}
|
||||
|
||||
return failures;
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_multipoly_ops(void)
|
||||
{
|
||||
int failures = 0;
|
||||
const char *test = "multipoly_ops";
|
||||
struct bn_multipoly *p1 = bn_multipoly_new(1, 1);
|
||||
struct bn_multipoly *p2 = bn_multipoly_new(3, 2);
|
||||
struct bn_multipoly *sum;
|
||||
struct bn_multipoly *product;
|
||||
|
||||
if (!p1 || !p2 || !bn_multipoly_set(p1, 1, 2, 3.0) ||
|
||||
!bn_multipoly_set(p2, 0, 0, 2.0) ||
|
||||
!bn_multipoly_set(p2, 2, 1, 5.0)) {
|
||||
report_failure(test, "could not construct bivariate polynomial operands");
|
||||
bn_multipoly_free(p1);
|
||||
bn_multipoly_free(p2);
|
||||
return failures + 1;
|
||||
}
|
||||
|
||||
sum = bn_multipoly_add(p1, p2);
|
||||
product = bn_multipoly_mul(p1, p2);
|
||||
if (!sum || sum->dgrs != 3 || sum->dgrt != 3 ||
|
||||
!scalar_close(sum->cf[0][0], 2.0, 0.0) ||
|
||||
!scalar_close(sum->cf[1][2], 3.0, 0.0) ||
|
||||
!scalar_close(sum->cf[2][1], 5.0, 0.0)) {
|
||||
report_failure(test, "bn_multipoly_add did not preserve differently sized operands");
|
||||
failures++;
|
||||
}
|
||||
|
||||
if (!product || product->dgrs != 4 || product->dgrt != 4 ||
|
||||
!scalar_close(product->cf[1][2], 6.0, 0.0) ||
|
||||
!scalar_close(product->cf[3][3], 15.0, 0.0)) {
|
||||
report_failure(test, "bn_multipoly_mul did not accumulate coefficient products");
|
||||
failures++;
|
||||
}
|
||||
|
||||
bn_multipoly_free(product);
|
||||
bn_multipoly_free(sum);
|
||||
bn_multipoly_free(p2);
|
||||
bn_multipoly_free(p1);
|
||||
return failures;
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_poly_legacy(void)
|
||||
{
|
||||
@@ -553,6 +700,8 @@ test_poly_roots(void)
|
||||
|
||||
static const struct bn_api_case poly_cases[] = {
|
||||
{"ops", test_poly_ops},
|
||||
{"edge", test_poly_edge_cases},
|
||||
{"multipoly", test_multipoly_ops},
|
||||
{"legacy", test_poly_legacy},
|
||||
{"roots", test_poly_roots},
|
||||
{NULL, NULL}
|
||||
|
||||
@@ -244,6 +244,12 @@ test_qmath_interp(void)
|
||||
failures++;
|
||||
}
|
||||
|
||||
quat_bisect(out, qid, qanti);
|
||||
if (!quat_is_unit_finite(out, 1.0e-12)) {
|
||||
report_failure(test, "quat_bisect antipodal branch failed to return a finite unit quaternion");
|
||||
failures++;
|
||||
}
|
||||
|
||||
quat_double(exact, qdouble_same_in, qdouble_same_in);
|
||||
if (!hvect_close(exact, qdouble_same_expected, 1.0e-3)) {
|
||||
report_failure(test, "quat_double legacy same-input case failed");
|
||||
@@ -326,6 +332,8 @@ test_qmath_logexp(void)
|
||||
quat_t v = {0.2, -0.1, 0.3, 0.0};
|
||||
quat_t q = HINIT_ZERO;
|
||||
quat_t out = HINIT_ZERO;
|
||||
quat_t qidentity = {0.0, 0.0, 0.0, 1.0};
|
||||
quat_t qzero = HINIT_ZERO;
|
||||
quat_t qin = {0.3, 0.4, 0.1, 0.85};
|
||||
int i;
|
||||
|
||||
@@ -347,6 +355,12 @@ test_qmath_logexp(void)
|
||||
failures++;
|
||||
}
|
||||
|
||||
quat_log(out, qidentity);
|
||||
if (!hvect_close(out, qzero, 0.0)) {
|
||||
report_failure(test, "quat_log did not map identity to the zero quaternion");
|
||||
failures++;
|
||||
}
|
||||
|
||||
for (i = 0; i < (int)(sizeof(exp_cases) / sizeof(exp_cases[0])); i++) {
|
||||
quat_exp(q, exp_cases[i].in);
|
||||
if (!hvect_close(q, exp_cases[i].expected, 1.0e-3)) {
|
||||
|
||||
@@ -250,22 +250,28 @@ brep_translate_scv(
|
||||
return -1;
|
||||
}
|
||||
|
||||
double *cv = NULL;
|
||||
if (nurbsSurface) {
|
||||
cv = nurbsSurface->CV(i, j);
|
||||
} else {
|
||||
if (!nurbsSurface)
|
||||
return -2;
|
||||
}
|
||||
|
||||
if (cv) {
|
||||
ON_3dPoint newPt;
|
||||
newPt.x = cv[X] + dx;
|
||||
newPt.y = cv[Y] + dy;
|
||||
newPt.z = cv[Z] + dz;
|
||||
nurbsSurface->SetCV(i, j, newPt);
|
||||
} else {
|
||||
ON_3dPoint point;
|
||||
if (!nurbsSurface->GetCV(i, j, point))
|
||||
return -3;
|
||||
|
||||
point.x += dx;
|
||||
point.y += dy;
|
||||
point.z += dz;
|
||||
|
||||
bool updated;
|
||||
if (nurbsSurface->IsRational()) {
|
||||
const double weight = nurbsSurface->Weight(i, j);
|
||||
updated = nurbsSurface->SetCV(i, j,
|
||||
ON_4dPoint(point.x * weight, point.y * weight,
|
||||
point.z * weight, weight));
|
||||
} else {
|
||||
updated = nurbsSurface->SetCV(i, j, point);
|
||||
}
|
||||
if (!updated)
|
||||
return -3;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -234,7 +234,7 @@ set(
|
||||
mime.cmake
|
||||
parallel.h
|
||||
parallel_cpp11thread.cpp
|
||||
process.h
|
||||
process_private.h
|
||||
sha1.h
|
||||
struetype.h
|
||||
vfont.h
|
||||
|
||||
+31
-17
@@ -388,31 +388,45 @@ mem_sysctl(int type, size_t *memsz)
|
||||
return -2;
|
||||
|
||||
#if defined(__FreeBSD__) && defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
|
||||
static const char *const page_size_name = "hw.pagesize";
|
||||
static const char *const total_memory_name = "hw.physmem";
|
||||
static const char *const free_pages_name = "vm.stats.vm.v_free_count";
|
||||
static const char *const available_page_names[] = {
|
||||
"vm.stats.vm.v_free_count",
|
||||
"vm.stats.vm.v_inactive_count",
|
||||
"vm.stats.vm.v_cache_count"
|
||||
};
|
||||
|
||||
uint64_t page_size = 0;
|
||||
size_t value_size = sizeof(page_size);
|
||||
if (sysctlbyname(page_size_name, &page_size, &value_size, NULL, 0) != 0 ||
|
||||
page_size == 0)
|
||||
return -1;
|
||||
if (type == BU_MEM_PAGE_SIZE)
|
||||
return mem_size_from_uint64(page_size, memsz);
|
||||
return mem_page_size(memsz);
|
||||
|
||||
uint64_t memory = 0;
|
||||
value_size = sizeof(memory);
|
||||
const char *memory_name = total_memory_name;
|
||||
if (type == BU_MEM_AVAIL) {
|
||||
memory_name = free_pages_name;
|
||||
if (sysctlbyname(memory_name, &memory, &value_size, NULL, 0) != 0 ||
|
||||
memory > UINT64_MAX / page_size)
|
||||
return -1;
|
||||
memory *= page_size;
|
||||
} else if (sysctlbyname(memory_name, &memory, &value_size, NULL, 0) != 0) {
|
||||
return -1;
|
||||
/* FreeBSD's free queue omits clean inactive and cache pages that the VM
|
||||
* can reclaim without paging another process. Counting only v_free_count
|
||||
* makes an otherwise idle system appear memory-starved and needlessly
|
||||
* disables memory-aware parallel work. */
|
||||
for (size_t i = 0; i < sizeof(available_page_names) / sizeof(available_page_names[0]); i++) {
|
||||
uint32_t pages = 0;
|
||||
size_t value_size = sizeof(pages);
|
||||
if (sysctlbyname(available_page_names[i], &pages, &value_size,
|
||||
NULL, 0) != 0 || value_size != sizeof(pages)) {
|
||||
/* v_free_count is required. Cache accounting is absent on some
|
||||
* supported FreeBSD versions, so supplementary queues are optional. */
|
||||
if (i == 0)
|
||||
return -1;
|
||||
continue;
|
||||
}
|
||||
if ((uint64_t)pages > UINT64_MAX - memory)
|
||||
return -1;
|
||||
memory += (uint64_t)pages;
|
||||
}
|
||||
return mem_pages_to_bytes(memory, memsz);
|
||||
}
|
||||
|
||||
size_t value_size = sizeof(memory);
|
||||
if (sysctlbyname(total_memory_name, &memory, &value_size, NULL, 0) != 0 ||
|
||||
(value_size != sizeof(uint32_t) && value_size != sizeof(uint64_t)))
|
||||
return -1;
|
||||
|
||||
return mem_size_from_uint64(memory, memsz);
|
||||
#endif
|
||||
return 1;
|
||||
|
||||
+47
-1
@@ -24,6 +24,9 @@
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
#include <string.h>
|
||||
#if !defined(_WIN32) || defined(__CYGWIN__)
|
||||
# include <stdatomic.h>
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_SYS_TYPES_H
|
||||
# include <sys/types.h>
|
||||
@@ -130,6 +133,36 @@ void parallel_cpp11thread(void (*func)(int, void *), size_t ncpu, void *arg);
|
||||
|
||||
int BU_SEM_THREAD = BU_SEM_ID_THREAD;
|
||||
|
||||
#if defined(_WIN32) && !defined(__CYGWIN__)
|
||||
static LONG bu_cpu_limit = 0;
|
||||
|
||||
static size_t
|
||||
cpu_limit_get(void)
|
||||
{
|
||||
return (size_t)InterlockedCompareExchange(&bu_cpu_limit, 0, 0);
|
||||
}
|
||||
|
||||
static void
|
||||
cpu_limit_set(size_t ncpu)
|
||||
{
|
||||
(void)InterlockedExchange(&bu_cpu_limit, (LONG)ncpu);
|
||||
}
|
||||
#else
|
||||
static atomic_size_t bu_cpu_limit = ATOMIC_VAR_INIT(0);
|
||||
|
||||
static size_t
|
||||
cpu_limit_get(void)
|
||||
{
|
||||
return atomic_load_explicit(&bu_cpu_limit, memory_order_acquire);
|
||||
}
|
||||
|
||||
static void
|
||||
cpu_limit_set(size_t ncpu)
|
||||
{
|
||||
atomic_store_explicit(&bu_cpu_limit, ncpu, memory_order_release);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
typedef enum {
|
||||
PARALLEL_GET = 0,
|
||||
@@ -355,7 +388,9 @@ bu_avail_cpus(void)
|
||||
}
|
||||
|
||||
if (LIKELY(ncpu > 0)) {
|
||||
return ncpu;
|
||||
size_t cpu_limit = cpu_limit_get();
|
||||
return (cpu_limit && cpu_limit < (size_t)ncpu) ? cpu_limit :
|
||||
(size_t)ncpu;
|
||||
}
|
||||
|
||||
/* non-PARALLEL */
|
||||
@@ -363,6 +398,13 @@ bu_avail_cpus(void)
|
||||
}
|
||||
|
||||
|
||||
void
|
||||
bu_avail_cpus_set(size_t ncpu)
|
||||
{
|
||||
cpu_limit_set((ncpu > MAX_PSW) ? MAX_PSW : ncpu);
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
|
||||
|
||||
@@ -538,6 +580,10 @@ parallel_interface_arg_stub(struct thread_data *user_thread_data)
|
||||
void
|
||||
bu_parallel(void (*func)(int, void *), size_t ncpu, void *arg)
|
||||
{
|
||||
size_t cpu_limit = cpu_limit_get();
|
||||
if (ncpu && cpu_limit && ncpu > cpu_limit)
|
||||
ncpu = cpu_limit;
|
||||
|
||||
#ifndef PARALLEL
|
||||
|
||||
if (!func)
|
||||
|
||||
+9
-3
@@ -49,7 +49,7 @@
|
||||
#include "bu/str.h"
|
||||
#include "bu/datetime.h"
|
||||
#include "bu/vls.h"
|
||||
#include "./process.h"
|
||||
#include "./process_private.h"
|
||||
|
||||
#ifndef HAVE_KILL
|
||||
# include <TlHelp32.h>
|
||||
@@ -1077,11 +1077,17 @@ bu_process_poll(struct bu_process *pinfo, int *exit_status)
|
||||
}
|
||||
|
||||
#if defined(_WIN32)
|
||||
/* An exit code can be available before process teardown releases
|
||||
* inherited files and pipes. Only report completion once signaled. */
|
||||
DWORD wait_result = WaitForSingleObject(pinfo->hProcess, 0);
|
||||
if (wait_result == WAIT_TIMEOUT)
|
||||
return 0;
|
||||
if (wait_result != WAIT_OBJECT_0)
|
||||
return -1;
|
||||
|
||||
DWORD status = 0;
|
||||
if (!GetExitCodeProcess(pinfo->hProcess, &status))
|
||||
return -1;
|
||||
if (status == STILL_ACTIVE)
|
||||
return 0;
|
||||
|
||||
pinfo->exit_status = (status == BU_MSVC_ABORT_EXIT) ?
|
||||
ERROR_PROCESS_ABORTED : (int)status;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* P R O C E S S . H
|
||||
/* P R O C E S S _ P R I V A T E . H
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2013-2026 United States Government as represented by
|
||||
@@ -20,8 +20,8 @@
|
||||
|
||||
/* Private libbu process related definitions shared between multiple files */
|
||||
|
||||
#ifndef LIBBU_PROCESS_H
|
||||
#define LIBBU_PROCESS_H
|
||||
#ifndef LIBBU_PROCESS_PRIVATE_H
|
||||
#define LIBBU_PROCESS_PRIVATE_H
|
||||
|
||||
/* Apparently the termination code on Windows is arbitrary and somewhat
|
||||
* ill-defined - see https://bugs.python.org/issue31863 for more info. Try our
|
||||
@@ -29,7 +29,7 @@
|
||||
* abort identification. */
|
||||
#define BU_MSVC_ABORT_EXIT 97101 /* ascii - a == 97 && e == 101 */
|
||||
|
||||
#endif /* LIBBU_PROCESS_H */
|
||||
#endif /* LIBBU_PROCESS_PRIVATE_H */
|
||||
|
||||
/*
|
||||
* Local Variables:
|
||||
+48
-43
@@ -22,59 +22,54 @@
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "vmath.h"
|
||||
|
||||
#include "bu/log.h"
|
||||
#include "bu/malloc.h"
|
||||
#include "bu/str.h"
|
||||
|
||||
int
|
||||
bu_scan_fastf_t(int *c, const char *src, const char *delim, size_t n, ...)
|
||||
{
|
||||
va_list ap;
|
||||
int offset = 0;
|
||||
int current_n = 0, part_n = 0;
|
||||
int len, delim_len;
|
||||
int current_n = 0;
|
||||
size_t i;
|
||||
char *delim_fmt;
|
||||
|
||||
if (UNLIKELY(!delim || n < 1)) {
|
||||
if (c) {
|
||||
*c = 0;
|
||||
}
|
||||
|
||||
|
||||
if (UNLIKELY(!delim || !*delim || n < 1)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
va_start(ap, n);
|
||||
|
||||
/* TODO: we should just simply skip all occurrences of delim chars
|
||||
* after reading a fastf_t, avoid dynamic memory allocation and
|
||||
* avoid scanf/sscanf (we don't need to scan the delimiter, just
|
||||
* skip chars in a loop until none are found.
|
||||
*/
|
||||
|
||||
delim_len = (int)strlen(delim);
|
||||
/* + 3 here to make room for the two characters '%' and 'n' as
|
||||
* well as the terminating '\0'
|
||||
*/
|
||||
delim_fmt = (char *)bu_malloc(delim_len + 3, "bu_scan_fastf_t");
|
||||
bu_strlcpy(delim_fmt, delim, delim_len + 1);
|
||||
bu_strlcat(delim_fmt, "%n", delim_len + 3);
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
/* Read in the next fastf_t */
|
||||
double scan = 0;
|
||||
double scan = 0.0;
|
||||
fastf_t *arg;
|
||||
|
||||
if (src)
|
||||
part_n = sscanf(src + offset, "%lf%n", &scan, &len);
|
||||
else
|
||||
part_n = scanf("%lf%n", &scan, &len);
|
||||
if (src) {
|
||||
const char *input = src + offset;
|
||||
char *end;
|
||||
|
||||
current_n += part_n;
|
||||
offset += len;
|
||||
if (part_n != 1) {
|
||||
break;
|
||||
scan = strtod(input, &end);
|
||||
if (end == input) {
|
||||
break;
|
||||
}
|
||||
offset += (int)(end - input);
|
||||
} else {
|
||||
int len = 0;
|
||||
|
||||
if (scanf("%lf%n", &scan, &len) != 1) {
|
||||
break;
|
||||
}
|
||||
offset += len;
|
||||
}
|
||||
|
||||
current_n++;
|
||||
arg = va_arg(ap, fastf_t *);
|
||||
if (arg) {
|
||||
*arg = scan;
|
||||
@@ -84,25 +79,35 @@ bu_scan_fastf_t(int *c, const char *src, const char *delim, size_t n, ...)
|
||||
break;
|
||||
}
|
||||
|
||||
/* Make sure that a delimiter is present */
|
||||
if (src)
|
||||
part_n = sscanf(src + offset, delim_fmt, &len);
|
||||
else
|
||||
part_n = scanf(delim_fmt, &len);
|
||||
if (src) {
|
||||
const char *input = src + offset;
|
||||
|
||||
offset += len;
|
||||
while (*input && strchr(delim, *input)) {
|
||||
input++;
|
||||
}
|
||||
if (input == src + offset) {
|
||||
break;
|
||||
}
|
||||
offset += (int)(input - (src + offset));
|
||||
} else {
|
||||
int character;
|
||||
int delimiter_count = 0;
|
||||
|
||||
/* as delim_fmt should only have a %n and that doesn't get
|
||||
* counted in the scanf return, make sure the return is 0 as
|
||||
* no values should be scanned.
|
||||
*/
|
||||
if (part_n != 0 || len != delim_len) {
|
||||
break;
|
||||
while ((character = fgetc(stdin)) != EOF) {
|
||||
if (!strchr(delim, character)) {
|
||||
(void)ungetc(character, stdin);
|
||||
break;
|
||||
}
|
||||
delimiter_count++;
|
||||
offset++;
|
||||
}
|
||||
if (!delimiter_count) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
va_end(ap);
|
||||
bu_free(delim_fmt, "bu_scan_fastf_t");
|
||||
|
||||
if (c) {
|
||||
*c = offset;
|
||||
|
||||
+10
-1
@@ -210,7 +210,7 @@ mkstemp(char *file_template)
|
||||
for (i=(int)start; i>=(int)end; i--) {
|
||||
file_template[i] = replace[(int)(replacelen * ((double)rand() / (double)RAND_MAX))];
|
||||
}
|
||||
fd = open(file_template, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
|
||||
fd = open(file_template, O_CREAT | O_EXCL | O_TRUNC | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
|
||||
} while ((fd == -1) && (counter++ < 1000));
|
||||
|
||||
return fd;
|
||||
@@ -285,6 +285,15 @@ bu_temp_file(char *filepath, size_t len)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Ensure the descriptor is binary before associating it with a stream. */
|
||||
if (UNLIKELY(setmode(fd, O_BINARY) == -1)) {
|
||||
perror("setmode");
|
||||
close(fd);
|
||||
bu_file_delete(tempfile);
|
||||
bu_log(_TF_FAIL);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (filepath) {
|
||||
if (UNLIKELY(len < strlen(tempfile))) {
|
||||
bu_log("INTERNAL ERROR: bu_temp_file filepath buffer size is insufficient (%zu < %zu)\n", len, strlen(tempfile));
|
||||
|
||||
@@ -42,6 +42,7 @@ set(
|
||||
test_process.c
|
||||
test_ptbl.c
|
||||
test_realpath.c
|
||||
test_scan.c
|
||||
test_semaphore.c
|
||||
test_snooze.c
|
||||
test_sort.c
|
||||
@@ -127,6 +128,7 @@ brlcad_add_test(NAME bu_list_empty COMMAND bu_test test_list 0)
|
||||
brlcad_add_test(NAME bu_list_single COMMAND bu_test test_list 1)
|
||||
brlcad_add_test(NAME bu_list_many COMMAND bu_test test_list 16)
|
||||
brlcad_add_test(NAME bu_sscanf_compare COMMAND bu_sscanf)
|
||||
brlcad_add_test(NAME bu_scan_fastf_t COMMAND bu_test test_scan)
|
||||
brlcad_add_test(NAME bu_gethostname_lookup COMMAND bu_gethostname)
|
||||
|
||||
|
||||
@@ -198,6 +200,7 @@ brlcad_add_test(NAME bu_file_mime_png COMMAND bu_test test_file_mime png 3 BU_
|
||||
# bu_temp_filename testing #
|
||||
####################################
|
||||
brlcad_add_test(NAME bu_temp_filename COMMAND bu_test test_temp_filename "single")
|
||||
brlcad_add_test(NAME bu_temp_binary COMMAND bu_test test_temp_filename "binary")
|
||||
#BRLCAD_ADD_TEST(NAME bu_temp_filename COMMAND bu_test test_temp_filename "parallel")
|
||||
|
||||
#
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
|
||||
#include "bio.h"
|
||||
#include "bresource.h"
|
||||
#if defined(__APPLE__) && defined(HAVE_SYS_SYSCTL_H)
|
||||
#if (defined(__APPLE__) || defined(__FreeBSD__)) && defined(HAVE_SYS_SYSCTL_H)
|
||||
# include <sys/sysctl.h>
|
||||
#endif
|
||||
|
||||
@@ -214,8 +214,12 @@ mem_test_failure(const char *query, ssize_t result, const size_t *output,
|
||||
|
||||
|
||||
static int
|
||||
platform_mem_tests(ssize_t all_mem)
|
||||
platform_mem_tests(ssize_t all_mem, ssize_t avail_mem, ssize_t page_mem)
|
||||
{
|
||||
(void)all_mem;
|
||||
(void)avail_mem;
|
||||
(void)page_mem;
|
||||
|
||||
#if defined(__APPLE__) && defined(HAVE_SYS_SYSCTL_H)
|
||||
uint64_t native_total = 0;
|
||||
size_t value_size = sizeof(native_total);
|
||||
@@ -230,8 +234,51 @@ platform_mem_tests(ssize_t all_mem)
|
||||
"reported %llu\n", all_mem, (unsigned long long)native_total);
|
||||
return -2;
|
||||
}
|
||||
#else
|
||||
(void)all_mem;
|
||||
#elif defined(__FreeBSD__) && defined(HAVE_SYS_SYSCTL_H)
|
||||
uint64_t native_total = 0;
|
||||
size_t value_size = sizeof(native_total);
|
||||
if (sysctlbyname("hw.physmem", &native_total, &value_size, NULL, 0) != 0 ||
|
||||
(value_size != sizeof(uint32_t) && value_size != sizeof(uint64_t))) {
|
||||
bu_log("bu_mem platform test: unable to query hw.physmem\n");
|
||||
return -1;
|
||||
}
|
||||
if (native_total != (uint64_t)all_mem) {
|
||||
bu_log("bu_mem platform test: BU_MEM_ALL returned %zd; hw.physmem "
|
||||
"reported %llu\n", all_mem, (unsigned long long)native_total);
|
||||
return -2;
|
||||
}
|
||||
|
||||
uint64_t reclaimable_pages = 0;
|
||||
const char *const page_names[] = {
|
||||
"vm.stats.vm.v_free_count",
|
||||
"vm.stats.vm.v_inactive_count",
|
||||
"vm.stats.vm.v_cache_count"
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(page_names) / sizeof(page_names[0]); i++) {
|
||||
uint32_t pages = 0;
|
||||
value_size = sizeof(pages);
|
||||
if (sysctlbyname(page_names[i], &pages, &value_size, NULL, 0) != 0 ||
|
||||
value_size != sizeof(pages)) {
|
||||
if (i == 0)
|
||||
return -3;
|
||||
continue;
|
||||
}
|
||||
reclaimable_pages += pages;
|
||||
}
|
||||
/* VM counters may change between the bu_mem and direct sysctl queries.
|
||||
* A one-percent allowance is ample for that race while still detecting
|
||||
* the former free-pages-only implementation. */
|
||||
uint64_t native_available = reclaimable_pages * (uint64_t)page_mem;
|
||||
uint64_t allowance = native_total / 100u;
|
||||
uint64_t available_difference = ((uint64_t)avail_mem > native_available) ?
|
||||
(uint64_t)avail_mem - native_available :
|
||||
native_available - (uint64_t)avail_mem;
|
||||
if (available_difference > allowance) {
|
||||
bu_log("bu_mem platform test: BU_MEM_AVAIL returned %zd; FreeBSD "
|
||||
"reclaimable queues reported %llu\n", avail_mem,
|
||||
(unsigned long long)native_available);
|
||||
return -4;
|
||||
}
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
@@ -445,7 +492,7 @@ main(int ac, char *av[])
|
||||
if (avail_mem > all_mem)
|
||||
return mem_test_failure("BU_MEM_AVAIL exceeds BU_MEM_ALL", avail_mem,
|
||||
NULL, -5);
|
||||
if (platform_mem_tests(all_mem) != 0)
|
||||
if (platform_mem_tests(all_mem, avail_mem, page_mem) != 0)
|
||||
return -6;
|
||||
ssize_t process_mem = bu_mem(BU_MEM_PROCESS_AVAIL, NULL);
|
||||
ssize_t resident_mem = bu_mem(BU_MEM_PROCESS_RESIDENT, NULL);
|
||||
|
||||
@@ -121,6 +121,30 @@ main(int argc, char *argv[])
|
||||
if (bu_getprogname()[0] == '\0')
|
||||
bu_setprogname(argv[0]);
|
||||
|
||||
{
|
||||
size_t detected_cpus = bu_avail_cpus();
|
||||
size_t requested_cpus = (detected_cpus > MAX_PSW) ? MAX_PSW :
|
||||
detected_cpus;
|
||||
struct parallel_data limit_data = {1, NULL};
|
||||
bu_avail_cpus_set(1);
|
||||
if (bu_avail_cpus() != 1) {
|
||||
bu_log("bu_avail_cpus process limit [FAIL]\n");
|
||||
return 1;
|
||||
}
|
||||
memset(counter, 0, sizeof(counter));
|
||||
bu_parallel(callback, requested_cpus, &limit_data);
|
||||
if (tally(MAX_PSW) != 1) {
|
||||
bu_log("bu_parallel process limit [FAIL]\n");
|
||||
return 1;
|
||||
}
|
||||
bu_avail_cpus_set(0);
|
||||
if (bu_avail_cpus() != detected_cpus) {
|
||||
bu_log("bu_avail_cpus process limit reset [FAIL]\n");
|
||||
return 1;
|
||||
}
|
||||
bu_log("bu_avail_cpus and bu_parallel process limit [PASS]\n");
|
||||
}
|
||||
|
||||
while ((c = bu_getopt(argc, argv, "P:!:")) != -1) {
|
||||
switch (c) {
|
||||
case 'P':
|
||||
@@ -137,8 +161,9 @@ main(int argc, char *argv[])
|
||||
}
|
||||
|
||||
/* test calling without a hook function */
|
||||
memset(counter, 0, sizeof(counter));
|
||||
bu_parallel(NULL, ncpu, NULL);
|
||||
if (tally(ncpu) != 0) {
|
||||
if (tally(MAX_PSW) != 0) {
|
||||
bu_log("bu_parallel zero callback [FAIL]\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
/* T E S T _ S C A N . C
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this file; see the file named COPYING for more
|
||||
* information.
|
||||
*/
|
||||
/** @file test_scan.c
|
||||
*
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "test_api.h"
|
||||
|
||||
|
||||
static int
|
||||
scan_fastf_repeated_delimiters(void)
|
||||
{
|
||||
const char *input = "0.0,,0.0,1.0";
|
||||
fastf_t first = -1.0;
|
||||
fastf_t second = -1.0;
|
||||
fastf_t third = -1.0;
|
||||
int chars = -1;
|
||||
|
||||
return bu_scan_fastf_t(&chars, input, ",", 3,
|
||||
&first, &second, &third) == 3
|
||||
&& chars == (int)strlen(input)
|
||||
&& ZERO(first)
|
||||
&& ZERO(second)
|
||||
&& EQUAL(third, 1.0);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
scan_fastf_mixed_delimiters(void)
|
||||
{
|
||||
const char *input = "1, ;2,, 3";
|
||||
fastf_t first = -1.0;
|
||||
fastf_t second = -1.0;
|
||||
fastf_t third = -1.0;
|
||||
int chars = -1;
|
||||
|
||||
return bu_scan_fastf_t(&chars, input, ",; ", 3,
|
||||
&first, &second, &third) == 3
|
||||
&& chars == (int)strlen(input)
|
||||
&& EQUAL(first, 1.0)
|
||||
&& EQUAL(second, 2.0)
|
||||
&& EQUAL(third, 3.0);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
scan_fastf_percent_delimiter(void)
|
||||
{
|
||||
const char *input = "1%2%%3";
|
||||
fastf_t first = -1.0;
|
||||
fastf_t second = -1.0;
|
||||
fastf_t third = -1.0;
|
||||
int chars = -1;
|
||||
|
||||
return bu_scan_fastf_t(&chars, input, "%", 3,
|
||||
&first, &second, &third) == 3
|
||||
&& chars == (int)strlen(input)
|
||||
&& EQUAL(first, 1.0)
|
||||
&& EQUAL(second, 2.0)
|
||||
&& EQUAL(third, 3.0);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
scan_fastf_reports_consumed_prefix(void)
|
||||
{
|
||||
fastf_t first = -1.0;
|
||||
fastf_t second = -1.0;
|
||||
int chars = -1;
|
||||
|
||||
return bu_scan_fastf_t(&chars, "1,not-a-number", ",", 2,
|
||||
&first, &second) == 1
|
||||
&& chars == 2
|
||||
&& EQUAL(first, 1.0)
|
||||
&& EQUAL(second, -1.0);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
scan_fastf_accepts_null_destinations(void)
|
||||
{
|
||||
fastf_t second = -1.0;
|
||||
int chars = -1;
|
||||
|
||||
return bu_scan_fastf_t(&chars, "1,2", ",", 2,
|
||||
NULL, &second) == 2
|
||||
&& chars == 3
|
||||
&& EQUAL(second, 2.0);
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
scan_fastf_rejects_invalid_configuration(void)
|
||||
{
|
||||
fastf_t value = -1.0;
|
||||
int chars = -1;
|
||||
|
||||
if (bu_scan_fastf_t(&chars, "1", NULL, 1, &value) != 0
|
||||
|| chars != 0 || !EQUAL(value, -1.0))
|
||||
return 0;
|
||||
|
||||
chars = -1;
|
||||
if (bu_scan_fastf_t(&chars, "1", "", 1, &value) != 0
|
||||
|| chars != 0 || !EQUAL(value, -1.0))
|
||||
return 0;
|
||||
|
||||
chars = -1;
|
||||
return bu_scan_fastf_t(&chars, "1", ",", 0) == 0 && chars == 0;
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
test_scan(void)
|
||||
{
|
||||
int errors = 0;
|
||||
|
||||
TEST_API_CHECK(scan_fastf_repeated_delimiters(),
|
||||
"bu_scan_fastf_t should skip repeated delimiters");
|
||||
TEST_API_CHECK(scan_fastf_mixed_delimiters(),
|
||||
"bu_scan_fastf_t should treat delim as a character set");
|
||||
TEST_API_CHECK(scan_fastf_percent_delimiter(),
|
||||
"bu_scan_fastf_t should treat percent as delimiter data");
|
||||
TEST_API_CHECK(scan_fastf_reports_consumed_prefix(),
|
||||
"bu_scan_fastf_t should report the deterministic consumed prefix");
|
||||
TEST_API_CHECK(scan_fastf_accepts_null_destinations(),
|
||||
"bu_scan_fastf_t should accept NULL value destinations");
|
||||
TEST_API_CHECK(scan_fastf_rejects_invalid_configuration(),
|
||||
"bu_scan_fastf_t should reset c for invalid configuration");
|
||||
|
||||
return errors ? BRLCAD_ERROR : BRLCAD_OK;
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
main(int UNUSED(argc), char *argv[])
|
||||
{
|
||||
if (bu_getprogname()[0] == '\0') {
|
||||
bu_setprogname(argv[0]);
|
||||
}
|
||||
|
||||
return test_scan();
|
||||
}
|
||||
|
||||
/*
|
||||
* Local Variables:
|
||||
* tab-width: 8
|
||||
* mode: C
|
||||
* indent-tabs-mode: t
|
||||
* c-file-style: "stroustrup"
|
||||
* End:
|
||||
* ex: shiftwidth=4 tabstop=8 cino=N-s
|
||||
*/
|
||||
@@ -35,6 +35,57 @@
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "bio.h"
|
||||
#include "bu/app.h"
|
||||
#include "bu/file.h"
|
||||
|
||||
|
||||
static int
|
||||
temp_file_binary(void)
|
||||
{
|
||||
/* LF and DOS EOF expose text-mode translation on Windows. */
|
||||
const unsigned char expected[] = {0x00, 0x0a, 0x1a, 0x0d, 0xff};
|
||||
unsigned char actual[sizeof(expected) + 1] = {0};
|
||||
char path[MAXPATHLEN] = {0};
|
||||
size_t count;
|
||||
FILE *fp = bu_temp_file(path, sizeof(path));
|
||||
|
||||
if (!fp) {
|
||||
bu_log("temp_filename failure: cannot create temporary file\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
count = fwrite(expected, 1, sizeof(expected), fp);
|
||||
if (fclose(fp) != 0 || count != sizeof(expected)) {
|
||||
bu_log("temp_filename failure: cannot write binary data\n");
|
||||
bu_file_delete(path);
|
||||
return 1;
|
||||
}
|
||||
|
||||
fp = fopen(path, "rb");
|
||||
if (!fp) {
|
||||
bu_log("temp_filename failure: cannot reopen temporary file\n");
|
||||
bu_file_delete(path);
|
||||
return 1;
|
||||
}
|
||||
|
||||
count = fread(actual, 1, sizeof(actual), fp);
|
||||
if (fclose(fp) != 0 || count != sizeof(expected) || memcmp(actual, expected, sizeof(expected))) {
|
||||
bu_log("temp_filename failure: binary data changed (%zu bytes read, expected %zu)\n", count, sizeof(expected));
|
||||
bu_file_delete(path);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!bu_file_delete(path)) {
|
||||
bu_log("temp_filename failure: cannot delete temporary file\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
temp_filename_thread(int cpu, void* ptr)
|
||||
@@ -96,6 +147,9 @@ main(int argc, char *argv[])
|
||||
if (strlen(under_size) != 4) /* buffer size -1 */
|
||||
bu_exit(EXIT_FAILURE, "temp_filename failure: expected size [%d], got [%ld]]\n", 4, strlen(under_size));
|
||||
|
||||
} else if (!bu_strcmp(curr, "binary")) {
|
||||
if (temp_file_binary())
|
||||
return EXIT_FAILURE;
|
||||
} else if (!bu_strcmp(curr, "parallel")) {
|
||||
// test parallel / threaded -
|
||||
uint8_t threads = bu_avail_cpus();
|
||||
|
||||
+15
-10
@@ -26,11 +26,10 @@
|
||||
#include "bu/app.h"
|
||||
#include "bu/malloc.h"
|
||||
#include "bu/vfont.h"
|
||||
#include "bu/vls.h"
|
||||
|
||||
#define FONTDIR2 "/usr/lib/vfont"
|
||||
#define DEFAULT_FONT "nonie.r.12"
|
||||
#define FONTNAMESZ 128
|
||||
|
||||
#include "./vfont.h"
|
||||
|
||||
|
||||
@@ -127,7 +126,7 @@ vfont_get(char *font)
|
||||
register struct vfont *vfp = VFONT_NULL;
|
||||
register FILE *fp = NULL;
|
||||
register int i;
|
||||
char fname[FONTNAMESZ] = {'\0'};
|
||||
struct bu_vls fname = BU_VLS_INIT_ZERO;
|
||||
unsigned char header[2*5]; /* 5 16-bit vax shorts */
|
||||
unsigned char dispatch[10*256]; /* 256 10-byte structs */
|
||||
uint16_t magic;
|
||||
@@ -135,21 +134,24 @@ vfont_get(char *font)
|
||||
const char *const_font;
|
||||
|
||||
const_font = (font == NULL) ? DEFAULT_FONT : (const char *)font;
|
||||
bu_vls_strcpy(&fname, const_font);
|
||||
|
||||
/* Open the file and read in the header information. */
|
||||
if ((fp = fopen(const_font, "rb")) == NULL) {
|
||||
snprintf(fname, FONTNAMESZ, "%s/%s", bu_dir(NULL, 0, BU_DIR_DATA, "vfont", NULL), const_font);
|
||||
if ((fp = fopen(fname, "rb")) == NULL) {
|
||||
snprintf(fname, FONTNAMESZ, "%s/%s", FONTDIR2, const_font);
|
||||
if ((fp = fopen(fname, "rb")) == NULL) {
|
||||
bu_vls_sprintf(&fname, "%s/%s", bu_dir(NULL, 0, BU_DIR_DATA, "vfont", NULL), const_font);
|
||||
if ((fp = fopen(bu_vls_addr(&fname), "rb")) == NULL) {
|
||||
bu_vls_sprintf(&fname, "%s/%s", FONTDIR2, const_font);
|
||||
if ((fp = fopen(bu_vls_addr(&fname), "rb")) == NULL) {
|
||||
bu_vls_free(&fname);
|
||||
return VFONT_NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fread((char *)header, sizeof(header), 1, fp) != 1 ||
|
||||
fread((char *)dispatch, sizeof(dispatch), 1, fp) != 1) {
|
||||
fprintf(stderr, "vfont_get(%s): header read error\n", fname);
|
||||
fprintf(stderr, "vfont_get(%s): header read error\n", bu_vls_addr(&fname));
|
||||
fclose(fp);
|
||||
bu_vls_free(&fname);
|
||||
return VFONT_NULL;
|
||||
}
|
||||
magic = _vax_gshort(&header[0*2]) & 0xFFFF;
|
||||
@@ -157,8 +159,9 @@ vfont_get(char *font)
|
||||
|
||||
if (UNLIKELY(magic != 0436)) {
|
||||
fprintf(stderr, "vfont_get(%s): bad magic number 0%o\n",
|
||||
fname, magic);
|
||||
bu_vls_addr(&fname), magic);
|
||||
fclose(fp);
|
||||
bu_vls_free(&fname);
|
||||
return VFONT_NULL;
|
||||
}
|
||||
|
||||
@@ -166,10 +169,11 @@ vfont_get(char *font)
|
||||
BU_ALLOC(vfp, struct vfont);
|
||||
vfp->vf_bits = (char *)bu_malloc((size_t)size, "vfont bits");
|
||||
if (fread(vfp->vf_bits, (size_t)size, 1, fp) != 1) {
|
||||
fprintf(stderr, "vfont_get(%s): bitmap read error\n", fname);
|
||||
fprintf(stderr, "vfont_get(%s): bitmap read error\n", bu_vls_addr(&fname));
|
||||
fclose(fp);
|
||||
bu_free(vfp->vf_bits, "vfont bits");
|
||||
bu_free((char *)vfp, "vfont");
|
||||
bu_vls_free(&fname);
|
||||
return VFONT_NULL;
|
||||
}
|
||||
|
||||
@@ -194,6 +198,7 @@ vfont_get(char *font)
|
||||
vdp->vd_width = _vax_gshort(&cp[8]);
|
||||
}
|
||||
fclose(fp);
|
||||
bu_vls_free(&fname);
|
||||
return vfp;
|
||||
}
|
||||
|
||||
|
||||
@@ -188,8 +188,7 @@ test_uncertain()
|
||||
require(result.shells.empty() || (result.shells.front().orientation == ShellOrientation::Indeterminate &&
|
||||
!result.shells.front().corrected), "invalid parameter-loop senses caused an incorrect face repair");
|
||||
auto flat = box();
|
||||
ON_Xform flatten;
|
||||
flatten.DiagonalTransformation(1.0);
|
||||
ON_Xform flatten = ON_Xform::DiagonalTransformation(1.0);
|
||||
flatten[2][2] = 1.0e-13;
|
||||
require(flat->Transform(flatten), "could not construct thin shell");
|
||||
result = repair_brep_orientation(*flat);
|
||||
|
||||
+26
-13
@@ -463,6 +463,9 @@ cmd_translate::exec(struct ged *gedp, void *u_data, int argc, const char **argv)
|
||||
return _edit_xform_apply(ctx,
|
||||
[&](struct rt_edit *s) -> int
|
||||
{
|
||||
vect_t to_vec_base;
|
||||
VSCALE(to_vec_base, to_vec, s->local2base);
|
||||
|
||||
/* Resolve FROM position (k) */
|
||||
point_t from_kp = VINIT_ZERO;
|
||||
bool have_from = false;
|
||||
@@ -514,7 +517,7 @@ cmd_translate::exec(struct ged *gedp, void *u_data, int argc, const char **argv)
|
||||
}
|
||||
} else if (do_abs) {
|
||||
/* Absolute translate: to_vec IS the target position */
|
||||
VMOVE(target, to_vec);
|
||||
VMOVE(target, to_vec_base);
|
||||
/* Keep unspecified axes at the current keypoint */
|
||||
if (n_coord_flags > 0) {
|
||||
if (!x_only) target[X] = s->e_keypoint[X];
|
||||
@@ -532,17 +535,16 @@ cmd_translate::exec(struct ged *gedp, void *u_data, int argc, const char **argv)
|
||||
/* Relative translate (default): to_vec is a delta */
|
||||
vect_t delta = VINIT_ZERO;
|
||||
if (n_coord_flags > 0) {
|
||||
if (x_only) delta[X] = to_vec[X];
|
||||
if (y_only) delta[Y] = to_vec[Y];
|
||||
if (z_only) delta[Z] = to_vec[Z];
|
||||
if (x_only) delta[X] = to_vec_base[X];
|
||||
if (y_only) delta[Y] = to_vec_base[Y];
|
||||
if (z_only) delta[Z] = to_vec_base[Z];
|
||||
} else {
|
||||
VMOVE(delta, to_vec);
|
||||
VMOVE(delta, to_vec_base);
|
||||
}
|
||||
VADD2(target, s->e_keypoint, delta);
|
||||
}
|
||||
|
||||
VMOVE(s->e_para, target);
|
||||
s->e_inpara = 3;
|
||||
rt_edit_set_translation_target(s, target);
|
||||
rt_edit_set_edflag(s, RT_PARAMS_EDIT_TRANS);
|
||||
rt_edit_process(s);
|
||||
return BRLCAD_OK;
|
||||
@@ -583,10 +585,11 @@ cmd_tra::exec(struct ged *gedp, void *u_data, int argc, const char **argv)
|
||||
return _edit_xform_apply(ctx,
|
||||
[&](struct rt_edit *s) -> int
|
||||
{
|
||||
vect_t target;
|
||||
VADD2(target, s->e_keypoint, delta);
|
||||
VMOVE(s->e_para, target);
|
||||
s->e_inpara = 3;
|
||||
vect_t delta_base;
|
||||
point_t target;
|
||||
VSCALE(delta_base, delta, s->local2base);
|
||||
VADD2(target, s->e_keypoint, delta_base);
|
||||
rt_edit_set_translation_target(s, target);
|
||||
rt_edit_set_edflag(s, RT_PARAMS_EDIT_TRANS);
|
||||
rt_edit_process(s);
|
||||
return BRLCAD_OK;
|
||||
@@ -618,6 +621,7 @@ _parse_pos_or_obj(point_t *pos, const char **argv, int argc, struct ged *gedp)
|
||||
n++;
|
||||
}
|
||||
}
|
||||
VSCALE(*pos, *pos, gedp->dbip->dbi_local2base);
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -1170,6 +1174,15 @@ cmd_scale::exec(struct ged *gedp, void *u_data, int argc, const char **argv)
|
||||
}
|
||||
}
|
||||
|
||||
/* Scale references define factors, so normalize model coordinates to
|
||||
* the database-local numeric values used by this command. */
|
||||
if (have_k)
|
||||
VSCALE(k_vec, k_vec, gedp->dbip->dbi_base2local);
|
||||
if (have_a)
|
||||
VSCALE(a_vec, a_vec, gedp->dbip->dbi_base2local);
|
||||
if (have_r)
|
||||
VSCALE(r_vec, r_vec, gedp->dbip->dbi_base2local);
|
||||
|
||||
/* ---- Determine scale factors from whatever was provided -------- */
|
||||
/* Helper: detect if the three vector components are all nearly equal */
|
||||
auto vec_is_uniform = [](const vect_t v) -> bool {
|
||||
@@ -2036,7 +2049,7 @@ _exec_desc_cmd_on_edit(struct rt_edit *s, struct ged *gedp,
|
||||
|
||||
s->e_inpara = _desc_cmd_inpara(cmd_desc);
|
||||
rt_edit_set_edflag(s, cmd_desc->cmd_id);
|
||||
rt_edit_process(s);
|
||||
int edit_ret = rt_edit_process(s);
|
||||
|
||||
/* Forward any error message logged by the edit handler */
|
||||
if (s->log_str && bu_vls_strlen(s->log_str) > 0) {
|
||||
@@ -2046,7 +2059,7 @@ _exec_desc_cmd_on_edit(struct rt_edit *s, struct ged *gedp,
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
return BRLCAD_OK;
|
||||
return edit_ret;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -3,16 +3,21 @@ brlcad_find_package(manifold REQUIRED)
|
||||
set(FACETIZE_LIBS libged libbu manifold::manifold)
|
||||
|
||||
add_subdirectory(subprocess)
|
||||
add_subdirectory(tests)
|
||||
|
||||
set(
|
||||
FACETIZE_SRCS
|
||||
brep.cpp
|
||||
facetize.cpp
|
||||
nmg.cpp
|
||||
orchestrator.cpp
|
||||
plan.cpp
|
||||
process.cpp
|
||||
regions.cpp
|
||||
transfer.cpp
|
||||
tri.cpp
|
||||
util.cpp
|
||||
validation.cpp
|
||||
worker.cpp
|
||||
)
|
||||
|
||||
@@ -26,23 +31,14 @@ ged_plugin_library(ged-facetize
|
||||
# Plugin requires subprocess to work
|
||||
add_dependencies(ged-facetize ged_exec facetize_process)
|
||||
|
||||
# Old version of facetize
|
||||
set(OLD_FACETIZE_SRCS
|
||||
old_facetize.cpp
|
||||
old_facetize_log.c
|
||||
)
|
||||
|
||||
ged_plugin_library(ged-old_facetize
|
||||
${OLD_FACETIZE_SRCS}
|
||||
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
LIBS ${FACETIZE_LIBS}
|
||||
)
|
||||
|
||||
cmakefiles(
|
||||
CMakeLists.txt
|
||||
tess_opts.h
|
||||
ged_facetize.h
|
||||
old_facetize.h
|
||||
orchestrator.h
|
||||
process.h
|
||||
transfer.h
|
||||
validation.h
|
||||
worker.h
|
||||
TODO
|
||||
)
|
||||
|
||||
@@ -35,26 +35,27 @@
|
||||
#include "./ged_facetize.h"
|
||||
|
||||
int
|
||||
_nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **argv)
|
||||
_nonovlp_brep_facetize(struct _ged_facetize_state *s, const FacetizePlan &plan)
|
||||
{
|
||||
int newobj_cnt;
|
||||
struct directory **dpa = NULL;
|
||||
|
||||
RT_CHECK_DBI(s->dbip);
|
||||
|
||||
if (argc <= 0) return BRLCAD_ERROR;
|
||||
|
||||
dpa = (struct directory **)bu_calloc(argc, sizeof(struct directory *), "dp array");
|
||||
newobj_cnt = _ged_sort_existing_objs(s->dbip, argc, argv, dpa);
|
||||
if (_ged_validate_objs_list(s, argc, argv, newobj_cnt) == BRLCAD_ERROR) {
|
||||
bu_free(dpa, "dp array");
|
||||
return BRLCAD_ERROR;
|
||||
int argc = (int)plan.inputs.size();
|
||||
std::vector<const char *> argv = plan.input_argv();
|
||||
struct directory **dpa = (struct directory **)bu_calloc(argc,
|
||||
sizeof(struct directory *), "BRep input directory array");
|
||||
for (int i = 0; i < argc; i++) {
|
||||
dpa[i] = db_lookup(s->dbip, argv[i], LOOKUP_QUIET);
|
||||
if (!dpa[i]) {
|
||||
facetize_failure(s, "BRep input object '%s' disappeared before processing", argv[i]);
|
||||
bu_free(dpa, "BRep input directory array");
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
/* If anything specified has subtractions or intersections, we can't facetize it with
|
||||
* this logic - that would require all-up Boolean evaluation processing. */
|
||||
const char *non_union = "-bool + -or -bool -";
|
||||
if (db_search(NULL, DB_SEARCH_QUIET, non_union, newobj_cnt, dpa, s->dbip, NULL, NULL, NULL) > 0) {
|
||||
if (db_search(NULL, DB_SEARCH_QUIET, non_union, argc, dpa, s->dbip, NULL, NULL, NULL) > 0) {
|
||||
bu_free(dpa, "dp array");
|
||||
bu_vls_printf(s->gedp->ged_result_str, "Found intersection or subtraction objects in specified inputs - currently unsupported. Aborting.\n");
|
||||
return BRLCAD_ERROR;
|
||||
@@ -63,7 +64,7 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
|
||||
/* If anything other than combs or breps exists in the specified inputs, we can't
|
||||
* process with this logic - requires a preliminary brep conversion. */
|
||||
const char *obj_types = "! -type c -and ! -type brep";
|
||||
if (db_search(NULL, DB_SEARCH_QUIET, obj_types, newobj_cnt, dpa, s->dbip, NULL, NULL, NULL) > 0) {
|
||||
if (db_search(NULL, DB_SEARCH_QUIET, obj_types, argc, dpa, s->dbip, NULL, NULL, NULL) > 0) {
|
||||
bu_free(dpa, "dp array");
|
||||
bu_vls_printf(s->gedp->ged_result_str, "Found objects in specified inputs which are not of type comb or brep- currently unsupported. Aborting.\n");
|
||||
return BRLCAD_ERROR;
|
||||
@@ -83,12 +84,17 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
|
||||
bu_free(dpa, "dp array");
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
for (int i = 0; i < newobj_cnt; i++) {
|
||||
int xac = 3;
|
||||
for (int i = 0; i < argc; i++) {
|
||||
int xac = 2;
|
||||
const char *xav[3] = {NULL};
|
||||
xav[0] = "xpush";
|
||||
xav[1] = dpa[i]->d_namep;
|
||||
ged_exec_xpush(wgedp, xac, (const char **)xav);
|
||||
if (ged_exec_xpush(wgedp, xac, (const char **)xav) != BRLCAD_OK) {
|
||||
facetize_failure(s, "xpush failed for BRep input '%s'", dpa[i]->d_namep);
|
||||
ged_close(wgedp);
|
||||
bu_free(dpa, "BRep input directory array");
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
/* Used the libged tolerances */
|
||||
@@ -103,7 +109,7 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
|
||||
const char *active_breps = "-type brep";
|
||||
struct bu_ptbl *br;
|
||||
BU_ALLOC(br, struct bu_ptbl);
|
||||
if (db_search(br, DB_SEARCH_RETURN_UNIQ_DP, active_breps, newobj_cnt, dpa, wgedp->dbip, NULL, NULL, NULL) < 0) {
|
||||
if (db_search(br, DB_SEARCH_RETURN_UNIQ_DP, active_breps, argc, dpa, wgedp->dbip, NULL, NULL, NULL) < 0) {
|
||||
bu_free(dpa, "dp array");
|
||||
bu_free(br, "brep results");
|
||||
return BRLCAD_ERROR;
|
||||
@@ -210,13 +216,6 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
|
||||
}
|
||||
}
|
||||
|
||||
/* Done changing stuff in working database. */
|
||||
ged_close(wgedp);
|
||||
|
||||
for (size_t i = 0; i < ss_cdt.size(); i++) {
|
||||
ON_Brep_CDT_Destroy(ss_cdt[i]);
|
||||
}
|
||||
|
||||
/* Keep out just what we asked for into a .g file */
|
||||
struct bu_vls kwfile = BU_VLS_INIT_ZERO;
|
||||
bu_vls_sprintf(&kwfile, "%s_keep", bu_vls_cstr(s->wfile));
|
||||
@@ -227,7 +226,21 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
|
||||
av[i+2] = argv[i];
|
||||
}
|
||||
av[argc+2] = NULL;
|
||||
ged_exec_keep(wgedp, argc+2, av);
|
||||
if (ged_exec_keep(wgedp, argc+2, av) != BRLCAD_OK) {
|
||||
facetize_failure(s, "unable to stage processed BRep hierarchy");
|
||||
bu_free(av, "av");
|
||||
bu_vls_free(&kwfile);
|
||||
ged_close(wgedp);
|
||||
for (size_t i = 0; i < ss_cdt.size(); i++)
|
||||
ON_Brep_CDT_Destroy(ss_cdt[i]);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
/* Done changing stuff in working database. */
|
||||
ged_close(wgedp);
|
||||
|
||||
for (size_t i = 0; i < ss_cdt.size(); i++)
|
||||
ON_Brep_CDT_Destroy(ss_cdt[i]);
|
||||
|
||||
/* Merge working geometry into original file */
|
||||
av[0] = "dbconcat";
|
||||
@@ -235,14 +248,13 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
|
||||
av[2] = bu_vls_cstr(&kwfile);
|
||||
av[3] = "brep_facetize_"; // TODO - customize
|
||||
av[4] = NULL;
|
||||
ged_exec_dbconcat(s->gedp, 4, av);
|
||||
int concat_ret = ged_exec_dbconcat(s->gedp, 4, av);
|
||||
bu_free(av, "av");
|
||||
bu_vls_free(&kwfile);
|
||||
|
||||
/* Clean up */
|
||||
bu_dirclear(s->wdir);
|
||||
s->cleanup_workspace = true;
|
||||
|
||||
return BRLCAD_OK;
|
||||
return (concat_ret == BRLCAD_OK) ? BRLCAD_OK : BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
@@ -253,4 +265,3 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
|
||||
// c-file-style: "stroustrup"
|
||||
// End:
|
||||
// ex: shiftwidth=4 tabstop=8
|
||||
|
||||
|
||||
+199
-299
@@ -32,6 +32,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "bu/app.h"
|
||||
#include "bu/file.h"
|
||||
#include "bu/path.h"
|
||||
#include "bu/opt.h"
|
||||
#include "wdb.h"
|
||||
@@ -42,6 +43,8 @@
|
||||
#include "./tess_opts.h"
|
||||
#include "./ged_facetize.h"
|
||||
|
||||
static const char FACETIZE_NMG_OUTPUT_FILE_SUFFIX[] = "_nmg_outputs.g";
|
||||
|
||||
static int
|
||||
facetize_process_output(struct bu_vls *output, const char **command)
|
||||
{
|
||||
@@ -98,223 +101,132 @@ _facetize_methods_help(struct ged *gedp)
|
||||
bu_vls_free(&method_output);
|
||||
}
|
||||
|
||||
struct _ged_facetize_state *
|
||||
_ged_facetize_state_create()
|
||||
static int
|
||||
facetize_commit_nmg_outputs(struct _ged_facetize_state *s,
|
||||
const std::vector<std::string> &output_names)
|
||||
{
|
||||
struct _ged_facetize_state *s = NULL;
|
||||
BU_GET(s, struct _ged_facetize_state);
|
||||
s->verbosity = 0;
|
||||
s->no_empty = 0;
|
||||
s->make_nmg = 0;
|
||||
s->nonovlp_brep = 0;
|
||||
s->no_fixup = 0;
|
||||
s->nmg_booleval = 0;
|
||||
s->use_variant_plan = 1;
|
||||
s->tolerate_failures = 0;
|
||||
s->tolerated_failures = 0;
|
||||
s->tolerated_failure_details = 0;
|
||||
s->tolerated_failure_omitted = 0;
|
||||
s->inspection_regions = 0;
|
||||
s->perturb_sa_tol = 10.0;
|
||||
s->perturb_vol_tol = 10.0;
|
||||
if (!s || output_names.empty())
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
s->wdir = NULL;
|
||||
|
||||
BU_GET(s->log_file, struct bu_vls);
|
||||
bu_vls_init(s->log_file);
|
||||
s->log_file_is_temporary = 0;
|
||||
|
||||
s->lfile = NULL;
|
||||
|
||||
BU_GET(s->failure_msg, struct bu_vls);
|
||||
bu_vls_init(s->failure_msg);
|
||||
|
||||
BU_GET(s->tolerated_failure_log, struct bu_vls);
|
||||
bu_vls_init(s->tolerated_failure_log);
|
||||
|
||||
BU_GET(s->region_summary, struct bu_vls);
|
||||
bu_vls_init(s->region_summary);
|
||||
|
||||
BU_GET(s->primitive_summary, struct bu_vls);
|
||||
bu_vls_init(s->primitive_summary);
|
||||
|
||||
BU_GET(s->inspection_log, struct bu_vls);
|
||||
bu_vls_init(s->inspection_log);
|
||||
|
||||
BU_GET(s->wfile, struct bu_vls);
|
||||
bu_vls_init(s->wfile);
|
||||
|
||||
BU_GET(s->bname, struct bu_vls);
|
||||
bu_vls_init(s->bname);
|
||||
|
||||
s->regions = 0;
|
||||
s->resume = 0;
|
||||
s->in_place = 0;
|
||||
|
||||
BU_GET(s->suffix, struct bu_vls);
|
||||
bu_vls_init(s->suffix);
|
||||
|
||||
BU_GET(s->prefix, struct bu_vls);
|
||||
bu_vls_init(s->prefix);
|
||||
|
||||
BU_GET(s->solid_suffix, struct bu_vls);
|
||||
bu_vls_init(s->solid_suffix);
|
||||
bu_vls_sprintf(s->solid_suffix, ".bot");
|
||||
|
||||
s->max_time = 0;
|
||||
s->max_pnts = 0;
|
||||
|
||||
s->tol = NULL;
|
||||
s->nonovlp_threshold = 0;
|
||||
|
||||
s->gedp = NULL;
|
||||
s->write_profiled = 0;
|
||||
s->write_profile_bytes = 0.0;
|
||||
s->write_profile_usec = 0.0;
|
||||
|
||||
s->variant_plan = NULL;
|
||||
|
||||
return s;
|
||||
}
|
||||
void _ged_facetize_state_destroy(struct _ged_facetize_state *s)
|
||||
{
|
||||
if (!s)
|
||||
return;
|
||||
|
||||
if (s->wdir)
|
||||
bu_free(s->wdir, "wdir");
|
||||
|
||||
if (s->bname) {
|
||||
bu_vls_free(s->bname);
|
||||
BU_PUT(s->bname, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->lfile) {
|
||||
fclose(s->lfile);
|
||||
s->lfile = NULL;
|
||||
}
|
||||
|
||||
if (s->log_file) {
|
||||
bu_vls_free(s->log_file);
|
||||
BU_PUT(s->log_file, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->failure_msg) {
|
||||
bu_vls_free(s->failure_msg);
|
||||
BU_PUT(s->failure_msg, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->tolerated_failure_log) {
|
||||
bu_vls_free(s->tolerated_failure_log);
|
||||
BU_PUT(s->tolerated_failure_log, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->region_summary) {
|
||||
bu_vls_free(s->region_summary);
|
||||
BU_PUT(s->region_summary, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->primitive_summary) {
|
||||
bu_vls_free(s->primitive_summary);
|
||||
BU_PUT(s->primitive_summary, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->inspection_log) {
|
||||
bu_vls_free(s->inspection_log);
|
||||
BU_PUT(s->inspection_log, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->wfile) {
|
||||
bu_vls_free(s->wfile);
|
||||
BU_PUT(s->wfile, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->prefix) {
|
||||
bu_vls_free(s->prefix);
|
||||
BU_PUT(s->prefix, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->suffix) {
|
||||
bu_vls_free(s->suffix);
|
||||
BU_PUT(s->suffix, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->solid_suffix) {
|
||||
bu_vls_free(s->solid_suffix);
|
||||
BU_PUT(s->solid_suffix, struct bu_vls);
|
||||
}
|
||||
|
||||
if (s->variant_plan) {
|
||||
delete (FacetizeVariantPlan *)s->variant_plan;
|
||||
s->variant_plan = NULL;
|
||||
}
|
||||
|
||||
BU_PUT(s, struct _ged_facetize_state);
|
||||
}
|
||||
|
||||
int
|
||||
_ged_facetize_objs(struct _ged_facetize_state *s, int argc, const char **argv)
|
||||
{
|
||||
int ret = BRLCAD_ERROR;
|
||||
int newobj_cnt, i;
|
||||
int ok_cnt = 0;
|
||||
const char *oname = NULL;
|
||||
const char *av[2];
|
||||
struct directory **dpa = NULL;
|
||||
struct directory *idpa[2];
|
||||
struct db_i *dbip = s->dbip;
|
||||
|
||||
RT_CHECK_DBI(dbip);
|
||||
|
||||
if (argc < 0) return BRLCAD_ERROR;
|
||||
|
||||
dpa = (struct directory **)bu_calloc(argc, sizeof(struct directory *), "dp array");
|
||||
newobj_cnt = _ged_sort_existing_objs(dbip, argc, argv, dpa);
|
||||
if (_ged_validate_objs_list(s, argc, argv, newobj_cnt) == BRLCAD_ERROR) {
|
||||
bu_free(dpa, "dp array");
|
||||
std::string keep_file = std::string(bu_vls_cstr(s->wfile)) +
|
||||
FACETIZE_NMG_OUTPUT_FILE_SUFFIX;
|
||||
(void)bu_file_delete(keep_file.c_str());
|
||||
struct ged *working_gedp = ged_open("db", bu_vls_cstr(s->wfile), 1);
|
||||
if (!working_gedp) {
|
||||
facetize_failure(s, "unable to open staged NMG Boolean database '%s'",
|
||||
bu_vls_cstr(s->wfile));
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
if (!s->in_place) {
|
||||
oname = argv[argc-1];
|
||||
argc--;
|
||||
std::vector<const char *> keep_argv;
|
||||
keep_argv.reserve(output_names.size() + 2);
|
||||
keep_argv.push_back("keep");
|
||||
keep_argv.push_back(keep_file.c_str());
|
||||
for (const std::string &output_name : output_names)
|
||||
keep_argv.push_back(output_name.c_str());
|
||||
int keep_result = ged_exec_keep(working_gedp, (int)keep_argv.size(),
|
||||
keep_argv.data());
|
||||
ged_close(working_gedp);
|
||||
if (keep_result != BRLCAD_OK) {
|
||||
facetize_failure(s, "unable to stage NMG Boolean outputs for import");
|
||||
(void)bu_file_delete(keep_file.c_str());
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
/* If we're doing an NMG output, or we have been instructed to, use the
|
||||
* old-school libnmg booleval */
|
||||
if (s->make_nmg || s->nmg_booleval) {
|
||||
if (!s->in_place) {
|
||||
ret = _ged_facetize_nmgeval(s, argc, argv, oname);
|
||||
goto booleval_cleanup;
|
||||
} else {
|
||||
for (i = 0; i < argc; i++) {
|
||||
av[0] = argv[i];
|
||||
av[1] = NULL;
|
||||
ret = _ged_facetize_nmgeval(s, 1, av, av[0]);
|
||||
if (ret == BRLCAD_ERROR && s->tolerate_failures) {
|
||||
facetize_tolerated_failure(s, "object '%s' failed during NMG boolean evaluation and was skipped", argv[i]);
|
||||
continue;
|
||||
}
|
||||
if (ret == BRLCAD_ERROR)
|
||||
goto booleval_cleanup;
|
||||
ok_cnt++;
|
||||
}
|
||||
if (s->tolerate_failures && ok_cnt > 0)
|
||||
ret = BRLCAD_OK;
|
||||
goto booleval_cleanup;
|
||||
const char *concat_argv[] = {"dbconcat", "-O", keep_file.c_str(), NULL};
|
||||
int concat_result = ged_exec_dbconcat(s->gedp, 3, concat_argv);
|
||||
(void)bu_file_delete(keep_file.c_str());
|
||||
if (concat_result != BRLCAD_OK) {
|
||||
facetize_failure(s, "unable to import staged NMG Boolean outputs");
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
bu_vls_trunc(s->gedp->ged_result_str, 0);
|
||||
db_update_nref(s->dbip);
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
|
||||
int
|
||||
_ged_facetize_objs(struct _ged_facetize_state *s, const FacetizePlan &plan)
|
||||
{
|
||||
int ret = BRLCAD_ERROR;
|
||||
int ok_cnt = 0;
|
||||
struct db_i *dbip = s->dbip;
|
||||
RT_CHECK_DBI(dbip);
|
||||
|
||||
int argc = (int)plan.inputs.size();
|
||||
std::vector<const char *> argv = plan.input_argv();
|
||||
struct directory **dpa = (struct directory **)bu_calloc(argc,
|
||||
sizeof(struct directory *), "facetize input directory array");
|
||||
for (int i = 0; i < argc; i++) {
|
||||
dpa[i] = db_lookup(dbip, argv[i], LOOKUP_QUIET);
|
||||
if (!dpa[i]) {
|
||||
facetize_failure(s, "input object '%s' disappeared before evaluation", argv[i]);
|
||||
bu_free(dpa, "facetize input directory array");
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
// If we're not doing NMG, use the Manifold booleval
|
||||
if (!s->in_place) {
|
||||
ret = _ged_facetize_booleval(s, argc, dpa, oname, false, false);
|
||||
const char *output_name = plan.execution.writes_in_place() ?
|
||||
NULL : plan.output.c_str();
|
||||
|
||||
if (plan.execution.uses_nmg_boolean()) {
|
||||
if (_ged_facetize_working_file_setup(s, NULL) != BRLCAD_OK) {
|
||||
facetize_failure(s,
|
||||
"unable to prepare the NMG Boolean working database");
|
||||
goto booleval_cleanup;
|
||||
}
|
||||
struct db_i *work_dbip = db_open(bu_vls_cstr(s->wfile),
|
||||
DB_OPEN_READWRITE);
|
||||
if (!work_dbip || db_dirbuild(work_dbip) < 0) {
|
||||
if (work_dbip)
|
||||
db_close(work_dbip);
|
||||
facetize_failure(s,
|
||||
"unable to open the NMG Boolean working database");
|
||||
goto booleval_cleanup;
|
||||
}
|
||||
|
||||
std::vector<std::string> successful_outputs;
|
||||
if (!plan.execution.writes_in_place()) {
|
||||
ret = _ged_facetize_nmgeval(s, work_dbip,
|
||||
s->dbip->dbi_filename, plan.inputs, output_name);
|
||||
if (ret == BRLCAD_OK)
|
||||
successful_outputs.emplace_back(output_name);
|
||||
} else {
|
||||
for (int i = 0; i < argc; i++) {
|
||||
std::vector<std::string> object_input(1, plan.inputs[i]);
|
||||
ret = _ged_facetize_nmgeval(s, work_dbip,
|
||||
s->dbip->dbi_filename, object_input, argv[i]);
|
||||
if (ret == BRLCAD_ERROR && s->tolerate_failures) {
|
||||
facetize_tolerated_failure(s,
|
||||
"object '%s' failed during NMG boolean evaluation and was skipped",
|
||||
argv[i]);
|
||||
continue;
|
||||
}
|
||||
if (ret == BRLCAD_ERROR)
|
||||
break;
|
||||
successful_outputs.emplace_back(argv[i]);
|
||||
}
|
||||
if (s->tolerate_failures && !successful_outputs.empty())
|
||||
ret = BRLCAD_OK;
|
||||
}
|
||||
db_close(work_dbip);
|
||||
if (ret == BRLCAD_OK)
|
||||
ret = facetize_commit_nmg_outputs(s, successful_outputs);
|
||||
if (ret == BRLCAD_OK)
|
||||
s->cleanup_workspace = true;
|
||||
goto booleval_cleanup;
|
||||
}
|
||||
|
||||
if (!plan.execution.writes_in_place()) {
|
||||
ret = _ged_facetize_booleval(s, argc, dpa, output_name, false, false);
|
||||
} else {
|
||||
for (i = 0; i < argc; i++) {
|
||||
idpa[0] = dpa[i];
|
||||
idpa[1] = NULL;
|
||||
ret = _ged_facetize_booleval(s, 1, (struct directory **)idpa, argv[i], false, false);
|
||||
for (int i = 0; i < argc; i++) {
|
||||
struct directory *object_dpa[] = {dpa[i], NULL};
|
||||
ret = _ged_facetize_booleval(s, 1, object_dpa, argv[i], false, false);
|
||||
if (ret == BRLCAD_ERROR && s->tolerate_failures) {
|
||||
facetize_tolerated_failure(s, "object '%s' failed during BoT boolean evaluation and was skipped", argv[i]);
|
||||
facetize_tolerated_failure(s,
|
||||
"object '%s' failed during BoT boolean evaluation and was skipped",
|
||||
argv[i]);
|
||||
continue;
|
||||
}
|
||||
if (ret == BRLCAD_ERROR)
|
||||
@@ -328,11 +240,10 @@ _ged_facetize_objs(struct _ged_facetize_state *s, int argc, const char **argv)
|
||||
// Report on the primitive processing
|
||||
facetize_collect_primitive_summary(s);
|
||||
|
||||
// After collecting info for summary, we can now clean up working files
|
||||
bu_dirclear(s->wdir);
|
||||
s->cleanup_workspace = true;
|
||||
|
||||
booleval_cleanup:
|
||||
bu_free(dpa, "dp array");
|
||||
bu_free(dpa, "facetize input directory array");
|
||||
|
||||
return ret;
|
||||
}
|
||||
@@ -348,22 +259,32 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
|
||||
long verbosity = 0;
|
||||
int force_perturb = 0;
|
||||
int disable_perturb = 0;
|
||||
method_options_t *method_options = new method_options_t;
|
||||
struct _ged_facetize_state *s = _ged_facetize_state_create();
|
||||
s->gedp = gedp;
|
||||
s->dbip = gedp->dbip;
|
||||
s->method_opts = method_options;
|
||||
int nmg_output = 0;
|
||||
int region_mode = 0;
|
||||
int in_place = 0;
|
||||
int nmg_boolean = 0;
|
||||
int nonoverlap_brep = 0;
|
||||
bool use_perturbation = false;
|
||||
|
||||
GED_CHECK_DATABASE_OPEN(gedp, BRLCAD_ERROR);
|
||||
GED_CHECK_READ_ONLY(gedp, BRLCAD_ERROR);
|
||||
GED_CHECK_ARGC_GT_0(gedp, argc, BRLCAD_ERROR);
|
||||
|
||||
FacetizeSession session(gedp);
|
||||
struct _ged_facetize_state *s = session.state();
|
||||
method_options_t *method_options = session.method_options();
|
||||
FacetizePlan plan;
|
||||
|
||||
/* General options */
|
||||
struct bu_opt_desc d[25];
|
||||
struct bu_opt_desc d[26];
|
||||
BU_OPT(d[ 0], "h", "help", "", NULL, &print_help, "Print help and exit");
|
||||
BU_OPT(d[ 1], "v", "verbose", "", &bu_opt_incr_long, &verbosity, "Verbose output (multiple flags increase verbosity)");
|
||||
BU_OPT(d[ 2], "q", "quiet", "", NULL, &quiet, "Suppress all output (overrides verbose flag)");
|
||||
BU_OPT(d[ 3], "n", "nmg-output", "", NULL, &(s->make_nmg), "Create an N-Manifold Geometry (NMG) object (default is to create a triangular BoT mesh). Note that this will disable most other processing options and may reduce the conversion success rate.");
|
||||
BU_OPT(d[ 4], "r", "regions", "", NULL, &(s->regions), "For combs, walk the trees and create new copies of the hierarchies with each region's CSG tree replaced by a facetized evaluation of that region. By default, enables perturb methodology (can be disabled - see --no-perturb)");
|
||||
BU_OPT(d[ 3], "n", "nmg-output", "", NULL, &nmg_output, "Create an N-Manifold Geometry (NMG) object (default is to create a triangular BoT mesh). Note that this will disable most other processing options and may reduce the conversion success rate.");
|
||||
BU_OPT(d[ 4], "r", "regions", "", NULL, ®ion_mode, "For combs, walk the trees and create new copies of the hierarchies with each region's CSG tree replaced by a facetized evaluation of that region. By default, enables perturb methodology (can be disabled - see --no-perturb)");
|
||||
BU_OPT(d[ 5], "s", "suffix", "<str>", &bu_opt_vls, s->suffix, "When creating new objects for facetize outputs, use this suffix to avoid conflicts");
|
||||
BU_OPT(d[ 6], "p", "prefix", "<str>", &bu_opt_vls, s->prefix, "When creating new objects for facetize, use this prefix to avoid conflicts");
|
||||
BU_OPT(d[ 7], "", "in-place", "", NULL, &(s->in_place), "Replace the specified object(s) with their facetizations. (Warning: this option changes pre-existing geometry!)");
|
||||
BU_OPT(d[ 7], "", "in-place", "", NULL, &in_place, "Replace the specified object(s) with their facetizations. (Warning: this option changes pre-existing geometry!)");
|
||||
BU_OPT(d[ 8], "", "max-time", "#", &bu_opt_int, &(s->max_time), "Maximum time to spend per object (in seconds). Default is method specific. Note that specifying shorter times may cut off conversions (particularly using sampling methods) that could succeed with longer runtimes. Per-method time limits can also be adjusted to allow longer runtimes on slower methods.");
|
||||
BU_OPT(d[ 9], "", "max-pnts", "#", &bu_opt_int, &(s->max_pnts), "Maximum number of pnts per object to use when applying ray sampling methods.");
|
||||
BU_OPT(d[10], "", "resume", "", NULL, &(s->resume), "Resume an interrupted conversion");
|
||||
@@ -371,20 +292,17 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
|
||||
BU_OPT(d[12], "", "method-opts", "METHOD opt1=val opt2=val...", &_tess_method_opts, method_options, "For the specified method, set the specified options.");
|
||||
BU_OPT(d[13], "", "no-empty", "", NULL, &(s->no_empty), "Do not output empty BoT objects if the boolean evaluation results in an empty solid.");
|
||||
BU_OPT(d[14], "", "log-file", "<filename>", &bu_opt_vls, s->log_file, "Specify a location to use for the log file.");
|
||||
BU_OPT(d[15], "", "nmg-booleval", "", NULL, &s->nmg_booleval, "Use libnmg Boolean evaluation algorithm, even if we're producing a BoT. Less robust, but if it succeeds it may produce cleaner output for coplanar inputs.");
|
||||
BU_OPT(d[15], "", "nmg-booleval", "", NULL, &nmg_boolean, "Use libnmg Boolean evaluation algorithm, even if we're producing a BoT. Less robust, but if it succeeds it may produce cleaner output for coplanar inputs.");
|
||||
BU_OPT(d[16], "", "disable-fixup", "", NULL, &s->no_fixup, "Disable post-processing steps intended to improve generated meshes.");
|
||||
BU_OPT(d[17], "", "perturb", "", NULL, &force_perturb, "Enable the coplanarity-avoidance perturbation step (overrides non -r option default, conflicts with --no-perturb).");
|
||||
BU_OPT(d[18], "", "no-perturb", "", NULL, &disable_perturb, "Disable the coplanarity-avoidance perturbation step (overrides -r option default, conflicts with --perturb).");
|
||||
BU_OPT(d[19], "B", "", "", NULL, &s->nonovlp_brep, "EXPERIMENTAL: non-overlapping facetization to BoT objects of union-only brep comb tree.");
|
||||
BU_OPT(d[19], "B", "", "", NULL, &nonoverlap_brep, "EXPERIMENTAL: non-overlapping facetization to BoT objects of union-only brep comb tree.");
|
||||
BU_OPT(d[20], "t", "threshold", "#", &bu_opt_fastf_t, &s->nonovlp_threshold, "EXPERIMENTAL: max ovlp threshold length for -B mode.");
|
||||
BU_OPT(d[21], "", "perturb-sa-tol", "#", &bu_opt_fastf_t, &s->perturb_sa_tol, "Surface-area percentage threshold (0-100) that triggers the coplanarity-avoidance perturb retry when the CSG Crofton SA differs from the BoT SA by more than this amount. Default is 10.");
|
||||
BU_OPT(d[22], "", "perturb-vol-tol", "#", &bu_opt_fastf_t, &s->perturb_vol_tol, "Volume percentage threshold (0-100) that triggers the coplanarity-avoidance perturb retry when the CSG Crofton volume differs from the BoT volume by more than this amount. Default is 10.");
|
||||
BU_OPT(d[23], "", "tolerate-failures", "", NULL, &s->tolerate_failures, "Continue after failed primitive or subtree evaluations and generate a partial result. The output will not be a complete representation of the input if any failures are tolerated.");
|
||||
BU_OPT_NULL(d[24]);
|
||||
|
||||
GED_CHECK_DATABASE_OPEN(gedp, BRLCAD_ERROR);
|
||||
GED_CHECK_READ_ONLY(gedp, BRLCAD_ERROR);
|
||||
GED_CHECK_ARGC_GT_0(gedp, argc, BRLCAD_ERROR);
|
||||
BU_OPT(d[24], "j", "jobs", "#", &bu_opt_int, &s->max_workers, "Maximum number of facetize worker processes. The default is selected conservatively from CPU and memory availability.");
|
||||
BU_OPT_NULL(d[25]);
|
||||
|
||||
/* skip command name argv[0] */
|
||||
argc-=(argc>0); argv+=(argc>0);
|
||||
@@ -399,7 +317,7 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
|
||||
bu_vls_printf(gedp->ged_result_str, "option parsing failed: %s\n", bu_vls_cstr(&omsg));
|
||||
ret = BRLCAD_ERROR;
|
||||
bu_vls_free(&omsg);
|
||||
goto ged_facetize_memfree;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
bu_vls_free(&omsg);
|
||||
|
||||
@@ -407,17 +325,49 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
|
||||
if (force_perturb && disable_perturb) {
|
||||
bu_vls_printf(gedp->ged_result_str, "Can only specify one of --perturb or --no-perturb\n");
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_memfree;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
if (s->max_workers < 0 || s->max_workers > MAX_PSW) {
|
||||
bu_vls_printf(gedp->ged_result_str,
|
||||
"--jobs must be between 0 and %d\n", MAX_PSW);
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
if (s->max_time < 0) {
|
||||
bu_vls_printf(gedp->ged_result_str,
|
||||
"--max-time must be greater than or equal to 0\n");
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
if (s->max_pnts < 0) {
|
||||
bu_vls_printf(gedp->ged_result_str,
|
||||
"--max-pnts must be greater than or equal to 0\n");
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
|
||||
// Set no_perturb according to options. Enable by default for -r, disable
|
||||
// if not doing -r (one large BoT, generally a less likely candidate for
|
||||
// worrying about volume/surf_area matching.)
|
||||
s->no_perturb = (s->regions) ? 0 : 1;
|
||||
if (region_mode && nonoverlap_brep) {
|
||||
bu_vls_printf(gedp->ged_result_str,
|
||||
"--regions and -B select different processing scopes and cannot be combined\n");
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
|
||||
s->execution.output_format = nmg_output ?
|
||||
FacetizeOutputFormat::Nmg : FacetizeOutputFormat::Bot;
|
||||
s->execution.boolean_engine = (nmg_output || nmg_boolean) ?
|
||||
FacetizeBooleanEngine::Nmg : FacetizeBooleanEngine::Manifold;
|
||||
s->execution.scope = nonoverlap_brep ? FacetizeScope::NonOverlappingBrep :
|
||||
(region_mode ? FacetizeScope::Regions : FacetizeScope::Objects);
|
||||
s->execution.commit_mode = in_place ?
|
||||
FacetizeCommitMode::InPlace : FacetizeCommitMode::NewObject;
|
||||
use_perturbation = region_mode;
|
||||
if (disable_perturb)
|
||||
s->no_perturb = 1;
|
||||
use_perturbation = false;
|
||||
if (force_perturb)
|
||||
s->no_perturb = 0;
|
||||
use_perturbation = true;
|
||||
s->execution.perturb_mode = use_perturbation ?
|
||||
FacetizePerturbMode::Enabled : FacetizePerturbMode::Disabled;
|
||||
|
||||
s->verbosity = (int)verbosity;
|
||||
|
||||
@@ -442,88 +392,38 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
|
||||
s->verbosity = -1;
|
||||
|
||||
/* Don't allow incorrect type suffixes */
|
||||
if (s->make_nmg && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".bot")) {
|
||||
if (s->execution.writes_nmg() && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".bot")) {
|
||||
bu_vls_sprintf(s->solid_suffix, ".nmg");
|
||||
}
|
||||
if (!s->make_nmg && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".nmg")) {
|
||||
if (!s->execution.writes_nmg() && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".nmg")) {
|
||||
bu_vls_sprintf(s->solid_suffix, ".bot");
|
||||
}
|
||||
|
||||
/* Check if we want/need help */
|
||||
need_help += (argc < 1);
|
||||
need_help += (argc < 2 && !s->in_place && !s->regions && !s->resume && !s->nonovlp_brep);
|
||||
if (print_help || need_help || argc < 1) {
|
||||
need_help = argc < (s->execution.writes_in_place() ? 1 : 2);
|
||||
if (print_help || need_help) {
|
||||
_ged_cmd_help(gedp, usage, d);
|
||||
_facetize_methods_help(gedp);
|
||||
ret = (need_help) ? BRLCAD_ERROR : BRLCAD_OK;
|
||||
goto ged_facetize_memfree;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
|
||||
/* Beyond this point, we're likely to need info on the cache directory. Generate some
|
||||
* paths and strings we will need. */
|
||||
{
|
||||
// Get the root filename
|
||||
char rfname[MAXPATHLEN];
|
||||
bu_file_realpath(gedp->dbip->dbi_filename, rfname);
|
||||
bu_path_component(s->bname, rfname, BU_PATH_BASENAME);
|
||||
|
||||
// Hash the path string and construct a location in the cache directory
|
||||
unsigned long long hash_num = bu_data_hash((void *)bu_vls_cstr(s->bname), bu_vls_strlen(s->bname));
|
||||
struct bu_vls dname = BU_VLS_INIT_ZERO;
|
||||
bu_vls_sprintf(&dname, "facetize_%llu", hash_num);
|
||||
s->wdir = (char *)bu_calloc(MAXPATHLEN, sizeof(char), "wdir");
|
||||
bu_dir(s->wdir, MAXPATHLEN, BU_DIR_CACHE, bu_vls_cstr(&dname), NULL);
|
||||
|
||||
// If we're starting over, clear the old working directory
|
||||
if (!s->resume && bu_file_directory(s->wdir)) {
|
||||
bu_dirclear(s->wdir);
|
||||
}
|
||||
|
||||
if (!bu_file_directory(s->wdir)) {
|
||||
// Set up the directory
|
||||
bu_mkdir(s->wdir);
|
||||
}
|
||||
|
||||
if (!bu_vls_strlen(s->log_file)) {
|
||||
char tmplfile[MAXPATHLEN];
|
||||
s->log_file_is_temporary = 1;
|
||||
bu_vls_sprintf(&dname, "facetize_%s.log", bu_vls_cstr(s->bname));
|
||||
bu_dir(tmplfile, MAXPATHLEN, s->wdir, bu_vls_cstr(&dname), NULL);
|
||||
bu_vls_sprintf(s->log_file, "%s", tmplfile);
|
||||
}
|
||||
bu_vls_free(&dname);
|
||||
|
||||
s->lfile = fopen(bu_vls_cstr(s->log_file), "a");
|
||||
if (!s->lfile) {
|
||||
bu_vls_printf(gedp->ged_result_str, "Unable to open log file %s for writing\n", bu_vls_cstr(s->log_file));
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_memfree;
|
||||
}
|
||||
if (s->execution.processes_breps() &&
|
||||
NEAR_ZERO(s->nonovlp_threshold, SMALL_FASTF)) {
|
||||
bu_vls_printf(gedp->ged_result_str,
|
||||
"-B option requires a specified length threshold\n");
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
|
||||
/* If we're doing the experimental brep-only logic, it's a separate process */
|
||||
if (s->nonovlp_brep) {
|
||||
if (NEAR_ZERO(s->nonovlp_threshold, SMALL_FASTF)) {
|
||||
bu_vls_printf(gedp->ged_result_str, "-B option requires a specified length threshold\n");
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_memfree;
|
||||
}
|
||||
ret = _nonovlp_brep_facetize(s, argc, argv);
|
||||
goto ged_facetize_memfree;
|
||||
if (facetize_build_plan(s, argc, argv, plan) != BRLCAD_OK ||
|
||||
facetize_prepare_workspace(s, plan) != BRLCAD_OK) {
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_facetize_done;
|
||||
}
|
||||
ret = facetize_execute_plan(s, plan);
|
||||
|
||||
/* Multi-region mode has a different processing logic */
|
||||
if (s->regions) {
|
||||
ret = _ged_facetize_regions(s, argc, argv);
|
||||
} else {
|
||||
ret = _ged_facetize_objs(s, argc, argv);
|
||||
}
|
||||
|
||||
ged_facetize_memfree:
|
||||
facetize_summary(s);
|
||||
_ged_facetize_state_destroy(s);
|
||||
delete method_options;
|
||||
|
||||
ged_facetize_done:
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,11 +36,12 @@
|
||||
#include "vmath.h"
|
||||
#include "bu/vls.h"
|
||||
#include "bn/tol.h"
|
||||
#include "bg/spsr.h"
|
||||
#include "rt/geom.h"
|
||||
#include "raytrace.h"
|
||||
#include "ged/defines.h"
|
||||
|
||||
#include "./orchestrator.h"
|
||||
|
||||
__BEGIN_DECLS
|
||||
|
||||
#define FACETIZE_METHOD_ATTR "facetize_method"
|
||||
@@ -50,10 +51,7 @@ struct _ged_facetize_state {
|
||||
// Output
|
||||
int verbosity;
|
||||
int no_empty;
|
||||
int make_nmg;
|
||||
int nonovlp_brep;
|
||||
int no_fixup;
|
||||
int no_perturb;
|
||||
int use_variant_plan;
|
||||
int tolerate_failures;
|
||||
int tolerated_failures;
|
||||
@@ -68,6 +66,7 @@ struct _ged_facetize_state {
|
||||
fastf_t perturb_vol_tol;
|
||||
|
||||
char *wdir;
|
||||
bool cleanup_workspace;
|
||||
struct bu_vls *wfile;
|
||||
struct bu_vls *bname;
|
||||
struct bu_vls *log_file;
|
||||
@@ -80,14 +79,13 @@ struct _ged_facetize_state {
|
||||
struct bu_vls *inspection_log;
|
||||
|
||||
// Processing
|
||||
int regions;
|
||||
FacetizeExecutionOptions execution;
|
||||
int resume;
|
||||
int in_place;
|
||||
int nmg_booleval;
|
||||
|
||||
// Settings
|
||||
int max_time;
|
||||
int max_pnts;
|
||||
int max_workers;
|
||||
struct bu_vls *prefix;
|
||||
struct bu_vls *suffix;
|
||||
|
||||
@@ -102,7 +100,6 @@ struct _ged_facetize_state {
|
||||
struct db_i *dbip;
|
||||
union tree *facetize_tree;
|
||||
void *method_opts;
|
||||
void *log_s;
|
||||
|
||||
/* Cache-local write measurements seed and refine worker write deadlines. */
|
||||
int write_profiled;
|
||||
@@ -132,13 +129,15 @@ extern int
|
||||
_db_uniq_test(struct bu_vls *n, void *data);
|
||||
|
||||
extern int
|
||||
_ged_validate_objs_list(struct _ged_facetize_state *s, int argc, const char *argv[], int newobj_cnt);
|
||||
_ged_facetize_regions(struct _ged_facetize_state *s, const FacetizePlan &plan);
|
||||
|
||||
extern int
|
||||
_ged_facetize_regions(struct _ged_facetize_state *s, int argc, const char **argv);
|
||||
_ged_facetize_objs(struct _ged_facetize_state *s, const FacetizePlan &plan);
|
||||
|
||||
extern int
|
||||
_ged_facetize_nmgeval(struct _ged_facetize_state *s, int argc, const char **argv, const char *newname);
|
||||
_ged_facetize_nmgeval(struct _ged_facetize_state *s,
|
||||
struct db_i *target_dbip, const char *database_path,
|
||||
const std::vector<std::string> &input_names, const char *newname);
|
||||
|
||||
extern int
|
||||
_ged_facetize_booleval(struct _ged_facetize_state *s, int argc, struct directory **dpa, const char *newname, bool output_to_working, bool cleanup);
|
||||
@@ -158,7 +157,16 @@ _ged_facetize_leaves_tri(struct _ged_facetize_state *s, struct db_i *dbip, struc
|
||||
extern int
|
||||
_ged_facetize_booleval_tri(struct _ged_facetize_state *s, struct db_i *dbip, struct rt_wdb *wdbp, int argc, const char **argv, const char *newname, struct bu_list *vlfree, bool output_to_working, int curr_cnt, int total_cnt);
|
||||
|
||||
extern int _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **argv);
|
||||
/**
|
||||
* Evaluate a tessellated CSG tree and write the resulting BoT to an explicit
|
||||
* database. The input database is never modified unless it is also supplied
|
||||
* as @p output_dbip. This form lets isolated workers evaluate into an
|
||||
* in-memory database before entering the staged-write protocol.
|
||||
*/
|
||||
extern int
|
||||
_ged_facetize_booleval_tri_to_db(struct _ged_facetize_state *s, struct db_i *dbip, struct rt_wdb *wdbp, int argc, const char **argv, const char *newname, struct bu_list *vlfree, struct db_i *output_dbip, int curr_cnt, int total_cnt);
|
||||
|
||||
extern int _nonovlp_brep_facetize(struct _ged_facetize_state *s, const FacetizePlan &plan);
|
||||
|
||||
extern struct rt_bot_internal *
|
||||
bot_fixup(struct _ged_facetize_state *s, struct db_i *wdbip, struct directory *bot_dp, const char *bname);
|
||||
@@ -229,17 +237,20 @@ struct FacetizeVariantPlan {
|
||||
* Returns an allocated FacetizeVariantPlan owned by the caller (or NULL on
|
||||
* allocation failure). Primitives without ft_perturb support are counted in
|
||||
* n_perturb_fallbacks and will fall back to the original mesh at booleval time.
|
||||
* If working_dbip is non-NULL it must be an indexed writable handle for the
|
||||
* working database; it is borrowed and remains open on return.
|
||||
*/
|
||||
extern FacetizeVariantPlan *
|
||||
_ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
|
||||
int argc,
|
||||
struct directory **dpa);
|
||||
struct directory **dpa,
|
||||
struct db_i *working_dbip);
|
||||
|
||||
/**
|
||||
* Tessellate the variant primitives in the working .g using the NMG method.
|
||||
* Called after _ged_facetize_leaves_tri() once original leaves are already
|
||||
* BoTs, either eagerly for direct booleval or lazily on the first
|
||||
* validation-triggered retry in region mode. Updates
|
||||
* Tessellate the variant primitives in the working .g using the configured
|
||||
* primitive methods and options. Called after _ged_facetize_leaves_tri() once
|
||||
* original leaves are already BoTs, either eagerly for direct booleval or
|
||||
* lazily on the first validation-triggered retry in region mode. Updates
|
||||
* plan->n_variant_tess_failures for any variants that could not be
|
||||
* tessellated (they will silently fall back to the original mesh at booleval).
|
||||
*/
|
||||
|
||||
+158
-380
@@ -19,405 +19,183 @@
|
||||
*/
|
||||
/** @file libged/facetize/nmg.cpp
|
||||
*
|
||||
* Classic NMG boolean evaluation path.
|
||||
*
|
||||
* Parent-side launch policy for isolated NMG Boolean evaluation.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "bio.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "bu/app.h"
|
||||
#include "bu/datetime.h"
|
||||
#include "bu/file.h"
|
||||
#include "bu/hook.h"
|
||||
#include "bu/vls.h"
|
||||
#include "bu/log.h"
|
||||
#include "bu/path.h"
|
||||
#include "bu/process.h"
|
||||
#include "bu/snooze.h"
|
||||
#include "raytrace.h"
|
||||
|
||||
#include "../ged_private.h"
|
||||
#include "./ged_facetize.h"
|
||||
#include "./process.h"
|
||||
#include "./transfer.h"
|
||||
#include "./worker.h"
|
||||
|
||||
struct _ged_facetize_logging_state {
|
||||
struct bu_hook_list *saved_bomb_hooks;
|
||||
struct bu_hook_list *saved_log_hooks;
|
||||
struct bu_vls *nmg_log;
|
||||
struct bu_vls *nmg_log_header;
|
||||
int nmg_log_print_header;
|
||||
int stderr_stashed;
|
||||
int serr;
|
||||
int fnull;
|
||||
};
|
||||
|
||||
extern "C" {
|
||||
static int
|
||||
_facetize_bomb_hook(void *cdata, void *str)
|
||||
{
|
||||
struct _ged_facetize_state *o = (struct _ged_facetize_state *)cdata;
|
||||
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
|
||||
if (log_s->nmg_log_print_header) {
|
||||
bu_vls_printf(log_s->nmg_log, "%s\n", bu_vls_addr(log_s->nmg_log_header));
|
||||
log_s->nmg_log_print_header = 0;
|
||||
}
|
||||
bu_vls_printf(log_s->nmg_log, "%s\n", (const char *)str);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
_facetize_nmg_logging_hook(void *data, void *str)
|
||||
{
|
||||
struct _ged_facetize_state *o = (struct _ged_facetize_state *)data;
|
||||
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
|
||||
if (log_s->nmg_log_print_header) {
|
||||
bu_vls_printf(log_s->nmg_log, "%s\n", bu_vls_addr(log_s->nmg_log_header));
|
||||
log_s->nmg_log_print_header = 0;
|
||||
}
|
||||
bu_vls_printf(log_s->nmg_log, "%s\n", (const char *)str);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
_facetize_log_nmg(struct _ged_facetize_state *o)
|
||||
{
|
||||
if (fileno(stderr) < 0)
|
||||
return;
|
||||
|
||||
/* Seriously, bu_bomb, we don't want you blathering
|
||||
* to stderr... shut down stderr temporarily. */
|
||||
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
|
||||
log_s->fnull = open(bu_file_null(), O_WRONLY);
|
||||
if (log_s->fnull != -1) {
|
||||
log_s->serr = fileno(stderr);
|
||||
log_s->stderr_stashed = dup(log_s->serr);
|
||||
dup2(log_s->fnull, log_s->serr);
|
||||
close(log_s->fnull);
|
||||
}
|
||||
|
||||
/* Set bu_log logging to capture in nmg_log, rather than the
|
||||
* application defaults */
|
||||
bu_log_hook_delete_all();
|
||||
bu_log_add_hook(_facetize_nmg_logging_hook, (void *)o);
|
||||
|
||||
/* Also engage the nmg bomb hooks */
|
||||
bu_bomb_delete_all_hooks();
|
||||
bu_bomb_add_hook(_facetize_bomb_hook, (void *)o);
|
||||
}
|
||||
|
||||
static void
|
||||
_facetize_log_default(struct _ged_facetize_state *o)
|
||||
{
|
||||
if (fileno(stderr) < 0 || !o || !o->log_s)
|
||||
return;
|
||||
|
||||
/* Put stderr back */
|
||||
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
|
||||
if (log_s->fnull != -1) {
|
||||
fflush(stderr);
|
||||
dup2(log_s->stderr_stashed, log_s->serr);
|
||||
close(log_s->stderr_stashed);
|
||||
log_s->fnull = -1;
|
||||
}
|
||||
|
||||
/* Restore bu_bomb hooks to the application defaults */
|
||||
bu_bomb_delete_all_hooks();
|
||||
bu_bomb_restore_hooks(log_s->saved_bomb_hooks);
|
||||
|
||||
/* Restore bu_log hooks to the application defaults */
|
||||
bu_log_hook_delete_all();
|
||||
bu_log_hook_restore_all(log_s->saved_log_hooks);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static union tree *
|
||||
facetize_region_end(struct db_tree_state *tsp,
|
||||
const struct db_full_path *pathp,
|
||||
union tree *curtree,
|
||||
void *client_data)
|
||||
{
|
||||
union tree **facetize_tree;
|
||||
|
||||
if (tsp) RT_CK_DBTS(tsp);
|
||||
if (pathp) RT_CK_FULL_PATH(pathp);
|
||||
|
||||
struct _ged_facetize_state *s = (struct _ged_facetize_state *)client_data;
|
||||
facetize_tree = &s->facetize_tree;
|
||||
|
||||
if (curtree->tr_op == OP_NOP) return curtree;
|
||||
|
||||
if (*facetize_tree) {
|
||||
union tree *tr;
|
||||
BU_ALLOC(tr, union tree);
|
||||
RT_TREE_INIT(tr);
|
||||
tr->tr_op = OP_UNION;
|
||||
tr->tr_b.tb_regionp = REGION_NULL;
|
||||
tr->tr_b.tb_left = *facetize_tree;
|
||||
tr->tr_b.tb_right = curtree;
|
||||
*facetize_tree = tr;
|
||||
} else {
|
||||
*facetize_tree = curtree;
|
||||
}
|
||||
|
||||
/* Tree has been saved, and will be freed later */
|
||||
return TREE_NULL;
|
||||
}
|
||||
|
||||
|
||||
static union tree *
|
||||
facetize_nmg_leaf_tess(struct db_tree_state *tsp, const struct db_full_path *pathp, struct rt_db_internal *ip, void *client_data)
|
||||
{
|
||||
union tree *ret = rt_booltree_leaf_tess(tsp, pathp, ip, NULL);
|
||||
if (!ret) {
|
||||
struct _ged_facetize_state *s = (struct _ged_facetize_state *)client_data;
|
||||
if (s && s->tolerate_failures && pathp) {
|
||||
char *path_str = db_path_to_string(pathp);
|
||||
facetize_tolerated_failure(s, "NMG leaf tessellation failed for '%s'; leaf will be omitted from boolean evaluation", path_str ? path_str : "(unknown)");
|
||||
if (path_str)
|
||||
bu_free(path_str, "path string");
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
static struct model *
|
||||
_try_nmg_facetize(struct _ged_facetize_state *s, struct bu_list *vlfree, int argc, const char **argv)
|
||||
{
|
||||
struct db_i *dbip = s->dbip;
|
||||
int i;
|
||||
int failed = 0;
|
||||
struct db_tree_state init_state;
|
||||
union tree *facetize_tree;
|
||||
struct model *nmg_model;
|
||||
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
|
||||
|
||||
struct _ged_facetize_logging_state *log_s;
|
||||
BU_GET(log_s, struct _ged_facetize_logging_state);
|
||||
BU_GET(log_s->nmg_log, struct bu_vls);
|
||||
bu_vls_init(log_s->nmg_log);
|
||||
BU_GET(log_s->nmg_log_header, struct bu_vls);
|
||||
bu_vls_init(log_s->nmg_log_header);
|
||||
|
||||
s->log_s = log_s;
|
||||
|
||||
_facetize_log_nmg(s);
|
||||
|
||||
db_init_db_tree_state(&init_state, dbip);
|
||||
|
||||
|
||||
/* Establish tolerances */
|
||||
init_state.ts_ttol = &wdbp->wdb_ttol;
|
||||
init_state.ts_tol = &wdbp->wdb_tol;
|
||||
|
||||
s->facetize_tree = (union tree *)0;
|
||||
facetize_tree = (union tree *)0;
|
||||
nmg_model = nmg_mm();
|
||||
init_state.ts_m = &nmg_model;
|
||||
|
||||
if (!BU_SETJUMP) {
|
||||
/* try */
|
||||
i = db_walk_tree(dbip, argc, (const char **)argv,
|
||||
1,
|
||||
&init_state,
|
||||
0, /* take all regions */
|
||||
facetize_region_end,
|
||||
facetize_nmg_leaf_tess,
|
||||
(void *)s
|
||||
);
|
||||
} else {
|
||||
/* catch */
|
||||
BU_UNSETJUMP;
|
||||
_facetize_log_default(s);
|
||||
bu_vls_free(log_s->nmg_log_header);
|
||||
bu_vls_free(log_s->nmg_log);
|
||||
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s, struct _ged_facetize_logging_state);
|
||||
s->log_s = NULL;
|
||||
if (s->facetize_tree) {
|
||||
db_free_tree(s->facetize_tree);
|
||||
s->facetize_tree = NULL;
|
||||
}
|
||||
return NULL;
|
||||
} BU_UNSETJUMP;
|
||||
|
||||
facetize_tree = s->facetize_tree;
|
||||
|
||||
if (i < 0) {
|
||||
/* Destroy NMG */
|
||||
_facetize_log_default(s);
|
||||
bu_vls_free(log_s->nmg_log_header);
|
||||
bu_vls_free(log_s->nmg_log);
|
||||
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s, struct _ged_facetize_logging_state);
|
||||
s->log_s = NULL;
|
||||
if (s->facetize_tree) {
|
||||
db_free_tree(s->facetize_tree);
|
||||
s->facetize_tree = NULL;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (facetize_tree) {
|
||||
if (!BU_SETJUMP) {
|
||||
/* try */
|
||||
failed = nmg_boolean(facetize_tree, nmg_model, vlfree, &wdbp->wdb_tol);
|
||||
} else {
|
||||
/* catch */
|
||||
BU_UNSETJUMP;
|
||||
_facetize_log_default(s);
|
||||
bu_vls_free(log_s->nmg_log_header);
|
||||
bu_vls_free(log_s->nmg_log);
|
||||
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s, struct _ged_facetize_logging_state);
|
||||
s->log_s = NULL;
|
||||
if (s->facetize_tree) {
|
||||
db_free_tree(s->facetize_tree);
|
||||
s->facetize_tree = NULL;
|
||||
}
|
||||
return NULL;
|
||||
} BU_UNSETJUMP;
|
||||
|
||||
} else {
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
if (!failed && facetize_tree) {
|
||||
NMG_CK_REGION(facetize_tree->tr_d.td_r);
|
||||
facetize_tree->tr_d.td_r = (struct nmgregion *)NULL;
|
||||
}
|
||||
|
||||
if (failed && s->tolerate_failures) {
|
||||
facetize_tolerated_failure(s, "NMG boolean evaluation failed after leaf tessellation; no partial NMG result could be generated for this tree");
|
||||
}
|
||||
|
||||
if (facetize_tree) {
|
||||
db_free_tree(facetize_tree);
|
||||
s->facetize_tree = NULL;
|
||||
}
|
||||
|
||||
_facetize_log_default(s);
|
||||
bu_vls_free(log_s->nmg_log_header);
|
||||
bu_vls_free(log_s->nmg_log);
|
||||
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
|
||||
BU_PUT(log_s, struct _ged_facetize_logging_state);
|
||||
s->log_s = NULL;
|
||||
return (failed) ? NULL : nmg_model;
|
||||
}
|
||||
|
||||
static int
|
||||
_write_nmg(struct _ged_facetize_state *s, struct model *nmg_model, const char *name)
|
||||
{
|
||||
struct db_i *dbip = s->dbip;
|
||||
struct rt_db_internal intern;
|
||||
struct directory *dp;
|
||||
|
||||
/* Export NMG as a new solid */
|
||||
RT_DB_INTERNAL_INIT(&intern);
|
||||
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
|
||||
intern.idb_type = ID_NMG;
|
||||
intern.idb_meth = &OBJ[ID_NMG];
|
||||
intern.idb_ptr = (void *)nmg_model;
|
||||
|
||||
dp = db_diradd(dbip, name, RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&intern.idb_type);
|
||||
if (dp == RT_DIR_NULL) {
|
||||
if (s->verbosity > 0) {
|
||||
bu_log("Cannot add %s to directory\n", name);
|
||||
}
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
if (rt_db_put_internal(dp, dbip, &intern) < 0) {
|
||||
if (s->verbosity > 0) {
|
||||
bu_log("Failed to write %s to database\n", name);
|
||||
}
|
||||
rt_db_free_internal(&intern);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
|
||||
static int
|
||||
_write_bot(struct _ged_facetize_state *s, struct rt_bot_internal *bot, const char *name)
|
||||
{
|
||||
struct db_i *dbip = s->dbip;
|
||||
struct rt_db_internal intern;
|
||||
struct directory *dp;
|
||||
|
||||
/* Export BoT as a new solid */
|
||||
RT_DB_INTERNAL_INIT(&intern);
|
||||
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
|
||||
intern.idb_type = ID_BOT;
|
||||
intern.idb_meth = &OBJ[ID_BOT];
|
||||
intern.idb_ptr = (void *)bot;
|
||||
|
||||
dp = db_diradd(dbip, name, RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&intern.idb_type);
|
||||
if (dp == RT_DIR_NULL) {
|
||||
if (s->verbosity > 0) {
|
||||
bu_log("Cannot add %s to directory\n", name);
|
||||
}
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
if (rt_db_put_internal(dp, dbip, &intern) < 0) {
|
||||
if (s->verbosity > 0) {
|
||||
bu_log("Failed to write %s to database\n", name);
|
||||
}
|
||||
rt_db_free_internal(&intern);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
static const int FACETIZE_NMG_POLL_USEC = 1000;
|
||||
static const char FACETIZE_NMG_RESULT_FILE[] = "nmg_boolean_result.g";
|
||||
|
||||
int
|
||||
_ged_facetize_nmgeval(struct _ged_facetize_state *s, int argc, const char **argv, const char *oname)
|
||||
_ged_facetize_nmgeval(struct _ged_facetize_state *s,
|
||||
struct db_i *target_dbip, const char *database_path,
|
||||
const std::vector<std::string> &input_names, const char *output_name)
|
||||
{
|
||||
int ret = BRLCAD_OK;
|
||||
struct db_i *dbip = s->dbip;
|
||||
struct rt_wdb *wdbp;
|
||||
struct rt_bot_internal *bot = NULL;
|
||||
struct bu_list *vlfree = &rt_vlfree;
|
||||
struct model *nmg_model = _try_nmg_facetize(s, vlfree, argc, argv);
|
||||
if (!s || !target_dbip || !database_path || !database_path[0] ||
|
||||
input_names.empty() || !output_name || !output_name[0] || !s->wdir)
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
if (nmg_model == NULL) {
|
||||
if (s->verbosity > 1) {
|
||||
bu_log("NMG(%s): no resulting region, aborting\n", oname);
|
||||
FacetizeWorkerRequest request;
|
||||
request.operation = s->execution.writes_nmg() ?
|
||||
FacetizeWorkerOperation::NmgBooleanToNmg :
|
||||
FacetizeWorkerOperation::NmgBooleanToBot;
|
||||
request.input_names = input_names;
|
||||
request.output_name = output_name;
|
||||
if (!request.valid())
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
char result_file[MAXPATHLEN];
|
||||
bu_dir(result_file, MAXPATHLEN, s->wdir, FACETIZE_NMG_RESULT_FILE, NULL);
|
||||
(void)bu_file_delete(result_file);
|
||||
|
||||
char executable[MAXPATHLEN];
|
||||
bu_dir(executable, MAXPATHLEN, BU_DIR_BIN, "ged_exec", BU_DIR_EXT, NULL);
|
||||
std::vector<std::string> command;
|
||||
command.push_back(executable);
|
||||
command.push_back("facetize_process");
|
||||
command.push_back(database_path);
|
||||
|
||||
struct bu_process *process = NULL;
|
||||
FILE *process_input = NULL;
|
||||
FacetizeWorkerClient channel;
|
||||
if (facetize_process_start(&process, &process_input, channel, command,
|
||||
result_file, "--nmg-server") != BRLCAD_OK) {
|
||||
(void)bu_file_delete(result_file);
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: unable to start the NMG Boolean worker for %s\n",
|
||||
output_name);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
if (!channel.send_request(request)) {
|
||||
(void)facetize_process_stop(s, &process, process_input, channel, true);
|
||||
(void)bu_file_delete(result_file);
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: unable to submit %s to the NMG Boolean worker\n",
|
||||
output_name);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
facetize_log(s, 1, "FACETIZE: evaluating %s with NMG Boolean...\n",
|
||||
output_name);
|
||||
FacetizeWorkerStatus status;
|
||||
int64_t request_start = bu_gettime();
|
||||
int64_t write_deadline = 0;
|
||||
bool write_permitted = false;
|
||||
bool interrupted = false;
|
||||
bool evaluation_timed_out = false;
|
||||
bool write_timed_out = false;
|
||||
while (!status.result_received) {
|
||||
facetize_process_drain_stdout(s, process, channel, &status);
|
||||
facetize_process_drain_stderr(s, process);
|
||||
|
||||
int64_t now = bu_gettime();
|
||||
if (status.write_ready && !write_permitted) {
|
||||
if (s->max_time > 0 && now - request_start >=
|
||||
BU_SEC2USEC(s->max_time)) {
|
||||
interrupted = true;
|
||||
evaluation_timed_out = true;
|
||||
break;
|
||||
}
|
||||
write_permitted = true;
|
||||
double write_timeout = facetize_write_timeout_seconds(
|
||||
status.payload_size, 0.0, 0.0);
|
||||
write_deadline = now + BU_SEC2USEC(write_timeout);
|
||||
if (!channel.send_write_proceed()) {
|
||||
interrupted = true;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
ret = BRLCAD_ERROR;
|
||||
goto ged_nmg_obj_memfree;
|
||||
if (status.result_received) {
|
||||
if (status.write_started && !status.write_done)
|
||||
interrupted = true;
|
||||
break;
|
||||
}
|
||||
if (bu_process_poll(process, NULL) != 0) {
|
||||
/* The final status may reach the pipe just before process exit.
|
||||
* Drain once more before deciding the worker was interrupted. */
|
||||
facetize_process_drain_stdout(s, process, channel, &status);
|
||||
facetize_process_drain_stderr(s, process);
|
||||
interrupted = !status.result_received ||
|
||||
(status.write_started && !status.write_done);
|
||||
break;
|
||||
}
|
||||
if (!write_permitted && s->max_time > 0 &&
|
||||
now - request_start >= BU_SEC2USEC(s->max_time)) {
|
||||
interrupted = true;
|
||||
evaluation_timed_out = true;
|
||||
break;
|
||||
}
|
||||
if (write_permitted && now >= write_deadline) {
|
||||
interrupted = true;
|
||||
write_timed_out = true;
|
||||
break;
|
||||
}
|
||||
(void)bu_snooze(FACETIZE_NMG_POLL_USEC);
|
||||
}
|
||||
|
||||
if (!s->make_nmg) {
|
||||
|
||||
wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
|
||||
if (!BU_SETJUMP) {
|
||||
/* try */
|
||||
bot = (struct rt_bot_internal *)nmg_mdl_to_bot(nmg_model, vlfree, &wdbp->wdb_tol);
|
||||
} else {
|
||||
/* catch */
|
||||
BU_UNSETJUMP;
|
||||
return BRLCAD_ERROR;
|
||||
} BU_UNSETJUMP;
|
||||
|
||||
ret = _write_bot(s, bot, oname);
|
||||
int process_status = facetize_process_stop(s, &process, process_input,
|
||||
channel, interrupted);
|
||||
int ret = BRLCAD_ERROR;
|
||||
if (!interrupted && process_status == BRLCAD_OK &&
|
||||
status.result_received && status.write_done &&
|
||||
status.result == BRLCAD_OK) {
|
||||
int expected_type = request.operation ==
|
||||
FacetizeWorkerOperation::NmgBooleanToNmg ? ID_NMG : ID_BOT;
|
||||
ret = facetize_transfer_staged_object(target_dbip, result_file,
|
||||
output_name, expected_type);
|
||||
}
|
||||
(void)bu_file_delete(result_file);
|
||||
|
||||
if (ret == BRLCAD_OK) {
|
||||
facetize_log(s, 1,
|
||||
"FACETIZE: NMG Boolean evaluation succeeded for %s\n",
|
||||
output_name);
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
if (evaluation_timed_out) {
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: NMG Boolean evaluation timed out after %d seconds for %s\n",
|
||||
s->max_time, output_name);
|
||||
} else if (write_timed_out) {
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: staging the NMG Boolean result timed out for %s\n",
|
||||
output_name);
|
||||
} else if (interrupted) {
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: NMG Boolean worker exited while processing %s\n",
|
||||
output_name);
|
||||
} else if (process_status != BRLCAD_OK) {
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: NMG Boolean worker exited abnormally after processing %s\n",
|
||||
output_name);
|
||||
} else if (status.result != BRLCAD_OK) {
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: NMG Boolean evaluation failed for %s\n",
|
||||
output_name);
|
||||
} else {
|
||||
|
||||
/* Write the NMG */
|
||||
ret = _write_nmg(s, nmg_model, oname);
|
||||
|
||||
facetize_log(s, 0,
|
||||
"FACETIZE: unable to transfer the staged NMG Boolean result for %s\n",
|
||||
output_name);
|
||||
}
|
||||
|
||||
ged_nmg_obj_memfree:
|
||||
if (s->verbosity >= 0 && ret != BRLCAD_OK) {
|
||||
bu_log("NMG: failed to generate %s\n", oname);
|
||||
}
|
||||
|
||||
return ret;
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,92 +0,0 @@
|
||||
/* O L D _ F A C E T I Z E . H
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2008-2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this file; see the file named COPYING for more
|
||||
* information.
|
||||
*/
|
||||
/** @file libged/old_facetize.h
|
||||
*
|
||||
* The facetize command, circa v7.38.2
|
||||
*
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
#include "vmath.h"
|
||||
#include "bu.h"
|
||||
#include "bg.h"
|
||||
|
||||
__BEGIN_DECLS
|
||||
|
||||
/* Ideally all of this could be in facetize.cpp, but the open() calls
|
||||
* used by the logging routines are problematic in C++ with Visual C++. */
|
||||
struct _old_ged_facetize_opts {
|
||||
int quiet;
|
||||
int verbosity;
|
||||
int regions;
|
||||
int resume;
|
||||
int retry;
|
||||
int in_place;
|
||||
fastf_t feature_size;
|
||||
fastf_t feature_scale;
|
||||
fastf_t d_feature_size;
|
||||
int max_time;
|
||||
struct bg_tess_tol *tol;
|
||||
struct bu_vls *faceted_suffix;
|
||||
|
||||
/* NMG specific options */
|
||||
int triangulate;
|
||||
int make_nmg;
|
||||
int nmgbool;
|
||||
int manifold;
|
||||
int screened_poisson;
|
||||
int continuation;
|
||||
int method_flags;
|
||||
int nmg_use_tnurbs;
|
||||
|
||||
/* Poisson specific options */
|
||||
int max_pnts;
|
||||
struct bg_3d_spsr_opts s_opts;
|
||||
|
||||
/* Brep specific options */
|
||||
double nonovlp_threshold;
|
||||
|
||||
/* internal */
|
||||
struct bu_attribute_value_set *c_map;
|
||||
struct bu_attribute_value_set *s_map;
|
||||
struct bu_hook_list *saved_bomb_hooks;
|
||||
struct bu_hook_list *saved_log_hooks;
|
||||
struct bu_vls *nmg_log;
|
||||
struct bu_vls *nmg_log_header;
|
||||
int nmg_log_print_header;
|
||||
int stderr_stashed;
|
||||
int serr;
|
||||
int fnull;
|
||||
|
||||
struct bu_vls *froot;
|
||||
struct bu_vls *manifold_comb;
|
||||
struct bu_vls *nmg_comb;
|
||||
struct bu_vls *continuation_comb;
|
||||
struct bu_vls *spsr_comb;
|
||||
};
|
||||
|
||||
extern void
|
||||
_old_ged_facetize_log_nmg(struct _old_ged_facetize_opts *o);
|
||||
|
||||
extern void
|
||||
_old_ged_facetize_log_default(struct _old_ged_facetize_opts *o);
|
||||
|
||||
__END_DECLS
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
/* F A C E T I Z E _ L O G . C
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2008-2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this file; see the file named COPYING for more
|
||||
* information.
|
||||
*/
|
||||
/** @file libged/facetize_log.c
|
||||
*
|
||||
* logging mechanisms for the facetize command.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "bio.h"
|
||||
|
||||
#include "bu/hook.h"
|
||||
#include "bu/vls.h"
|
||||
#include "../ged_private.h"
|
||||
#include "./old_facetize.h"
|
||||
|
||||
static int
|
||||
_ged_facetize_bomb_hook(void *cdata, void *str)
|
||||
{
|
||||
struct _old_ged_facetize_opts *o = (struct _old_ged_facetize_opts *)cdata;
|
||||
if (o->nmg_log_print_header) {
|
||||
bu_vls_printf(o->nmg_log, "%s\n", bu_vls_addr(o->nmg_log_header));
|
||||
o->nmg_log_print_header = 0;
|
||||
}
|
||||
bu_vls_printf(o->nmg_log, "%s\n", (const char *)str);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
_ged_facetize_nmg_logging_hook(void *data, void *str)
|
||||
{
|
||||
struct _old_ged_facetize_opts *o = (struct _old_ged_facetize_opts *)data;
|
||||
if (o->nmg_log_print_header) {
|
||||
bu_vls_printf(o->nmg_log, "%s\n", bu_vls_addr(o->nmg_log_header));
|
||||
o->nmg_log_print_header = 0;
|
||||
}
|
||||
bu_vls_printf(o->nmg_log, "%s\n", (const char *)str);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
_old_ged_facetize_log_nmg(struct _old_ged_facetize_opts *o)
|
||||
{
|
||||
if (fileno(stderr) < 0)
|
||||
return;
|
||||
|
||||
/* Seriously, bu_bomb, we don't want you blathering
|
||||
* to stderr... shut down stderr temporarily. */
|
||||
o->fnull = open(bu_file_null(), O_WRONLY);
|
||||
if (o->fnull != -1) {
|
||||
o->serr = fileno(stderr);
|
||||
o->stderr_stashed = dup(o->serr);
|
||||
dup2(o->fnull, o->serr);
|
||||
close(o->fnull);
|
||||
}
|
||||
|
||||
/* Set bu_log logging to capture in nmg_log, rather than the
|
||||
* application defaults */
|
||||
bu_log_hook_delete_all();
|
||||
bu_log_add_hook(_ged_facetize_nmg_logging_hook, (void *)o);
|
||||
|
||||
/* Also engage the nmg bomb hooks */
|
||||
bu_bomb_delete_all_hooks();
|
||||
bu_bomb_add_hook(_ged_facetize_bomb_hook, (void *)o);
|
||||
}
|
||||
|
||||
|
||||
void
|
||||
_old_ged_facetize_log_default(struct _old_ged_facetize_opts *o)
|
||||
{
|
||||
if (fileno(stderr) < 0)
|
||||
return;
|
||||
|
||||
/* Put stderr back */
|
||||
if (o->fnull != -1) {
|
||||
fflush(stderr);
|
||||
dup2(o->stderr_stashed, o->serr);
|
||||
close(o->stderr_stashed);
|
||||
o->fnull = -1;
|
||||
}
|
||||
|
||||
/* Restore bu_bomb hooks to the application defaults */
|
||||
bu_bomb_delete_all_hooks();
|
||||
bu_bomb_restore_hooks(o->saved_bomb_hooks);
|
||||
|
||||
/* Restore bu_log hooks to the application defaults */
|
||||
bu_log_hook_delete_all();
|
||||
bu_log_hook_restore_all(o->saved_log_hooks);
|
||||
}
|
||||
|
||||
/*
|
||||
* Local Variables:
|
||||
* tab-width: 8
|
||||
* mode: C
|
||||
* indent-tabs-mode: t
|
||||
* c-file-style: "stroustrup"
|
||||
* End:
|
||||
* ex: shiftwidth=4 tabstop=8
|
||||
*/
|
||||
@@ -0,0 +1,363 @@
|
||||
/* O R C H E S T R A T O R . C P P
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*/
|
||||
/** @file libged/facetize/orchestrator.cpp
|
||||
*
|
||||
* Command planning, session lifetime, and workspace ownership for facetize.
|
||||
*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "bu/app.h"
|
||||
#include "bu/file.h"
|
||||
#include "bu/path.h"
|
||||
#include "bu/vls.h"
|
||||
|
||||
#include "../ged_private.h"
|
||||
#include "./ged_facetize.h"
|
||||
#include "./tess_opts.h"
|
||||
|
||||
static const unsigned int FACETIZE_WORKSPACE_SCHEMA = 1;
|
||||
static const char FACETIZE_MANIFEST_NAME[] = "request.manifest";
|
||||
|
||||
std::vector<const char *>
|
||||
FacetizePlan::input_argv() const
|
||||
{
|
||||
std::vector<const char *> argv;
|
||||
argv.reserve(inputs.size());
|
||||
for (const std::string &input : inputs)
|
||||
argv.push_back(input.c_str());
|
||||
return argv;
|
||||
}
|
||||
|
||||
static struct _ged_facetize_state *
|
||||
facetize_state_create()
|
||||
{
|
||||
struct _ged_facetize_state *s = NULL;
|
||||
BU_GET(s, struct _ged_facetize_state);
|
||||
s->verbosity = 0;
|
||||
s->no_empty = 0;
|
||||
s->no_fixup = 0;
|
||||
s->use_variant_plan = 1;
|
||||
s->tolerate_failures = 0;
|
||||
s->tolerated_failures = 0;
|
||||
s->tolerated_failure_details = 0;
|
||||
s->tolerated_failure_omitted = 0;
|
||||
s->inspection_regions = 0;
|
||||
s->perturb_sa_tol = 10.0;
|
||||
s->perturb_vol_tol = 10.0;
|
||||
s->wdir = NULL;
|
||||
s->cleanup_workspace = false;
|
||||
|
||||
BU_GET(s->log_file, struct bu_vls);
|
||||
bu_vls_init(s->log_file);
|
||||
s->log_file_is_temporary = 0;
|
||||
s->lfile = NULL;
|
||||
|
||||
BU_GET(s->failure_msg, struct bu_vls);
|
||||
bu_vls_init(s->failure_msg);
|
||||
BU_GET(s->tolerated_failure_log, struct bu_vls);
|
||||
bu_vls_init(s->tolerated_failure_log);
|
||||
BU_GET(s->region_summary, struct bu_vls);
|
||||
bu_vls_init(s->region_summary);
|
||||
BU_GET(s->primitive_summary, struct bu_vls);
|
||||
bu_vls_init(s->primitive_summary);
|
||||
BU_GET(s->inspection_log, struct bu_vls);
|
||||
bu_vls_init(s->inspection_log);
|
||||
BU_GET(s->wfile, struct bu_vls);
|
||||
bu_vls_init(s->wfile);
|
||||
BU_GET(s->bname, struct bu_vls);
|
||||
bu_vls_init(s->bname);
|
||||
BU_GET(s->suffix, struct bu_vls);
|
||||
bu_vls_init(s->suffix);
|
||||
BU_GET(s->prefix, struct bu_vls);
|
||||
bu_vls_init(s->prefix);
|
||||
BU_GET(s->solid_suffix, struct bu_vls);
|
||||
bu_vls_init(s->solid_suffix);
|
||||
bu_vls_sprintf(s->solid_suffix, ".bot");
|
||||
|
||||
s->resume = 0;
|
||||
s->max_time = 0;
|
||||
s->max_pnts = 0;
|
||||
s->max_workers = 0;
|
||||
s->tol = NULL;
|
||||
s->nonovlp_threshold = 0;
|
||||
s->error_flag = 0;
|
||||
s->gedp = NULL;
|
||||
s->dbip = NULL;
|
||||
s->facetize_tree = NULL;
|
||||
s->method_opts = NULL;
|
||||
s->write_profiled = 0;
|
||||
s->write_profile_bytes = 0.0;
|
||||
s->write_profile_usec = 0.0;
|
||||
s->variant_plan = NULL;
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
static void
|
||||
facetize_state_destroy(struct _ged_facetize_state *s)
|
||||
{
|
||||
if (!s)
|
||||
return;
|
||||
|
||||
if (s->lfile)
|
||||
fclose(s->lfile);
|
||||
/* Windows cannot delete the workspace while its log is still open. */
|
||||
if (s->cleanup_workspace)
|
||||
bu_dirclear(s->wdir);
|
||||
if (s->wdir)
|
||||
bu_free(s->wdir, "wdir");
|
||||
|
||||
struct bu_vls *strings[] = {
|
||||
s->bname, s->log_file, s->failure_msg, s->tolerated_failure_log,
|
||||
s->region_summary, s->primitive_summary, s->inspection_log, s->wfile,
|
||||
s->prefix, s->suffix, s->solid_suffix
|
||||
};
|
||||
for (struct bu_vls *str : strings) {
|
||||
if (!str)
|
||||
continue;
|
||||
bu_vls_free(str);
|
||||
BU_PUT(str, struct bu_vls);
|
||||
}
|
||||
|
||||
delete (FacetizeVariantPlan *)s->variant_plan;
|
||||
BU_PUT(s, struct _ged_facetize_state);
|
||||
}
|
||||
|
||||
FacetizeSession::FacetizeSession(struct ged *gedp)
|
||||
{
|
||||
methods = new method_options_t;
|
||||
session_state = facetize_state_create();
|
||||
session_state->gedp = gedp;
|
||||
session_state->dbip = gedp->dbip;
|
||||
session_state->method_opts = methods;
|
||||
}
|
||||
|
||||
FacetizeSession::~FacetizeSession()
|
||||
{
|
||||
facetize_summary(session_state);
|
||||
facetize_state_destroy(session_state);
|
||||
delete methods;
|
||||
}
|
||||
|
||||
int
|
||||
facetize_build_plan(struct _ged_facetize_state *s, int argc,
|
||||
const char **argv, FacetizePlan &plan)
|
||||
{
|
||||
if (!s || !s->dbip || argc <= 0 || !argv)
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
plan.execution = s->execution;
|
||||
plan.inputs.clear();
|
||||
plan.output.clear();
|
||||
|
||||
std::vector<std::string> missing;
|
||||
for (int i = 0; i < argc; i++) {
|
||||
if (db_lookup(s->dbip, argv[i], LOOKUP_QUIET) == RT_DIR_NULL)
|
||||
missing.emplace_back(argv[i]);
|
||||
else
|
||||
plan.inputs.emplace_back(argv[i]);
|
||||
}
|
||||
|
||||
if (plan.execution.writes_in_place()) {
|
||||
if (!missing.empty()) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"In-place conversion requires every input object to exist:\n");
|
||||
for (const std::string &name : missing)
|
||||
bu_vls_printf(s->gedp->ged_result_str, " %s\n", name.c_str());
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
} else {
|
||||
if (missing.size() != 1) {
|
||||
if (missing.empty())
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"A new output object name is required.\n");
|
||||
else
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"Exactly one new output object name is required; found %zu.\n",
|
||||
missing.size());
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
plan.output = missing.front();
|
||||
}
|
||||
|
||||
if (plan.inputs.empty()) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"No existing input objects were specified.\n");
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
|
||||
static std::string
|
||||
facetize_request_signature(struct _ged_facetize_state *s,
|
||||
const FacetizePlan &plan, const char *source_path,
|
||||
const struct stat &source_stat)
|
||||
{
|
||||
std::ostringstream signature;
|
||||
signature << "schema=" << FACETIZE_WORKSPACE_SCHEMA << '\n';
|
||||
signature << "source=" << source_path << '\n';
|
||||
signature << "source_size=" << source_stat.st_size << '\n';
|
||||
signature << "source_mtime=" << source_stat.st_mtime << '\n';
|
||||
signature << "scope=" << static_cast<int>(plan.execution.scope) << '\n';
|
||||
signature << "engine=" << static_cast<int>(plan.execution.boolean_engine) << '\n';
|
||||
signature << "output_format=" << static_cast<int>(plan.execution.output_format) << '\n';
|
||||
signature << "commit=" << static_cast<int>(plan.execution.commit_mode) << '\n';
|
||||
signature << "perturb=" << static_cast<int>(plan.execution.perturb_mode) << '\n';
|
||||
signature << "no_empty=" << s->no_empty << '\n';
|
||||
signature << "no_fixup=" << s->no_fixup << '\n';
|
||||
signature << "tolerate_failures=" << s->tolerate_failures << '\n';
|
||||
signature << "max_time=" << s->max_time << '\n';
|
||||
signature << "max_pnts=" << s->max_pnts << '\n';
|
||||
signature << "max_workers=" << s->max_workers << '\n';
|
||||
signature << "perturb_sa_tol=" << s->perturb_sa_tol << '\n';
|
||||
signature << "perturb_vol_tol=" << s->perturb_vol_tol << '\n';
|
||||
signature << "prefix=" << bu_vls_cstr(s->prefix) << '\n';
|
||||
signature << "suffix=" << bu_vls_cstr(s->suffix) << '\n';
|
||||
signature << "output=" << plan.output << '\n';
|
||||
for (const std::string &input : plan.inputs)
|
||||
signature << "input=" << input << '\n';
|
||||
|
||||
method_options_t *methods = (method_options_t *)s->method_opts;
|
||||
if (methods) {
|
||||
for (const std::string &method : methods->methods)
|
||||
signature << "method=" << method << '\n';
|
||||
for (const auto &method_entry : methods->options_map)
|
||||
for (const auto &option_entry : method_entry.second)
|
||||
signature << "method_option=" << method_entry.first << ':'
|
||||
<< option_entry.first << '=' << option_entry.second << '\n';
|
||||
}
|
||||
return signature.str();
|
||||
}
|
||||
|
||||
static bool
|
||||
read_file(const char *path, std::string &contents)
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
if (!input)
|
||||
return false;
|
||||
std::ostringstream buffer;
|
||||
buffer << input.rdbuf();
|
||||
contents = buffer.str();
|
||||
return input.good() || input.eof();
|
||||
}
|
||||
|
||||
static bool
|
||||
write_file(const char *path, const std::string &contents)
|
||||
{
|
||||
std::ofstream output(path, std::ios::binary | std::ios::trunc);
|
||||
if (!output)
|
||||
return false;
|
||||
output.write(contents.data(), (std::streamsize)contents.size());
|
||||
return output.good();
|
||||
}
|
||||
|
||||
int
|
||||
facetize_prepare_workspace(struct _ged_facetize_state *s,
|
||||
const FacetizePlan &plan)
|
||||
{
|
||||
char source_path[MAXPATHLEN];
|
||||
if (!bu_file_realpath(s->dbip->dbi_filename, source_path)) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"Unable to resolve database path '%s'.\n", s->dbip->dbi_filename);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
struct stat source_stat;
|
||||
if (stat(source_path, &source_stat) != 0) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"Unable to inspect database '%s'.\n", source_path);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
bu_path_component(s->bname, source_path, BU_PATH_BASENAME);
|
||||
unsigned long long path_hash = bu_data_hash(source_path, strlen(source_path));
|
||||
struct bu_vls workspace_name = BU_VLS_INIT_ZERO;
|
||||
bu_vls_sprintf(&workspace_name, "facetize_%llu", path_hash);
|
||||
s->wdir = (char *)bu_calloc(MAXPATHLEN, sizeof(char), "facetize workspace");
|
||||
bu_dir(s->wdir, MAXPATHLEN, BU_DIR_CACHE, bu_vls_cstr(&workspace_name), NULL);
|
||||
|
||||
bool workspace_exists = bu_file_directory(s->wdir);
|
||||
if (!s->resume && workspace_exists)
|
||||
bu_dirclear(s->wdir);
|
||||
if (!bu_file_directory(s->wdir))
|
||||
bu_mkdir(s->wdir);
|
||||
if (!bu_file_directory(s->wdir)) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"Unable to create facetize workspace '%s'.\n", s->wdir);
|
||||
bu_vls_free(&workspace_name);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
char manifest_path[MAXPATHLEN];
|
||||
bu_dir(manifest_path, MAXPATHLEN, s->wdir, FACETIZE_MANIFEST_NAME, NULL);
|
||||
std::string expected_manifest = facetize_request_signature(s, plan,
|
||||
source_path, source_stat);
|
||||
if (s->resume) {
|
||||
std::string actual_manifest;
|
||||
if (!read_file(manifest_path, actual_manifest) || actual_manifest != expected_manifest) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"Cannot resume: workspace does not match the database and facetize options.\n");
|
||||
bu_vls_free(&workspace_name);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
} else if (!write_file(manifest_path, expected_manifest)) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"Unable to write facetize workspace manifest '%s'.\n", manifest_path);
|
||||
bu_vls_free(&workspace_name);
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
if (!bu_vls_strlen(s->log_file)) {
|
||||
char log_path[MAXPATHLEN];
|
||||
s->log_file_is_temporary = 1;
|
||||
bu_vls_sprintf(&workspace_name, "facetize_%s.log", bu_vls_cstr(s->bname));
|
||||
bu_dir(log_path, MAXPATHLEN, s->wdir, bu_vls_cstr(&workspace_name), NULL);
|
||||
bu_vls_sprintf(s->log_file, "%s", log_path);
|
||||
}
|
||||
bu_vls_free(&workspace_name);
|
||||
|
||||
s->lfile = fopen(bu_vls_cstr(s->log_file), "a");
|
||||
if (!s->lfile) {
|
||||
bu_vls_printf(s->gedp->ged_result_str,
|
||||
"Unable to open log file %s for writing\n", bu_vls_cstr(s->log_file));
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
|
||||
int
|
||||
facetize_execute_plan(struct _ged_facetize_state *s,
|
||||
const FacetizePlan &plan)
|
||||
{
|
||||
if (plan.execution.processes_breps())
|
||||
return _nonovlp_brep_facetize(s, plan);
|
||||
if (plan.execution.processes_regions())
|
||||
return _ged_facetize_regions(s, plan);
|
||||
return _ged_facetize_objs(s, plan);
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
// tab-width: 8
|
||||
// mode: C++
|
||||
// c-basic-offset: 4
|
||||
// indent-tabs-mode: t
|
||||
// c-file-style: "stroustrup"
|
||||
// End:
|
||||
// ex: shiftwidth=4 tabstop=8
|
||||
@@ -0,0 +1,96 @@
|
||||
/* O R C H E S T R A T O R . H
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*/
|
||||
|
||||
#ifndef LIBGED_FACETIZE_ORCHESTRATOR_H
|
||||
#define LIBGED_FACETIZE_ORCHESTRATOR_H
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "bu/defines.h"
|
||||
|
||||
struct ged;
|
||||
struct _ged_facetize_state;
|
||||
class method_options_t;
|
||||
|
||||
enum class FacetizeOutputFormat {
|
||||
Bot,
|
||||
Nmg
|
||||
};
|
||||
|
||||
enum class FacetizeBooleanEngine {
|
||||
Manifold,
|
||||
Nmg
|
||||
};
|
||||
|
||||
enum class FacetizeScope {
|
||||
Objects,
|
||||
Regions,
|
||||
NonOverlappingBrep
|
||||
};
|
||||
|
||||
enum class FacetizeCommitMode {
|
||||
NewObject,
|
||||
InPlace
|
||||
};
|
||||
|
||||
enum class FacetizePerturbMode {
|
||||
Disabled,
|
||||
Enabled
|
||||
};
|
||||
|
||||
struct FacetizeExecutionOptions {
|
||||
FacetizeOutputFormat output_format = FacetizeOutputFormat::Bot;
|
||||
FacetizeBooleanEngine boolean_engine = FacetizeBooleanEngine::Manifold;
|
||||
FacetizeScope scope = FacetizeScope::Objects;
|
||||
FacetizeCommitMode commit_mode = FacetizeCommitMode::NewObject;
|
||||
FacetizePerturbMode perturb_mode = FacetizePerturbMode::Disabled;
|
||||
|
||||
bool writes_nmg() const { return output_format == FacetizeOutputFormat::Nmg; }
|
||||
bool uses_nmg_boolean() const { return boolean_engine == FacetizeBooleanEngine::Nmg; }
|
||||
bool processes_regions() const { return scope == FacetizeScope::Regions; }
|
||||
bool processes_breps() const { return scope == FacetizeScope::NonOverlappingBrep; }
|
||||
bool writes_in_place() const { return commit_mode == FacetizeCommitMode::InPlace; }
|
||||
bool uses_perturbation() const { return perturb_mode == FacetizePerturbMode::Enabled; }
|
||||
};
|
||||
|
||||
struct FacetizePlan {
|
||||
FacetizeExecutionOptions execution;
|
||||
std::vector<std::string> inputs;
|
||||
std::string output;
|
||||
|
||||
std::vector<const char *> input_argv() const;
|
||||
};
|
||||
|
||||
class FacetizeSession {
|
||||
public:
|
||||
explicit FacetizeSession(struct ged *gedp);
|
||||
~FacetizeSession();
|
||||
|
||||
FacetizeSession(const FacetizeSession &) = delete;
|
||||
FacetizeSession &operator=(const FacetizeSession &) = delete;
|
||||
|
||||
struct _ged_facetize_state *state() const { return session_state; }
|
||||
method_options_t *method_options() const { return methods; }
|
||||
|
||||
private:
|
||||
struct _ged_facetize_state *session_state = nullptr;
|
||||
method_options_t *methods = nullptr;
|
||||
};
|
||||
|
||||
int facetize_build_plan(struct _ged_facetize_state *s, int argc,
|
||||
const char **argv, FacetizePlan &plan);
|
||||
int facetize_prepare_workspace(struct _ged_facetize_state *s,
|
||||
const FacetizePlan &plan);
|
||||
int facetize_execute_plan(struct _ged_facetize_state *s,
|
||||
const FacetizePlan &plan);
|
||||
|
||||
#endif /* LIBGED_FACETIZE_ORCHESTRATOR_H */
|
||||
@@ -344,7 +344,10 @@ create_variant_in_working_g(struct db_i *wdbip,
|
||||
point_t bmin, bmax;
|
||||
/* If bounds fail, keep -1 and fall back to the non-micro/default floor. */
|
||||
fastf_t bbox_diag = -1.0;
|
||||
if (rt_bound_internal(src_dbip, src_dp, bmin, bmax) == 0)
|
||||
struct bn_tol tol;
|
||||
BN_TOL_INIT(&tol);
|
||||
if (src_intern.idb_meth && src_intern.idb_meth->ft_bbox &&
|
||||
src_intern.idb_meth->ft_bbox(&src_intern, &bmin, &bmax, &tol) == 0)
|
||||
bbox_diag = DIST_PNT_PNT(bmin, bmax);
|
||||
|
||||
fastf_t factor = variant_perturb_factor(src_name, is_sub, idx, bbox_diag);
|
||||
@@ -395,7 +398,8 @@ create_variant_in_working_g(struct db_i *wdbip,
|
||||
FacetizeVariantPlan *
|
||||
_ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
|
||||
int argc,
|
||||
struct directory **dpa)
|
||||
struct directory **dpa,
|
||||
struct db_i *working_dbip)
|
||||
{
|
||||
if (!s || !s->dbip || argc <= 0 || !dpa)
|
||||
return NULL;
|
||||
@@ -427,18 +431,22 @@ _ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
|
||||
* name is not in dbnames, then insert the chosen name into
|
||||
* dbnames to reserve it for subsequent instances.
|
||||
* ============================================================ */
|
||||
struct db_i *wdbip =
|
||||
db_open(bu_vls_cstr(s->wfile), DB_OPEN_READWRITE);
|
||||
struct db_i *wdbip = working_dbip;
|
||||
bool close_wdbip = false;
|
||||
if (!wdbip) {
|
||||
delete plan;
|
||||
return NULL;
|
||||
wdbip = db_open(bu_vls_cstr(s->wfile), DB_OPEN_READWRITE);
|
||||
if (!wdbip) {
|
||||
delete plan;
|
||||
return NULL;
|
||||
}
|
||||
close_wdbip = true;
|
||||
if (db_dirbuild(wdbip) < 0) {
|
||||
db_close(wdbip);
|
||||
delete plan;
|
||||
return NULL;
|
||||
}
|
||||
db_update_nref(wdbip);
|
||||
}
|
||||
if (db_dirbuild(wdbip) < 0) {
|
||||
db_close(wdbip);
|
||||
delete plan;
|
||||
return NULL;
|
||||
}
|
||||
db_update_nref(wdbip);
|
||||
|
||||
/* Pre-collect all names currently in the working .g */
|
||||
std::set<std::string> dbnames;
|
||||
@@ -553,7 +561,8 @@ _ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
|
||||
}
|
||||
}
|
||||
|
||||
db_close(wdbip);
|
||||
if (close_wdbip)
|
||||
db_close(wdbip);
|
||||
return plan;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
/* P R O C E S S . C P P
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*
|
||||
* This library 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.
|
||||
*/
|
||||
|
||||
/* Apple's POSIX feature profile hides F_SETNOSIGPIPE. */
|
||||
#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE)
|
||||
# define _DARWIN_C_SOURCE
|
||||
#endif
|
||||
#include "common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
|
||||
#if defined(__APPLE__)
|
||||
# include <errno.h>
|
||||
# include <fcntl.h>
|
||||
# include <string.h>
|
||||
#endif
|
||||
|
||||
#include "bu/datetime.h"
|
||||
#include "bu/file.h"
|
||||
#include "bu/log.h"
|
||||
#include "bu/process.h"
|
||||
#include "bu/snooze.h"
|
||||
|
||||
#include "./ged_facetize.h"
|
||||
#include "./process.h"
|
||||
|
||||
static const size_t FACETIZE_PROCESS_IO_BUFFER_SIZE = 4096u;
|
||||
static const size_t FACETIZE_FILE_COPY_BUFFER_SIZE = 1024u * 1024u;
|
||||
static const int FACETIZE_PROCESS_POLL_USEC = 1000;
|
||||
static const int FACETIZE_PROCESS_SHUTDOWN_TIMEOUT_SEC = 5;
|
||||
static const double FACETIZE_USEC_TO_SEC_DIVISOR = 1.0e6;
|
||||
static const double FACETIZE_WRITE_TIMEOUT_FACTOR = 10.0;
|
||||
static const double FACETIZE_WRITE_TIMEOUT_MIN_SEC = 5.0;
|
||||
static const double FACETIZE_WRITE_TIMEOUT_MAX_SEC = 300.0;
|
||||
const size_t FACETIZE_WRITE_PROFILE_MIN_BYTES = 1024u * 1024u;
|
||||
|
||||
void
|
||||
facetize_process_drain_stdout(struct _ged_facetize_state *state,
|
||||
struct bu_process *process, FacetizeWorkerClient &channel,
|
||||
FacetizeWorkerStatus *status)
|
||||
{
|
||||
char buffer[FACETIZE_PROCESS_IO_BUFFER_SIZE];
|
||||
int fd = bu_process_fileno(process, BU_PROCESS_STDOUT);
|
||||
FacetizeWorkerStatus ignored_status;
|
||||
FacetizeWorkerStatus *output_status = status ? status : &ignored_status;
|
||||
std::vector<std::string> diagnostics;
|
||||
while (fd >= 0 && bu_process_pending(fd)) {
|
||||
int count = bu_process_read_n(process, BU_PROCESS_STDOUT,
|
||||
(int)sizeof(buffer), buffer);
|
||||
if (count <= 0)
|
||||
break;
|
||||
channel.consume_output(buffer, (size_t)count, *output_status,
|
||||
diagnostics);
|
||||
}
|
||||
for (const std::string &diagnostic : diagnostics)
|
||||
facetize_log(state, 1, "%s\n", diagnostic.c_str());
|
||||
}
|
||||
|
||||
void
|
||||
facetize_process_drain_stderr(struct _ged_facetize_state *state,
|
||||
struct bu_process *process)
|
||||
{
|
||||
char buffer[FACETIZE_PROCESS_IO_BUFFER_SIZE];
|
||||
int fd = bu_process_fileno(process, BU_PROCESS_STDERR);
|
||||
while (fd >= 0 && bu_process_pending(fd)) {
|
||||
int count = bu_process_read_n(process, BU_PROCESS_STDERR,
|
||||
(int)sizeof(buffer), buffer);
|
||||
if (count <= 0)
|
||||
break;
|
||||
facetize_log(state, 1, "%.*s", count, buffer);
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
facetize_process_reap(struct _ged_facetize_state *state,
|
||||
struct bu_process **process, FacetizeWorkerClient &channel,
|
||||
bool terminate)
|
||||
{
|
||||
if (!process || !*process)
|
||||
return BRLCAD_ERROR;
|
||||
if (terminate)
|
||||
(void)bu_process_terminate(*process);
|
||||
|
||||
int64_t deadline = bu_gettime() +
|
||||
BU_SEC2USEC(FACETIZE_PROCESS_SHUTDOWN_TIMEOUT_SEC);
|
||||
int poll_result = bu_process_poll(*process, NULL);
|
||||
while (poll_result == 0 && bu_gettime() < deadline) {
|
||||
facetize_process_drain_stdout(state, *process, channel, NULL);
|
||||
facetize_process_drain_stderr(state, *process);
|
||||
(void)bu_snooze(FACETIZE_PROCESS_POLL_USEC);
|
||||
poll_result = bu_process_poll(*process, NULL);
|
||||
}
|
||||
facetize_process_drain_stdout(state, *process, channel, NULL);
|
||||
facetize_process_drain_stderr(state, *process);
|
||||
if (poll_result != 1)
|
||||
(void)bu_process_terminate(*process);
|
||||
return bu_process_wait_n(process, 0);
|
||||
}
|
||||
|
||||
int
|
||||
facetize_process_stop(struct _ged_facetize_state *state,
|
||||
struct bu_process **process, FILE *&process_input,
|
||||
FacetizeWorkerClient &channel, bool terminate)
|
||||
{
|
||||
int status = facetize_process_reap(state, process, channel, terminate);
|
||||
process_input = NULL;
|
||||
channel.reset(NULL);
|
||||
return status;
|
||||
}
|
||||
|
||||
int
|
||||
facetize_process_start(struct bu_process **process, FILE **process_input,
|
||||
FacetizeWorkerClient &channel,
|
||||
const std::vector<std::string> &command,
|
||||
const std::string &result_file, const char *mode)
|
||||
{
|
||||
if (!process || !process_input || !mode)
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
std::vector<const char *> process_command;
|
||||
for (const std::string &argument : command)
|
||||
process_command.push_back(argument.c_str());
|
||||
if (!result_file.empty()) {
|
||||
process_command.push_back("--result-file");
|
||||
process_command.push_back(result_file.c_str());
|
||||
}
|
||||
process_command.push_back(mode);
|
||||
process_command.push_back(NULL);
|
||||
|
||||
*process = NULL;
|
||||
*process_input = NULL;
|
||||
channel.reset(NULL);
|
||||
bu_process_create(process, process_command.data(), BU_PROCESS_HIDE_WINDOW);
|
||||
if (*process)
|
||||
*process_input = bu_process_file_open(*process, BU_PROCESS_STDIN);
|
||||
bool input_ready = *process && *process_input;
|
||||
#if defined(__APPLE__)
|
||||
if (input_ready && fcntl(fileno(*process_input), F_SETNOSIGPIPE, 1) < 0) {
|
||||
/* Darwin sends a broken pipe's SIGPIPE to the process, so masking
|
||||
* only the writing thread cannot protect this worker channel. */
|
||||
bu_log("FACETIZE: unable to suppress SIGPIPE on worker stdin: %s\n",
|
||||
strerror(errno));
|
||||
input_ready = false;
|
||||
}
|
||||
#endif
|
||||
if (input_ready && setvbuf(*process_input, NULL, _IONBF, 0) == 0) {
|
||||
channel.reset(*process_input);
|
||||
return BRLCAD_OK;
|
||||
}
|
||||
|
||||
if (*process) {
|
||||
(void)bu_process_terminate(*process);
|
||||
(void)bu_process_wait_n(process, 0);
|
||||
}
|
||||
*process_input = NULL;
|
||||
return BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
double
|
||||
facetize_write_timeout_seconds(size_t payload_size,
|
||||
double profiled_write_bytes, double profiled_write_usec)
|
||||
{
|
||||
if (profiled_write_bytes <= 0.0 || profiled_write_usec <= 0.0)
|
||||
return FACETIZE_WRITE_TIMEOUT_MAX_SEC;
|
||||
|
||||
double bytes_per_second = profiled_write_bytes *
|
||||
FACETIZE_USEC_TO_SEC_DIVISOR / profiled_write_usec;
|
||||
double projected_seconds = (double)payload_size / bytes_per_second;
|
||||
double timeout_seconds = projected_seconds * FACETIZE_WRITE_TIMEOUT_FACTOR;
|
||||
return std::min(FACETIZE_WRITE_TIMEOUT_MAX_SEC,
|
||||
std::max(FACETIZE_WRITE_TIMEOUT_MIN_SEC, timeout_seconds));
|
||||
}
|
||||
|
||||
int
|
||||
facetize_file_copy(const char *source, const char *destination,
|
||||
FacetizeFileCopyProgress progress, void *progress_data)
|
||||
{
|
||||
if (!source || !destination)
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
std::ifstream input(source, std::ios::binary);
|
||||
if (!input.is_open())
|
||||
return BRLCAD_ERROR;
|
||||
std::ofstream output(destination, std::ios::binary | std::ios::trunc);
|
||||
if (!output.is_open())
|
||||
return BRLCAD_ERROR;
|
||||
|
||||
std::vector<char> buffer(FACETIZE_FILE_COPY_BUFFER_SIZE);
|
||||
uint64_t bytes_copied = 0;
|
||||
bool copy_succeeded = true;
|
||||
while (input) {
|
||||
input.read(buffer.data(), (std::streamsize)buffer.size());
|
||||
std::streamsize count = input.gcount();
|
||||
if (count <= 0)
|
||||
break;
|
||||
output.write(buffer.data(), count);
|
||||
if (!output.good()) {
|
||||
copy_succeeded = false;
|
||||
break;
|
||||
}
|
||||
bytes_copied += (uint64_t)count;
|
||||
if (progress)
|
||||
progress(bytes_copied, progress_data);
|
||||
}
|
||||
copy_succeeded = copy_succeeded && input.eof() && !input.bad();
|
||||
if (copy_succeeded) {
|
||||
output.flush();
|
||||
copy_succeeded = output.good();
|
||||
}
|
||||
input.close();
|
||||
output.close();
|
||||
if (!copy_succeeded)
|
||||
bu_file_delete(destination);
|
||||
return copy_succeeded ? BRLCAD_OK : BRLCAD_ERROR;
|
||||
}
|
||||
|
||||
// Local Variables:
|
||||
// tab-width: 8
|
||||
// mode: C++
|
||||
// c-basic-offset: 4
|
||||
// indent-tabs-mode: t
|
||||
// c-file-style: "stroustrup"
|
||||
// End:
|
||||
// ex: shiftwidth=4 tabstop=8
|
||||
@@ -0,0 +1,64 @@
|
||||
/* P R O C E S S . H
|
||||
* BRL-CAD
|
||||
*
|
||||
* Copyright (c) 2026 United States Government as represented by
|
||||
* the U.S. Army Research Laboratory.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public License
|
||||
* version 2.1 as published by the Free Software Foundation.
|
||||
*/
|
||||
|
||||
#ifndef LIBGED_FACETIZE_PROCESS_H
|
||||
#define LIBGED_FACETIZE_PROCESS_H
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "bu/defines.h"
|
||||
|
||||
#include "./worker.h"
|
||||
|
||||
struct bu_process;
|
||||
struct _ged_facetize_state;
|
||||
|
||||
extern const size_t FACETIZE_WRITE_PROFILE_MIN_BYTES;
|
||||
|
||||
typedef void (*FacetizeFileCopyProgress)(uint64_t bytes_copied, void *data);
|
||||
|
||||
void
|
||||
facetize_process_drain_stdout(struct _ged_facetize_state *state,
|
||||
struct bu_process *process, FacetizeWorkerClient &channel,
|
||||
FacetizeWorkerStatus *status);
|
||||
|
||||
void
|
||||
facetize_process_drain_stderr(struct _ged_facetize_state *state,
|
||||
struct bu_process *process);
|
||||
|
||||
int
|
||||
facetize_process_start(struct bu_process **process, FILE **process_input,
|
||||
FacetizeWorkerClient &channel,
|
||||
const std::vector<std::string> &command,
|
||||
const std::string &result_file, const char *mode);
|
||||
|
||||
int
|
||||
facetize_process_reap(struct _ged_facetize_state *state,
|
||||
struct bu_process **process, FacetizeWorkerClient &channel,
|
||||
bool terminate);
|
||||
|
||||
int
|
||||
facetize_process_stop(struct _ged_facetize_state *state,
|
||||
struct bu_process **process, FILE *&process_input,
|
||||
FacetizeWorkerClient &channel, bool terminate);
|
||||
|
||||
double
|
||||
facetize_write_timeout_seconds(size_t payload_size,
|
||||
double profiled_write_bytes, double profiled_write_usec);
|
||||
|
||||
int
|
||||
facetize_file_copy(const char *source, const char *destination,
|
||||
FacetizeFileCopyProgress progress = NULL, void *progress_data = NULL);
|
||||
|
||||
#endif /* LIBGED_FACETIZE_PROCESS_H */
|
||||
+1247
-329
File diff suppressed because it is too large
Load Diff
@@ -4,12 +4,18 @@ set(TESS_LIBS libged manifold::manifold)
|
||||
set(
|
||||
GED_TESS_SRCS
|
||||
brep_csg.cpp
|
||||
continuation.cpp
|
||||
sample.cpp
|
||||
spsr.cpp
|
||||
main.cpp
|
||||
mdc.cpp
|
||||
nmg.cpp
|
||||
nmg_boolean.cpp
|
||||
util.cpp
|
||||
../plan.cpp
|
||||
../process.cpp
|
||||
../tri.cpp
|
||||
../transfer.cpp
|
||||
../util.cpp
|
||||
../validation.cpp
|
||||
../worker.cpp
|
||||
)
|
||||
|
||||
@@ -20,6 +26,7 @@ ged_subprocess_library(facetize_process
|
||||
|
||||
cmakefiles(
|
||||
CMakeLists.txt
|
||||
nmg_boolean.h
|
||||
tessellate.h
|
||||
${GED_TESS_SRCS}
|
||||
)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user