Skip to content

Instantly share code, notes, and snippets.

@MatthewBarker
Created February 16, 2016 14:54
Show Gist options
  • Save MatthewBarker/8ccd0d716f2d9bfacd12 to your computer and use it in GitHub Desktop.
Save MatthewBarker/8ccd0d716f2d9bfacd12 to your computer and use it in GitHub Desktop.
Converts an SVG to an OBJ (only supports paths and hex colours in the fill attribute)
var fs = require('fs'),
glob = require('glob'),
hex2rgb = require('color-functions/lib/hex2rgb'),
os = require('os'),
svgMesh3d = require('svg-mesh-3d'),
xpath = require('xpath.js'),
DOMParser = require('xmldom').DOMParser;
function simplicialComplexToObj(mesh) {
var result = '';
mesh.positions.forEach(function (position) {
result += 'v ' + position.join(' ') + '\n';
});
mesh.cells.forEach(function (cell) {
cell = cell.map(function(index) { return index + 1; });
result += 'f ' + cell.join(' ') + '\n';
});
return result;
}
function convertFile (file, options) {
var text = fs.readFileSync(file, 'utf-8'),
svg = new DOMParser().parseFromString(text),
paths = xpath(svg, '//*[local-name() = \'path\']'),
objFile = file.replace('svg', 'obj'),
mtlFile = file.replace('svg', 'mtl'),
materials = [];
fs.writeFileSync(objFile, '# Created with SVG to OBJ' + os.EOL);
fs.appendFileSync(objFile, 'mtllib ' + mtlFile + os.EOL);
paths.forEach(function (path) {
var data = xpath(path, '@d'),
style = xpath(path, '@style'),
mesh = data.length ? svgMesh3d(data[0].value, options) : '',
obj = mesh ? simplicialComplexToObj(mesh) : '',
hex = '#fff';
if (style.length) {
var rules = style[0].value.split(';');
rules.forEach(function (rule){
var keyValue = rule.split(':');
if (keyValue[0] === 'fill' && keyValue[1].substring(0, 1) === '#') {
hex = keyValue[1].substring(1);
}
});
}
if (materials.indexOf(hex) === -1) {
materials.push(hex);
}
fs.appendFileSync(objFile, 'usemtl ' + hex + os.EOL);
fs.appendFileSync(objFile, obj + os.EOL);
});
fs.writeFileSync(mtlFile, '# Created with SVG to OBJ' + os.EOL);
materials.forEach(function (hex) {
var rgb = hex2rgb(hex),
r = (rgb.r / 255).toFixed(4),
g = (rgb.g / 255).toFixed(4),
b = (rgb.b / 255).toFixed(4);
fs.appendFileSync(mtlFile, 'newmtl ' + hex + os.EOL);
fs.appendFileSync(mtlFile, 'Ka ' + r + ' ' + g + ' ' + b + os.EOL);
fs.appendFileSync(mtlFile, 'Kd ' + r + ' ' + g + ' ' + b + os.EOL);
fs.appendFileSync(mtlFile, 'illum 1' + os.EOL);
});
}
function convertFiles (pattern, options) {
glob(pattern, function (error, files) {
if (error) {
throw error;
}
files.forEach(function (file) {
convertFile (file, options);
});
});
}
module.exports = {
convertFile: convertFile,
convertFiles: convertFiles
};
@ArnavVashisthCodingAccountnew

Great! Does it accept (or can it be customized to do so) URL(s)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment