STL TO OpenSCAD converter
Convert STL files to open SCAD, read more about it here:
http://www.thingiverse.com/thing:62666
HTML
<script src="https://raw.github.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
<script src="http://blog.vjeux.com/wp-content/uploads/2010/01/binaryReader.js"></script>
<div>Convert STL files to open SCAD, read more about it here: <a href='http://www.thingiverse.com/thing:62666' target=_new>Thingiverse: STL to OpenSCAD converter</a>
</div>
<br/>
<div>
<span id="error"></span>
</div>
<input type="file" id="files" name="file" />
<div/>
<button onclick="abortRead();">Cancel read</button>
<div/>
<div id="progress_bar">
<div class="percent">0%</div>
</div>
<div><span id="conversion"></span>
</div>
<div>
<span id="result"></span>
</div>
<a href="#">Download!</a>
CSS
body {
font-family: Helvetica, Verdana
}
p {
padding: 7px 10px;
}
#error {
color: red;
}
#progress_bar {
margin: 10px 0;
padding: 3px;
border: 1px solid #000;
font-size: 14px;
clear: both;
opacity: 0;
-moz-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-webkit-transition: opacity 1s linear;
}
#progress_bar.loading {
opacity: 1.0;
}
#progress_bar .percent {
background-color: #99ccff;
height: auto;
width: 0;
}
JavaScript
//STL to OpenSCAD converter
//This code will read an STL file and Generate an OpenSCAD file based on the content
//it supports both ASCII and Binary STL files.
var reader;
var progress = document.querySelector('.percent');
var vertices = [];
var triangles = [];
var modules = '';
var calls = '';
var vertexIndex = 0;
var converted = 0;
var totalObjects = 0;
var convertedObjects = 0;
function _reset() {
vertices = [];
triangles = [];
modules = '';
calls = '';
vertexIndex = 0;
converted = 0;
totalObjects = 0;
document.getElementById('error').innerText = '';
document.getElementById('conversion').innerText = '';
}
//stl: the stl file context as a string
//parseResult: This function checks if the file is ASCII or Binary, and parses the file accordingly
function parseResult(stl) {
_reset();
var isAscii = true;
for (var i = 0; i < stl.length; i++) {
if (stl[i].charCodeAt(0) == 0) {
isAscii = false;
break;
}
}
if (!isAscii) {
parseBinaryResult(stl);
} else {
parseAsciiResult(stl);
}
}
function parseBinaryResult(stl) {
//This makes more sense if you read http://en.wikipedia.org/wiki/STL_(file_format)#Binary_STL
var br = new BinaryReader(stl);
br.seek(80); //Skip header
var totalTriangles = br.readUInt32(); //Read # triangles
for (var tr = 0; tr < totalTriangles; tr++) {
try {
document.getElementById('conversion').innerText = 'In Progress - Converted ' + (++converted) + ' out of ' + totalTriangles + ' triangles!';
/*
REAL32[3] – Normal vector
REAL32[3] – Vertex 1
REAL32[3] – Vertex 2
REAL32[3] – Vertex 3
UINT16 – Attribute byte count*/
//Skip Normal Vector;
br.readFloat();
br.readFloat();
br.readFloat(); //SKIP NORMAL
//Parse every 3 subsequent floats as a vertex
...