Coder Social home page Coder Social logo

dxf-viewer's Introduction

DXF viewer npm

If you just need to view your DXF, click here.

This package provides DXF 2D viewer component written in JavaScript. It renders drawings using WebGL (via three.js library). It was carefully crafted with performance in mind, intended for drawing huge real-world files without performance problems.

The usage example is available here: https://github.com/vagran/dxf-viewer-example-src

Deployed demo: https://vagran.github.io/dxf-viewer-example/

Install

npm install dxf-viewer

Features

  • File fetching, parsing and preparation for rendering is separated in such a way that it can be easily off-loaded to web-worker using provided helpers. So the most heavy-weight processing part does not affect UI responsiveness. The example above demonstrates this technique.
  • Geometry batching - minimal number of rendering batches is created during file processing, thus minimizing total required number of draw calls.
  • Instanced rendering - features which are rendered multiple times with different transforms (e.g. DXF block instances) are rendered by a single draw call using instanced rendering WebGL feature.
  • Multiple fonts support. List of fonts can be specified for text rendering. Raw TTF files are supported. Fonts are lazy-loaded, once a character encountered which glyph is not yet available through already loaded fonts, next font is fetched and checked for the necessary glyph.
  • Layers - layers are taken into account when creating rendering batches so that they can be easily hidden/shown.

Incomplete features

There are still many incomplete features. I will try to implement some of them when I have some time. Most significant reason for missing implementation is lack of corresponding sample files.

  • Stream parsing for input file. Currently, mostly relying on dxf-parser package which is not stream parser and thus buffers whole the file before parsing. This prevents from supporting big DXF file (above gigabyte) due to string size limit in JS engine (also making unnecessary memory waste for the buffer).
  • Text styling. Currently, text rendering is using just the specified fonts in the specified order. DXF style and font attributes are ignored. Text glyphs are always rendered infilled.
  • Advanced formatting support for MTEXT (fonts, coloring, stacking).
  • Line patterns - all lines are rendered in continuous style for now. I am going to use 1-D texture generated on preparation stage, texture coordinates (which should account pattern continuity flag in DXF vertices attributes), and a dedicated shader to implement this feature.
  • Line patterns with shapes (e.g. with circles).
  • Wide lines. Currently, all lines are rendered as thin lines. Physical width is not implemented.
  • Variable width lines (i.e. with start and end width specified).
  • Smoothed polyline (curve-fit/spline-fit addition vertices).
  • Some features in hatching implementation: outer hatching style, solid/gradient infill, MPolygon support, double lines, boundaries defined by external entities.
  • Block instancing in a grid. Grid attributes are ignored now.
  • Dimensions-specific features and styles (various pre-defined arrowhead blocks, text positioning tuning, limits and tolerances). Dimensions types other than linear ones.
  • Leaders
  • Non-UTF-8 file encoding support. Currently, such files are displayed incorrectly. $DWGCODEPAGE parameter is ignored.
  • Full OCS support. Currently, it is assumed that entity extrusion direction is either +Z or -Z (which is commonly used for features mirroring in CAD). Arbitrary directions is not properly processed.
  • Paper space, layouts (sheets), viewports.
  • Many less commonly used DXF features.

samples

Contributing

Please refer to the contribution guidelines for details on how to make pull requests (PRs). The project also requires various example files for testing purposes. If you encounter any issues with DXF rendering, it would be greatly appreciated if you could provide an example file that demonstrates the problem by attaching it to a created issue. Creating minimal examples in CAD software can also be very helpful. Additionally, creating examples in various proprietary CAD software to which I do not have access would be highly valuable. Since the entrance level to start coding in this project is quite high, it is often more useful to receive a detailed issue report with sample files rather than a pull request.

License

This project is licensed under the terms of the Mozilla Public License 2.0.

Donations

Want to say thanks to the project maintainer? Here is the link: Donate

dxf-viewer's People

Contributors

arlebedev avatar dotoritos-kim avatar jdh-invicara avatar mpanknin avatar szrharrison avatar vagran avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dxf-viewer's Issues

AxesHelper

Артем привет! У меня некоторые проблемы с тем, чтобы переместить оси x,y в начало чертежа. Т.е. я хочу, чтобы чертеж был в такой области, чтобы он не занимал отрицательные координаты (находился правее и выше от осей; с началом в самой левой и нижней точке чертежа) Надеюсь понятно объяснил...
Можешь помочь с этим, если это возможно? Вот несколько скриншотов с демонстрацией того, что некоторые элементы чертежа находятся под осью y, и левее x
Я пытался манипулировать значением из origin, но слабо выходит
Снимок экрана 2023-05-25 в 15 09 11
Снимок экрана 2023-05-25 в 15 09 30

