### Complete Viewer Setup with Manual Controls Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/OrbitControls.md A comprehensive example of setting up DxfViewer, loading a DXF, fitting the view, subscribing to view changes, and implementing manual control buttons for zoom and fit. ```javascript import { DxfViewer } from 'dxf-viewer' import THREE from 'three' async function setupViewerWithControls() { const container = document.getElementById('viewer') const viewer = new DxfViewer(container, { autoResize: true, antialias: true }) // Load DXF - controls are automatically created await viewer.Load({ url: 'drawing.dxf', fonts: ['fonts/arial.typeface.json'] }) // Get bounds and fit view const bounds = viewer.GetBounds() if (bounds) { viewer.FitView(bounds.minX, bounds.maxX, bounds.minY, bounds.maxY, 0.1) } // Subscribe to view changes viewer.Subscribe('viewChanged', () => { const camera = viewer.GetCamera() console.log(`Camera position: (${camera.position.x}, ${camera.position.y}) console.log(`Camera zoom: ${camera.zoom}`) }) // Manual view control buttons (optional) document.getElementById('zoom-fit').onclick = () => { const bounds = viewer.GetBounds() if (bounds) { viewer.FitView(bounds.minX, bounds.maxX, bounds.minY, bounds.maxY, 0.1) } } document.getElementById('zoom-in').onclick = () => { const camera = viewer.GetCamera() const aspect = viewer.GetCanvas().width / viewer.GetCanvas().height const width = (camera.right - camera.left) / 1.2 const height = width / aspect viewer.SetView(new THREE.Vector3(camera.position.x, camera.position.y, 0), width) } document.getElementById('zoom-out').onclick = () => { const camera = viewer.GetCamera() const aspect = viewer.GetCanvas().width / viewer.GetCanvas().height const width = (camera.right - camera.left) * 1.2 const height = width / aspect viewer.SetView(new THREE.Vector3(camera.position.x, camera.position.y, 0), width) } return viewer } ``` -------------------------------- ### DxfWorker Setup Example (Worker Thread) Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfWorker.md Set up the worker thread by calling DxfViewer.SetupWorker(). This must be done within the worker script (e.g., dxf-worker.js). ```javascript import { DxfViewer } from 'dxf-viewer' DxfViewer.SetupWorker() // Sets up worker-side message handler ``` -------------------------------- ### Complete DXF Viewer Application Example Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/README.md This snippet shows how to initialize and use the DxfViewer in a web application. It includes configuration, event handling for loading and messages, DXF file loading with progress callbacks, and basic UI interaction for resetting the view. Ensure you have 'dxf-viewer' and 'three' libraries installed and 'dxf-worker.js' available. ```javascript import { DxfViewer } from 'dxf-viewer' import THREE from 'three' async function initViewer() { // Create viewer with configuration const viewer = new DxfViewer(document.getElementById('viewer'), { canvasWidth: 1920, canvasHeight: 1080, autoResize: true, clearColor: new THREE.Color(0xffffff), antialias: true, sceneOptions: { arcTessellationAngle: 10 * Math.PI / 180, suppressPaperSpace: true } }) // Listen for events viewer.Subscribe('loaded', () => { const bounds = viewer.GetBounds() if (bounds) { viewer.FitView(bounds.minX, bounds.maxX, bounds.minY, bounds.maxY, 0.05) } console.log(`Loaded ${viewer.GetLayers().length} layers`) }) viewer.Subscribe('message', event => { if (event.level === 'warn') { console.warn(event.message) } }) // Load DXF try { await viewer.Load({ url: 'plan.dxf', fonts: ['arial.typeface.json'], progressCbk: (phase, processed, total) => { console.log(`${phase}: ${(processed/total*100).toFixed(1)}%`) }, workerFactory: () => new Worker('dxf-worker.js') }) } catch (error) { console.error('Failed to load DXF:', error) } // Add UI controls document.getElementById('reset-view').onclick = () => { const bounds = viewer.GetBounds() if (bounds) { viewer.FitView(bounds.minX, bounds.maxX, bounds.minY, bounds.maxY) } } // Return viewer for later use return viewer } // Initialize on page load initViewer().catch(console.error) ``` -------------------------------- ### Install dxf-viewer Package Source: https://github.com/vagran/dxf-viewer/blob/master/README.md Install the dxf-viewer package using npm. This command fetches and installs the latest version of the library into your project. ```bash npm install dxf-viewer ``` -------------------------------- ### Setup Worker for DxfViewer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md Demonstrates how to set up the worker for the DxfViewer class. This is typically done once when initializing the viewer. ```javascript import { DxfViewer } from "@dxf-viewer/core"; // Setup worker for main thread DxfViewer.SetupWorker(); ``` -------------------------------- ### Install DXF Viewer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/README.md Install the DXF Viewer package using npm. This command should be run in your project's terminal. ```bash npm install dxf-viewer ``` -------------------------------- ### Batch Organization Example Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/BatchingKey.md Organizes entities by creating appropriate BatchingKey instances based on entity properties. This example requires the BatchingKey class and a getGeometryType helper function. ```javascript import { BatchingKey } from 'dxf-viewer' // Organize entities by creating appropriate keys const batches = new Map() function addEntity(entity) { // Determine batch key based on entity properties const key = new BatchingKey( entity.layer || "0", entity.blockName || null, getGeometryType(entity), entity.color, entity.lineType || null ) // Add to batch const keyStr = JSON.stringify({ layer: key.layerName, block: key.blockName, geom: key.geometryType, color: key.color, line: key.lineType }) if (!batches.has(keyStr)) { batches.set(keyStr, { key: key, entities: [] }) } batches.get(keyStr).entities.push(entity) } function getGeometryType(entity) { switch (entity.type) { case 'LINE': case 'LWPOLYLINE': return BatchingKey.GeometryType.INDEXED_LINES case 'CIRCLE': case 'ARC': return BatchingKey.GeometryType.INDEXED_LINES case 'SOLID': case '3DFACE': return BatchingKey.GeometryType.INDEXED_TRIANGLES case 'INSERT': return BatchingKey.GeometryType.BLOCK_INSTANCE case 'POINT': return BatchingKey.GeometryType.POINT_INSTANCE default: return BatchingKey.GeometryType.INDEXED_TRIANGLES } } ``` -------------------------------- ### Minimal DXF Viewer Setup Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/QUICK-START.md Initialize the DxfViewer and load a DXF file. Ensure the target DOM element with id 'viewer' exists. ```javascript import { DxfViewer } from 'dxf-viewer' // Create viewer const viewer = new DxfViewer(document.getElementById('viewer')) // Load DXF await viewer.Load({ url: 'drawing.dxf' }) ``` -------------------------------- ### Load DXF File Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/entry-points.md Basic example to load a DXF file into the viewer. Ensure the container element is available and the DXF file is accessible. ```javascript import { DxfViewer } from 'dxf-viewer' const viewer = new DxfViewer(container) await viewer.Load({ url: 'drawing.dxf' }) ``` -------------------------------- ### Complete Scene Building with DxfScene Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfScene.md Demonstrates how to fetch a DXF file, create a DxfScene with custom options, load fonts, build the scene, and access its properties. This example shows the typical workflow for initializing and populating a scene. ```javascript import { DxfFetcher, DxfScene } from 'dxf-viewer' async function loadScene() { // Fetch the DXF file const fetcher = new DxfFetcher('drawing.dxf') const dxf = await fetcher.Fetch() // Create scene with custom options const scene = new DxfScene({ sceneOptions: { arcTessellationAngle: 5 * Math.PI / 180, // Finer arcs wireframeMesh: false, suppressPaperSpace: false } }) // Create font fetchers const fontFetchers = [ async () => { const response = await fetch('fonts/arial.typeface.json') const data = await response.json() // Note: depends on opentype.js being available return data } ] // Build scene await scene.Build(dxf, fontFetchers) // Access scene data console.log(`Bounds: ${scene.bounds.minX}, ${scene.bounds.minY} to ${scene.bounds.maxX}, ${scene.bounds.maxY}`) console.log(`Layers: ${scene.layers.size}`) console.log(`Blocks: ${scene.blocks.size}`) console.log(`Vertices: ${scene.vertices.byteLength} bytes`) return scene } ``` -------------------------------- ### Complete DXF Viewer Configuration Example Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/configuration.md Demonstrates a comprehensive configuration for the `DxfViewer`, including display settings, color options, quality parameters, scene geometry, text rendering, and loading a DXF file with progress callbacks and custom worker. It also shows how to fit the loaded drawing to the view. ```javascript import { DxfViewer } from 'dxf-viewer' import THREE from 'three' // Create viewer with comprehensive configuration const viewer = new DxfViewer(document.getElementById('viewer'), { // Display settings canvasWidth: 1920, canvasHeight: 1080, autoResize: true, // Color and appearance clearColor: new THREE.Color(0xffffff), clearAlpha: 1.0, antialias: true, blackWhiteInversion: true, pointSize: 2.5, // Quality and performance colorCorrection: false, preserveDrawingBuffer: false, fileEncoding: "utf-8", // Scene geometry options sceneOptions: { arcTessellationAngle: 10 * Math.PI / 180, minArcTessellationSubdivisions: 8, wireframeMesh: false, suppressPaperSpace: false, // Text rendering textOptions: { curveSubdivision: 2, fallbackChar: "?" } } }) // Load DXF with full configuration await viewer.Load({ url: 'building-plan.dxf', fonts: [ 'fonts/arial.typeface.json', 'fonts/times.typeface.json', 'fonts/symbol.typeface.json' ], progressCbk: (phase, processed, total) => { updateProgressBar(phase, processed, total) }, workerFactory: () => new Worker('dxf-worker.js') }) // Fit drawing to view with padding const bounds = viewer.GetBounds() if (bounds) { viewer.FitView(bounds.minX, bounds.maxX, bounds.minY, bounds.maxY, 0.05) } ``` -------------------------------- ### Initialize DxfViewer Worker Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Example of setting up a web worker for DxfViewer file processing. This involves importing the DxfViewer and calling SetupWorker in the worker script, then providing the worker to the Load method in the main thread. ```javascript import { DxfViewer } from 'dxf-viewer' DxfViewer.SetupWorker() ``` ```javascript const worker = new Worker('worker.js') await viewer.Load({ url: 'drawing.dxf', workerFactory: () => worker }) ``` -------------------------------- ### Entity Decomposition Examples Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/architecture.md Illustrates the decomposition of complex DXF entities into simpler geometric primitives for rendering. ```text Arc → tessellate to angle/subdivisions → connected line segments ``` ```text LWPOLYLINE → decompose each segment → indexed line or triangle geometry ``` ```text TEXT/MTEXT → parse special chars → fetch fonts → generate glyph paths → convert to filled polygons → triangulate ``` ```text HATCH → apply pattern rules → generate boundary → create line patterns → triangulate fill → indexed geometry ``` -------------------------------- ### NativeArray Function Example Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DynamicBuffer.md Demonstrates how to use the NativeArray function to get TypedArray constructors and create buffers. Ensure NativeArray and NativeType are imported. ```javascript import { NativeArray, NativeType } from 'dxf-viewer' const FloatArrayCtor = NativeArray(NativeType.FLOAT32) const buffer = new FloatArrayCtor(100) const UintArrayCtor = NativeArray(NativeType.UINT16) const indices = new UintArrayCtor(512) ``` -------------------------------- ### Initialize DXF Viewer with Custom Options Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/types.md Example of creating a new DxfViewer instance with specific configuration options, including canvas dimensions, rendering settings, and scene parameters. ```typescript import { DxfViewer } from 'dxf-viewer' import THREE from 'three' const options: DxfViewerOptions = { canvasWidth: 1920, canvasHeight: 1080, autoResize: true, clearColor: new THREE.Color("#ffffff"), clearAlpha: 1.0, antialias: true, sceneOptions: { arcTessellationAngle: 5 * Math.PI / 180, // Finer arcs minArcTessellationSubdivisions: 16, suppressPaperSpace: true, textOptions: { curveSubdivision: 3, fallbackChar: "?" } } } const viewer = new DxfViewer(container, options) ``` -------------------------------- ### RegisterPattern Example Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/Pattern.md Example of how to create and register a new pattern using the RegisterPattern function. Ensure the Pattern object has a non-null name. ```javascript import { Pattern, RegisterPattern } from 'dxf-viewer' const pattern = new Pattern([ { angle: Math.PI / 4, offset: new THREE.Vector2(2.5, 0) } ], "STANDARD_HATCH") RegisterPattern(pattern, true) // Register as metric ``` -------------------------------- ### Complete Text Rendering Setup Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/TextRenderer.md Demonstrates how to initialize TextRenderer with custom font fetchers and options, parse special characters in text, and load necessary fonts for rendering. Use this for setting up text rendering in your application. ```javascript import { TextRenderer, ParseSpecialChars, HAlign, VAlign } from 'dxf-viewer' import opentype from 'opentype.js' async function setupTextRendering() { // Create font fetchers using opentype.js const fontFetchers = [ () => opentype.load('fonts/arial.ttf'), () => opentype.load('fonts/times.ttf'), () => opentype.load('fonts/courier.ttf') ] // Create text renderer with custom options const textRenderer = new TextRenderer(fontFetchers, { curveSubdivision: 2, fallbackChar: "?" }) // Test text with special characters const texts = [ "Dimension: %%d45", "Tolerance: %%p0.5", "Diameter: %%c25" ] for (const text of texts) { // Parse special characters const parsed = ParseSpecialChars(text) console.log(`Original: ${text}`) console.log(`Parsed: ${parsed}`) // Load fonts for this text const allCharsSupported = await textRenderer.FetchFonts(parsed) if (!allCharsSupported) { console.warn(`Some characters in "${parsed}" cannot be rendered`) } } return textRenderer } ``` -------------------------------- ### CompareValues Example Usage Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/BatchingKey.md Demonstrates how to use the CompareValues function with different data types and null values. Ensure CompareValues is imported from 'dxf-viewer'. ```javascript import { CompareValues } from 'dxf-viewer' console.log(CompareValues(null, "abc")) // -1 console.log(CompareValues("abc", null)) // 1 console.log(CompareValues("abc", "xyz")) // -1 console.log(CompareValues(5, 5)) // 0 ``` -------------------------------- ### Configuration Options Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/COMPLETION_SUMMARY.txt This section details all configuration options available for the DXF Viewer, including their defaults, descriptions, performance impact, tuning presets, and environment-specific setup. ```APIDOC ## Configuration The `configuration.md` file provides comprehensive details on all configurable aspects of the DXF Viewer. ### All Options with Defaults A complete listing of all available configuration options, including their default values. ### Option Descriptions Detailed explanations for each configuration option, outlining its purpose and effect on the viewer's behavior. ### Performance Impact Notes Information regarding the performance implications of specific configuration settings, helping users optimize for their environment. ### Tuning Presets Predefined configuration presets designed for common use cases or performance targets. ### Environment-Specific Setup Guidance on configuring the DXF Viewer for different deployment environments (e.g., browser, Node.js). ### Complete Example A full configuration example demonstrating how to set various options. ### Performance Guide Recommendations and best practices for tuning the DXF Viewer's performance through configuration. ``` -------------------------------- ### Example Progress Handler for DXF Loading Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/configuration.md Implement a detailed progress callback to log different phases of DXF file loading, including font loading, file download, parsing, and scene preparation. ```javascript await viewer.Load({ url: 'drawing.dxf', progressCbk: (phase, processed, total) => { switch (phase) { case 'font': console.log('Loading fonts...') break case 'fetch': const percent = total ? (processed / total * 100).toFixed(1) : '?' console.log(`Downloading: ${percent}%`) break case 'parse': console.log('Parsing DXF file...') break case 'prepare': const prepPercent = (processed || 0).toFixed(1) console.log(`Preparing scene: ${prepPercent}%`) break } } }) ``` -------------------------------- ### Setup Web Worker in Worker Thread Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/configuration.md Initialize the DXF Viewer's worker thread by calling `SetupWorker()`. This prepares the worker to handle DXF processing. ```javascript // worker.js import { DxfViewer } from 'dxf-viewer' DxfViewer.SetupWorker() console.log('DXF Worker ready') ``` -------------------------------- ### LookupPattern Example Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/Pattern.md Example demonstrating how to look up a pattern by its name using the LookupPattern function. The lookup is case-insensitive. ```javascript import { LookupPattern } from 'dxf-viewer' const pattern = LookupPattern("SOLID", true) if (pattern) { console.log("Found pattern:", pattern.name) } else { console.log("Pattern not found") } ``` -------------------------------- ### DxfWorker Constructor Example (Main Thread) Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfWorker.md Instantiate DxfWorker on the main thread, passing a Web Worker instance. Ensure the worker is set up with DxfViewer.SetupWorker() on its side. ```javascript import { DxfWorker } from 'dxf-viewer' // Create worker-based DXF processor const worker = new Worker('dxf-worker.js') const dxfWorker = new DxfWorker(worker) ``` -------------------------------- ### Synchronous DXF Loading Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfWorker.md Use this pattern for simple or non-critical loading directly on the main thread. It requires no worker setup. ```javascript import { DxfWorker, DxfScene, DxfFetcher } from 'dxf-viewer' // No worker - process in main thread const dxfWorker = new DxfWorker(null) const result = await dxfWorker.Load('drawing.dxf', null, {}) console.log('Scene loaded synchronously') ``` -------------------------------- ### Setup Worker for Main Thread Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md This code snippet shows how to set up the worker for the main thread when integrating DxfWorker. This is a prerequisite for using the worker. ```javascript import { DxfWorker } from "@dxf-viewer/core"; // Setup worker for main thread DxfWorker.SetupWorker(); ``` -------------------------------- ### Importing DxfViewer and DxfFetcher with require Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/entry-points.md Use require to import DxfViewer and DxfFetcher in CommonJS environments. Ensure the 'dxf-viewer' package is installed. ```javascript const { DxfViewer, DxfFetcher } = require('dxf-viewer') ``` -------------------------------- ### Tree-Shakeable ES6 Module Imports Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/entry-points.md Example of importing specific components from the dxf-viewer library using ES6 modules to enable tree-shaking. ```javascript // Only imports DxfViewer and Pattern import { DxfViewer, Pattern } from 'dxf-viewer' // Can be tree-shaken away if not used import { DxfWorker, TextRenderer } from 'dxf-viewer' ``` -------------------------------- ### Three.js Scene Structure Example Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/architecture.md Outlines the hierarchical structure of a Three.js scene, showing how different batches are represented as meshes or points. ```text THREE.Scene ├── Mesh (INDEXED_LINES batch) → Geometry + Material ├── Mesh (INDEXED_TRIANGLES batch) → Geometry + Material ├── Mesh (BLOCK_INSTANCE batch) → Geometry + InstancedMesh ├── Points (POINTS batch) → Points + PointsMaterial └── ... other batches and custom objects ``` -------------------------------- ### API Reference Overview Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/COMPLETION_SUMMARY.txt This section provides an overview of the API reference files available for the DXF Viewer. These files contain detailed documentation for constructors, parameters, return types, error conditions, properties, and methods, along with complete code examples. ```APIDOC ## API Reference Files This project includes a dedicated directory for API reference files, offering in-depth documentation for each component of the DXF Viewer. ### Constructor Documentation Detailed information about how to instantiate classes, including all available parameters and their default values. ### Parameter Tables Comprehensive tables outlining parameters for constructors, methods, and properties, including their types, default values, and descriptions. ### Return Type Documentation Clear documentation of the return types for all methods and functions, specifying what data can be expected. ### Error/Throw Conditions Documentation of potential errors or exceptions that may be thrown, along with conditions under which they occur. ### Property Documentation Descriptions of all public properties available on classes, including their types and accessibility. ### Method Documentation Detailed explanations of all public methods, including their signatures, parameters, and return values. ### Complete Code Examples Illustrative code snippets demonstrating the usage of various API elements in real-world scenarios. ### Cross-references Links and references to related documentation sections, types, and concepts for a cohesive understanding. ### Source File Paths Indication of the original source file path for each documented API element, aiding in code navigation and understanding. ``` -------------------------------- ### Create and Register a Custom Hatch Pattern Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/Pattern.md Example of creating a simple diagonal hatch pattern with dashed lines and registering it with the DXF Viewer. Requires importing Pattern and RegisterPattern from 'dxf-viewer' and THREE from 'three'. ```javascript import { Pattern, RegisterPattern } from 'dxf-viewer' import THREE from 'three' // Create a simple diagonal hatch pattern const lines = [ { angle: Math.PI / 4, // 45 degrees base: new THREE.Vector2(0, 0), offset: new THREE.Vector2(2.5, 0), dashes: [2, 1] // Dash/space pattern }, { angle: -Math.PI / 4, // -45 degrees (opposite direction) base: new THREE.Vector2(0, 0), offset: new THREE.Vector2(2.5, 0) // No dashes = solid line } ] const pattern = new Pattern(lines, "CROSSHATCH") RegisterPattern(pattern, true) // Register as metric pattern ``` -------------------------------- ### Entry Points and Public APIs Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/COMPLETION_SUMMARY.txt This section details all exported symbols from the DXF Viewer library, including classes, types, and deprecated APIs. It provides import examples and version compatibility information. ```APIDOC ## Entry Points The `entry-points.md` file lists all exported symbols from the DXF Viewer library, serving as the primary guide for integrating the library into your projects. ### All Exports Listed A comprehensive list of all classes, functions, types, and constants that are publicly exported by the library. ### Import Examples Code snippets demonstrating how to import and use the exported components in various JavaScript/TypeScript environments. ### Class Reference Detailed documentation for each exported class, including its purpose, constructor, properties, and methods. ### Type Definitions Complete definitions for all exported types, including interfaces, type aliases, and their respective fields. ### Deprecated APIs Noted Clear identification of any APIs that are deprecated, along with recommendations for alternatives and information on when they will be removed. ### Version Compatibility Information regarding version compatibility between different releases of the DXF Viewer library and potential dependencies. ``` -------------------------------- ### Get DxfViewer Scene Information Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md Provides examples of how to access underlying scene components and metadata from the DxfViewer instance, such as layers, the Three.js scene, camera, and canvas. ```javascript const layers = viewer.GetLayers(); const scene = viewer.GetScene(); const camera = viewer.GetCamera(); const canvas = viewer.GetCanvas(); const renderer = viewer.GetRenderer(); const origin = viewer.GetOrigin(); const bounds = viewer.GetBounds(); ``` -------------------------------- ### Creating BatchingKey Instances Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/BatchingKey.md Demonstrates how to create BatchingKey instances for different rendering scenarios, such as solid red lines and blue triangles within a block. Ensure the BatchingKey class is imported before use. ```javascript import { BatchingKey } from 'dxf-viewer' // Key for solid red lines on layer "0" const key1 = new BatchingKey( "0", // layer null, // not in a block BatchingKey.GeometryType.INDEXED_LINES, // geometry type 0xFFFF0000, // red color (ARGB) 0 // line type 0 (solid) ) // Key for blue triangles in block "DOOR" const key2 = new BatchingKey( "0", // layer "DOOR", // block name BatchingKey.GeometryType.INDEXED_TRIANGLES, // geometry type 0xFF0000FF, // blue color (ARGB) null // not a line ) ``` -------------------------------- ### Get() Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DynamicBuffer.md Retrieves the value at a specified index in the buffer. Throws an error if the index is out of range. ```APIDOC ## Get() ### Description Retrieves a value at the specified index. ### Parameters #### Parameters - **index** (number) - Required - Index of the value to retrieve. ### Returns `number` — The value at the specified index. ### Throws Error if index is out of range. ### Example ```javascript const buffer = new DynamicBuffer(NativeType.FLOAT32) buffer.Push(42.5) buffer.Push(17.3) console.log(buffer.Get(0)) // 42.5 console.log(buffer.Get(1)) // 17.3 console.log(buffer.Get(2)) // Error: Index out of range ``` ``` -------------------------------- ### CopyTo() Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DynamicBuffer.md Copies a specified range of elements from this buffer to a destination buffer, starting at a given offset. ```APIDOC ## CopyTo() ### Description Copies a range of elements to the specified destination buffer. ### Parameters #### Parameters - **dstBuffer** (TypedArray) - Required - Destination buffer (must be same typed array type). - **dstOffset** (number) - Required - Offset in destination buffer (in elements). - **srcOffset** (number) - Optional - Offset in source buffer (in elements). Default is 0. - **size** (number) - Optional - Number of elements to copy. -1 copies until end of source buffer. Default is -1. ### Example ```javascript import { DynamicBuffer, NativeType } from 'dxf-viewer' // Build buffer dynamically const dynamicBuf = new DynamicBuffer(NativeType.FLOAT32) dynamicBuf.Push(1.0) dynamicBuf.Push(2.0) dynamicBuf.Push(3.0) dynamicBuf.Push(4.0) // Create final static buffer const finalBuf = new Float32Array(6) // Copy first 2 elements starting at destination offset 0 dynamicBuf.CopyTo(finalBuf, 0, 0, 2) // Copy last 2 elements starting at destination offset 2 dynamicBuf.CopyTo(finalBuf, 2, 2, 2) console.log(Array.from(finalBuf)) // [1.0, 2.0, 3.0, 4.0, 0, 0] ``` ``` -------------------------------- ### Get Current Size of DynamicBuffer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DynamicBuffer.md Determine the number of elements currently stored in the buffer using the GetSize() method. ```javascript const buffer = new DynamicBuffer(NativeType.UINT32) console.log(buffer.GetSize()) // 0 buffer.Push(100) buffer.Push(200) console.log(buffer.GetSize()) // 2 ``` -------------------------------- ### Initialize DxfViewer with Text Options Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/configuration.md Configure text rendering options, including curve subdivision for glyph smoothness and a fallback character for missing glyphs. ```javascript const viewer = new DxfViewer(container, { sceneOptions: { textOptions: { // Curve subdivision for smooth glyphs curveSubdivision: 2, // Default: 2 // Fallback character when glyph not found fallbackChar: "?" // Default: "❓?" (Unicode replacement + question mark) } } }) ``` -------------------------------- ### Basic Viewer Configuration Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/QUICK-START.md Set up the DxfViewer with specific canvas dimensions, auto-resize, and background color. Requires THREE.js for color definition. ```javascript import { DxfViewer } from 'dxf-viewer' const viewer = new DxfViewer(container, { canvasWidth: 1024, canvasHeight: 768, autoResize: true, clearColor: new THREE.Color(0xffffff) }) ``` -------------------------------- ### Fetch DXF File with DxfFetcher Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md Illustrates how to use the DxfFetcher to retrieve a DXF file. It supports progress callbacks for monitoring the download status. ```javascript fetcher.Fetch((progress) => { console.log(`Downloaded: ${progress * 100}%`); }); ``` -------------------------------- ### GetRenderer() Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Fetches the Three.js WebGL renderer instance. Returns null if the renderer is not available, for example, due to a lost WebGL context. ```APIDOC ## GetRenderer() ### Description Returns the Three.js WebGL renderer. ### Method ```javascript GetRenderer(): THREE.WebGLRenderer | null ``` ### Returns #### Success Response - **THREE.WebGLRenderer | null** - The WebGLRenderer instance, or null if renderer is unavailable. ### Response Example ```javascript const renderer = viewer.GetRenderer() if (renderer) { renderer.setClearColor(new THREE.Color("#ffffff")) } ``` ``` -------------------------------- ### Initialize DxfScene with Options Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfScene.md Instantiate DxfScene with custom scene options for rendering, such as arc tessellation and wireframe settings. Ensure DxfScene is imported from 'dxf-viewer'. ```javascript import { DxfScene } from 'dxf-viewer' const scene = new DxfScene({ sceneOptions: { arcTessellationAngle: 10 * Math.PI / 180, minArcTessellationSubdivisions: 8, wireframeMesh: false, suppressPaperSpace: false } }) ``` -------------------------------- ### Get Three.js Camera Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Retrieve the Three.js orthographic camera used by the viewer using GetCamera(). This can be useful for inspecting camera properties. ```javascript const camera = viewer.GetCamera() console.log('Camera position:', camera.position) ``` -------------------------------- ### SetupWorker() Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Initializes the DxfViewer within a web worker to facilitate asynchronous file processing. This is crucial for offloading computationally intensive tasks from the main thread, improving UI responsiveness. ```APIDOC ## SetupWorker() ### Description Call this function in a web worker to enable worker-based file processing. ### Method Static method call ### Parameters None ### Request Example ```javascript // In worker.js import { DxfViewer } from 'dxf-viewer' DxfViewer.SetupWorker() ``` ### Response None ``` -------------------------------- ### Retrieve and Log Layer Information Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/types.md Example of iterating through the layers of a loaded DXF drawing and logging their display name, internal name, and color. ```typescript for (const layer: LayerInfo of viewer.GetLayers()) { console.log(`Layer: ${layer.displayName} (${layer.name}) - Color: ${layer.color}`) } ``` -------------------------------- ### Configure for High-Quality Output with Fine Tessellation and Quality Settings Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/configuration.md Set up the viewer for high-quality rendering suitable for prints or screenshots by using fine tessellation and enabling quality-focused settings. Increase antialiasing, enable color correction, and preserve the drawing buffer. Fine-tune text rendering for smoother glyphs. ```javascript const viewer = new DxfViewer(container, { // Fine tessellation sceneOptions: { arcTessellationAngle: 2 * Math.PI / 180, // Fine segments minArcTessellationSubdivisions: 32 }, // Quality settings antialias: true, colorCorrection: true, preserveDrawingBuffer: true, // Better text rendering sceneOptions: { textOptions: { curveSubdivision: 3, // Smoother glyphs fallbackChar: "?" } } }) ``` -------------------------------- ### DynamicBuffer Vertex Data Layout Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/architecture.md Example of vertex data organization within a DynamicBuffer, showing per-vertex attributes like position and color. ```text [x1, y1, r1, g1, b1, a1, x2, y2, r2, g2, b2, a2, ...] └────────────────────────┬──────────────────────┘ Per-vertex data ``` -------------------------------- ### Instantiate DxfFetcher Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfFetcher.md Create a new instance of DxfFetcher with the URL of the DXF file and an optional encoding. ```javascript import { DxfFetcher } from 'dxf-viewer' const fetcher = new DxfFetcher('drawing.dxf', 'utf-8') ``` -------------------------------- ### Retrieve Value from DynamicBuffer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DynamicBuffer.md Access elements by their index using the Get() method. This method will throw an error if the index is out of the buffer's range. ```javascript const buffer = new DynamicBuffer(NativeType.FLOAT32) buffer.Push(42.5) buffer.Push(17.3) console.log(buffer.Get(0)) // 42.5 console.log(buffer.Get(1)) // 17.3 console.log(buffer.Get(2)) // Error: Index out of range ``` -------------------------------- ### Build DXF Scene with DxfScene Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md Demonstrates the asynchronous process of building a DXF scene using the DxfScene class. This involves calling the Build method. ```javascript import { DxfScene } from "@dxf-viewer/core"; const scene = new DxfScene({}); await scene.Build(); ``` -------------------------------- ### Configure Three.js Renderer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Get the Three.js WebGL renderer using GetRenderer() and configure its properties, such as the clear color. The renderer may be null if unavailable. ```javascript const renderer = viewer.GetRenderer() if (renderer) { renderer.setClearColor(new THREE.Color("#ffffff")) } ``` -------------------------------- ### Basic DXF Viewer Usage Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/README.md Initialize the DXF Viewer and load a DXF file. Ensure you have an HTML element with the ID 'viewer' in your document. The Load function is asynchronous and requires awaiting. ```javascript import { DxfViewer } from 'dxf-viewer' const viewer = new DxfViewer(document.getElementById('viewer')) await viewer.Load({ url: 'drawing.dxf' }) ``` -------------------------------- ### Load and Render DXF File with DxfViewer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md Illustrates the process of loading a DXF file into the viewer and then rendering the scene. This involves calling the Load and Render methods sequentially. ```javascript await viewer.Load("path/to/your/file.dxf"); await viewer.Render(); ``` -------------------------------- ### Get HTML Canvas Element Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Obtain the DOM canvas element using GetCanvas(). This allows direct manipulation of the canvas, such as adding CSS classes. ```javascript const canvas = viewer.GetCanvas() canvas.classList.add('my-canvas') ``` -------------------------------- ### Get Layer Information Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Retrieve information about all layers in the DXF using GetLayers. Optionally filter for layers that contain content by setting nonEmptyOnly to true. ```javascript for (const layer of viewer.GetLayers()) { console.log(`${layer.displayName}: ${layer.color}`) } ``` -------------------------------- ### Check DxfViewer Renderer Availability Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md Demonstrates how to check if the DxfViewer has successfully initialized and has access to a WebGL renderer. ```javascript if (viewer.HasRenderer()) { console.log("Renderer is available."); } ``` -------------------------------- ### Instantiate DxfViewer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Create a new DxfViewer instance. Specify the DOM container and optional configuration options like canvas dimensions, resize behavior, background color, and anti-aliasing. ```javascript import { DxfViewer } from 'dxf-viewer' const container = document.getElementById('viewer') const viewer = new DxfViewer(container, { canvasWidth: 1024, canvasHeight: 768, autoResize: true, clearColor: new THREE.Color("#ffffff"), antialias: true }) ``` -------------------------------- ### Load DXF Drawing with Parameters Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/types.md Demonstrates how to load a DXF file into the viewer using load parameters, specifying the URL, font paths, a progress callback, and a worker factory. ```typescript const loadParams: DxfViewerLoadParams = { url: 'drawings/building.dxf', fonts: [ 'fonts/arial.typeface.json', 'fonts/times.typeface.json' ], progressCbk: (phase, processed, total) => { console.log(`${phase}: ${processed}/${total}`) }, workerFactory: () => new Worker('dxf-worker.js') } await viewer.Load(loadParams) ``` -------------------------------- ### Get Scene Origin Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Retrieve the scene origin using GetOrigin(). This Vector2 value is crucial for correctly positioning custom elements relative to the DXF drawing coordinates. ```javascript const origin = viewer.GetOrigin() console.log(`Origin: (${origin.x}, ${origin.y})`) ``` -------------------------------- ### Load DXF File with Configuration Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/configuration.md Specify the DXF file URL, font files for text rendering, a progress callback, and a web worker factory for background processing. ```javascript await viewer.Load({ // DXF file URL (required) url: "drawing.dxf", // Font files for text rendering fonts: [ "fonts/arial.typeface.json", "fonts/times.typeface.json" ], // Progress reporting callback progressCbk: (phase, processed, total) => { const percent = (processed / total * 100).toFixed(1) console.log(`${phase}: ${percent}%`) }, // Web worker factory for background processing workerFactory: () => new Worker("dxf-worker.js") }) ``` -------------------------------- ### Initialize DxfViewer with Scene Options Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/configuration.md Configure scene-specific options during DxfViewer initialization, such as arc tessellation, mesh rendering style, and paper space visibility. ```javascript const viewer = new DxfViewer(container, { sceneOptions: { // Arc and circle tessellation arcTessellationAngle: 10 * Math.PI / 180, // Default: ~10 degrees minArcTessellationSubdivisions: 8, // Default: 8 // Mesh rendering style wireframeMesh: false, // Default: false (solid) // Paper space visibility suppressPaperSpace: false // Default: false (show paper space) } }) ``` -------------------------------- ### Get Scene Bounds Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfViewer.md Obtain the bounding box of the DXF scene in model space coordinates using GetBounds(). This returns an object with min/max X and Y values, or null if the scene is empty. ```javascript const bounds = viewer.GetBounds() if (bounds) { const width = bounds.maxX - bounds.minX const height = bounds.maxY - bounds.minY console.log(`Drawing size: ${width} x ${height}`) } ``` -------------------------------- ### Type Definitions Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/COMPLETION_SUMMARY.txt This section provides complete definitions for all types used within the DXF Viewer, including field descriptions, default values, usage examples, enum definitions, and constant values. ```APIDOC ## Types The `types.md` file serves as a central repository for all type definitions within the DXF Viewer project. ### Complete Type Definitions Exhaustive definitions for all interfaces, types, and classes, ensuring clarity on data structures. ### Field Descriptions Detailed descriptions for each field within types and interfaces, explaining their purpose and expected data. ### Default Values Documentation of default values for fields and parameters where applicable, aiding in configuration and usage. ### Usage Examples Practical examples illustrating how to use the defined types in various programming contexts. ### Enum Definitions Complete definitions for all enumerated types, providing a clear set of named constants. ### Constant Values Documentation of all exported constant values, including their definitions and intended use. ``` -------------------------------- ### Create Custom Hatch Pattern Instance Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/INDEX.md Shows how to create a Pattern instance directly from its lines definition, name, and offsetInLineSpace property. ```javascript import { Pattern } from "@dxf-viewer/core"; const pattern = new Pattern([ { type: "LINE", angle: 45, scale: 1, offset: [0, 0] }, ], "Diagonal", false); ``` -------------------------------- ### DxfViewer API Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/MANIFEST.txt Documentation for the main DxfViewer class, covering its constructor, methods, and event subscriptions. ```APIDOC ## DxfViewer Class ### Description Provides the primary interface for interacting with the DXF viewer. It allows loading DXF files, controlling the view, managing layers, and subscribing to events. ### Constructor Documentation for the constructor with full parameter details is available in `DxfViewer.md`. ### Methods Includes over 20 methods such as `Load`, `SetView`, `FitView`, and `ShowLayer`. Detailed documentation for each method is available in `DxfViewer.md`. ### Events Supports subscription to 8 different event types. Details can be found in `DxfViewer.md`. ### Static Methods Documentation for static methods is available in `DxfViewer.md`. ### Examples Complete usage examples are provided within `DxfViewer.md`. ``` -------------------------------- ### Programmatic Camera Control with DxfViewer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/OrbitControls.md Shows how to control the camera programmatically using DxfViewer methods for setting specific views or fitting drawing bounds. ```javascript // Set view to specific position and size viewer.SetView(center, width) // Fit bounds into view viewer.FitView(minX, maxX, minY, maxY, padding) // Get current camera for direct access const camera = viewer.GetCamera() ``` -------------------------------- ### Building a Vertex Buffer with DynamicBuffer Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DynamicBuffer.md Demonstrates how to create a DynamicBuffer for vertex data, add vertices with position and color, and convert it to a Float32Array. Use this when the number of vertices is not known beforehand. ```javascript import { DynamicBuffer, NativeType } from 'dxf-viewer' // Create dynamic buffer for vertex data (x, y, color as separate components) const vertexBuffer = new DynamicBuffer(NativeType.FLOAT32, 256) // Add vertices const vertices = [ // Vertex 1: position (x, y) and color (r, g, b, a) { x: 0, y: 0, r: 1, g: 0, b: 0, a: 1 }, { x: 100, y: 0, r: 0, g: 1, b: 0, a: 1 }, { x: 50, y: 100, r: 0, g: 0, b: 1, a: 1 } ] for (const v of vertices) { vertexBuffer.Push(v.x) vertexBuffer.Push(v.y) vertexBuffer.Push(v.r) vertexBuffer.Push(v.g) vertexBuffer.Push(v.b) vertexBuffer.Push(v.a) } console.log(`Vertex count: ${vertexBuffer.GetSize() / 6}`) // 3 console.log(`Buffer capacity: ${vertexBuffer.capacity} elements`) // Convert to final buffer for WebGL const finalVertexBuffer = new Float32Array(vertexBuffer.GetSize()) vertexBuffer.CopyTo(finalVertexBuffer, 0) ``` -------------------------------- ### DxfScene Variables Property Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfScene.md The `vars` property is a `Map` storing DXF system variables (header variables), indexed by their names without the leading '$'. Examples include `ANGBASE`, `ANGDIR`, `PDMODE`, `PDSIZE`, and `MEASUREMENT`. ```javascript vars: Map ``` -------------------------------- ### Fetch Method Source: https://github.com/vagran/dxf-viewer/blob/master/_autodocs/api-reference/DxfFetcher.md Fetches the DXF file from the configured URL and parses its content. It supports an optional progress callback for download and parsing updates. ```APIDOC ## Method Fetch ### Description Fetches the DXF file from the configured URL and parses its content. It supports an optional progress callback for download and parsing updates. ### Parameters #### Path Parameters - **progressCbk** ((phase: string, receivedSize: number, totalSize: number) => void | null) - Optional - Optional callback function for progress updates. Called with phase "fetch" as data is downloaded, then "parse" when parsing begins. ### Returns `Promise` - Resolves with parsed DXF object containing header, tables, blocks, and entities. ### Throws - Error if fetch fails or URL is unreachable. - Error if DXF parsing fails due to invalid format. ### Example ```javascript const fetcher = new DxfFetcher('drawing.dxf') try { const dxf = await fetcher.Fetch((phase, received, total) => { if (phase === 'fetch') { const percent = (received / total * 100).toFixed(1) console.log(`Downloading: ${percent}%`) } else if (phase === 'parse') { console.log('Parsing DXF...') } }) console.log(`Header: ${JSON.stringify(dxf.header)}`) console.log(`Entities: ${dxf.entities.length}`) } catch (err) { console.error('Failed to fetch DXF:', err) } ``` ```