-
Notifications
You must be signed in to change notification settings - Fork 1
/
amf-parser.js
288 lines (247 loc) · 8.14 KB
/
amf-parser.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
/**
* @author kaosat-dev
*
* Description: A THREE loader for AMF files (3d printing, cad, sort of a next gen stl).
* Features:
* * supports both zipped and uncompressed amf files
* * supports a lot of the amf spec : objects, colors, textures, materials , constellations etc
*
* Limitations:
* performance / memory usage can peek for large files
* Still some minor issues with color application ordering (see AMF docs)
* No support for composite materials
* No support for math formulas in materials
* No support for curved edges
*
* Usage:
* var loader = new AMFParser();
* loader.addEventListener( 'load', function ( event ) {
*
* var geometry = event.content;
* scene.add( new THREE.Mesh( geometry ) );
*
* } );
* loader.load( './models/amf/slotted_disk.amf' );
*/
/*AMF SPECS breakdown:
* 1..N Objects
*--->1..1 Mesh
*----->1..1 Vertices
*------->1..N Vertex
*--------->1..1 Coordinates
*--------->1..1 Color
*--------->1..1 Normal
*----->1..N Volumes (THREE.js geometry is at this level)
* 1--N Materials
*/
/*Algorithm
For each Object in amf
** CurrentMesh = new THREE.Mesh();
grab vertex attributes (position, normal, color)
** CurrentGeomtry = new THREE.Geometry()
grab volumes
for each Volume
grab triangles (vertex indices)
add data to geometry
Problem !! Materials are defined AFTER volumes
BUT volumes can reference materials ...
*/
var detectEnv = require("composite-detect");
if(detectEnv.isNode) var THREE = require("three");
if(detectEnv.isBrowser) var THREE = window.THREE;
if(detectEnv.isModule) var JSZip = require( 'jszip' );
if(detectEnv.isModule) var sax = require( 'sax' );
if(detectEnv.isModule) var Q = require('q');
var AMF = require("./amf.js");
AMFParser = function () {
this.outputs = ["geometry", "materials", "textures"]; //to be able to auto determine data type(s) fetched by parser
this.defaultMaterialType = THREE.MeshPhongMaterial;//THREE.MeshLambertMaterial; //
this.defaultColor = new THREE.Color( "#efefff" ); //#efefff //#00a9ff
this.defaultShading = THREE.FlatShading;
this.defaultSpecular = null;//0xffffff;
this.defaultShininess = null;//99;
this.defaultVertexNormal = new THREE.Vector3( 1, 1, 1 );
this.recomputeNormals = true;
};
AMFParser.prototype = {
constructor: AMFParser
};
AMFParser.prototype.parse = function(data, parameters)
{
var parameters = parameters || {};
var useWorker = parameters.useWorker || false;
var useBuffers = parameters.useBuffers || false;
var deferred = Q.defer();
var rootObject = new THREE.Object3D();//TODO: change storage of data : ie don't put everything under a single object
rootObject.name = "rootScene";
//TODO: use these steps:
/*
- generate three.buffergeometry from raw data's meshes list
- generate textures from raw data's textures list
- generate materials from raw data's materials list
- generate final assembly(ies)
*/
//useWorker = false;
var self = this;
var startTime = new Date();
var s = Date.now();
console.log("in amf parser");
function onDataLoaded( data )
{
if(data.constellations.length<1)
{
for(var i=0;i<data.objects.length;i++)
{
var modelData = data.objects[i];
var model = self.createModelBuffers( modelData );
rootObject.add( model );
}
}
else
{
//TODO:recurse through constellation
for(var i=0;i<data.constellations[0].children.length;i++)
{
var child = data.constellations[0].children[i];
var modelData = child.instance;
var model = self.createModelBuffers( modelData );
model.position.fromArray( child.pos );
model.rotation.set(child.rot[0],child.rot[1],child.rot[2]);
rootObject.add( model );
}
}
deferred.resolve( rootObject );
}
if ( useWorker ) {
var worker = new Worker( "./amf-worker.js" );
worker.onmessage = function( event ) {
if("data" in event.data)
{
var data = event.data.data;
console.log("data recieved in main thread", data);
onDataLoaded( data );
deferred.resolve( rootObject );
}
else if("progress" in event.data)
{
console.log("got progress", event.data.progress);
deferred.notify( {"parsing":event.data.progress} )
}
}
console.log("sending data to worker");
worker.postMessage( {data:data});
Q.catch( deferred.promise, function(){
worker.terminate()
});
}
else
{
var amf = new AMF();
amf.load( data, onDataLoaded );
}
return deferred;
}
AMFParser.prototype.recurse = function(node, newParent, callback)
{
if(node.children)
{
var newModel = callback(node);
newParent.add( newModel);
for(var i=0;i<node.children.length;i++)
{
var child = node.children[i];
this.recurse( child, newModel, callback );
}
}
return newModel;
}
AMFParser.prototype.createModelBuffers = function ( modelData ) {
console.log("creating model buffers",modelData);
var faces = modelData.faceCount;
var colorSize =3;
var vertices = new Float32Array( faces * 3 * 3 );
var normals = new Float32Array( faces * 3 * 3 );
var colors = new Float32Array( faces *3 * colorSize );
var indices = new Uint32Array( faces * 3 );
vertices.set( modelData._attributes.position );
normals.set( modelData._attributes.normal );
indices.set( modelData._attributes.indices );
colors.set( modelData._attributes.vcolors );
var geometry = new THREE.BufferGeometry();
geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
//geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, colorSize ) );
if(this.recomputeNormals)
{
//TODO: only do this, if no normals were specified???
geometry.computeFaceNormals();
geometry.computeVertexNormals();
}
var vs = require('./vertShader.vert')();
var fs = require('./fragShader.frag')();
var material = new THREE.RawShaderMaterial( {
uniforms: {
time: { type: "f", value: 1.0 }
},
vertexShader: vs,
fragmentShader: fs,
side: THREE.DoubleSide,
transparent: true
} );
var color = this.defaultColor ;
var material = new this.defaultMaterialType({color:0XFFFFFF,vertexColors: THREE.VertexColors});
var mesh = new THREE.Mesh( geometry, material );
return mesh
}
AMFParser.prototype._generateObject = function( object )
{
if(this.recomputeNormals)
{
//TODO: only do this, if no normals were specified???
object.geometry.computeFaceNormals();
object.geometry.computeVertexNormals();
}
object.geometry.computeBoundingBox();
object.geometry.computeBoundingSphere();
var color = this.defaultColor ;
var meshMaterial = new this.defaultMaterialType(
{
color: color,
//vertexColors: THREE.VertexColors, //TODO: add flags to dertermine if we need vertex or face colors
vertexColors: THREE.FaceColors,
specular: this.defaultSpecular,
shininess: this.defaultShininess,
shading: this.defaultShading
} );
object.material = meshMaterial;
//console.log("finished Object / THREE.Mesh",currentObject)
}
AMFParser.prototype._applyMaterials = function(materials, textures, meshes, facesThatNeedMaterial)
{//since materials are usually defined after objects/ volumes, we need to apply
//materials to those that need them
for(var i = 0 ; i<facesThatNeedMaterial.length; i++)
{
var curFace = facesThatNeedMaterial[i];
var mat = materials[curFace.matId];
curFace.item.color = mat.color;
curFace.item.vertexColors = [];
//console.log("curFace",curFace.item);
}
/*
if(Object.keys(this.textures).length>0)
{
var materialArray = [];
for (var textureIndex in textures)
{
var texture = this.textures[textureIndex];
materialArray.push(new THREE.MeshBasicMaterial({
map: texture,
color: color,
vertexColors: THREE.VertexColors
}));
}
currentMaterial = new THREE.MeshFaceMaterial(materialArray);
}*/
}
if (detectEnv.isModule) module.exports = AMFParser;