Support pre-defined dimension blocks

Sometimes DIMENSION entity may refer to a pre-drawn block. In such case the block should be rendered instead of generating dimension picture from its definition.

Simple Example

Hello Vagran
It's possible to have a simple example to show how we can load a simple dxf?
Because many people are not familiar Quasar and we can't understand the code to understand how we can use that.
Thank you

Is it possible to support acad_proxy_entity parsing 310 binary chunks?

I'm working on a Chinese project of dxf files based on dxf-viewer.

I've already done some work on entities such as attdef, linear dimension. And created some plugins to do annotation with simple drawings such as circle or rectangle, cursor selection, magnetic adsorption of lines and rerendering manual-created objects on canvas, text searching and locating, border searching for drawings. But my code adapts to this project too much, so i haven't rebuilt my code and contributed them to this project yet.

I'm going to apply to join your development group later. I think i'm helpful on some tasks :)

I'm now solving hatch, image, and acad_proxy_entity.

Acad_proxy_entity has a 310 binary chunks value, I can't decode the and stuck on it.

Such as:

0
ACAD_PROXY_ENTITY
5
41590
330
4116D
100
AcDbEntity
8
WALL
100
AcDbProxyEntity
90
498
91
528
71
31
97
55
70
0
160
8
310
0800000000000000
162
2
311
80
161
965
310
0500000000000012502030000820ECE7F703879A0C4DE8CB133369FDAC49E8ECECECECECECECECE7F703879A0C4DE897133369DDB049E8ECECECECECECECECECECECECECECECECECECECECECECECECECED89ECECECECECECED89ECECECECECED2E71EC02280019BF94AE078155102000800800000165028010
330
0
330
0
330
0
330
0
330
4158F
330
41591
340
0
340
0
340
462B
340
0
330
0
330
0
94
0

Are you going to solve this problem or provide some ideas to me? There is so little information on it. I've even search in Russian and German, noting helpful. The only helpful link is broken and can't visit in China. T^T

Infinite loop when window.onmessage type doesn't match

When the msg.data.type of a window.onmessage event does not match DxfWorker.WorkerMsg.LOAD or DxfWorker.WorkerMsg.DESTROY, DxfWorker._ProcessRequest will post a response that seems to retrigger the same error flow, resulting in an infinite loop.

This flow is triggered for me when using the webpack dev server, which posts a message when a hot reload is performed, as well as when using vue dev tools, which post a message when the plugin is initialized.

A possible solution to this would be creating a way to recognize onmessage events that are created by dxf-viewer so those from other sources can be ignored, maybe a message type prefix or a specific field in the data?

Question: All geometries use RawShaderMaterial ?

in scene, I see all geometries use RawShaderMaterial. but I want use clipPlanes to cut geometry. but the implementation of this shader is not very clear.

file path: DxFViewer.js / _GenerateShaders function
example:

vertex: `
  // other code
  ${fullInstanceAttr}
  ${pointInstanceAttr}

  // add new param
  out vec3 vPosition; 
  uniform mat4 modelViewMatrix;
  // other define param
 
  void main() {

   vec4 pos = vec4(position, 0.0, 1.0);
   // used by fragment Shader
   vPosition = vec3(position, 0.0);
   // other code
  }
`
fragment: `
// other code
out vec4 fragColor;
uniform vec4 clipPlanes[4];
out vec3 vPosition;

void main(){
  #if NUM_PLANES > 0 
    float distances[4];
    for (int i = 0; i < 4; i++) {
      distances[i] = dot(vPosition, clipPlanes[i].xyz) - clipPlanes[i].w;
    }
   if (distances[0] > 0.0 || distances[1] > 0.0 || distances[2] > 0.0 || distances[3] > 0.0) discard;
 #endif

  fragColor = vec4(color, 1.0);
}
`

but is not work。 I see three source code in path(src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl).

Can you help me?

ATTRIB/ATTDEF proper processing

It should be investigated how to properly handle ATTRIB/ATTDEF entities.

Here is one piece of information.

As I see, they are not always rendered by Autodesk viewer, but are listed in block attributes instead:
image

flutter ios

Hello,

Is there any way to use this dxf-viewer as part of an IOS app in flutter?
ie to display .DXF image on iPhone in flutter/dart app?

Thanks,
Niall

DXF Viewer not supporting some entities

Hi vagran,

