pax_global_header00006660000000000000000000000064142260151120014504gustar00rootroot0000000000000052 comment=27cd7f641810e71e7ae61aeb989e5d8f457396f1 pynest2d-5.0.0/000077500000000000000000000000001422601511200132565ustar00rootroot00000000000000pynest2d-5.0.0/CMakeLists.txt000066400000000000000000000044561422601511200160270ustar00rootroot00000000000000# Copyright (c) 2022 Ultimaker B.V. # pynest2d is released under the terms of the LGPLv3 or higher. project(pynest2d) cmake_minimum_required(VERSION 3.20) # Lowest version it's been tested with. include(cmake/StandardProjectSettings.cmake) list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") if(NOT DEFINED Python_VERSION) set(Python_VERSION 3.10 CACHE STRING "Python Version" FORCE) message(STATUS "Setting Python version to ${Python_VERSION}. Set Python_VERSION if you want to compile against an other version.") endif() if(APPLE) set(Python_FIND_FRAMEWORK NEVER) endif() find_package(cpython ${Python_VERSION} QUIET COMPONENTS Interpreter Development) if(NOT TARGET cpython::cpython) find_package(Python ${Python_VERSION} EXACT REQUIRED COMPONENTS Interpreter Development) else() add_library(Python::Python ALIAS cpython::python) set(Python_SITEARCH "${CMAKE_INSTALL_PREFIX}/lib/python${Python_VERSION}/site-packages") set(Python_EXECUTABLE ${cpython_PACKAGE_FOLDER_RELEASE}/bin/python3) set(ENV{PYTHONPATH} ${Python_SITEARCH}) endif() message(STATUS "Linking and building ${project_name} against Python ${Python_VERSION}") find_package(SIP REQUIRED 6.5.0) find_package(Libnest2D REQUIRED) # The library we're creating bindings for. add_library(pynest2d INTERFACE) set_project_standards(pynest2d) use_threads(pynest2d) set_rpath(TARGETS pynest2d PATHS "$<$:usr/bin>" "$<$:usr/bin/lib>" "$<$:../lib>" "$<$:../Resources/lib>" "../../" # In distributions of Cura, the libnest2d dependency is 2 directories up from where pynest2d gets installed. RELATIVE) target_include_directories(pynest2d INTERFACE $ $ ) find_package(Threads) find_package(clipper) find_package(NLopt) find_package(Boost) target_link_libraries(pynest2d INTERFACE Libnest2D::libnest2d Python::Python Threads::Threads clipper::clipper NLopt::nlopt boost::boost) add_sip_module(pynest2d) if(Python_SITELIB_LOCAL) install_sip_module(pynest2d ${Python_SITELIB_LOCAL}) else() install_sip_module(pynest2d) endif() pynest2d-5.0.0/LICENSE000066400000000000000000000167231422601511200142740ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.pynest2d-5.0.0/README.md000066400000000000000000000046671422601511200145520ustar00rootroot00000000000000Introduction and Scope ==== This repository contains CPython bindings for [libnest2d](https://github.com/tamasmeszaros/libnest2d) (though note that we may use as of yet unmerged work done on [our own fork of libnest2d, here](https://github.com/Ultimaker/libnest2d) whenever convenient), a library to pack 2D polygons into a small space. Libnest2d implements the 2D bin packing problem. The objective of this repository is to allow libnest2d to be called from Python using Numpy. There is a [competing solution](https://github.com/markfink/nest2D) to provide Python bindings to this end. However it doesn't expose enough of the configurability for Cura's purposes. This repository aims to be a more transparent binding of libnest2d. Usage ==== This is an example of how you can use these Python bindings to arrange multiple shapes in a volume. ```python >>> from pynest2d import * >>> bin = Box(1000, 1000) # A bounding volume in which the items must be arranged, a 1000x1000 square centered around 0. >>> i1 = Item([Point(0, 0), Point(100, 100), Point(50, 100)]) # Long thin triangle. >>> i2 = Item([Point(0, 0), Point(100, 0), Point(100, 100), Point(0, 100)]) # Square. >>> i3 = Item([Point(0, 0), Point(100, 0), Point(50, 100)]) # Equilateral triangle. >>> num_bins = nest([i1, i2, i3], bin) # The actual arranging! >>> num_bins # How many bins are required to add all objects. 1 >>> transformed_i1 = i1.transformedShape() # The original item is unchanged, but the transformed shape is. >>> print(transformed_i1.toString()) Contour { 18 96 117 46 117 -4 18 96 } >>> transformed_i.vertex(0).x() 18 >>> transformed_i.vertex(0).y() 96 >>> i1.rotation() 4.71238898038469 ``` For full documentation, see [libnest2d](https://github.com/tamasmeszaros/libnest2d). These bindings stay close to the original function signatures. Building ==== This library has a couple of dependencies that need to be installed prior to building: * [libnest2d](https://github.com/Ultimaker/libnest2d), the library for which this library offers CPython bindings, and its dependencies: * [Clipper](http://www.angusj.com/delphi/clipper.php), a polygon clipping library. * [NLopt](https://nlopt.readthedocs.io/en/latest/), a library to solve non-linear optimization problems. * [Boost](https://www.boost.org/), the headers only. * [Sip](https://www.riverbankcomputing.com/software/sip/download), an application to generate Python bindings more easily. pynest2d-5.0.0/cmake/000077500000000000000000000000001422601511200143365ustar00rootroot00000000000000pynest2d-5.0.0/cmake/CMakeBuilder.py000066400000000000000000000006041422601511200171770ustar00rootroot00000000000000from sipbuild import SetuptoolsBuilder class CMakeBuilder(SetuptoolsBuilder): def __init__(self, project, **kwargs): print("Using the CMake builder") super().__init__(project, **kwargs) def build(self): """ Only Generate the source files """ print("Generating the source files") self._generate_bindings() self._generate_scripts()pynest2d-5.0.0/cmake/COPYING-CMAKE-SCRIPTS000066400000000000000000000024571422601511200173440ustar00rootroot00000000000000Redistribution 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 copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pynest2d-5.0.0/cmake/FindSIP.cmake000066400000000000000000000047511422601511200166030ustar00rootroot00000000000000# Find SIP # ~~~~~~~~ # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # Find the installed version of SIP. FindSIP should be called after Python # has been found. # # This file defines the following variables: # # SIP_VERSION - The version of SIP found expressed as a 6 digit hex number # suitable for comparison as a string. # # SIP_VERSION_STR - The version of SIP found as a human readable string. # # SIP_BINARY_PATH - Path and filename of the SIP command line executable. # # SIP_INCLUDE_DIR - Directory holding the SIP C++ header file. # # SIP_DEFAULT_SIP_DIR - Default directory where .sip files should be installed # into. # Copyright (c) 2007, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. IF(SIP_VERSION OR SIP_BUILD_EXECUTABLE) # Already in cache, be silent SET(SIP_FOUND TRUE) ELSE() FIND_FILE(_find_sip_py FindSIP.py PATHS ${CMAKE_MODULE_PATH} NO_CMAKE_FIND_ROOT_PATH) EXECUTE_PROCESS(COMMAND ${Python_EXECUTABLE} ${_find_sip_py} OUTPUT_VARIABLE sip_config) IF(sip_config) STRING(REGEX REPLACE "^sip_version:([^\n]+).*$" "\\1" SIP_VERSION ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_num:([^\n]+).*$" "\\1" SIP_VERSION_NUM ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_str:([^\n]+).*$" "\\1" SIP_VERSION_STR ${sip_config}) STRING(REGEX REPLACE ".*\ndefault_sip_dir:([^\n]+).*$" "\\1" SIP_DEFAULT_SIP_DIR ${sip_config}) IF(${SIP_VERSION_STR} VERSION_LESS 5) STRING(REGEX REPLACE ".*\nsip_bin:([^\n]+).*$" "\\1" SIP_BINARY_PATH ${sip_config}) STRING(REGEX REPLACE ".*\nsip_inc_dir:([^\n]+).*$" "\\1" SIP_INCLUDE_DIR ${sip_config}) STRING(REGEX REPLACE ".*\nsip_module_dir:([^\n]+).*$" "\\1" SIP_MODULE_DIR ${sip_config}) ELSE(${SIP_VERSION_STR} VERSION_LESS 5) FIND_PROGRAM(SIP_BUILD_EXECUTABLE sip-build) ENDIF(${SIP_VERSION_STR} VERSION_LESS 5) SET(SIP_FOUND TRUE) ENDIF(sip_config) IF(SIP_FOUND) IF(NOT SIP_FIND_QUIETLY) MESSAGE(STATUS "Found SIP version: ${SIP_VERSION_STR}") ENDIF(NOT SIP_FIND_QUIETLY) ELSE(SIP_FOUND) IF(SIP_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find SIP") ENDIF(SIP_FIND_REQUIRED) ENDIF(SIP_FOUND) ENDIF() include(${CMAKE_SOURCE_DIR}/cmake/SIPMacros.cmake) ADD_DEFINITIONS(-DSIP_VERSION=0x${SIP_VERSION}) pynest2d-5.0.0/cmake/FindSIP.py000066400000000000000000000055361422601511200161550ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Copyright (c) 2007, Simon Edwards # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Simon Edwards nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Simon Edwards ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Simon Edwards BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # FindSIP.py # Copyright (c) 2007, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. try: import sipbuild print("sip_version:%06.0x" % sipbuild.version.SIP_VERSION) print("sip_version_num:%d" % sipbuild.version.SIP_VERSION) print("sip_version_str:%s" % sipbuild.version.SIP_VERSION_STR) from distutils.sysconfig import get_python_lib python_modules_dir = get_python_lib(plat_specific=1) print("default_sip_dir:%s" % python_modules_dir) except ImportError: # Code for SIP v4 import sipconfig sipcfg = sipconfig.Configuration() print("sip_version:%06.0x" % sipcfg.sip_version) print("sip_version_num:%d" % sipcfg.sip_version) print("sip_version_str:%s" % sipcfg.sip_version_str) print("sip_bin:%s" % sipcfg.sip_bin) print("default_sip_dir:%s" % sipcfg.default_sip_dir) print("sip_inc_dir:%s" % sipcfg.sip_inc_dir) # SIP 4.19.10+ has new sipcfg.sip_module_dir if hasattr(sipcfg, "sip_module_dir"): print("sip_module_dir:%s" % sipcfg.sip_module_dir) else: print("sip_module_dir:%s" % sipcfg.sip_mod_dir) pynest2d-5.0.0/cmake/SIPMacros.cmake000066400000000000000000000130701422601511200171410ustar00rootroot00000000000000# Macros for SIP # ~~~~~~~~~~~~~~ set(SIP_ARGS --pep484-pyi --no-protected-is-public) function(add_sip_module MODULE_TARGET) if(NOT SIP_BUILD_EXECUTABLE) set(SIP_BUILD_EXECUTABLE ${CMAKE_PREFIX_PATH}/Scripts/sip-build) endif() message(STATUS "SIP: Generating pyproject.toml") configure_file(${CMAKE_SOURCE_DIR}/pyproject.toml.in ${CMAKE_CURRENT_BINARY_DIR}/pyproject.toml) configure_file(${CMAKE_SOURCE_DIR}/cmake/CMakeBuilder.py ${CMAKE_CURRENT_BINARY_DIR}/CMakeBuilder.py) if(WIN32) set(ext .pyd) set(env_path_sep ";") else() set(ext .so) set(env_path_sep ":") endif() message(STATUS "SIP: Generating source files") execute_process( COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${PYTHONPATH}${env_path_sep}$ENV{PYTHONPATH}${env_path_sep}${CMAKE_CURRENT_BINARY_DIR}" ${SIP_BUILD_EXECUTABLE} ${SIP_ARGS} COMMAND_ECHO STDOUT WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/ ) # This will generate the source-files during the configuration step in CMake. Needed to obtain the sources # Touch the generated files (8 in total) to make them dirty and force them to rebuild message(STATUS "SIP: Touching the source files") set(_sip_output_files) list(LENGTH SIP_FILES _no_outputfiles) foreach(_concat_file_nr RANGE 0 ${_no_outputfiles}) if(${_concat_file_nr} LESS 8) list(APPEND _sip_output_files "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/sip${MODULE_TARGET}part${_concat_file_nr}.cpp") endif() endforeach() # Find the generated source files message(STATUS "SIP: Collecting the generated source files") file(GLOB sip_c "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/*.c") file(GLOB sip_cpp "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/*.cpp") file(GLOB sip_hdr "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/*.h") # Add the user specified source files message(STATUS "SIP: Collecting the user specified source files") get_target_property(usr_src ${MODULE_TARGET} SOURCES) # create the target library and link all the files (generated and user specified message(STATUS "SIP: Linking the interface target against the shared library") set(sip_sources "${sip_c}" "${sip_cpp}") if(${usr_src}) list(APPEND sip_sources "${usr_src}") endif() if (BUILD_SHARED_LIBS) add_library("sip_${MODULE_TARGET}" SHARED ${sip_sources}) else() add_library("sip_${MODULE_TARGET}" STATIC ${sip_sources}) endif() # Make sure that the library name of the target is the same as the MODULE_TARGET with the appropriate extension target_link_libraries("sip_${MODULE_TARGET}" PRIVATE "${MODULE_TARGET}") set_target_properties("sip_${MODULE_TARGET}" PROPERTIES PREFIX "") set_target_properties("sip_${MODULE_TARGET}" PROPERTIES SUFFIX ${ext}) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES OUTPUT_NAME "${MODULE_TARGET}") # Make sure all rpaths are set from the INTERFACE target get_target_property(_SKIP_BUILD_RPATH ${MODULE_TARGET} SKIP_BUILD_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES SKIP_BUILD_RPATH "${_SKIP_BUILD_RPATH}") get_target_property(_BUILD_WITH_INSTALL_RPATH ${MODULE_TARGET} BUILD_WITH_INSTALL_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES BUILD_WITH_INSTALL_RPATH "${_BUILD_WITH_INSTALL_RPATH}") get_target_property(_INSTALL_RPATH_USE_LINK_PATH ${MODULE_TARGET} INSTALL_RPATH_USE_LINK_PATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES INSTALL_RPATH_USE_LINK_PATH "${_INSTALL_RPATH_USE_LINK_PATH}") get_target_property(_MACOSX_RPATH ${MODULE_TARGET} MACOSX_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES MACOSX_RPATH "${_MACOSX_RPATH}") get_target_property(_INSTALL_RPATH ${MODULE_TARGET} INSTALL_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES INSTALL_RPATH "${_INSTALL_RPATH}") # Add the custom command to (re-)generate the files and mark them as dirty. This allows the user to actually work # on the sip definition files without having to reconfigure the complete project. add_custom_command( TARGET "sip_${MODULE_TARGET}" COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${PYTHONPATH}${env_path_sep}$ENV{PYTHONPATH}${env_path_sep}${CMAKE_CURRENT_BINARY_DIR}" ${SIP_BUILD_EXECUTABLE} ${SIP_ARGS} COMMAND ${CMAKE_COMMAND} -E touch ${_sip_output_files} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/ MAIN_DEPENDENCY ${MODULE_SIP} DEPENDS ${sip_sources} VERBATIM ) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES RESOURCE "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/${MODULE_TARGET}.pyi") endfunction() function(install_sip_module MODULE_TARGET) if(DEFINED ARGV1) set(_install_path ${ARGV1}) else() if(DEFINED Python_SITEARCH) set(_install_path ${Python_SITEARCH}) elseif(DEFINED Python_SITELIB) set(_install_path ${Python_SITELIB}) else() message(FATAL_ERROR "SIP: Specify the site-packages location") endif() endif() message(STATUS "SIP: Installing Python module and PEP 484 file in ${_install_path}") install(TARGETS "sip_${MODULE_TARGET}" ARCHIVE DESTINATION ${_install_path} LIBRARY DESTINATION ${_install_path} RUNTIME DESTINATION ${_install_path} RESOURCE DESTINATION ${_install_path} ) endfunction()pynest2d-5.0.0/cmake/StandardProjectSettings.cmake000066400000000000000000000364121422601511200221560ustar00rootroot00000000000000include(GNUInstallDirs) # Standard install dirs if(NOT DEFINED BUILD_SHARED_LIBS) set(BUILD_SHARED_LIBS ON) message(STATUS "Setting BUILD_SHARED_LIBS to ${BUILD_SHARED_LIBS}") endif() # Set a default build type if none was specified if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Release' as none was specified.") set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui, ccmake set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() # Generate compile_commands.json to make it easier to work with clang based tools message(STATUS "Generating compile commands to ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json") set(CMAKE_EXPORT_COMPILE_COMMANDS ON) option(ENABLE_IPO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)" ON) if(ENABLE_IPO) include(CheckIPOSupported) check_ipo_supported( RESULT result OUTPUT output) if(result) set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) else() message(SEND_ERROR "IPO is not supported: ${output}") endif() endif() if (NOT MSVC) # Compile with the -fPIC options if supported if(DEFINED POSITION_INDEPENDENT_CODE) # Use the user/Conan set value message(STATUS "Using POSITION_INDEPENDENT_CODE: ${POSITION_INDEPENDENT_CODE}") else() set(POSITION_INDEPENDENT_CODE ON) # Defaults to on message(STATUS "Setting POSITION_INDEPENDENT_CODE: ${POSITION_INDEPENDENT_CODE}") endif() else() # Set Visual Studio flags MD/MDd or MT/MTd if(NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY) if(BUILD_STATIC OR NOT BUILD_SHARED_LIBS) message(STATUS "Setting MT/MTd flags") set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") else() message(STATUS "Setting MD/MDd flags") set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") endif() endif() endif() # Use C++17 Standard message(STATUS "Setting C++17 support with extensions off and standard required") set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Set common project options for the target function(set_project_standards project_name) get_target_property(type ${project_name} TYPE) if(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") option(ENABLE_BUILD_WITH_TIME_TRACE "Enable -ftime-trace to generate time tracing .json files on clang" OFF) if(ENABLE_BUILD_WITH_TIME_TRACE) message(STATUS "Enabling time tracing for ${project_name}") if (${type} STREQUAL "INTERFACE_LIBRARY") add_compile_definitions(${project_name} INTERFACE -ftime-trace) else() add_compile_definitions(${project_name} PRIVATE -ftime-trace) endif() endif() if (APPLE) message(STATUS "Compiling ${project_name} against libc++") if (${type} STREQUAL "INTERFACE_LIBRARY") target_compile_options(${project_name} INTERFACE "-stdlib=libc++") else() target_compile_options(${project_name} PRIVATE "-stdlib=libc++") endif() endif() endif() endfunction() function(set_rpath) # Sets the RPATHS for targets (Linux and Windows, these can either be absolute paths or relative to the executable # Usage: # set_rpath(TARGETS # PATHS # RELATIVE) # if the RELATIVE option is used the paths will be specified from either $ORIGIN on Linux or @executable_path on Mac set(options RELATIVE) set(oneValueArgs ) set(multiValueArgs TARGETS PATHS) cmake_parse_arguments(SET_RPATH "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) foreach(_target IN ITEMS ${SET_RPATH_TARGETS}) message(STATUS "Setting SKIP_BUILD_RPATH for target ${_target} to FALSE") set_target_properties(${_target} PROPERTIES SKIP_BUILD_RPATH FALSE) message(STATUS "Setting BUILD_WITH_INSTALL_RPATH for target ${_target} to FALSE") set_target_properties(${_target} PROPERTIES BUILD_WITH_INSTALL_RPATH FALSE) message(STATUS "Setting INSTALL_RPATH_USE_LINK_PATH for target ${_target} to TRUE") set_target_properties(${_target} PROPERTIES INSTALL_RPATH_USE_LINK_PATH TRUE) if(APPLE) message(STATUS "Setting MACOSX_RPATH for target ${_target}") set_target_properties(${_target} PROPERTIES MACOSX_RPATH ON) endif() if(SET_RPATH_RELATIVE) list(PREPEND SET_RPATH_PATHS "") if(APPLE) set(loader_path "${SET_RPATH_PATHS}") list(TRANSFORM loader_path PREPEND "@loader_path/") list(TRANSFORM SET_RPATH_PATHS PREPEND "@executable_path/") list(APPEND SET_RPATH_PATHS ${loader_path}) else(LINUX) list(TRANSFORM SET_RPATH_PATHS PREPEND "\$ORIGIN/") endif() endif() set_target_properties(${_target} PROPERTIES INSTALL_RPATH "${SET_RPATH_PATHS}") message(STATUS "Setting install RPATH for target ${_target} to ${SET_RPATH_PATHS}") endforeach() endfunction() # Ultimaker uniform Python linking method function(use_python project_name) find_package(Python REQUIRED) get_target_property(type ${project_name} TYPE) if(${type} STREQUAL "INTERFACE_LIBRARY") target_link_libraries(${project_name} INTERFACE Python::Python) else() target_link_libraries(${project_name} PRIVATE Python::Python) endif() message(STATUS "Linking and building ${project_name} against Python ${Python_VERSION}") endfunction() # Ultimaker uniform Thread linking method function(use_threads project_name) message(STATUS "Enabling threading support for ${project_name}") set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads) get_target_property(type ${project_name} TYPE) if (${type} STREQUAL "INTERFACE_LIBRARY") target_link_libraries(${project_name} INTERFACE Threads::Threads) else() target_link_libraries(${project_name} PRIVATE Threads::Threads) endif() endfunction() # https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md function(set_project_warnings project_name) message(STATUS "Setting warnings for ${project_name}") set(MSVC_WARNINGS /W4 # Baseline reasonable warnings /w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss of data /w14254 # 'operator': conversion from 'type1:field_bits' to 'type2:field_bits', possible loss of data /w14263 # 'function': member function does not override any base class virtual member function /w14265 # 'classname': class has virtual functions, but destructor is not virtual instances of this class may not # be destructed correctly /w14287 # 'operator': unsigned/negative constant mismatch /we4289 # nonstandard extension used: 'variable': loop control variable declared in the for-loop is used outside # the for-loop scope /w14296 # 'operator': expression is always 'boolean_value' /w14311 # 'variable': pointer truncation from 'type1' to 'type2' /w14545 # expression before comma evaluates to a function which is missing an argument list /w14546 # function call before comma missing argument list /w14547 # 'operator': operator before comma has no effect; expected operator with side-effect /w14549 # 'operator': operator before comma has no effect; did you intend 'operator'? /w14555 # expression has no effect; expected expression with side- effect /w14619 # pragma warning: there is no warning number 'number' /w14640 # Enable warning on thread un-safe static member initialization /w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may cause unexpected runtime behavior. /w14905 # wide string literal cast to 'LPSTR' /w14906 # string literal cast to 'LPWSTR' /w14928 # illegal copy-initialization; more than one user-defined conversion has been implicitly applied /permissive- # standards conformance mode for MSVC compiler. ) set(CLANG_WARNINGS -Wall -Wextra # reasonable and standard -Wshadow # warn the user if a variable declaration shadows one from a parent context -Wnon-virtual-dtor # warn the user if a class with virtual functions has a non-virtual destructor. This helps # catch hard to track down memory errors -Wold-style-cast # warn for c-style casts -Wcast-align # warn for potential performance problem casts -Wunused # warn on anything being unused -Woverloaded-virtual # warn if you overload (not override) a virtual function -Wpedantic # warn if non-standard C++ is used -Wconversion # warn on type conversions that may lose data -Wsign-conversion # warn on sign conversions -Wnull-dereference # warn if a null dereference is detected -Wdouble-promotion # warn if float is implicit promoted to double -Wformat=2 # warn on security issues around functions that format output (ie printf) ) set(GCC_WARNINGS ${CLANG_WARNINGS} -Wmisleading-indentation # warn if indentation implies blocks where blocks do not exist -Wduplicated-cond # warn if if / else chain has duplicated conditions -Wduplicated-branches # warn if if / else branches have duplicated code -Wlogical-op # warn about logical operations being used where bitwise were probably wanted -Wuseless-cast # warn if you perform a cast to the same type ) if(MSVC) set(PROJECT_WARNINGS ${MSVC_WARNINGS}) elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") set(PROJECT_WARNINGS ${CLANG_WARNINGS}) elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(PROJECT_WARNINGS ${GCC_WARNINGS}) else() message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.") endif() get_target_property(type ${project_name} TYPE) if (${type} STREQUAL "INTERFACE_LIBRARY") target_compile_options(${project_name} INTERFACE ${PROJECT_WARNINGS}) else() target_compile_options(${project_name} PRIVATE ${PROJECT_WARNINGS}) endif() endfunction() # This function will prevent in-source builds function(assure_out_of_source_builds) # make sure the user doesn't play dirty with symlinks get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH) get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH) # disallow in-source builds if("${srcdir}" STREQUAL "${bindir}") message("######################################################") message("Warning: in-source builds are disabled") message("Please create a separate build directory and run cmake from there") message("######################################################") message(FATAL_ERROR "Quitting configuration") endif() endfunction() option(ALLOW_IN_SOURCE_BUILD "Allow building in your source folder. Strongly discouraged" OFF) if(NOT ALLOW_IN_SOURCE_BUILD) assure_out_of_source_builds() endif() function(enable_sanitizers project_name) if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") option(ENABLE_COVERAGE "Enable coverage reporting for gcc/clang" FALSE) if(ENABLE_COVERAGE) target_compile_options(${project_name} INTERFACE --coverage -O0 -g) target_link_libraries(${project_name} INTERFACE --coverage) endif() set(SANITIZERS "") option(ENABLE_SANITIZER_ADDRESS "Enable address sanitizer" FALSE) if(ENABLE_SANITIZER_ADDRESS) list(APPEND SANITIZERS "address") endif() option(ENABLE_SANITIZER_LEAK "Enable leak sanitizer" FALSE) if(ENABLE_SANITIZER_LEAK) list(APPEND SANITIZERS "leak") endif() option(ENABLE_SANITIZER_UNDEFINED_BEHAVIOR "Enable undefined behavior sanitizer" FALSE) if(ENABLE_SANITIZER_UNDEFINED_BEHAVIOR) list(APPEND SANITIZERS "undefined") endif() option(ENABLE_SANITIZER_THREAD "Enable thread sanitizer" FALSE) if(ENABLE_SANITIZER_THREAD) if("address" IN_LIST SANITIZERS OR "leak" IN_LIST SANITIZERS) message(WARNING "Thread sanitizer does not work with Address and Leak sanitizer enabled") else() list(APPEND SANITIZERS "thread") endif() endif() option(ENABLE_SANITIZER_MEMORY "Enable memory sanitizer" FALSE) if(ENABLE_SANITIZER_MEMORY AND CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") if("address" IN_LIST SANITIZERS OR "thread" IN_LIST SANITIZERS OR "leak" IN_LIST SANITIZERS) message(WARNING "Memory sanitizer does not work with Address, Thread and Leak sanitizer enabled") else() list(APPEND SANITIZERS "memory") endif() endif() list( JOIN SANITIZERS "," LIST_OF_SANITIZERS) endif() if(LIST_OF_SANITIZERS) if(NOT "${LIST_OF_SANITIZERS}" STREQUAL "") target_compile_options(${project_name} INTERFACE -fsanitize=${LIST_OF_SANITIZERS}) target_link_options(${project_name} INTERFACE -fsanitize=${LIST_OF_SANITIZERS}) endif() endif() endfunction() option(ENABLE_CPPCHECK "Enable static analysis with cppcheck" OFF) option(ENABLE_CLANG_TIDY "Enable static analysis with clang-tidy" OFF) option(ENABLE_INCLUDE_WHAT_YOU_USE "Enable static analysis with include-what-you-use" OFF) if(ENABLE_CPPCHECK) find_program(CPPCHECK cppcheck) if(CPPCHECK) message(STATUS "Using cppcheck") set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all --inline-suppr --inconclusive -i ${CMAKE_SOURCE_DIR}/imgui/lib) else() message(WARNING "cppcheck requested but executable not found") endif() endif() if(ENABLE_CLANG_TIDY) find_program(CLANGTIDY clang-tidy) if(CLANGTIDY) message(STATUS "Using clang-tidy") set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option) else() message(WARNING "clang-tidy requested but executable not found") endif() endif() if(ENABLE_INCLUDE_WHAT_YOU_USE) find_program(INCLUDE_WHAT_YOU_USE include-what-you-use) if(INCLUDE_WHAT_YOU_USE) message(STATUS "Using include-what-you-use") set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE ${INCLUDE_WHAT_YOU_USE}) else() message(WARNING "include-what-you-use requested but executable not found") endif() endif()pynest2d-5.0.0/pyproject.toml.in000066400000000000000000000006231422601511200166000ustar00rootroot00000000000000[build-system] requires = ["sip >=6, <7"] build-backend = "sipbuild.api" [tool.sip.metadata] name = "pynest2d" [tool.sip.project] builder-factory = "CMakeBuilder" sip-files-dir = "${CMAKE_CURRENT_SOURCE_DIR}/src/" sip-include-dirs = ["CMAKE_CURRENT_SOURCE_DIR/src/"] build-dir = "${CMAKE_CURRENT_BINARY_DIR}/pynest2d/" [tool.sip.bindings.pynest2d] exceptions = true release-gil = true concatenate = 8pynest2d-5.0.0/src/000077500000000000000000000000001422601511200140455ustar00rootroot00000000000000pynest2d-5.0.0/src/BottomLeftConfig.sip000066400000000000000000000022331422601511200177670ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. struct BottomLeftConfig { %Docstring "deindented" Configuration class for the BLPlacer class. With this you can configure some parameters on how the BLPlacer places objects. The following attributes can be set: * min_obj_distance (default 0): Minimum distance between objects. This seems to not be used by libnest2d at the moment. * epsilon (default 1): Resolution of placement. The lower the epsilon, the more placements will be attempted, resulting in better placement but longer computation time. * allow_rotations (default False): Whether the placer is allowed to rotate the items. This placer will only attempt 90 degree rotations if this setting is set to True. %End %TypeHeaderCode #include using BottomLeftConfig = BLConfig; //Specialise the templated BLConfig class since SIP doesn't deal with templates. %End long min_obj_distance; long epsilon; bool allow_rotations; };pynest2d-5.0.0/src/Box.sip000066400000000000000000000065621422601511200153230ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. class Box { %Docstring "deindented" A rectangular shape, to be used as a bin or to be placed in the scene. %End %TypeHeaderCode #include %End public: Box(Point center); %Docstring "deindented" Create a 0x0 box at the specified position. It's intended that you adjust the size later. :param center: The coordinates of the center of the box. %End Box(Point min, Point max); %Docstring "deindented" Create a box that spans between two points. The ``max`` parameter MUST have greater X and Y coordinates than the ``min`` parameter. If this is not the case, the box will get a negative width or height and madness will ensue. The width and height of the box will automatically be determined from the difference between these two points. The centre will be the average of the two points. :param min: The minimum coordinates of the box. :param max: The maximum coordinates of the box. %End Box(long width, long height); %Docstring "deindented" Create a box with the specified dimensions. The box will be centered on the 0,0 coordinate. :param width: The width of the box. :param height: The height of the box. %End Box(long width, long height, Point center); %Docstring "deindented" Create a box with the specified dimensions, centered in a specified location. :param width: The width of the box. :param height: The height of the box. :param center: The coordinates of the center of the box. %End static Box infinite(Point center); %Docstring "deindented" Create a box with theoretically infinite dimensions. This is useful as a bin to place items in without necessarily bounding the placement of these items at any limit. The center of the box will be used if items are aligned by the placer to the center of the bin. :param center: The theoretical center of the box (to be treated as if it's just a very big box rather than mathematically infinite). :return: A box with theoretically infinite dimensions. %End Point minCorner(); %Docstring "deindented" Returns the minimum coordinates that are still within the box. :return: The minimum coordinates of the box. %End Point maxCorner(); %Docstring "deindented" Returns the maximum coordinates that are still within the box. :return: The maximum coordinates of the box. %End long width(); %Docstring "deindented" Returns the width of the box, its span in the X direction. :return: The width of the box. %End long height(); %Docstring "deindented" Returns the height of the box, its span in the Y direction. :return: The height of the box. %End long area(); %Docstring "deindented" Returns the surface area of the box, i.e. the width times the height of the box. :return: The surface area of the box. %End Point center(); %Docstring "deindented" Returns the center of the box, exactly in between the ``minCorner()`` and the ``maxCorner()``. :return: The center of the box. %End };pynest2d-5.0.0/src/Circle.sip000066400000000000000000000026211422601511200157640ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. class Circle { %Docstring A circular shape, to be used as bin or to be placed in the scene. %End %TypeHeaderCode #include %End public: Circle(); %Docstring Construct a circle centered at 0,0 with radius 0. %End Circle(Point center, double r); %Docstring Construct a circle centered at a specified location and with a specified radius. :param center: The position of the center of the circle. :param r: The radius of the new circle. %End Point center(); %Docstring Gives the center position of the circle. :return: The center of the circle. %End void center(Point center); %Docstring Changes the center position of the circle. :param center: The new center of the circle. %End double radius(); %Docstring Gives the radius of the circle. :return: The radius of the circle. %End void radius(double r); %Docstring Changes the radius of the circle. :param r: The new radius for the circle. %End double area(); %Docstring Computes the area of the circle. The area is only a function of the radius: pi * r ** 2. :return: The area of the circle. %End };pynest2d-5.0.0/src/DJDHeuristicConfig.sip000066400000000000000000000036671422601511200202050ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. struct DJDHeuristicConfig { %Docstring This structure contains configuration options for the DJD Heuristic of selecting objects to place. The following options are available: * try_reverse_order (default True): If true, the algorithm will try to place pairs and triplets in all possible orders. It will have a hugely negative impact on performance. * try_pairs (default True): Whether to try pairs of items to pack. It will add a quadratic component to the complexity. * try_triplets (default False): Whether to try groups of 3 items to pack. This could be very slow for large numbers of items (>100) as it adds a cubic component to the complexity. * initial_fill_proportion (default 1/3): The initial fill proportion of the bin area that will be filled before trying items one by one, or pairs or triplets. The initial fill proportion suggested by Lopez-Camacho is one third of the area of the bin. * waste_increment (default 0.1): How much is the acceptable waste incremented at each iteration. * allow_parallel (default True): Allow parallel jobs for filling multiple bins. This will decrease the solution quality but can greatly boost up performance for large numbers of items. * force_parallel (default False): Always use parallel processing if the items don't fit into one bin. %End %TypeHeaderCode #include using DJDHeuristicConfig = DJDHeuristic::Config; //Make an alias since SIP doesn't deal with namespaces. %End bool try_reverse_order; bool try_pairs; bool try_triplets; double initial_fill_proportion; double waste_increment; double allow_parallel; bool force_parallel; };pynest2d-5.0.0/src/Item.sip000066400000000000000000000332571422601511200154720ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. class Item { %Docstring An item represents something that needs to be fit in the scene. An item has a certain shape. For these Python bindings that shape will always be a polygon. After the nesting has taken place, the item will be transformed. The transformation is encoded in a translation and a rotation. You may also manually scale the item if necessary. The transformed shape can be computed with the transformedShape() function. The original vertex coordinates are not modified then. The item will also be placed in a certain bin, which is normally the first bin unless the first bin is packed completely full. An item can be fixed in place with the markAsFixedInBin() function, preventing the nester to move it. It only blocks other items from being placed then. %End %TypeHeaderCode #include %End public: Item(PyObject* vertex_list); %Docstring Create a new item from a list of vertices. Each vertex must be a Point instance. :param vertex_list: A list of Points that form the vertices of the polygonal shape of this item. %End %MethodCode if(!PyList_Check(a0)) { return NULL; } std::vector vertices; const size_t size = PyList_GET_SIZE(a0); vertices.reserve(size); PyErr_Clear(); //To allow us to test if any Python errors occurred. for(size_t i = 0; i < size; ++i) { PyObject* vertex = PyList_GET_ITEM(a0, i); const long x = PyLong_AsLong(PyObject_CallMethod(vertex, "x", NULL)); const long y = PyLong_AsLong(PyObject_CallMethod(vertex, "y", NULL)); vertices.emplace_back(x, y); if(PyErr_Occurred() != NULL) //Something broke. Need to clean up. Maybe the input is not proper Point instances. { return NULL; } } sipCpp = new Item(vertices); //Makes a copy of the vertices! %End int binId(); %Docstring The bin that this item is assigned to, or -1 if it's not (yet) assigned to any bin. The assigned bin is a version of the bin shape. If all objects fit in one bin, their bin IDs will all be 0. If they don't fit, new bins will be created and some objects will be put in the new bin. :return: The currently assigned bin of this item. %End void binId(int idx); %Docstring Assign this item to a bin. Assigning to a negative number effectively takes this object out of all bins. Use -1 to unassign the item from all bins. :param idx: The index of the bin to assign the item to. %End bool isFixed(); %Docstring Whether this item is fixed in place, not able to be moved by the nester. If the item is fixed, the nester is not allowed to move it and must place other items around it. :return: Whether the item is fixed in a certain bin. %End bool isDisallowedArea(); %Docstring Whether this item is a disallowed area, not able to be moved by the nester and not grouped together with other items. If the item is a disallowed area, the nester is not allowed to move it and not allowed to place other items in the same spot. Contrary to simple fixed items, other items will not be packed nearby disallowed areas by the optimization. :return Whether the item is a disallowed area. %End void markAsFixedInBin(int binid); %Docstring Make this item a fixed item in a certain bin. If the item is fixed, the nester is not allowed to move it and must place other items around it in that bin. This currently only works with the FirstFit selector (which is the default). :param binid: The bin in which this item is fixed. %End void markAsDisallowedAreaInBin(int binid); %Docstring Make this item a disallowed area in a certain bin. If the item is a disallowed area, the nester is not allowed to move it and not allowed to place other items in the same spot. Contrary to simple fixed items, other items will not be packed nearby disallowed areas by the optimization. This currently only works with the FirstFit selector (which is the default). :param binid: The bin in which this item is a disallowed area. %End int priority(); %Docstring Gives the current priority of selecting this item. Items with greater priority (higher number) get selected first by the selectors. :return: The priority of selecting this item. %End void priority(int priority); %Docstring Sets the priority of selecting this item. Items with greater priority (higher number) get selected first by the selectors. This causes them to be placed in earlier bins and perhaps more towards the point where the objects get aligned to (depending on the placer). The priority is not a guarantee. The selector may still select different items first. It only serves as an intuitive way to steer which objects are the most important to be placed. :param priority: The priority to give to this item. %End std::string toString(); %Docstring Give a string representation of this item. This will give a list of all the vertices in the contour of the item. :return: A string representation of the item. %End Point vertex(long idx); %Docstring Get a vertex from the contour of the item. :param idx: The index of the vertex. Should not be vertexCount() or higher. :return: A point along the contour of the item. %End void setVertex(long idx, Point v); %Docstring Change a vertex on the contour of the item. :param idx: The index of the vertex to change. Should not be vertexCount() or higher. :param v: The new coordinates of that vertex. %End double area(); %Docstring Compute the surface area of the item. This is a signed area. If the polygon has the wrong winding order, this area will be negative. :return: The surface area of the item. %End bool isContourConvex(); %Docstring Compute whether the shape of this item is completely convex. The result is cached, so it is safe to query convexity multiple times on the same item as long as the item is not modified in between. :return: True if the item is convex, or False otherwise. %End bool isHoleConvex(long holeindex); %Docstring For holes in the shape, return if the hole is convex. :param holeindex: The index of the hole in the shape. Should be less than holeCount(). :return: True if the specified hole is convex, or False if it's concave. %End bool areHolesConvex(); %Docstring Returns whether all holes are convex. This is the same as going through all holes and querying isHoleConvex() for all of them. :return: True if all holes in the shape are convex, or False if there is at least one concave hole. %End long vertexCount(); %Docstring Get the number of vertices in total in the shape of the item. :return: The number of vertices in the contour. %End long holeCount(); %Docstring Get the number of holes in the shape of the item. :return: The number of holes in the shape. %End bool isInside(Point p); %Docstring Tests whether a point is contained in the shape of this item. :param p: The point to test whether it's contained in this item. :return: True if the point is inside the shape, or False if it's outside. %End bool isInside(Item sh); %Docstring Tests whether a different item is engulfed wholly inside of this item. :param sh: The item to test for whether it is inside of this item. :return: True if the item is wholly engulfed in this item, or False if it falls partially or completely outside of this item. %End bool isInside(Box box); %Docstring Tests whether the box falls completely inside of this item. :param box: The box to test for being contained in this item. :return: True if the box is wholly engulfed in this item, or False if it falls partially or completely outside of this item. %End bool isInside(Circle circle); %Docstring Tests whether the circle falls completely inside of this item. :param circle: The circle to test for being contained in this item. :return: True if the circle is wholly engulfed in this item, or False if it falls partially or completely outside of this item. %End Box boundingBox(); %Docstring Return the smallest axis-aligned bounding box around this item. :return: A bounding box around this item. %End Point referenceVertex(); %Docstring Return a vertex that serves as a reference for this item's shape. The vertex will always be the same if the vertices of the item are the same, even if those vertices are in a different order or if a different item has precisely the same vertices. This can be used for instance to always start iteration in the same spot if the shape is the same. :return: A vertex that serves as reference for the shape. %End Point rightmostTopVertex(); %Docstring Returns the right-most vertex (highest X coordinate). Or if multiple vertices are equally far right, the top-most one of those (highest Y coordinate). This works on the transformed shape. :return: The highest of the right-most vertices. %End Point leftmostBottomVertex(); %Docstring Returns the left-most vertex (lowest X coordinate). Or if multiple vertices are equally far left, the bottom-most one of those (lowest Y coordinate). This works on the transformed shape. :return: The lowest of the left-most vertices. %End void translate(Point delta); %Docstring Move the item relatively in a certain direction. The vertices are not actually transformed in-place, but the transformation of the item is changed. The moved vertices can be found by calling transformedShape(). To arrive at the transformed shape of an item, the rotation is applied first, then the translation. Translation is only afterwards, so first translating the object and then rotating it will not cause the item to rotate by the translation vector around 0. It will rotate around its original 0 coordinate instead. :param delta: The motion vector by which to move this item. %End Point translation(); %Docstring Get the current translation of the item. This gets changed by arranging the items in the bins. :return: The current translation of the item. %End void rotate(double radians); %Docstring Rotate the item by a certain amount. The vertices are not actually transformed in-place, but the transformation of the item is changed. The moved vertices can be found by calling transformedShape(). :param radians: The amount of rotation to apply, in radians. A positive rotation will rotate the item counter-clockwise. %End double rotation(); %Docstring Get the current amount of rotation applied to the model. This gets changed by arranging the items in the bins. :return: The current rotation of the model. %End void inflation(long distance); %Docstring Offset the shape by a certain amount. This will make the shape wider in all directions, as if performing a Minkowski sum with a circle with the specified distance as radius. A negative distance will result in an inset of the original shape. :param distance: The distance by which to offset the shape. %End long inflation(); %Docstring Get the current amount of inflation from the original shape. :return The current amount of inflation. %End Item transformedShape(); %Docstring Create a new item that has the transformation of this item applied to its vertices. From the new item you can get the vertex coordinates to get the polygonal coordinates of the transformed shape. :return: A copy of this item, but with the transformation applied to its vertices. %End void resetTransformation(); %Docstring Remove all transformations on this item, reverting it to its original state. %End static bool intersects(Item sh1, Item sh2); %Docstring Test whether two items intersect. Two items intersect only if they have a non-zero area of overlap. :param sh1: One of the items to test intersection with. :param sh2: The other item to test intersection with. :return: True if they intersect, or False if they are disjoint. %End static bool touches(Item sh1, Item sh2); %Docstring Test whether two items touch. Touching items includes the edge case where two items touch only on a vertex or on an edge but don't necessarily have any positive area of overlap. They may also just touch on the contour of the shape. If two items intersect, they also always touch. %End };pynest2d-5.0.0/src/ItemGroup.sip000066400000000000000000000044731422601511200165050ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. %MappedType ItemGroup { %TypeHeaderCode #include #include using ItemGroup = PlacementStrategyLike::ItemGroup; //Make an alias here since SIP doesn't namespace syntax nor template syntax. %End %ConvertFromTypeCode //From ItemGroup to Python list. const long size = sipCpp->size(); if(size < 0) { return NULL; } PyObject* result_list = PyList_New(size); if(!result_list) { return NULL; } for(size_t i = 0; i < size; ++i) { Item item = sipCpp->at(0); PyObject* python_item = sipConvertFromType(&item, sipType_Item, sipTransferObj); if(!python_item) { Py_DECREF(result_list); return NULL; } PyList_SET_ITEM(result_list, i, python_item); } return result_list; %End %ConvertToTypeCode //From Python list to ItemGroup. PyObject* iterator = PyObject_GetIter(sipPy); if(!sipIsErr) //We're only checking if it can be converted. { //Must be any iterable. const bool iterable = (iterator != NULL); Py_XDECREF(iterator); return iterable; } ItemGroup* result = new ItemGroup(); PyObject* list_item; while(list_item = PyIter_Next(iterator)) { if(!sipCanConvertToType(list_item, sipType_Item, SIP_NOT_NONE)) { PyErr_Format(PyExc_TypeError, "Object in iterable cannot be converted to a libnest2d Item."); *sipIsErr = 1; break; } int state; Item* item = reinterpret_cast(sipConvertToType(list_item, sipType_Item, 0, SIP_NOT_NONE, &state, sipIsErr)); if(!*sipIsErr) { result->push_back(*item); } sipReleaseType(item, sipType_Item, state); Py_DECREF(list_item); } Py_DECREF(iterator); if(*sipIsErr) { delete result; return 0; } *sipCppPtr = result; return sipGetState(sipTransferObj); %End };pynest2d-5.0.0/src/NfpConfig.sip000066400000000000000000000047051422601511200164410ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. struct NfpConfig { %Docstring This is a configuration structure to configure the NfpPPlacer. It has several attributes to configure how it places items. The following options are available: * alignment (default CENTER): Where to align the resulting packed pile. * starting_point (default CENTER): Where to start placing items in the bin. * rotations (default [0, 0.5 * pi, pi, 1.5 * pi]): Rotations to try to place the object in. More rotations may cause the objects to be packed closer together, but also significantly increases computation time. * accuracy (default 0.65): How far to search for the best placement. 0.0 is not very accurate, but computes fast. 1.0 is the best accuracy, but takes a lot of computation power. * explore_holes (default False): Whether to allow placing items inside holes in other shapes. This functionality doesn't currently work in libnest2d. * parallel (default True): Whether to try different options in multiple threads in parallel. %End %TypeHeaderCode #include using NfpConfig = NfpPConfig; //Specialise the templated NfpPConfig class since SIP doesn't deal with templates. %End enum class Alignment { CENTER, BOTTOM_LEFT, BOTTOM_RIGHT, TOP_LEFT, TOP_RIGHT, DONT_ALIGN }; Alignment alignment; Alignment starting_point; std::vector rotations { %GetCode sipPy = PyList_New(sipCpp->rotations.size()); for(size_t i = 0; i < sipCpp->rotations.size(); ++i) { PyList_SET_ITEM(sipPy, i, PyFloat_FromDouble(sipCpp->rotations[i])); } %End %SetCode if(!PyList_Check(sipPy)) { sipErr = 1; return 1; } sipCpp->rotations.clear(); PyErr_Clear(); size_t size = PyList_Size(sipPy); sipCpp->rotations.reserve(size); for(size_t i = 0; i < size; ++i) { sipCpp->rotations.push_back(PyFloat_AsDouble(PyList_GET_ITEM(sipPy, i))); } return 0; %End }; double accuracy; bool explore_holes; bool parallel; };pynest2d-5.0.0/src/Point.sip000066400000000000000000000016341422601511200156570ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. class Point { %Docstring Represents a point in 2D space or a 2D vector. %End %TypeHeaderCode #include %End public: Point(long x, long y); %Docstring Construct a new point with the given coordinates. :param x: The X coordinate of the new point. :param y: The Y coordinate of the new point. %End long x(); %Docstring Return the X coordinate of the point. :return: The X coordinate of the point. %End %MethodCode sipRes = sipCpp->X; //Use Clipper implementation. %End long y(); %Docstring Return the Y coordinate of the point. :return: The Y coordinate of the point. %End %MethodCode sipRes = sipCpp->Y; //Use Clipper implementation. %End };pynest2d-5.0.0/src/Rectangle.sip000066400000000000000000000257201422601511200164740ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. class Rectangle { %Docstring A rectangular item. This item can be placed in the bins and arranged there. Some algorithms may work faster on rectangles than on arbitrary polygons. %End %TypeHeaderCode #include %End public: Rectangle(long width, long height); %Docstring Construct a new rectangle with a specified width and height. The bottom-left corner of the rectangle will be placed at the 0-coordinate. :param width: The width of the new rectangle. :param height: The height of the new rectangle. %End long width(); %Docstring Get the width of this rectangle. :return: The width of the rectangle. %End long height(); %Docstring Get the height of this rectangle. :return: The height of the rectangle. %End //Members inherited from Item. int binId(); %Docstring The bin that this item is assigned to, or -1 if it's not (yet) assigned to any bin. The assigned bin is a version of the bin shape. If all objects fit in one bin, their bin IDs will all be 0. If they don't fit, new bins will be created and some objects will be put in the new bin. :return: The currently assigned bin of this item. %End void binId(int idx); %Docstring Assign this item to a bin. Assigning to a negative number effectively takes this object out of all bins. Use -1 to unassign the item from all bins. :param idx: The index of the bin to assign the item to. %End bool isFixed(); %Docstring Whether this item is fixed in place, not able to be moved by the nester. If the item is fixed, the nester is not allowed to move it and must place other items around it. :return: Whether the item is fixed in a certain bin. %End void markAsFixedInBin(int binid); %Docstring Make this item a fixed item in a certain bin. If the item is fixed, the nester is not allowed to move it and must place other items around it in that bin. This currently only works with the FirstFit selector (which is the default). :param binid: The bin in which this item is fixed. %End int priority(); %Docstring Gives the current priority of selecting this item. Items with greater priority (higher number) get selected first by the selectors. :return: The priority of selecting this item. %End void priority(int priority); %Docstring Sets the priority of selecting this item. Items with greater priority (higher number) get selected first by the selectors. This causes them to be placed in earlier bins and perhaps more towards the point where the objects get aligned to (depending on the placer). The priority is not a guarantee. The selector may still select different items first. It only serves as an intuitive way to steer which objects are the most important to be placed. :param priority: The priority to give to this item. %End std::string toString(); %Docstring Give a string representation of this item. This will give a list of all the vertices in the contour of the item. :return: A string representation of the item. %End double area(); %Docstring Compute the surface area of the item. This is a signed area. If the polygon has the wrong winding order, this area will be negative. :return: The surface area of the item. %End bool isContourConvex(); %Docstring Compute whether the shape of this item is completely convex. The result is cached, so it is safe to query convexity multiple times on the same item as long as the item is not modified in between. :return: True if the item is convex, or False otherwise. %End bool isHoleConvex(long holeindex); %Docstring For holes in the shape, return if the hole is convex. :param holeindex: The index of the hole in the shape. Should be less than holeCount(). :return: True if the specified hole is convex, or False if it's concave. %End bool areHolesConvex(); %Docstring Returns whether all holes are convex. This is the same as going through all holes and querying isHoleConvex() for all of them. :return: True if all holes in the shape are convex, or False if there is at least one concave hole. %End long vertexCount(); %Docstring Get the number of vertices in total in the shape of the item. :return: The number of vertices in the contour. %End long holeCount(); %Docstring Get the number of holes in the shape of the item. :return: The number of holes in the shape. %End bool isInside(Point p); %Docstring Tests whether a point is contained in the shape of this item. :param p: The point to test whether it's contained in this item. :return: True if the point is inside the shape, or False if it's outside. %End bool isInside(Item sh); %Docstring Tests whether a different item is engulfed wholly inside of this item. :param sh: The item to test for whether it is inside of this item. :return: True if the item is wholly engulfed in this item, or False if it falls partially or completely outside of this item. %End bool isInside(Box box); %Docstring Tests whether the box falls completely inside of this item. :param box: The box to test for being contained in this item. :return: True if the box is wholly engulfed in this item, or False if it falls partially or completely outside of this item. %End bool isInside(Circle circle); %Docstring Tests whether the circle falls completely inside of this item. :param circle: The circle to test for being contained in this item. :return: True if the circle is wholly engulfed in this item, or False if it falls partially or completely outside of this item. %End Box boundingBox(); %Docstring Return the smallest axis-aligned bounding box around this item. :return: A bounding box around this item. %End Point referenceVertex(); %Docstring Return a vertex that serves as a reference for this item's shape. The vertex will always be the same if the vertices of the item are the same, even if those vertices are in a different order or if a different item has precisely the same vertices. This can be used for instance to always start iteration in the same spot if the shape is the same. :return: A vertex that serves as reference for the shape. %End Point rightmostTopVertex(); %Docstring Returns the right-most vertex (highest X coordinate). Or if multiple vertices are equally far right, the top-most one of those (highest Y coordinate). This works on the transformed shape. :return: The highest of the right-most vertices. %End Point leftmostBottomVertex(); %Docstring Returns the left-most vertex (lowest X coordinate). Or if multiple vertices are equally far left, the bottom-most one of those (lowest Y coordinate). This works on the transformed shape. :return: The lowest of the left-most vertices. %End void translate(Point delta); %Docstring Move the item relatively in a certain direction. The vertices are not actually transformed in-place, but the transformation of the item is changed. The moved vertices can be found by calling transformedShape(). To arrive at the transformed shape of an item, the rotation is applied first, then the translation. Translation is only afterwards, so first translating the object and then rotating it will not cause the item to rotate by the translation vector around 0. It will rotate around its original 0 coordinate instead. :param delta: The motion vector by which to move this item. %End Point translation(); %Docstring Get the current translation of the item. This gets changed by arranging the items in the bins. :return: The current translation of the item. %End void rotate(double radians); %Docstring Rotate the item by a certain amount. The vertices are not actually transformed in-place, but the transformation of the item is changed. The moved vertices can be found by calling transformedShape(). :param radians: The amount of rotation to apply, in radians. A positive rotation will rotate the item counter-clockwise. %End double rotation(); %Docstring Get the current amount of rotation applied to the model. This gets changed by arranging the items in the bins. :return: The current rotation of the model. %End void inflation(long distance); %Docstring Offset the shape by a certain amount. This will make the shape wider in all directions, as if performing a Minkowski sum with a circle with the specified distance as radius. A negative distance will result in an inset of the original shape. :param distance: The distance by which to offset the shape. %End long inflation(); %Docstring Get the current amount of inflation from the original shape. :return The current amount of inflation. %End Item transformedShape(); %Docstring Create a new item that has the transformation of this item applied to its vertices. From the new item you can get the vertex coordinates to get the polygonal coordinates of the transformed shape. :return: A copy of this item, but with the transformation applied to its vertices. %End void resetTransformation(); %Docstring Remove all transformations on this item, reverting it to its original state. %End static bool intersects(Item sh1, Item sh2); %Docstring Test whether two items intersect. Two items intersect only if they have a non-zero area of overlap. :param sh1: One of the items to test intersection with. :param sh2: The other item to test intersection with. :return: True if they intersect, or False if they are disjoint. %End static bool touches(Item sh1, Item sh2); %Docstring Test whether two items touch. Touching items includes the edge case where two items touch only on a vertex or on an edge but don't necessarily have any positive area of overlap. They may also just touch on the contour of the shape. If two items intersect, they also always touch. %End };pynest2d-5.0.0/src/String.sip000066400000000000000000000030351422601511200160310ustar00rootroot00000000000000//Copyright (c) 2020 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. /*! * Mapping std::string to Python str objects. * * Based on implementation of libSavitar. */ %MappedType std::string { %TypeHeaderCode #include %End %ConvertFromTypeCode PyObject* result = PyUnicode_DecodeUTF8(sipCpp->c_str(), sipCpp->length(), NULL); if(!result) { result = PyBytes_FromString(sipCpp->c_str()); } return result; %End %ConvertToTypeCode if(!sipIsErr) //Just a request to check if we can convert. { return PyBytes_Check(sipPy) || PyUnicode_Check(sipPy); //We can convert from Python bytes and str. } if(sipPy == Py_None) //Convert None to empty string. Happens when we supply no parameter to the str() function. { *sipCppPtr = new std::string(); return 1; } else if(PyUnicode_Check(sipPy)) //Is a str. { PyObject* str = PyUnicode_AsEncodedString(sipPy, "UTF-8", ""); //Temporarily convert to Python str which has the AS_STRING function. *sipCppPtr = new std::string(PyBytes_AS_STRING(str)); Py_DECREF(str); //Temporary object goes immediately out of scope. return 1; } else if(PyBytes_Check(sipPy)) //Is a str. { *sipCppPtr = new std::string(PyBytes_AS_STRING(sipPy)); return 1; } else { return 0; } %End };pynest2d-5.0.0/src/pynest2d.sip000066400000000000000000000117101422601511200163320ustar00rootroot00000000000000//Copyright (c) 2022 Ultimaker B.V. //pynest2d is released under the terms of the LGPLv3 or higher. %Module(name = pynest2d, call_super_init = True) %Include BottomLeftConfig.sip %Include Box.sip %Include Circle.sip %Include DJDHeuristicConfig.sip %Include Item.sip %Include ItemGroup.sip %Include NfpConfig.sip %Include Point.sip %Include Rectangle.sip %Include String.sip %ModuleHeaderCode #include #include //Use the Subplex local optimizer. Also imported by libnest2d.hpp but somehow this needs to be imported in correct order! #include namespace libnest2d{ namespace placers{} } using namespace libnest2d; using namespace placers; %End /*! * Convert ranges of Item objects to and from Python lists. */ %MappedType std::vector { %TypeHeaderCode #include #include using ItemRange = std::pair::iterator, std::vector::iterator>; %End %ConvertFromTypeCode //From std::vector to Python list. const long size = sipCpp->size(); if(size < 0) { return NULL; } PyObject* result_list = PyList_New(size); if(!result_list) { return NULL; } for(size_t i = 0; i < size; ++i) { Item* item = sipCpp->at(0); PyObject* python_item = sipConvertFromType(item, sipType_Item, sipTransferObj); if(!python_item) { Py_DECREF(result_list); return NULL; } PyList_SET_ITEM(result_list, i, python_item); } return result_list; %End %ConvertToTypeCode //From Python list to vector of Items. PyObject* iterator = PyObject_GetIter(sipPy); if(!sipIsErr) //We're only checking if it can be converted. { //Must be any iterable. const bool iterable = (iterator != NULL); Py_XDECREF(iterator); return iterable; } std::vector* storage_vector = new std::vector(); PyObject* list_item; while(list_item = PyIter_Next(iterator)) { if(!sipCanConvertToType(list_item, sipType_Item, SIP_NOT_NONE)) { PyErr_Format(PyExc_TypeError, "Object in iterable cannot be converted to a libnest2d Item."); *sipIsErr = 1; break; } int state; Item* item = reinterpret_cast(sipConvertToType(list_item, sipType_Item, 0, SIP_NOT_NONE, &state, sipIsErr)); if(!*sipIsErr) { storage_vector->push_back(item); } sipReleaseType(item, sipType_Item, state); Py_DECREF(list_item); } Py_DECREF(iterator); if(*sipIsErr) { delete storage_vector; return 0; } *sipCppPtr = storage_vector; return sipGetState(sipTransferObj); %End }; long nest(std::vector items, Box bin, long distance = 1, NfpConfig config = NfpConfig()); %Docstring Arrange a number of items in bins, packing them closely with the goal to minimise the number of bins necessary to pack all given items. This function uses the FirstFit selector and NfpPPlacer in its algorithms, and Clipper as geometry back-end. The result of the packing is stored in the transformation of the input items. You can get the transformed items by calling transformedShape() on each of the items, or by looking at their rotation and translation. Items may also be placed on alternative bins if the first bin is not big enough to fit all items. :param items: An iterable of Item instances which are the items that need to be placed in the bins. :param bin: The shape in which to place these items. :param distance: (Default 1.) The distance to hold between adjacent items in the final pack result. Items will not get placed closer than this distance. Must be at least 1 unit. :param config: An NfpConfig instance that contains configuration options to specialize how objects get placed. Defaults will be used if this is not provided. :return: The number of bins necessary to fit all items. %End %MethodCode //Pre-process distance. if(a2 <= 0) { a2 = 1; //Need to keep at least 1 unit of distance, or the nester breaks. } //Pre-process items. std::vector to_arrange; to_arrange.reserve(a0->size()); for(Item* item : *a0) { to_arrange.push_back(*item); } //Pre-process config. NestConfig<> nest_config(*a3); //NestConfig wraps a placer and selector config. Only with the default selector there is no config, so just the placer then. sipRes = nest(to_arrange, *a1, a2, nest_config); for(size_t i = 0; i < a0->size(); ++i) { *(a0->at(i)) = to_arrange[i]; } %End