]> git.scottworley.com Git - nt3d/blob - nt3d.js
0443913962128ee0a511cb805d9ac404d24a509b
[nt3d] / nt3d.js
1 /* nt3d - Javascript library for doing some 3D stuff.
2 * Copyright (C) 2012 Scott Worley <ScottWorley@ScottWorley.com>
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 nt3d = {
19 triangle: function(a, b, c) {
20 return [a, b, c];
21 },
22 quad: function(a, b, c, d) {
23 return this.triangle(a, b, c).concat(
24 this.triangle(c, d, a));
25 },
26 trianglefan: function(fan) {
27 var result = [];
28 for (var i = 2; i < fan.length; i++) {
29 result.push(fan[0], fan[i-1], fan[i]);
30 }
31 return result;
32 },
33 closed_trianglefan: function(fan) {
34 return this.trianglefan(fan.concat([fan[1]]));
35 },
36 quadstrip: function(strip) {
37 if (strip.length % 2 != 0) {
38 alert("quadstrip length not divisble by 2!");
39 }
40 var result = [];
41 for (var i = 2; i < strip.length; i += 2) {
42 result = result.concat(this.quad(strip[i-2], strip[i-1], strip[i+1], strip[i]));
43 }
44 return result;
45 },
46 closed_quadstrip: function(strip) {
47 return this.quadstrip(strip.concat([strip[0], strip[1]]));
48 },
49 circle: function(r, n) {
50 var points = [];
51 for (var i = 0; i < n; i++) {
52 points.push([r*Math.cos(2*Math.PI*i/n),
53 r*Math.sin(2*Math.PI*i/n),
54 0]);
55 }
56 return points;
57 },
58 cone: function(base_center, apex, radius, steps) {
59 var base = this.circle(radius, steps);
60 base = this.rotate_onto(base, [0,0,1], this.sub(apex, base_center));
61 base = this.translate(base, base_center);
62 return this.closed_trianglefan([apex].concat(base)).concat(
63 this.trianglefan(base.reverse()));
64 },
65 extrude: function(shape, path, shapenormals, pathnormals) {
66 var guts_result = nt3d._extrude_guts(shape, path, shapenormals, pathnormals);
67 // Add the end-caps
68 // XXX: This doesn't work if shape is not convex
69 return guts_result.points.concat(
70 nt3d.trianglefan(guts_result.first_loop.reverse()),
71 nt3d.trianglefan(guts_result.last_loop));
72
73 },
74 closed_extrude: function(shape, path, shapenormals, pathnormals) {
75 var guts_result = nt3d._extrude_guts(shape, path, shapenormals, pathnormals);
76 // Stitch the ends together
77 return guts_result.points.concat(
78 nt3d.closed_quadstrip(nt3d.zip(guts_result.first_loop, guts_result.last_loop)));
79 },
80 _fix_pathnormals: function(shapenormals, pathnormals) {
81 // Fix pathnormals[i] to be perfectly perpendicular to
82 // shapenormals[i]. This lets extrude callers be sloppy
83 // with pathnormals, which can greatly simplify things.
84 var fixedpathnormals = [];
85 for (var i = 0; i < pathnormals.length; i++) {
86 var proj = this.project(shapenormals[i], pathnormals[i]);
87 fixedpathnormals[i] = this.sub(pathnormals[i], proj);
88 }
89 return fixedpathnormals;
90 },
91 _extrude_guts: function(shape, path, shapenormals, pathnormals) {
92 var fixedpathnormals = this._fix_pathnormals(shapenormals, pathnormals);
93 var result = { points: [] };
94 var prev_loop;
95 for (var i = 0; i < path.length; i++) {
96 // loop is shape in 3d with (0,0) at path[i], shape's
97 // z axis in the direction of shapenormals[i], and
98 // shape's x axis in the direction of pathnormals[i].
99 // We tack [1,0,0] onto the end as a hack to see where
100 // it ends up after rotation. This is removed later.
101 var loop = shape.concat([[1,0,0]]);
102
103 // This is done in three steps:
104 // 1. Rotate shape out of the xy plane so that [0,0,1]
105 // becomes shapenormals[i]. This puts the shape in
106 // the correct plane, but does not constrain its
107 // rotation about shapenormals[i].
108 loop = this.rotate_onto(loop, [0,0,1], shapenormals[i]);
109 var shapex = loop.pop();
110
111 // 2. Rotate around shapenormals[i] so that [1,0,0]
112 // becomes fixedpathnormals[i].
113 loop = this.rotate_onto(loop, shapex, fixedpathnormals[i]);
114
115 // (This would probably be faster and more numerically stable
116 // if the two rotations were applied as one combined operation
117 // rather than separate steps.)
118
119 // 3. Translate to path[i].
120 loop = this.translate(loop, path[i]);
121
122 if (i == 0) {
123 result.first_loop = loop;
124 } else {
125 result.points = result.points.concat(nt3d.closed_quadstrip(nt3d.zip(loop, prev_loop)));
126 }
127 prev_loop = loop;
128 }
129 result.last_loop = prev_loop;
130 return result;
131 },
132 zip: function(a, b) {
133 var result = [];
134 if (a.length != b.length) {
135 alert("Zip over different-sized inputs");
136 }
137 for (var i = 0; i < a.length; i++) {
138 result.push(a[i], b[i]);
139 }
140 return result;
141 },
142 magnitude: function(a) {
143 return Math.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]);
144 },
145 unit: function(a) {
146 return this.scale(a, 1 / this.magnitude(a));
147 },
148 sub: function(a, b) {
149 return [a[0] - b[0],
150 a[1] - b[1],
151 a[2] - b[2]];
152 },
153 neg: function(a) {
154 return [-a[0], -a[1], -a[2]];
155 },
156 dot: function(a, b) {
157 return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
158 },
159 scale: function(v, s) { // Scale vector v by scalar s
160 return [s*v[0], s*v[1], s*v[2]];
161 },
162 cross: function(a, b) {
163 return [a[1]*b[2] - a[2]*b[1],
164 a[2]*b[0] - a[0]*b[2],
165 a[0]*b[1] - a[1]*b[0]];
166 },
167 normal: function(a, b, c) {
168 return this.cross(this.sub(a, b), this.sub(b, c));
169 },
170 project: function(a, b) { // Project b onto a
171 var a_magnitude = this.magnitude(a);
172 return this.scale(a, this.dot(a, b) / a_magnitude * a_magnitude);
173 },
174 translate: function(points, offset) {
175 var translated = [];
176 for (var i = 0; i < points.length; i++) {
177 translated[i] = [points[i][0] + offset[0],
178 points[i][1] + offset[1],
179 points[i][2] + offset[2]];
180 }
181 return translated;
182 },
183 angle_between: function(a, b) { // a and b must be unit vectors
184 return Math.acos(this.dot(a, b));
185 },
186 rotate_about_origin: function(points, axis, angle) { // axis must be a unit vector
187 // From http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/
188 var cosangle = Math.cos(angle);
189 var sinangle = Math.sin(angle);
190 var rotated = [];
191 for (var i = 0; i < points.length; i++) {
192 var p = points[i];
193 var tmp = this.dot(p, axis) * (1 - cosangle);
194 rotated[i] = [
195 axis[0]*tmp + p[0]*cosangle + (-axis[2]*p[1] + axis[1]*p[2])*sinangle,
196 axis[1]*tmp + p[1]*cosangle + ( axis[2]*p[0] - axis[0]*p[2])*sinangle,
197 axis[2]*tmp + p[2]*cosangle + (-axis[1]*p[0] + axis[0]*p[1])*sinangle];
198 }
199 return rotated;
200 },
201 rotate_onto: function(points, a, b) {
202 // Rotate points such that a (in points-space) maps onto b
203 // by crossing a and b to get a rotation axis and using
204 // angle_between to get a rotation angle.
205 var angle = this.angle_between(this.unit(a), this.unit(b));
206 if (Math.abs(angle) < 1e-15) {
207 // No siginificant rotation to perform. Bail to avoid
208 // NaNs and numerical error
209 return points;
210 }
211 var axis = this.unit(this.cross(a, b));
212 return this.rotate_about_origin(points, axis, angle);
213 },
214 rotate: function(points, center, axis, angle) { // axis must be a unit vector
215 return this.translate(
216 this.rotate_about_origin(
217 this.translate(points, this.neg(center)),
218 axis,
219 angle),
220 center);
221 },
222 go: function() {
223 // Remove any previous download links
224 var old_download_link = document.getElementById("nt3d_download");
225 if (old_download_link) {
226 old_download_link.parentNode.removeChild(old_download_link);
227 }
228
229 // Continue in a callback, so that there's not a stale download
230 // link hanging around while we process.
231 setTimeout(function(the_this) { (function() {
232
233 // Get params from form
234 var params = [];
235 for (var i = 0; i < this.user_params.length; i++) {
236 var as_string = this.form.elements["param"+i].value;
237 var as_num = +as_string;
238 params[i] = isNaN(as_num) ? as_string : as_num;
239 }
240
241 // Run user_function
242 this.points = this.user_function.apply(null, params);
243 if (this.points.length % 3 != 0) {
244 alert("Points list length not divisble by 3!");
245 }
246 var n = this.points.length / 3;
247
248 // Make STL
249 this.stl = "solid " + this.user_function.name + "\n";
250 for (var i = 0; i < n; i++) {
251 var a = this.points[i*3+0];
252 var b = this.points[i*3+1];
253 var c = this.points[i*3+2];
254 var normal = this.normal(a, b, c);
255 this.stl += "facet normal " + normal[0] + " " + normal[1] + " " + normal[2] + "\n" +
256 "outer loop\n" +
257 "vertex " + a[0] + " " + a[1] + " " + a[2] + "\n"+
258 "vertex " + b[0] + " " + b[1] + " " + b[2] + "\n"+
259 "vertex " + c[0] + " " + c[1] + " " + c[2] + "\n"+
260 "endloop\n" +
261 "endfacet\n";
262 }
263 this.stl += "endsolid " + this.user_function.name + "\n";
264
265
266 // Offer result as download
267 var download_link = document.createElement("a");
268 download_link.appendChild(document.createTextNode("Download!"));
269 download_link.setAttribute("id", "nt3d_download");
270 download_link.setAttribute("style", "background-color: blue");
271 download_link.setAttribute("download", this.user_function.name + ".stl");
272 download_link.setAttribute("href", "data:application/sla," + encodeURIComponent(this.stl));
273 this.ui.appendChild(download_link);
274 setTimeout(function() { download_link.setAttribute("style", "-webkit-transition: background-color 0.4s; -moz-transition: background-color 0.4s; -o-transition: background-color 0.4s; -ms-transition: background-color 0.4s; transition: background-color 0.4s; background-color: inherit"); }, 0);
275
276 }).call(the_this); }, 0, this); // (We were in a callback this whole time, remember?)
277 },
278 framework: function (f, params) {
279 this.user_function = f;
280 this.user_params = params;
281
282 // Make the UI
283 this.ui = document.getElementById("nt3dui");
284 if (!this.ui) {
285 this.ui = document.createElement("div");
286 this.ui.setAttribute("id", "nt3dui");
287 document.body.appendChild(this.ui);
288 }
289 this.form = document.createElement("form");
290 this.form.setAttribute("onsubmit", "nt3d.go(); return false");
291 this.ui.appendChild(this.form);
292 var table = document.createElement("table");
293 this.form.appendChild(table);
294 var tr = document.createElement("tr");
295 table.appendChild(tr);
296 var th = document.createElement("th");
297 th.appendChild(document.createTextNode("Variable"));
298 tr.appendChild(th);
299 th = document.createElement("th");
300 th.appendChild(document.createTextNode("Value"));
301 tr.appendChild(th);
302 for (var i = 0; i < params.length; i++) {
303 tr = document.createElement("tr");
304 table.appendChild(tr);
305 var td = document.createElement("td");
306 td.appendChild(document.createTextNode(params[i][0]));
307 tr.appendChild(td);
308 td = document.createElement("td");
309 var input = document.createElement("input");
310 input.setAttribute("name", "param" + i);
311 input.setAttribute("value", params[i][1]);
312 td.appendChild(input);
313 tr.appendChild(td);
314 }
315 var go = document.createElement("input");
316 go.setAttribute("type", "button");
317 go.setAttribute("value", "Go!");
318 go.setAttribute("onclick", "nt3d.go()");
319 this.form.appendChild(go);
320 }
321 };