First of all this is an amazing viewer, but when I was testing you deployed demo, I noticed that some entities are not being handled.
I'll leave here two prints for you to see.
This is what the dxf supposed to look like.

dxf

And here's what is happening.

dxf-2

I don't if was your choice to not to handle this type of entity, but as I said earlier this is an amazing work.

Best regards,
José Cunha

Implement `hatch` entity

Hello, I'd like to implement the parser and renderer for hatch entity. Since this feature is essential to the CAD user, IMO it's important and valuable to proceed. My final goal is implementing a rendering logic for hatch, but to do so I have to parse hatch entity first.

If someone has any plan to do so (or even currently doing it), let's talk about more so that I can help and elaborate. If it's not, may I proceed to implement such feature? @vagran

Milestones

TBD

Reference

ATTDEF problem

I have a dxf with some ATTDEF object and the vewer doesn't load dxf at alll.
In the console there is "Unhandled entity type: ATTDEF".

how can i fix it?

Return type of GetCamera()

Hi
Thanks for creating and maintaining this great project!

I found a small bug in index.d.ts. I think return type of DxfViewer.GetCamera() should be "OrthographicCamera" instead of "Camera".

GetCamera(): THREE.Camera

Some entities not rendered

When I try to load the same file in your deployed demo and in my project (not Vue), results are different.
This is the result of your deployed demo:

image

This is my project output (as you can see, some entities are missing):

image

What could I have done wrong?
I see no errors in console.
Thanks.

Additional loader to handle the result

I'm trying to use the dxf-viewer on my project and we are getting some erros on loading dxfviewer.js

error  in ./node_modules/dxf-viewer/src/DxfViewer.js

Module parse failed: Unexpected token (788:60)
File was processed with these loaders:
* ./node_modules/@quasar/app/lib/webpack/loader.transform-quasar-imports.js
You may need an additional loader to handle the result of these loaders.
| 
|         const material = materialFactory.call(this.viewer, this.viewer._TransformColor(color),
>                                               instanceBatch?.GetInstanceType() ?? InstanceType.NONE)
| 
|         let objConstructor

It's a quasar app, and here is our package.json

{
  "name": "xxxxx",
  "version": "1.0.16",
  "description": "xxxxxx",
  "productName": "xxxxxx",
  "author": "xxxxx",
  "private": true,
  "scripts": {
    "build": "quasar build",
    "dev": "quasar dev",
    "lint": "eslint --ext .js,.vue src",
    "test": "echo \"No test specified\" && exit 0"
  },
  "dependencies": {
    "@quasar/extras": "^1.11.1",
    "@quasar/quasar-ui-qmarkdown": "^1.4.3",
    "@turf/bbox": "^6.0.1",
    "@turf/turf": "^5.1.6",
    "animated-number-vue": "^1.0.0",
    "arraybuffer-to-string": "^1.0.2",
    "axios": "^0.18.1",
    "core-js": "^3.6.5",
    "dxf-viewer": "^1.0.15",
    "firebase": "^8.9.1",
    "humanize-duration": "^3.27.1",
    "js-file-download": "^0.4.12",
    "lodash": "^4.17.15",
    "moment": "^2.24.0",
    "ol": "^6.4.0",
    "parse": "^2.11.0",
    "quasar": "^1.16.0",
    "three": "^0.138.3",
    "uuid": "^8.3.2",
    "vue-carousel-3d": "^1.0.1",
    "vue-i18n": "^8.0.0",
    "vue-the-mask": "^0.11.1",
    "vue2-google-maps": "^0.10.7",
    "vuelidate": "^0.7.4",
    "vuex-persist": "^3.1.3"
  },
  "devDependencies": {
    "@quasar/app": "^2.2.10",
    "@quasar/quasar-app-extension-qmarkdown": "^1.4.3",
    "babel-eslint": "^10.0.1",
    "cors": "^2.8.5",
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.0",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-node": "^11.0.0",
    "eslint-plugin-promise": "^4.0.1",
    "eslint-plugin-standard": "^4.0.0",
    "eslint-plugin-vue": "^6.1.2",
    "less": "^4.1.2",
    "less-loader": "^7.3.0",
    "pug": "^2.0.4",
    "pug-plain-loader": "^1.0.0",
    "worker-loader": "^3.0.8"
  },
  "engines": {
    "node": ">= 10.18.1",
    "npm": ">= 6.13.4",
    "yarn": ">= 1.21.1"
  },
  "browserslist": [
    "last 10 Chrome versions",
    "last 10 Firefox versions",
    "last 4 Edge versions",
    "last 7 Safari versions",
    "last 8 Android versions",
    "last 8 ChromeAndroid versions",
    "last 8 FirefoxAndroid versions",
    "last 10 iOS versions",
    "last 5 Opera versions"
  ]
}

