forked from davetowey/three-dxf-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DXFLoader.js
438 lines (318 loc) · 14.7 KB
/
DXFLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// A DXF Loader for three.js
// based heavily on three-dxf 0.1.2
// https://github.com/gdsestimating/three-dxf
// Depends on dxf-parser
// https://github.com/gdsestimating/dxf-parser
if (typeof THREE == 'undefined' && typeof require != 'undefined')
var THREE = require('three');
if (typeof DxfParser == 'undefined' && typeof require != 'undefined')
var DxfParser = require('dxf-parser');
/**
* Returns the angle in radians of the vector (p1,p2). In other words, imagine
* putting the base of the vector at coordinates (0,0) and finding the angle
* from vector (1,0) to (p1,p2).
* @param {Object} p1 start point of the vector
* @param {Object} p2 end point of the vector
* @return {Number} the angle
*/
THREE.Math.angle2 = function (p1, p2) {
var v1 = new THREE.Vector2(p1.x, p1.y);
var v2 = new THREE.Vector2(p2.x, p2.y);
v2.sub(v1); // sets v2 to be our chord
v2.normalize();
if (v2.y < 0) return -Math.acos(v2.x);
return Math.acos(v2.x);
};
THREE.Math.polar = function (point, distance, angle) {
var result = {};
result.x = point.x + distance * Math.cos(angle);
result.y = point.y + distance * Math.sin(angle);
return result;
};
/**
* Calculates points for a curve between two points
* @param startPoint - the starting point of the curve
* @param endPoint - the ending point of the curve
* @param bulge - a value indicating how much to curve
* @param segments - number of segments between the two given points
*/
THREE.BulgeGeometry = function (startPoint, endPoint, bulge, segments) {
var vertex, i,
center, p0, p1, angle,
radius, startAngle,
thetaAngle;
THREE.Geometry.call(this);
this.startPoint = p0 = startPoint ? new THREE.Vector2(startPoint.x, startPoint.y) : new THREE.Vector2(0, 0);
this.endPoint = p1 = endPoint ? new THREE.Vector2(endPoint.x, endPoint.y) : new THREE.Vector2(1, 0);
this.bulge = bulge = bulge || 1;
angle = 4 * Math.atan(bulge);
radius = p0.distanceTo(p1) / 2 / Math.sin(angle / 2);
center = THREE.Math.polar(startPoint, radius, THREE.Math.angle2(p0, p1) + (Math.PI / 2 - angle / 2));
this.segments = segments = segments || Math.max(Math.abs(Math.ceil(angle / (Math.PI / 18))), 6); // By default want a segment roughly every 10 degrees
startAngle = THREE.Math.angle2(center, p0);
thetaAngle = angle / segments;
this.vertices.push(new THREE.Vector3(p0.x, p0.y, 0));
for (i = 1; i <= segments - 1; i++) {
vertex = THREE.Math.polar(center, Math.abs(radius), startAngle + thetaAngle * i);
this.vertices.push(new THREE.Vector3(vertex.x, vertex.y, 0));
}
};
THREE.BulgeGeometry.prototype = Object.create(THREE.Geometry.prototype);
THREE.DXFLoader = function (manager) {
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.DXFLoader.prototype = {
constructor: THREE.DXFLoader,
load: function (url, onLoad, onProgress, onError) {
var scope = this;
var loader = new THREE.FileLoader(this.manager);
loader.load(url, function (text) {
onLoad(scope.parse(new DxfParser().parseSync(text)));
}, onProgress, onError);
},
parse: function (data) {
var group = new THREE.Object3D();
var i, entity, obj;
for (i = 0; i < data.entities.length; i++) {
entity = data.entities[i];
if (entity.type === 'DIMENSION') {
if (entity.block) {
var block = data.blocks[entity.block];
if (!block) {
console.error('Missing referenced block "' + entity.block + '"');
continue;
}
for (var j = 0; j < block.entities.length; j++) {
obj = drawEntity(block.entities[j], data);
}
} else {
console.log('WARNING: No block for DIMENSION entity');
}
} else {
obj = drawEntity(entity, data);
}
if (obj) {
obj.matrixAutoUpdate = false;
group.add(obj);
}
obj = null;
}
return group;
function drawEntity(entity, data) {
var mesh;
if (entity.type === 'CIRCLE' || entity.type === 'ARC') {
mesh = drawCircle(entity, data);
} else if (entity.type === 'LWPOLYLINE' || entity.type === 'LINE' || entity.type === 'POLYLINE') {
mesh = drawLine(entity, data);
} else if (entity.type === 'TEXT') {
mesh = drawText(entity, data);
} else if (entity.type === 'SOLID') {
mesh = drawSolid(entity, data);
} else if (entity.type === 'POINT') {
mesh = drawPoint(entity, data);
} else if (entity.type === 'INSERT') {
mesh = drawBlock(entity, data);
}
return mesh;
}
function drawLine(entity, data) {
var geometry = new THREE.Geometry(),
color = getColor(entity, data),
material, lineType, vertex, startPoint, endPoint, bulgeGeometry,
bulge, i, line;
// create geometry
for (i = 0; i < entity.vertices.length; i++) {
if (entity.vertices[i].bulge) {
bulge = entity.vertices[i].bulge;
startPoint = entity.vertices[i];
endPoint = i + 1 < entity.vertices.length ? entity.vertices[i + 1] : geometry.vertices[0];
bulgeGeometry = new THREE.BulgeGeometry(startPoint, endPoint, bulge);
geometry.vertices.push.apply(geometry.vertices, bulgeGeometry.vertices);
} else {
vertex = entity.vertices[i];
geometry.vertices.push(new THREE.Vector3(vertex.x, vertex.y, vertex.z));
}
}
if (entity.shape) geometry.vertices.push(geometry.vertices[0]);
// set material
if (entity.lineType) {
lineType = data.tables.lineType.lineTypes[entity.lineType];
}
if (lineType && lineType.pattern && lineType.pattern.length !== 0) {
material = new THREE.LineDashedMaterial({color: color, gapSize: 4, dashSize: 4});
} else {
material = new THREE.LineBasicMaterial({linewidth: 1, color: color});
}
// if(lineType && lineType.pattern && lineType.pattern.length !== 0) {
// geometry.computeLineDistances();
// // Ugly hack to add diffuse to this. Maybe copy the uniforms object so we
// // don't add diffuse to a material.
// lineType.material.uniforms.diffuse = { type: 'c', value: new THREE.Color(color) };
// material = new THREE.ShaderMaterial({
// uniforms: lineType.material.uniforms,
// vertexShader: lineType.material.vertexShader,
// fragmentShader: lineType.material.fragmentShader
// });
// }else {
// material = new THREE.LineBasicMaterial({ linewidth: 1, color: color });
// }
line = new THREE.Line(geometry, material);
return line;
}
function drawCircle(entity, data) {
var geometry, material, circle;
geometry = new THREE.CircleGeometry(entity.radius, 32, entity.startAngle, entity.angleLength);
geometry.vertices.shift();
material = new THREE.LineBasicMaterial({color: getColor(entity, data)});
circle = new THREE.Line(geometry, material);
circle.position.x = entity.center.x;
circle.position.y = entity.center.y;
circle.position.z = entity.center.z;
return circle;
}
function drawSolid(entity, data) {
var material, mesh, verts,
geometry = new THREE.Geometry();
verts = geometry.vertices;
verts.push(new THREE.Vector3(entity.points[0].x, entity.points[0].y, entity.points[0].z));
verts.push(new THREE.Vector3(entity.points[1].x, entity.points[1].y, entity.points[1].z));
verts.push(new THREE.Vector3(entity.points[2].x, entity.points[2].y, entity.points[2].z));
verts.push(new THREE.Vector3(entity.points[3].x, entity.points[3].y, entity.points[3].z));
// Calculate which direction the points are facing (clockwise or counter-clockwise)
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
vector1.subVectors(verts[1], verts[0]);
vector2.subVectors(verts[2], verts[0]);
vector1.cross(vector2);
// If z < 0 then we must draw these in reverse order
if (vector1.z < 0) {
geometry.faces.push(new THREE.Face3(2, 1, 0));
geometry.faces.push(new THREE.Face3(2, 3, 1));
} else {
geometry.faces.push(new THREE.Face3(0, 1, 2));
geometry.faces.push(new THREE.Face3(1, 3, 2));
}
material = new THREE.MeshBasicMaterial({color: getColor(entity, data)});
return new THREE.Mesh(geometry, material);
}
function drawText(entity, data) {
var geometry, material, text;
if (!font)
return console.warn('Text is not supported without a Three.js font loaded with THREE.FontLoader! Load a font of your choice and pass this into the constructor. See the sample for this repository or Three.js examples at http://threejs.org/examples/?q=text#webgl_geometry_text for more details.');
geometry = new THREE.TextGeometry(entity.text, {font: font, height: 0, size: entity.textHeight || 12});
material = new THREE.MeshBasicMaterial({color: getColor(entity, data)});
text = new THREE.Mesh(geometry, material);
text.position.x = entity.startPoint.x;
text.position.y = entity.startPoint.y;
text.position.z = entity.startPoint.z;
return text;
}
function drawPoint(entity, data) {
var geometry, material, point;
geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(entity.position.x, entity.position.y, entity.position.z));
// TODO: could be more efficient. PointCloud per layer?
var numPoints = 1;
var color = getColor(entity, data);
var colors = new Float32Array(numPoints * 3);
colors[0] = color.r;
colors[1] = color.g;
colors[2] = color.b;
geometry.colors = colors;
geometry.computeBoundingBox();
material = new THREE.PointsMaterial({size: 0.05, vertexColors: THREE.VertexColors});
point = new THREE.Points(geometry, material);
return point;
}
function drawBlock(entity, data) {
var block = data.blocks[entity.name];
var group = new THREE.Object3D()
if (entity.xScale) group.scale.x = entity.xScale;
if (entity.yScale) group.scale.y = entity.yScale;
if (entity.rotation) {
group.rotation.z = entity.rotation * Math.PI / 180;
}
if (entity.position) {
group.position.x = entity.position.x;
group.position.y = entity.position.y;
group.position.z = entity.position.z;
}
for (var i = 0; i < block.entities.length; i++) {
var childEntity = drawEntity(block.entities[i], data, group);
if (childEntity) group.add(childEntity);
}
return group;
}
function getColor(entity, data) {
var color = 0x000000; //default
if (entity.color) color = entity.color;
else if (data.tables && data.tables.layer && data.tables.layer.layers[entity.layer])
color = data.tables.layer.layers[entity.layer].color;
if (color == null || color === 0xffffff) {
color = 0x000000;
}
return color;
}
function createLineTypeShaders(data) {
var ltype, type;
if (!data.tables || !data.tables.lineType) return;
var ltypes = data.tables.lineType.lineTypes;
for (type in ltypes) {
ltype = ltypes[type];
if (!ltype.pattern) continue;
ltype.material = createDashedLineShader(ltype.pattern);
}
}
function createDashedLineShader(pattern) {
var i,
dashedLineShader = {},
totalLength = 0.0;
for (i = 0; i < pattern.length; i++) {
totalLength += Math.abs(pattern[i]);
}
dashedLineShader.uniforms = THREE.UniformsUtils.merge([
THREE.UniformsLib['common'],
THREE.UniformsLib['fog'],
{
'pattern': {type: 'fv1', value: pattern},
'patternLength': {type: 'f', value: totalLength}
}
]);
dashedLineShader.vertexShader = [
'attribute float lineDistance;',
'varying float vLineDistance;',
THREE.ShaderChunk['color_pars_vertex'],
'void main() {',
THREE.ShaderChunk['color_vertex'],
'vLineDistance = lineDistance;',
'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
'}'
].join('\n');
dashedLineShader.fragmentShader = [
'uniform vec3 diffuse;',
'uniform float opacity;',
'uniform float pattern[' + pattern.length + '];',
'uniform float patternLength;',
'varying float vLineDistance;',
THREE.ShaderChunk['color_pars_fragment'],
THREE.ShaderChunk['fog_pars_fragment'],
'void main() {',
'float pos = mod(vLineDistance, patternLength);',
'for ( int i = 0; i < ' + pattern.length + '; i++ ) {',
'pos = pos - abs(pattern[i]);',
'if( pos < 0.0 ) {',
'if( pattern[i] > 0.0 ) {',
'gl_FragColor = vec4(1.0, 0.0, 0.0, opacity );',
'break;',
'}',
'discard;',
'}',
'}',
THREE.ShaderChunk['color_fragment'],
THREE.ShaderChunk['fog_fragment'],
'}'
].join('\n');
return dashedLineShader;
}
}
};