]> git.scottworley.com Git - nt3d/blame - nt3d.js
Use "this" instead of the global name
[nt3d] / nt3d.js
CommitLineData
d82d3571
SW
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
18nt3d = {
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 },
0ab5ca18
SW
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 },
a9f371ff 33 closed_trianglefan: function(fan) {
70650839 34 return this.trianglefan(fan.concat([fan[1]]));
a9f371ff 35 },
4e2bdb62
SW
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) {
70650839 42 result = result.concat(this.quad(strip[i-2], strip[i-1], strip[i+1], strip[i]));
4e2bdb62
SW
43 }
44 return result;
45 },
46 closed_quadstrip: function(strip) {
70650839 47 return this.quadstrip(strip.concat([strip[0], strip[1]]));
4e2bdb62 48 },
fc382d22
SW
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 },
1a18e646
SW
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 },
2d38f724
SW
65 shapenormals_from_closed_path: function(path) {
66 return function(i) {
67 var prev = (i == 0) ? path.length-1 : i-1;
68 var next = (i == path.length-1) ? 0 : i+1;
69 return nt3d.sub(path[next], path[prev]);
70 };
71 },
72 shapenormals_from_path_and_extra_points: function(path, first_point, last_point) {
73 return function(i) {
74 var prev = (i == 0) ? first_point : path[i-1];
75 var next = (i == path.length-1) ? last_point : path[i+1];
76 return nt3d.sub(next, prev);
77 };
78 },
79 shapenormals_from_path_and_first_and_last_normals: function(path, first_normal, last_normal) {
80 return function(i) {
81 if (i == 0) { return first_normal; }
82 if (i == path.length-1) { return last_normal; }
83 return nt3d.sub(path[i+1], path[i-1]);
84 };
85 },
08c25ec8
SW
86 to_function: function(thing, make_indexer) {
87 // If thing is a point, just yield thing every time.
88 // If thing is a list of points && make_indexer, index into thing.
89 // If thing is already a function, just return it.
90 if (({}).toString.call(thing) === "[object Function]") {
91 return thing; // Already a function
92 }
93 if (make_indexer && Array.isArray(thing[0])) {
94 // Looks like a list of points.
95 return function(i) { return thing[i]; }
96 }
97 return function() { return thing; }
98 },
0ee732b2
SW
99 extrude: function(path, shape, shapenormals, pathnormals) {
100
2f26ede4 101 var guts_result = this._extrude_guts(path, shape, shapenormals, pathnormals);
94faa4e5
SW
102 // Add the end-caps
103 // XXX: This doesn't work if shape is not convex
104 return guts_result.points.concat(
2f26ede4
SW
105 this.trianglefan(guts_result.first_loop.reverse()),
106 this.trianglefan(guts_result.last_loop));
94faa4e5
SW
107
108 },
0ee732b2 109 closed_extrude: function(path, shape, shapenormals, pathnormals) {
2f26ede4 110 var guts_result = this._extrude_guts(path, shape, shapenormals, pathnormals);
94faa4e5
SW
111 // Stitch the ends together
112 return guts_result.points.concat(
2f26ede4 113 this.closed_quadstrip(this.zip(guts_result.first_loop, guts_result.last_loop)));
94faa4e5 114 },
0ee732b2 115 _extrude_guts: function(path, shape, shapenormals, pathnormals) {
08c25ec8
SW
116 var shape_fun = this.to_function(shape, false);
117 var shapenormal_fun = this.to_function(shapenormals, true);
118 var pathnormal_fun = this.to_function(pathnormals, true);
94faa4e5
SW
119 var result = { points: [] };
120 var prev_loop;
121 for (var i = 0; i < path.length; i++) {
08c25ec8
SW
122 var shapenormali = shapenormal_fun(i, path[i]);
123 var pathnormali = pathnormal_fun(i, path[i], shapenormali);
124
125 // Fix pathnormali to be perfectly perpendicular to
126 // shapenormali. pathnormali must be perpendicular to
127 // shapenormali or the second rotation will take loop
128 // back out of the shapenormali plane that the first
129 // rotation so carefully placed it in. But, letting
130 // callers be sloppy with the pathnormals can greatly
131 // simplify generating them -- so much so that you can
132 // often just pass a constant to use the same value
133 // along the whole path.
134 pathnormali = this.project_to_orthogonal(shapenormali, pathnormali);
135
136 var shapei = shape_fun(i, path[i], shapenormali, pathnormali);
137
138 // loop is shapei in 3d with (0,0) at path[i], shape's
139 // z axis in the direction of shapenormali, and shape's
140 // x axis in the direction of pathnormali. We tack
141 // [1,0,0] onto the end as a hack to see where it ends
142 // up after the first rotation. This is removed later.
143 var loop = shapei.concat([[1,0,0]]);
2f6b97f8 144
94faa4e5
SW
145 // This is done in three steps:
146 // 1. Rotate shape out of the xy plane so that [0,0,1]
08c25ec8 147 // becomes shapenormali. This puts the shape in
aceb2da8 148 // the correct plane, but does not constrain its
08c25ec8
SW
149 // rotation about shapenormali.
150 loop = this.rotate_onto(loop, [0,0,1], shapenormali);
aceb2da8 151 var shapex = loop.pop();
2f6b97f8 152
08c25ec8
SW
153 // 2. Rotate around shapenormali so that [1,0,0]
154 // becomes pathnormali.
155 loop = this.rotate_onto(loop, shapex, pathnormali);
aceb2da8
SW
156
157 // (This would probably be faster and more numerically stable
94faa4e5 158 // if the two rotations were applied as one combined operation
aceb2da8 159 // rather than separate steps.)
2f6b97f8
SW
160
161 // 3. Translate to path[i].
162 loop = this.translate(loop, path[i]);
163
94faa4e5
SW
164 if (i == 0) {
165 result.first_loop = loop;
166 } else {
2f26ede4 167 result.points = result.points.concat(this.closed_quadstrip(this.zip(loop, prev_loop)));
94faa4e5
SW
168 }
169 prev_loop = loop;
170 }
171 result.last_loop = prev_loop;
172 return result;
173 },
174 zip: function(a, b) {
175 var result = [];
176 if (a.length != b.length) {
177 alert("Zip over different-sized inputs");
178 }
179 for (var i = 0; i < a.length; i++) {
180 result.push(a[i], b[i]);
181 }
182 return result;
183 },
184 magnitude: function(a) {
185 return Math.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]);
186 },
187 unit: function(a) {
188 return this.scale(a, 1 / this.magnitude(a));
189 },
d82d3571
SW
190 sub: function(a, b) {
191 return [a[0] - b[0],
192 a[1] - b[1],
193 a[2] - b[2]];
194 },
1e62819c
SW
195 neg: function(a) {
196 return [-a[0], -a[1], -a[2]];
197 },
94faa4e5
SW
198 dot: function(a, b) {
199 return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
200 },
201 scale: function(v, s) { // Scale vector v by scalar s
202 return [s*v[0], s*v[1], s*v[2]];
203 },
d82d3571
SW
204 cross: function(a, b) {
205 return [a[1]*b[2] - a[2]*b[1],
206 a[2]*b[0] - a[0]*b[2],
207 a[0]*b[1] - a[1]*b[0]];
208 },
209 normal: function(a, b, c) {
210 return this.cross(this.sub(a, b), this.sub(b, c));
211 },
94faa4e5
SW
212 project: function(a, b) { // Project b onto a
213 var a_magnitude = this.magnitude(a);
214 return this.scale(a, this.dot(a, b) / a_magnitude * a_magnitude);
215 },
08c25ec8
SW
216 project_to_orthogonal: function(a, b) {
217 // The nearest thing to b that is orthogonal to a
218 return this.sub(b, this.project(a, b));
219 },
2f6b97f8
SW
220 translate: function(points, offset) {
221 var translated = [];
222 for (var i = 0; i < points.length; i++) {
223 translated[i] = [points[i][0] + offset[0],
224 points[i][1] + offset[1],
225 points[i][2] + offset[2]];
226 }
227 return translated;
94faa4e5
SW
228 },
229 angle_between: function(a, b) { // a and b must be unit vectors
230 return Math.acos(this.dot(a, b));
231 },
1e62819c 232 rotate_about_origin: function(points, axis, angle) { // axis must be a unit vector
94faa4e5
SW
233 // From http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/
234 var cosangle = Math.cos(angle);
235 var sinangle = Math.sin(angle);
2f6b97f8
SW
236 var rotated = [];
237 for (var i = 0; i < points.length; i++) {
238 var p = points[i];
239 var tmp = this.dot(p, axis) * (1 - cosangle);
240 rotated[i] = [
241 axis[0]*tmp + p[0]*cosangle + (-axis[2]*p[1] + axis[1]*p[2])*sinangle,
242 axis[1]*tmp + p[1]*cosangle + ( axis[2]*p[0] - axis[0]*p[2])*sinangle,
243 axis[2]*tmp + p[2]*cosangle + (-axis[1]*p[0] + axis[0]*p[1])*sinangle];
244 }
245 return rotated;
94faa4e5 246 },
aceb2da8
SW
247 rotate_onto: function(points, a, b) {
248 // Rotate points such that a (in points-space) maps onto b
249 // by crossing a and b to get a rotation axis and using
250 // angle_between to get a rotation angle.
251 var angle = this.angle_between(this.unit(a), this.unit(b));
252 if (Math.abs(angle) < 1e-15) {
253 // No siginificant rotation to perform. Bail to avoid
254 // NaNs and numerical error
255 return points;
256 }
257 var axis = this.unit(this.cross(a, b));
258 return this.rotate_about_origin(points, axis, angle);
259 },
1e62819c
SW
260 rotate: function(points, center, axis, angle) { // axis must be a unit vector
261 return this.translate(
262 this.rotate_about_origin(
263 this.translate(points, this.neg(center)),
264 axis,
265 angle),
266 center);
267 },
d82d3571 268 go: function() {
f72a4188
SW
269 // Remove any previous download links
270 var old_download_link = document.getElementById("nt3d_download");
271 if (old_download_link) {
272 old_download_link.parentNode.removeChild(old_download_link);
273 }
274
275 // Continue in a callback, so that there's not a stale download
276 // link hanging around while we process.
277 setTimeout(function(the_this) { (function() {
278
d82d3571
SW
279 // Get params from form
280 var params = [];
281 for (var i = 0; i < this.user_params.length; i++) {
ec5f883d
SW
282 var as_string = this.form.elements["param"+i].value;
283 var as_num = +as_string;
284 params[i] = isNaN(as_num) ? as_string : as_num;
d82d3571
SW
285 }
286
287 // Run user_function
288 this.points = this.user_function.apply(null, params);
289 if (this.points.length % 3 != 0) {
290 alert("Points list length not divisble by 3!");
291 }
292 var n = this.points.length / 3;
293
294 // Make STL
295 this.stl = "solid " + this.user_function.name + "\n";
296 for (var i = 0; i < n; i++) {
297 var a = this.points[i*3+0];
298 var b = this.points[i*3+1];
299 var c = this.points[i*3+2];
300 var normal = this.normal(a, b, c);
301 this.stl += "facet normal " + normal[0] + " " + normal[1] + " " + normal[2] + "\n" +
302 "outer loop\n" +
303 "vertex " + a[0] + " " + a[1] + " " + a[2] + "\n"+
304 "vertex " + b[0] + " " + b[1] + " " + b[2] + "\n"+
305 "vertex " + c[0] + " " + c[1] + " " + c[2] + "\n"+
306 "endloop\n" +
307 "endfacet\n";
308 }
309 this.stl += "endsolid " + this.user_function.name + "\n";
310
d82d3571
SW
311
312 // Offer result as download
313 var download_link = document.createElement("a");
314 download_link.appendChild(document.createTextNode("Download!"));
315 download_link.setAttribute("id", "nt3d_download");
4eea5cbf 316 download_link.setAttribute("style", "background-color: blue");
d82d3571
SW
317 download_link.setAttribute("download", this.user_function.name + ".stl");
318 download_link.setAttribute("href", "data:application/sla," + encodeURIComponent(this.stl));
319 this.ui.appendChild(download_link);
4eea5cbf 320 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);
f72a4188
SW
321
322 }).call(the_this); }, 0, this); // (We were in a callback this whole time, remember?)
d82d3571
SW
323 },
324 framework: function (f, params) {
325 this.user_function = f;
326 this.user_params = params;
327
328 // Make the UI
329 this.ui = document.getElementById("nt3dui");
330 if (!this.ui) {
331 this.ui = document.createElement("div");
332 this.ui.setAttribute("id", "nt3dui");
333 document.body.appendChild(this.ui);
334 }
335 this.form = document.createElement("form");
a26d0960 336 this.form.setAttribute("onsubmit", "nt3d.go(); return false");
d82d3571
SW
337 this.ui.appendChild(this.form);
338 var table = document.createElement("table");
339 this.form.appendChild(table);
340 var tr = document.createElement("tr");
341 table.appendChild(tr);
342 var th = document.createElement("th");
343 th.appendChild(document.createTextNode("Variable"));
344 tr.appendChild(th);
345 th = document.createElement("th");
346 th.appendChild(document.createTextNode("Value"));
347 tr.appendChild(th);
348 for (var i = 0; i < params.length; i++) {
349 tr = document.createElement("tr");
350 table.appendChild(tr);
351 var td = document.createElement("td");
352 td.appendChild(document.createTextNode(params[i][0]));
353 tr.appendChild(td);
354 td = document.createElement("td");
355 var input = document.createElement("input");
356 input.setAttribute("name", "param" + i);
357 input.setAttribute("value", params[i][1]);
358 td.appendChild(input);
359 tr.appendChild(td);
360 }
361 var go = document.createElement("input");
362 go.setAttribute("type", "button");
363 go.setAttribute("value", "Go!");
364 go.setAttribute("onclick", "nt3d.go()");
365 this.form.appendChild(go);
366 }
367};