Maibe there's any npm wich version conflicts ! i don't know !
any help would be appreciate

AxesHelper not shown

Hi vagran,
This project is great, I read the code and it was well organised.
I came with a question, in fact this is not a issues.
Here is the question:
`
// DxfViewer.js
constructor() {
...
this.canvas.addEventListener("pointerdown", this._OnPointerEvent.bind(this))
this.canvas.addEventListener("pointerup", this._OnPointerEvent.bind(this))

    /** 
     * AxesHelper
     */
    const axesHelper = new three.AxesHelper(1000);
    this.scene.add(axesHelper);
    this.Render()

}
`
I add an axesHelper to the scene, but when I load the dxf file, the axesHelper is not shown, I tried some work around and I still do not know why. Could you give me some advice?
Thank you, I really appreciate it.

DXF generated by Autodesk Revit not displaying correctly

When I open a 3D DXF file in the dxf-viewer I would expect to see a top-down view. This works as expected with output from Rhino.

Here's a 3D model generated from Rhino displayed in Autodesk DWG Trueview:

image

Here's the same model with camera orbited to look top-down:

image

And here's the same model when loaded into dxf-viewer-example:

image

However, when I open a DXF file generated from Autodesk Revit model's 3D view I get "extra lines drawn".

Here's a DXF output from a Revit model in Autodesk DWG Trueview (viewed top-down):

image

And here's the same model when loaded into dxf-viewer-example:

image

Here are the two DXF files - one from Rhino and one from Revit:

sampleDXFs3D.zip

What if I want to select only specific blocks?

The web browser sometimes freezes when opening a file with too many blocks. It was my mistake.
So, I would like to ask how can I render only certain blocks.
Looking forward to your kind reply from Mr. Vargan :)

How to implement the POLYLINE type

POLYINE type case

While looking at the source code, I noticed that there is no logic to handle the POLYLINE type.
I knew there was a part in three-dxf that handles this type. Wouldn't it be easy to make by referring to the logic?

I still have a hard time with dxf-viewer's compression algorithm. I'd like to contribute to this open source, but it's not easy.

Old orbitcontrols touches zoom issue

In the old version of OrbitControls, when zooming in or zooming out with touches, it operates based on a strange point.
I guess we'll have to find out where this is issue and fix it, or use the OrbitControls provided by the latest version of three.js.

can export a click event?

hi
Can there be a click event in dxf-viewer? I want to obtain information about clicked icons through click events.

thanks.

Getting scales or measurements

First of all thanks for taking time to improve the original dxf-parser! I've working on doing an adaption of this library for react-three-fiber.

But there's some feature sets I've been considering to try to include.
Right now I've been been a bit stuck on how to find ways on how to work with the scales in the DXF files, generally to enable the user to measure a distance or to normalise the different sizes of the dxf files that sometimes seems to widely different in terms of scale.

I've seen there's bounds and the origin measurements but I'm unsure if they can have any relation with calculating the document scale or line lengths in terms of millimetres/meters or other document scales. A good example of implementation I found was the Autodesk online viewer. My question is if anyone else has worked on this or have any insights in how this can be implemented?

Thanks!

zoomCenter is undefined

use Pad browse, zoom with two fingers, the zoomCenter@zoomPan is undefined at line 451 of OrbitControls.js,

some lines may send a undefined value
line767 --> line:465 --> line:451

dollyOut( dollyDelta.y );

line551 --> line:465 --> line:451
line555 --> line:465 --> line:451

dollyOut( getZoomScale() );

I try put these code before line 767, fix the error temporary.

const touch = event.touches[0];
const canvasRect = scope.domElement.getBoundingClientRect();
const zoomCenter = new THREE.Vector2(touch.pageX - canvasRect.left,
		touch.pageY - canvasRect.top);

dollyOut( dollyDelta.y, zoomCenter );

Pls check. @vagran

Raycaster

Hi, Dear Developer, I really loved your job. It is the fastest and most comprehensive dxfviewer. I am trying to implement Threejs.Raycaster. But I couldn't. I think The Vertices in buffer geometry do not contain z values. This is causing the error.
I tried to add z value to vertices. But I could not. This is beyond my abilities. I hope you add the raycaster feature in the future. I would love to work with you on this.
best regards,
ferhat

Text display

Hello, now I have a question, how to convert the font in dxf into Chinese.
image

Координаты/Coordinates

Добрый день! Можно ли получить координаты клика на чертеже? / Is it possible to get the coordinates of the click in the drawing?

Drawing function

Hi everyone!
i have a question: It is possible add function for drawing line, polyline or other elements?
Thanks!

about ole2frame

Could please give me some idea to parse ole2frame? I used sheet.js to parse 100 stream of ole2frame,The result is all the excel data,I can not know the ole2frame data come from which sheet.

Nice viewer, and some issues I found

Hello Vagran,

Nice to see your dxf-viewer, wonderful tool! We also created our own dxf viewer, but not open sourced! I tried your example web site, it already supports plenty of dxf features with a pretty good performance. Great job.

One file has some issue, as you can see, the color, and some hatches are not rendererd correctly. You may take a look when there is chance.
image

The file is here:
https://github.com/pattern-x/gemini-viewer-examples/blob/main/public/demo/models/dxf/rac_basic_sample_project.dxf

It looks like this in our system:
https://pattern-x.github.io/gemini-viewer-examples/#/Rac_basic_sample_project_dwg
image

Shading is only applied to the first few uploaded DXF file.

I'm building an app that allows users to upload DXF files and render them in the browser using Three.js. To shade the inner part of the DXF geometry, I'm using a MeshBasicMaterial with a grey color.

The problem is that the shading is only applied to the first few uploaded DXF file, and not the subsequent files. I have tried different approaches to fix this issue, including setting the render order of the shaded meshes, but the issue persists.

` createShapeObj(vertices, isColored) {
const objVertices = this._TransformVertex(vertices.map(el=>new three.Vector2(el.x, el.y)));

    let material = new three.MeshBasicMaterial( { color: isColored ? 0xE5E5E5 : 0xffffff } ); //shading only inner geometry
    const shape = new three.Shape();
    shape.moveTo(objVertices[0].x, objVertices[0].y);
    for(let i=1;i<objVertices.length;i++){
        shape.lineTo(objVertices[i].x, objVertices[i].y)
    }
    const geometry = new three.ShapeGeometry(shape);
    const mesh = new three.Mesh( geometry, material ) ;

    return {mesh};
}`

Note: I have tried dxf files

DxfViewer.Load(url) always breaks with an "Unexpected end of input: EOF group not read before end of file" error

I've been testing the viewer with different DXF files, and it always breaks with the same error in the DxfViewer.Load(url) step:

Uncaught (in promise) Error: Unexpected end of input: EOF group not read before end of file. Ended on code
at DxfArrayScanner.next (bundle.js:95279:19)
at parseAll (bundle.js:97136:32)
at DxfParser._parse (bundle.js:97725:5)
at DxfParser.parseSync (bundle.js:97058:21)
at DxfFetcher.Fetch (bundle.js:97786:23)
at async DxfWorker._Load (bundle.js:165347:21)
at async DxfViewer.Load (bundle.js:166831:23)

My code is the following:

import { DxfViewer } from "dxf-viewer";

var dxfCanvas = document.getElementById("dxf-canvas");
dxfCanvas.width = window.innerWidth;
dxfCanvas.height = window.innerHeight;

var dxfViewer = new DxfViewer(dxfCanvas);
dxfViewer.SetSize(dxfCanvas.width, dxfCanvas.height);

async function loadDxfUrl() {
    await dxfViewer.Load(dxfUrl);
}

loadDxfUrl();

dxfUrl is a blob url. I've been trying with different dxf files and all of them return the same error. The DXF files open in other viewers.
The files can be also parsed correctly using DxfFetcher with the following code:

import { DxfFetcher } from "dxf-viewer";

var dxfFetcher = new DxfFetcher(dxfUrl);
dxfFetcher.Fetch()
    .then(res => {
        console.log(res);
    });

Some Questions about the Parameters in the TextDecoder() Method

in DxfFetcher.js
class TextDecoder() use params gbk

 //... other code
 let buffer = ""
 let decoder = new TextDecoder("utf-8")

then can not resolve Chinese

20230704144714

I see this docs nodejs for textdecoder

i find has same params like gbk

 let decoder = new TextDecoder("gbk")

20230704145846

Can we consider making the encoding an optional parameter?

example:

export class DxfFetcher {
     constructor(url, decoder = 'utf-8') {
        this.url = url
        this.decoder = decoder
    }

   async Fetch(processCbk = null) {
     // .... other code
     let decoder = new TextDecoder(this.decoder)
     // .... other code
   }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.