### Start Nesting Optimization Source: https://github.com/jack000/deepnest/blob/master/_autodocs/architecture.md Initiates the nesting process by starting the genetic algorithm and launching worker processes for placement calculation. ```text DeepNest.start(progressCallback, displayCallback) │ ├─► Initialize Genetic Algorithm │ ├─► Create initial population (random permutations) │ └─► Seed by descending area │ ├─► Launch worker timer (every 100ms) │ └─► DeepNest.launchWorkers() │ ├─► Shuffle population for diversity │ ├─► For each individual in population: │ │ │ ├─► Background worker processes │ │ │ └─► NFP-based placement calculation │ ├─► Compute No-Fit Polygons (NFPs) │ ├─► Simulate gravity placement │ └─► Calculate fitness score │ └─► IPC response: background-response │ ├─► Update fitness in GA │ ├─► If better than best: │ ├─► Store in DeepNest.nests │ └─► Call displayCallback() │ └─► Breed next generation ├─► Select fittest individuals ├─► Apply crossover (shuffle) └─► Apply mutation (random permutation) ``` -------------------------------- ### Basic Nesting Workflow Source: https://github.com/jack000/deepnest/blob/master/_autodocs/INDEX.md Demonstrates the four main steps of using DeepNest: importing SVG, configuring parameters, starting the optimization process, and applying the placement results. Ensure DeepNest is imported and configured before starting. ```javascript // 1. Import SVG DeepNest.importsvg('file.svg', './', svgContent); // 2. Configure DeepNest.config({ spacing: 2, rotations: 4 }); // 3. Optimize DeepNest.start(); setTimeout(() => DeepNest.stop(), 10000); // 4. Export const sheets = DeepNest.applyPlacement(DeepNest.nests[0]); ``` -------------------------------- ### Set Part Quantities Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Allows you to specify the desired quantity for individual parts before starting the nesting process. This example sets the quantity for the first two parts. ```javascript DeepNest.parts[0].quantity = 5; // Make 5 copies of first part DeepNest.parts[1].quantity = 3; // Make 3 copies of second part ``` -------------------------------- ### start Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgnest-class.md Begins the nesting optimization process on the parsed SVG. Returns false if SVG or bin is not set, true otherwise. ```APIDOC ## start ### Description Begins the nesting optimization process on the parsed SVG. ### Method `start(progressCallback, displayCallback)` ### Parameters #### Path Parameters - **progressCallback** (function) - Optional - Called periodically during optimization - **displayCallback** (function) - Optional - Called when a new placement is found ### Response #### Success Response - **boolean** - False if SVG or bin is not set; true otherwise ### Request Example ```javascript const started = SvgNest.start( () => console.log('Progress'), () => console.log('New placement') ); ``` ``` -------------------------------- ### Starting a Nesting Operation Flow Source: https://github.com/jack000/deepnest/blob/master/_autodocs/ipc-protocol.md This sequence illustrates the IPC communication flow initiated by the user clicking 'Start' in the main window, leading to background workers processing nesting operations. ```text User clicks "Start" in Main Window │ └─► DeepNest.start(progressCb, displayCb) │ ├─► Create genetic algorithm population │ └─► Set workerTimer (100ms interval) │ └─► DeepNest.launchWorkers() │ └─► For each free background worker: │ ├─► ipcMain.send('background-start', {parts, config, population[i]}) │ └─► Main process routes to worker: ipcRenderer.send('background-start', ...) Worker processes placement ipcRenderer.send('background-response', {index, placement, fitness}) Main process receives and updates population displayCallback() triggered if new best found ``` -------------------------------- ### Start Nesting Process Source: https://github.com/jack000/deepnest/blob/master/main/index.html Initiates the nesting process. It checks if parts are loaded and if a sheet has been marked. If conditions are met, it starts the DeepNest algorithm and updates the UI. ```javascript function startnest(){ if(DeepNest.parts.length == 0){ message("Please import some parts first"); } else{ message("Please mark at least one part as the sheet"); } } document.querySelector('#startnest').onclick = startnest; ``` -------------------------------- ### Start Nesting Optimization Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Initiates the nesting optimization process using a genetic algorithm. Accepts optional callbacks for progress updates and notifications of new placements. ```javascript DeepNest.start( () => { console.log('Progress update'); }, () => { console.log('New placement found!'); } ); ``` -------------------------------- ### Start Nesting Optimization Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgnest-class.md Initiates the nesting optimization process. Accepts optional callbacks for progress and display updates. Returns false if SVG or bin is not set. ```javascript const started = SvgNest.start( () => console.log('Progress'), () => console.log('New placement') ); ``` -------------------------------- ### Multi-Stage Optimization Example Source: https://github.com/jack000/deepnest/blob/master/_autodocs/optimization-algorithm.md Demonstrates a practical approach to optimization by using multiple stages with different configurations. This allows for fast initial exploration followed by more refined and thorough optimization. Requires 'DeepNest.config', 'DeepNest.start', 'DeepNest.reset', and 'waitSeconds'. ```javascript // Stage 1: Fast exploration DeepNest.config({rotations: 2, populationSize: 5}); DeepNest.start(); await waitSeconds(10); // Stage 2: Refinement DeepNest.reset(); DeepNest.config({rotations: 4, populationSize: 15}); DeepNest.start(); await waitSeconds(30); // Stage 3: Polish DeepNest.reset(); DeepNest.config({rotations: 8, populationSize: 30}); DeepNest.start(); await waitSeconds(60); ``` -------------------------------- ### Ractive.js Main Instance Setup Source: https://github.com/jack000/deepnest/blob/master/main/index.html Initializes the main Ractive.js instance for the home content, setting up templates, data, computed properties, and components. It includes functions for filtering parts, serializing SVGs, and rendering parts. ```javascript var ractive = new Ractive({ el: '#homecontent', //magic: true, template: '#template-part-list', data: { parts: DeepNest.parts, imports: DeepNest.imports, getSelected: function(){ var parts = this.get('parts'); return parts.filter(function(p){ return p.selected; }); }, getSheets: function(){ var parts = this.get('parts'); return parts.filter(function(p){ return p.sheet; }); }, serializeSvg: function(svg){ return (new XMLSerializer()).serializeToString(svg); }, partrenderer: function(part){ var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('width', (part.bounds.width+10)+'px'); svg.setAttribute('height', (part.bounds.height+10)+'px'); svg.setAttribute('viewBox', (part.bounds.x-5)+' '+(part.bounds.y-5)+' '+(part.bounds.width+10)+' '+(part.bounds.height+10)); part.svgelements.forEach(function(e){ svg.appendChild(e.cloneNode(false)); }); return (new XMLSerializer()).serializeToString(svg); } }, computed: { getUnits: function(){ var units = config.getSync('units'); if(units == 'mm'){ return 'mm'; } else{ return 'in'; } } }, components: { dimensionLabel: label } }); ``` -------------------------------- ### Import and Nesting Control Buttons Source: https://github.com/jack000/deepnest/blob/master/main/index.html Provides buttons for importing parts and starting the nesting process. The 'Start nest' button is disabled if no sheets are available. ```html ``` -------------------------------- ### config Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgnest-class.md Gets or sets nesting configuration parameters. Returns the current configuration. ```APIDOC ## config ### Description Gets or sets nesting configuration parameters. ### Method `config(c)` ### Parameters #### Path Parameters - **c** (ConfigObject) - Optional - Configuration object with parameters to update ### Response #### Success Response - **ConfigObject** - Current configuration ### Request Example ```javascript const config = SvgNest.config(); SvgNest.config({ spacing: 2, rotations: 4 }); ``` ``` -------------------------------- ### Start Nesting Process Source: https://github.com/jack000/deepnest/blob/master/main/index.html Initiates the nesting process by checking for available sheets and updating the UI to display the nesting interface. It then selects and displays the first nest if no other nests are selected. ```javascript var startnest = function(){ for(var i=0; i 1 && this.DeepNest.nests[1].selected)){ this.DeepNest.nests.forEach(function(n){ n.selected = false; }); displayNest(this.DeepNest.nests[0]); this.DeepNest.nests[ } }; return false; } } }; ``` -------------------------------- ### Configure and Optimize Nesting Source: https://github.com/jack000/deepnest/blob/master/_autodocs/INDEX.md Configures DeepNest with specific parameters and starts the optimization process. It logs progress and stops after a set duration, then logs the best fitness found. ```javascript DeepNest.config({ spacing: 2, rotations: 4, populationSize: 15, threads: 4 }); DeepNest.start( () => console.log('Optimizing...'), () => console.log('Found better placement!') ); setTimeout(() => { DeepNest.stop(); const best = DeepNest.nests[0]; console.log(`Best fitness: ${best.fitness}`); }, 30000); ``` -------------------------------- ### Start Nesting Optimization Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Initiates the nesting optimization process. It accepts two callback functions: one for periodic updates during optimization and another for when a better solution is found. The optimization can be stopped using DeepNest.stop(). ```javascript DeepNest.start( () => { // Called periodically during optimization console.log('Optimizing...'); }, () => { // Called when a better solution is found console.log('Found better placement!'); console.log('Fitness:', DeepNest.nests[0].fitness); } ); // Let it run for a while... setTimeout(() => DeepNest.stop(), 5000); // Stop after 5 seconds ``` -------------------------------- ### Geometry Calculations with DeepNest and GeometryUtil Source: https://github.com/jack000/deepnest/blob/master/_autodocs/INDEX.md Provides examples for common geometry operations such as checking if a point is within a polygon, calculating a polygon's area and bounding box, and expanding a polygon. These functions are available through DeepNest or the GeometryUtil module. ```javascript // Test if point is in polygon const inside = DeepNest.pointInPolygon(point, polygon); // Get polygon area and bounds const area = GeometryUtil.polygonArea(polygon); const bounds = GeometryUtil.getPolygonBounds(polygon); // Offset/expand polygon const expanded = DeepNest.polygonOffset(polygon, 2); ``` -------------------------------- ### Iterative Improvement with DeepNest Configuration Changes Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Improve nesting results iteratively by starting with a fast configuration and then switching to a more refined one after an initial optimization period. This balances speed and quality. ```javascript // Start with fast configuration DeepNest.config({rotations: 2, populationSize: 5}); DeepNest.start(); setTimeout(() => { DeepNest.stop(); // Switch to better configuration DeepNest.config({rotations: 4, populationSize: 15}); DeepNest.start(); setTimeout(() => DeepNest.stop(), 30000); }, 5000); ``` -------------------------------- ### SvgParser.config Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgparser.md Gets or sets parser configuration options, such as tolerance for curve conversion and endpoint matching, as well as the scale factor. ```APIDOC ## SvgParser.config ### Description Gets or sets parser configuration options. ### Method Static method ### Signature ```javascript SvgParser.config(config) ``` ### Parameters #### Path Parameters - **config** (ConfigObject) - yes - Configuration object ### Response #### Success Response - **undefined** ### Configuration Options - `tolerance`: Maximum deviation for Bezier-to-line conversion (default: 2) - `endpointTolerance`: Tolerance for endpoint matching (default: 2) - `scale`: SVG scale factor (default: 72) ### Request Example ```javascript SvgParser.config({ tolerance: 0.5, endpointTolerance: 1, scale: 72 }); ``` ``` -------------------------------- ### Configure SvgParser Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgparser.md Gets or sets parser configuration options like tolerance and scale. Use this to fine-tune the SVG parsing and conversion process. ```javascript SvgParser.config(config) ``` ```javascript SvgParser.config({ tolerance: 0.5, endpointTolerance: 1, scale: 72 }); ``` -------------------------------- ### Get or Set Nesting Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Retrieves the current nesting configuration or updates specific parameters. Useful for tuning the nesting algorithm's behavior. ```javascript // Get current config const currentConfig = DeepNest.config(); // Update config DeepNest.config({ spacing: 2, rotations: 4, populationSize: 20, threads: 4 }); ``` -------------------------------- ### Get and Set Nesting Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgnest-class.md Retrieves the current nesting configuration or updates specific parameters. Useful for adjusting optimization settings like spacing and rotation. ```javascript const config = SvgNest.config(); SvgNest.config({ spacing: 2, rotations: 4 }); ``` -------------------------------- ### Set SvgNest Configuration Parameters Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md Configures parameters specifically for SvgNest, such as curve tolerance and spacing. This method is used to adjust nesting behavior before starting the process. ```javascript SvgNest.config({ curveTolerance: 0.5, spacing: 1.0 }); ``` -------------------------------- ### Stop Nesting Process Source: https://github.com/jack000/deepnest/blob/master/main/index.html Handles the action to stop the current nesting process. It sends a background stop command, updates the UI to reflect the stopped state, and resets the button to 'Start nest'. ```javascript var stop = document.querySelector('#stopnest'); stop.onclick = function(e){ if(stop.className == 'button stop'){ ipcRenderer.send('background-stop'); DeepNest.stop(); document.querySelectorAll('li.progress').forEach(function(p){ p.removeAttribute('id'); p.className = 'progress'; }); stop.className = 'button stop disabled'; setTimeout(function(){ stop.className = 'button start'; stop.innerHTML = 'Start nest'; }, 3000); } else if(stop.className == 'button start'){ stop.className = 'button stop disabled'; setTimeout(function(){ stop.className = 'button stop'; stop.innerHTML = 'Stop nest'; }, 1000); startnest(); } } ``` -------------------------------- ### Optimize for Large Files with DeepNest Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Configure DeepNest for performance with large files by reducing precision, enabling simplification, and using a smaller population size. Shorten optimization time by starting and stopping the process within a specific duration. ```javascript // Reduce precision where safe DeepNest.config({ curveTolerance: 1.0, // Looser tolerance simplify: true // Approximate with convex hull }); // Smaller population DeepNest.config({ populationSize: 5, rotations: 2 }); // Short optimization time DeepNest.start(); setTimeout(() => DeepNest.stop(), 10000); // 10 seconds ``` -------------------------------- ### Applying Webfont in CSS Source: https://github.com/jack000/deepnest/blob/master/main/font/lato-lig-demo.html This CSS example demonstrates how to apply a previously defined webfont to an HTML element. The 'font-family' property is used to specify the webfont name, followed by fallback fonts. ```css p { font-family: 'WebFont', Arial, sans-serif; } ``` -------------------------------- ### Initialize Ractive Component for Nesting UI Source: https://github.com/jack000/deepnest/blob/master/main/index.html Initializes a Ractive component to manage the UI for nesting results. It defines template, data, and helper functions for selecting nests, getting part sources, assigning colors, and calculating placement statistics. ```javascript window.nest = new Ractive({ el: '#nestcontent', //magic: true, template: '#nest-template', data: { nests: DeepNest.nests, getSelected: function(){ var ne = this.get('nests'); return ne.filter(function(n){ return n.selected; }); }, getNestedPartSources: function(n){ var p = []; for(var i=0; i < n.placements.length; i++){ var sheet = n.placements[i]; for(var j=0; j < sheet.sheetplacements.length; j++){ p.push(sheet.sheetplacements[j].source); } } return p; }, getColorBySource: function(id){ return 'hsl('+(360*(id/DeepNest.parts.length))+', 100%, 80%)'; }, getPartsPlaced: function(){ var ne = this.get('nests'); var selected = ne.filter(function(n){ return n.selected; }); if(selected.length == 0){ return ''; } selected = selected.pop(); var num = 0; for(var i=0; i { // Calculate placement and fitness const placement = computePlacement(payload.parts, payload.population[0]); const fitness = calculateFitness(placement); // Send result back ipcRenderer.send('background-response', { index: payload.index, placement: placement, fitness: fitness }); }); ``` -------------------------------- ### Fast Preview Nesting Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Sets up Deepnest for quick, interactive previews. This configuration uses fewer rotation angles, a smaller population, less mutation, fewer threads, and a shorter time ratio for rapid results. ```javascript DeepNest.config({ rotations: 2, // 180° increments populationSize: 5, // Small population mutationRate: 5, // Less variation threads: 2, // Few threads timeRatio: 0.2 // Quick evaluation }); // Run for 5 seconds DeepNest.start(); setTimeout(() => DeepNest.stop(), 5000); ``` -------------------------------- ### DeepNest.config Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Gets or sets nesting configuration parameters. It can be called with no arguments to retrieve the current configuration or with a ConfigObject to update specific parameters. ```APIDOC ## DeepNest.config ### Description Gets or sets nesting configuration parameters. ### Method `config(c)` ### Parameters #### Path Parameters - **c** (ConfigObject) - Optional - Configuration object with parameters to update ### Response #### Success Response (200) - **ConfigObject** - Current configuration ### Request Example ```javascript // Get current config const currentConfig = DeepNest.config(); // Update config DeepNest.config({ spacing: 2, rotations: 4, populationSize: 20, threads: 4 }); ``` ``` -------------------------------- ### Initialize and Show Auth0 Lock Source: https://github.com/jack000/deepnest/blob/master/main/login.html Sets up the Auth0 Lock widget for user authentication, configuring redirect URLs, container, and theme. Use this to initiate the login process. ```javascript function ready(fn){ if (document.readyState != 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } const path = require('path'); const url = require('url'); ready(function(){ var callbackurl = url.format({ pathname: path.join(__dirname, './login.html'), protocol: 'file:', slashes: true }); var lock = new Auth0Lock('PJGZ1xzyBhBLOCEdRFdIYGNEA1HtIHdt', 'deepnest.auth0.com', { closable: false, auth: { sso: false, redirectUrl: 'http://accounts.deepnest.io' }, container: 'auth', languageDictionary: { title: "Deepnest login" }, theme: { logo: 'img/auth0logo.svg', primaryColor: '#24C7ED' } }); lock.show(); }); ``` -------------------------------- ### Reset Nesting Results Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Clears all previously computed nesting results and associated callbacks. Useful for starting a new nesting job from scratch. ```javascript DeepNest.reset(); ``` -------------------------------- ### Initialize UI Elements and Version Info Source: https://github.com/jack000/deepnest/blob/master/main/index.html This snippet initializes UI elements by removing specific CSS classes and displays the application version by reading from package.json. It also adds spinner elements to form description lists. ```javascript ('.config_explain').forEach(function(el){ el.className = 'config_explain'; }); } }); // add spinner element to each form dd var dd = document.querySelectorAll('#configform dd'); Array.from(dd).forEach(d => { var spinner = document.createElement("div"); spinner.className = 'spinner'; d.appendChild(spinner); }); // version info var pjson = require('../package.json'); var version = document.querySelector('#package-version'); version.innerText = pjson.version; ``` -------------------------------- ### Main Window Handling 'background-response' Source: https://github.com/jack000/deepnest/blob/master/_autodocs/ipc-protocol.md This snippet demonstrates how the main window receives fitness results from a background worker, updates the genetic algorithm population, and potentially stores a new best nest. ```javascript ipcRenderer.on('background-response', (event, payload) => { // Update GA population with fitness GA.population[payload.index].fitness = payload.fitness; GA.population[payload.index].processing = false; // Store if better than current best if (DeepNest.nests.length === 0 || payload.fitness < DeepNest.nests[0].fitness) { DeepNest.nests.unshift(payload); } }); ``` -------------------------------- ### Get Polygon Bounding Box Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Calculates the axis-aligned bounding box for a given polygon. It returns the minimum x, y coordinates and the width and height of the box. ```javascript const polygon = [{x: 5, y: 10}, {x: 15, y: 20}, {x: 10, y: 25}]; const bounds = GeometryUtil.getPolygonBounds(polygon); console.log(`Position: (${bounds.x}, ${bounds.y})`); console.log(`Size: ${bounds.width} × ${bounds.height}`); ``` -------------------------------- ### DeepNest.start Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Begins the nesting optimization process using a genetic algorithm. It accepts optional callbacks for progress updates and for notification when a better placement is found. ```APIDOC ## DeepNest.start ### Description Begins the nesting optimization process using a genetic algorithm. ### Method `start(progressCallback, displayCallback)` ### Parameters #### Path Parameters - **progressCallback** (function) - Optional - Called periodically with progress updates - **displayCallback** (function) - Optional - Called when a new better placement is found ### Request Example ```javascript DeepNest.start( () => { console.log('Progress update'); }, () => { console.log('New placement found!'); } ); ``` ``` -------------------------------- ### Configuration Form Initialization Source: https://github.com/jack000/deepnest/blob/master/main/index.html Sets default configuration values using electron-settings and updates the form with current settings. Handles various input types including checkboxes and unit conversions. ```javascript const config = require('electron-settings'); window.config = config; var defaultconfig = { units: 'inch', scale: 72, // actual stored value will be in units/inch spacing: 0, curveTolerance: 0.72, // store distances in native units rotations: 4, threads: 4, populationSize: 10, mutationRate: 10, placementType: 'box', // how to place each part (possible values gravity, box, convexhull) mergeLines: true, // whether to merge lines timeRatio: 0.5, // ratio of material reduction to laser time. 0 = optimize material only, 1 = optimize laser time only simplify: false, dxfImportScale: "1", dxfExportScale: "72", endpointTolerance: 0.36, conversionServer: 'http://convert.deepnest.io' }; config.defaults(defaultconfig); const defaultConversionServer = 'http://convert.deepnest.io'; // set to default if not set (for people with old configs stored) for (var key in defaultconfig) { if(typeof config.getSync(key) === 'undefined'){ config.setSync(key, defaultconfig[key]); } } config.get().then(val => { window.DeepNest.config(val); updateForm(val); }); ``` -------------------------------- ### Configure Nesting Parameters Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Sets the configuration options for the nesting process. This includes parameters like spacing between parts, allowed rotations, population size for optimization, and the number of worker threads to use. ```javascript DeepNest.config({ spacing: 2, // 2 unit gap between parts rotations: 4, // Try 4 rotation angles populationSize: 15, // 15 candidate solutions per generation threads: 4 // Use 4 worker threads }); ``` -------------------------------- ### Clear DeepNest State Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Reset DeepNest to its initial state by clearing nesting results, callbacks, parts, and import data. This is useful before starting a new nesting operation. ```javascript DeepNest.reset(); // Clear nesting results and callbacks DeepNest.parts = []; // Clear parts DeepNest.imports = []; // Clear imports ``` -------------------------------- ### Balanced (Default) Configuration Preset Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md The default configuration preset, offering a balance between nesting quality and speed. Recommended for general use. ```javascript { rotations: 4, populationSize: 10, mutationRate: 10, curveTolerance: 0.3, threads: 4, timeRatio: 0.5 } ``` -------------------------------- ### Gravity Placement Algorithm Source: https://github.com/jack000/deepnest/blob/master/_autodocs/optimization-algorithm.md Calculates the optimal placement for a part by trying all rotations and positions relative to already placed parts, simulating gravity to find the best fit. Requires helper functions like rotatePart, computeNFP, and isValidPosition. ```javascript function gravityPlace(part, alreadyPlaced, config) { const positions = []; // Try all rotation angles for (let rot = 0; rot < config.rotations; rot++) { const angle = (rot / config.rotations) * 360; const rotatedPart = rotatePart(part, angle); // Try all placements relative to already-placed parts for (let i = 0; i < alreadyPlaced.length; i++) { const placed = alreadyPlaced[i]; const nfp = computeNFP(rotatedPart, placed); // Try points along the NFP for (let p of nfp) { // Check if position is valid if (isValidPosition(rotatedPart, p, alreadyPlaced)) { positions.push({x: p.x, y: p.y, rotation: angle, nfp: nfp}); } } } } // Simulate gravity: find leftmost, then topmost position positions.sort((a, b) => { if (a.x !== b.x) return a.x - b.x; return a.y - b.y; }); // Return best position return positions[0]; } ``` -------------------------------- ### DXF Import Configuration Preset Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md A preset optimized for importing DXF files, focusing on accurate curve representation and line merging. Simplify is set to false by default. ```javascript { scale: 1, curveTolerance: 0.01, simplify: false, mergeLines: true } ``` -------------------------------- ### Part List and Tools for Management Source: https://github.com/jack000/deepnest/blob/master/main/index.html Displays a sortable table of parts with options to select, delete, and manage quantity. Includes tools for adding rectangles and managing import details. ```html
{{#each parts:i}} {{/each}}
Size Sheet Quantity
{{{ partrenderer(this) }}} {{bounds.width}}
    {{ getSelected().length == parts.length ? 'Deselect' : 'Select' }} all

Add Rectangle

width {{ getUnits }} height {{ getUnits }} Add Cancel
``` -------------------------------- ### High-Quality Nesting Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Configures Deepnest for high-quality, dense nesting at the cost of longer processing time. This setup uses more rotation angles, a larger population, higher mutation rate, and more threads. ```javascript DeepNest.config({ rotations: 8, // 45° increments populationSize: 30, // Large population mutationRate: 15, // More variation threads: 8, // Use all cores timeRatio: 0.9 // Spend more time optimizing }); // Run for 60 seconds DeepNest.start(); setTimeout(() => DeepNest.stop(), 60000); ``` -------------------------------- ### Fast (Low Quality) Configuration Preset Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md A preset configuration optimized for speed, sacrificing some quality. Suitable for quick previews or less critical nesting tasks. ```javascript { rotations: 2, populationSize: 5, mutationRate: 5, curveTolerance: 1.0, threads: 2, timeRatio: 0.2 } ``` -------------------------------- ### Set placementType Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md Set the placement algorithm type. Currently, only 'gravity' is implemented, which places parts using a gravity simulation from top-left. ```javascript DeepNest.config({ placementType: 'gravity' }); ``` -------------------------------- ### applyPlacement Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgnest-class.md Generates SVG elements representing a placement solution. ```APIDOC ## applyPlacement ### Description Generates SVG elements representing a placement solution. ### Method `applyPlacement(placement)` ### Parameters #### Path Parameters - **placement** (Array) - Required - Placement solution to render ### Response #### Success Response - **Array** - Array of SVG documents (one per sheet) ### Request Example ```javascript const sheets = SvgNest.applyPlacement(bestPlacement); ``` ``` -------------------------------- ### Handle File Import Source: https://github.com/jack000/deepnest/blob/master/main/index.html Initiates the file import process when the import button is clicked. Handles dialogs and file type validation. ```javascript var electron = require('electron'); var app = electron.remote; var fs = require('fs'); var importbutton = document.querySelector('#import'); importbutton.onclick = function(){ if(importbutton.className == 'button import disabled' || importbutton.className == 'button import spinner'){ return false; } importbutton.className = 'button import disabled'; setTimeout(function(){ var dialog = app.dialog; dialog.showOpenDialog({ filters: [ { name: 'CAD formats', extensions: ['svg', 'dxf', 'cdr'] } ]}, function (fileName) { if(fileName === undefined){ importbutton.className = 'button import'; console.log("No file selected"); } else{ var ext = path.extname(fileName[0]); var filename = path.basename(fileName[0]); if(ext.toLowerCase() == '.svg'){ readFile(fileName[0]); importbutton.className = 'button import'; } else{ importbutton.className = 'button import spinner'; // send to conversion server var url = config.getSync('conversionServer'); if(!url){ url = defaultConversionServer; } var req = request.post(url, function (err, resp, body) { importbutton.className = 'button import'; if (err) { message('could not contact file conversion server', true); } else { if(body.substring(0, 5) == 'error'){ message(body, true); } else{ // expected input dimensions on server is points // scale based on unit preferences var con = null; var dxfFlag = false; if(ext.toLowerCase() == '.dxf'){ //var unit = config.getSync('units'); con = Number(config.getSync('dxfImportScale')); dxfFlag = true; console.log('con', con); / if(unit == 'inch'){ con = 72; } else{ // mm con = 2.83465; } */ } // dirpath is used for loading images embedded in svg files // converted svgs will not have images importData(body, filename, null, con, dxfFlag); } } }); var form = req.form(); form.append('format', 'svg'); form.append('fileUpload', fs.createReadStream(fileName[0])); } } }); }, 50); }; ``` -------------------------------- ### Launch Background Nesting Workers Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Distributes the population processing for nesting optimization across background workers. Requires parts, configuration, and callbacks for progress and display. ```javascript DeepNest.launchWorkers(parts, config, progressCallback, displayCallback); ``` -------------------------------- ### Set timeRatio Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md Adjust the time allocation ratio for GA execution, balancing exploration and refinement time. Higher values allocate more time to optimization. ```javascript DeepNest.config({ timeRatio: 0.8 }); // Spend more time optimizing ``` -------------------------------- ### Launch Nesting Workers Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgnest-class.md Launches background workers for processing population individuals and calculating fitness. Requires detailed nesting parameters. ```javascript SvgNest.launchWorkers(tree, binPolygon, config, progressCallback, displayCallback); ``` -------------------------------- ### Configuration Input Hover Effect Source: https://github.com/jack000/deepnest/blob/master/main/index.html Adds a hover effect to configuration inputs to display explanations. When hovering over an input, it highlights the corresponding explanation element. ```javascript document.querySelectorAll('#config input, #config select').forEach(function(e){ e.onmouseover = function(event){ var inputid = e.getAttribute('data-config'); if(inputid){ document.querySelectorAll('.config_explain').forEach(function(el){ el.className = 'config_explain'; }); var selected = document.querySelector('#explain_'+inputid); if(selected){ selected.className = 'config_explain active'; } } } e.onmouseleave = function(event){ ``` -------------------------------- ### Set populationSize Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md Configure the number of candidate solutions (individuals) in each generation of the genetic algorithm. Larger populations explore more solutions but are slower to evaluate. ```javascript DeepNest.config({ populationSize: 20 }); // Larger population for better solutions ``` -------------------------------- ### Monitor DeepNest Optimization Progress Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Monitor the optimization process by tracking fitness improvements and logging progress. This callback-based approach allows for real-time feedback on the nesting algorithm's performance. ```javascript let lastFitness = Infinity; let improvementCount = 0; DeepNest.start( () => { // Progress }, () => { // New placement found const current = DeepNest.nests[0].fitness; if (current < lastFitness) { improvementCount++; const improvement = ((lastFitness - current) / lastFitness * 100).toFixed(2); console.log(`Improvement #${improvementCount}: ${improvement}%`); lastFitness = current; } } ); ``` -------------------------------- ### SvgParser Configuration Defaults Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgparser.md Shows the default configuration values used by SvgParser for tolerance, scale, and endpoint matching. ```javascript { tolerance: 2, // Max deviation for Bezier approximation toleranceSvg: 0.01, // Fudge factor for SVG rendering inaccuracy scale: 72, // Points per unit endpointTolerance: 2 // Endpoint matching tolerance } ``` -------------------------------- ### Initialize EasyTabs Source: https://github.com/jack000/deepnest/blob/master/main/font/lato-hai-demo.html This JavaScript code initializes the EasyTabs plugin on an element with the ID 'container'. It sets the default content to the first tab. ```javascript $(document).ready(function() { $('#container').easyTabs({defaultContent:1}); }); ``` -------------------------------- ### launchWorkers Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/svgnest-class.md Launches background workers to process population individuals and compute fitness. ```APIDOC ## launchWorkers ### Description Launches background workers to process population individuals and compute fitness. ### Method `launchWorkers(tree, binPolygon, config, progressCallback, displayCallback)` ### Parameters #### Path Parameters - **tree** (Array) - Required - Parts tree structure to place - **binPolygon** (Array) - Required - Bin shape as polygon vertices - **config** (ConfigObject) - Required - Nesting configuration - **progressCallback** (function) - Required - Called on progress updates - **displayCallback** (function) - Required - Called when better placement found ### Response #### Success Response - **undefined** ``` -------------------------------- ### Main Window Handling 'background-progress' Source: https://github.com/jack000/deepnest/blob/master/_autodocs/ipc-protocol.md This snippet shows how the main window receives progress updates from a background worker and uses it to update a progress bar. ```javascript ipcRenderer.on('background-progress', (event, payload) => { updateProgressBar(payload.processed / payload.total); }); ``` -------------------------------- ### Set rotations Configuration Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md Specify the number of equally-spaced rotation angles to try for each part. Each rotation creates a distinct candidate for optimization. ```javascript DeepNest.config({ rotations: 8 }); // Try 0°, 45°, 90°, 135°, 180°, 225°, 270°, 315° ``` -------------------------------- ### Log Detailed Part Information for Debugging Source: https://github.com/jack000/deepnest/blob/master/_autodocs/quick-reference.md Log detailed information about each part, including its area, bounding box dimensions, vertex count, and number of holes. This is helpful for debugging issues with specific parts. ```javascript DeepNest.parts.forEach((part, i) => { const area = Math.abs(GeometryUtil.polygonArea(part.polygontree)); const bounds = GeometryUtil.getPolygonBounds(part.polygontree); console.log(`Part ${i}:`); console.log(` Area: ${area}`); console.log(` Bounds: ${bounds.width}×${bounds.height}`); console.log(` Vertices: ${part.polygontree.length}`); if (part.polygontree.children) { console.log(` Holes: ${part.polygontree.children.length}`); } }); ``` -------------------------------- ### Import SVG File Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Imports an SVG file, parses it, and extracts parts for nesting. Requires filename, directory path, and SVG content string. Scaling factor and DXF flag are optional. ```javascript const fs = require('fs'); const svgContent = fs.readFileSync('part.svg', 'utf8'); DeepNest.importsvg('part.svg', './', svgContent, 1.0, false); ``` -------------------------------- ### DeepNest.applyPlacement Source: https://github.com/jack000/deepnest/blob/master/_autodocs/api-reference/deepnest-class.md Generates SVG elements representing a placement solution for export or rendering. It takes a placement solution as an array of Placement objects. ```APIDOC ## DeepNest.applyPlacement ### Description Generates SVG elements representing a placement solution for export or rendering. ### Method `applyPlacement(placement)` ### Parameters #### Path Parameters - **placement** (Array) - Required - Placement solution to render ### Response #### Success Response (200) - **Array** - Array of SVG documents, one per sheet ### Request Example ```javascript const bestPlacement = DeepNest.nests[0]; const svgSheets = DeepNest.applyPlacement(bestPlacement); svgSheets.forEach((sheet, index) => { console.log(`Sheet ${index}:`, sheet); }); ``` ``` -------------------------------- ### Login Container CSS Source: https://github.com/jack000/deepnest/blob/master/main/login.html Basic CSS to ensure the authentication container fills the entire viewport. Apply this to the element with id 'auth'. ```css html, body{ margin: 0; padding: 0; } #auth{ width: 100%; height: 100%; } ``` -------------------------------- ### Placement Type Definition (Array) Source: https://github.com/jack000/deepnest/blob/master/_autodocs/types.md Alternative representation of placement configuration as an array of arrays, where each nested array contains items placed on a single sheet. ```javascript Array> ``` -------------------------------- ### ConfigObject Type Definition Source: https://github.com/jack000/deepnest/blob/master/_autodocs/types.md Defines configuration parameters for nesting operations, covering geometry, genetic algorithm, execution, and optimization settings. ```javascript { // Geometry clipperScale: number, // Integer scale for Clipper (default: 10000000) curveTolerance: number, // Max deviation for curve approximation (default: 0.3) spacing: number, // Minimum spacing between parts (default: 0) // Genetic Algorithm populationSize: number, // GA population size (default: 10, min: 2) mutationRate: number, // Mutation probability % (default: 10) rotations: number, // Number of rotation angles (default: 4, max: rotations*360°) // Execution threads: number, // Worker threads (default: 4, max: 8) placementType: string, // Algorithm type: 'gravity' (default) timeRatio: number, // Time allocation ratio (default: 0.5) // Optimization mergeLines: boolean, // Merge coincident lines in output (default: true) simplify: boolean, // Enable polygon simplification (default: false) scale: number, // SVG scale in points per unit (default: 72) // SvgParser options tolerance: number, // SVG curve tolerance (inherited from SvgParser) endpointTolerance: number // Endpoint matching tolerance } ``` -------------------------------- ### Navigate Back from Nesting View Source: https://github.com/jack000/deepnest/blob/master/main/index.html Handles the 'Back' button click, which stops the nesting process if it's running, resets the DeepNest state, clears the display, and returns the user to the main view, disabling the export button. ```javascript var back = document.querySelector('#back'); back.onclick = function(e){ setTimeout(function(){ if(DeepNest.working){ ipcRenderer.send('background-stop'); DeepNest.stop(); document.querySelectorAll('li.progress').forEach(function(p){ p.removeAttribute('id'); p.className = 'progress'; }); } DeepNest.reset(); deleteCache(); window.nest.update('nests'); document.querySelector('#nestdisplay').innerHTML = ''; stop.className = 'button stop'; stop.innerHTML = 'Stop nest'; // disable export button document.querySelector('#export_wrapper').className = ''; document.querySelector('#export').className = 'button export disabled'; }, 2000); document.querySelector('#main').className = 'active'; document.querySelector('#nest').className = ''; } ``` -------------------------------- ### Set DeepNest Configuration Parameters Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md Allows setting one or more configuration parameters for DeepNest. You can also retrieve the current configuration by calling config() without arguments. ```javascript // Set one or more parameters DeepNest.config({ spacing: 2.5, rotations: 8, populationSize: 20 }); // Get current configuration const current = DeepNest.config(); console.log(current.spacing); // 2.5 ``` -------------------------------- ### Configure DeepNest with Simplify Source: https://github.com/jack000/deepnest/blob/master/_autodocs/configuration.md Enables aggressive polygon simplification to reduce vertex count. Use for complex polygons where shape detail loss is acceptable. ```javascript DeepNest.config({ simplify: true }); // Simplify complex polygons ``` -------------------------------- ### Main Navigation Handling Source: https://github.com/jack000/deepnest/blob/master/main/index.html Manages click events for navigation tabs, updating the active tab and displaying the corresponding page. It also handles resizing for the home page. ```javascript var tabs = document.querySelectorAll('#sidenav li'); Array.from(tabs).forEach(tab => { tab.addEventListener('click', function(e) { if(this.className == 'active' || this.className == 'disabled'){ return false; } var activetab = document.querySelector('#sidenav li.active'); activetab.className = ''; var activepage = document.querySelector('.page.active'); activepage.className = 'page'; this.className = 'active'; tabpage = document.querySelector('#' + this.dataset.page); tabpage.className = 'page active'; if(tabpage.getAttribute('id') == 'home'){ resize(); } return false; }); }); ```