/
watch-blender-file.js
65 lines (56 loc) · 2.1 KB
/
watch-blender-file.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
var chokidar = require('chokidar')
var cp = require('child_process')
var cuid = require('cuid')
var fs = require('fs')
// Keep track of connected clients so that we can send the vertex data to every connected browser tab
var connectedClients = {}
// Watch our blend file for changes
chokidar.watch('./*.blend', {})
.on('change', function (blenderFilePath) {
var modelName = blenderFilePath.split('.blend')[0]
var wavefrontPath = modelName + '.obj'
var jsonPath = modelName + '.json'
// Use the blender CLI to export our .blend model as OBJ
cp.exec(
// Make sure that `blender` is in your PATH.
// On mac you can try adding the following to your ~/.bash_profile:
// # Blender CLI
// export PATH="$PATH:/Applications/blender.app/Contents/MacOS"
`blender ${blenderFilePath} --background --python blender-to-obj.py -- ${wavefrontPath}`,
function (err, stdout, stderr) {
if (err) {
return console.error(`exec error: ${err}`)
}
// Write to stdout just for some quick debugging of our experiment
console.log(`stdout: ${stdout}`)
// Convert OBJ file into JSON using wavefront-obj-parser
cp.exec(
`cat ${wavefrontPath} | node ./node_modules/wavefront-obj-parser/bin/obj2json.js > ${jsonPath}`,
function (err, stdout, stderr) {
if (err) { throw err }
// Send JSON file to connected clients
fs.readFile(jsonPath, function (err, jsonModelFile) {
if (err) { throw err }
for (var clientId in connectedClients) {
if (connectedClients[clientId].readyState === WebSocket.OPEN) {
connectedClients[clientId].send(
jsonModelFile.toString()
)
}
}
})
}
)
}
)
})
var WebSocket = require('ws')
var wsServer = new WebSocket.Server({port: 8989})
// Start WebSocket server and keep track of currently connected clients
wsServer.on('connection', function (ws) {
ws.clientId = cuid()
connectedClients[ws.clientId] = ws
ws.on('close', function () {
delete connectedClients[ws.clientId]
})
})