-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3d.jsx
297 lines (249 loc) · 8.51 KB
/
3d.jsx
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
let objs = []
const loadManager = new THREE.LoadingManager()
const textureLoader = new THREE.TextureLoader(loadManager)
const mdConverter = new showdown.Converter()
mdConverter.setFlavor('github')
const config = {
// path: './photos_2',
meshScale: 10,
imageDepth: 2,
minTextWidth: 800,
minTextHeight: 80
}
// Util
const removeProperty = (obj, propertyName) => {
let { [propertyName]: _, ...result } = obj
return result
}
// Select only the 'body' of a node in directory-tree-formatted json
const nodeData = x => removeProperty({...x, name: x.path, id: x.path}, 'children')
const domElemFromText = (text, path, extension) => {
const root = document.createElement('div')
root.id = 'c-' + path
root.style.width = config.minTextWidth + 'px'
// root.style.height = config.minTextHeight + 'px'
switch (extension) {
case '.txt': {
const textElem = document.createElement('p')
textElem.innerText = text
root.appendChild(textElem)
break
}
case '.markdown':
case '.md': {
const textElem = document.createElement('div')
textElem.innerHTML = mdConverter.makeHtml(text)
// textElem.style.width = config.minTextWidth + 'px'
root.appendChild(textElem)
break
}
case '.cpp':
case '.c':
case '.h': {
const textElem = document.createElement('div')
textElem.innerHTML = mdConverter.makeHtml('```c++\n' + text + '\n```')
// textElem.style.width = config.minTextWidth + 'px'
hljs.highlightBlock(textElem)
root.appendChild(textElem)
break
}
default:
console.error('Unknown plaintext extension: ', extension)
}
return root
}
const torusMaterial =
new THREE.MeshLambertMaterial({
color: Math.round(Math.random() * Math.pow(2, 24)),
transparent: true,
opacity: 0.75
})
const twoFaceBoxFaceMaterials = [
// The two primary faces will be inserted later.
/*
new THREE.MeshBasicMaterial({ // Front face
color: 0xff0000,
}),
new THREE.MeshBasicMaterial({ // Back face
color: 0x00ff00,
}),
*/
new THREE.MeshBasicMaterial({
color: 0x0000ff,
}),
new THREE.MeshBasicMaterial({
color: 0x0000ff,
}),
new THREE.MeshBasicMaterial({
color: 0x0000ff,
}),
new THREE.MeshBasicMaterial({
color: 0x0000ff,
})
]
const numericCSS = (numStr) => {
return parseInt(numStr.slice(0,-2))
}
const fetchText = async (path) => {
try {
const res = await fetch(path)
const mime = res.headers.get('Content-Type')
console.log(mime)
switch (mime) {
case 'text/plain':
break
}
return await res.text()
} catch (e) {
console.error(e)
}
}
/* Build Nodes & Links for ForceGraphVR, loading files & creating textures as we go */
const buildGraphData = async (dir) => {
/* DFS: immediately visit each leaf, so we can begin loading it as a texture */
let q = [dir] // stack, initialized with root dir
let nodes = [] // {path, name: path, size, type, id: path, (type: 'file' ? extension: String), (extension: 'jpg'|'png' ? tex: Object)}
let links = [] // {source: id1, target: id2}
while (q.length != 0) {
const o = q.pop()
// Skip dotfiles
// -- If this line is uncommented, models all stack :(
// if (o.path.split('/').slice(-1)[0][0] === '.') break
// Now, Capture the file or directory as a node
nodes = [...nodes, nodeData(o)]
let n = nodeData(o)
switch (o.type) {
case 'file': { // Leaves! Note: Links are created by parents.
console.log(o.path)
const res = await fetch(o.path)
const mime = res.headers.get('Content-Type')
// console.log(mime.split('/'))
const mime0 = mime.split(';')[0]
switch (mime0) { // ;charset=utf-8
case 'text/plain':
case 'text/markdown':
case 'text/x-c':
case 'text/html':
const txt = await res.text()
console.info('txt:', txt)
const elem = domElemFromText(txt, o.path, o.extension)
console.info(elem)
document.body.appendChild(elem)
html2canvas(elem).then(canvas => {
if (canvas.height == 0) {
console.log(canvas.id)
canvas.height = 2
canvas.style.width = 2 // canvas.height
}
document.body.appendChild(canvas) // TODO hide?
console.info(canvas)
const mesh = new THREE.BoxGeometry(config.imageDepth, numericCSS(canvas.style.height), numericCSS(canvas.style.width))
const mat = new THREE.MeshBasicMaterial()
mat.map = new THREE.CanvasTexture(canvas) // TODO Add option for CSS3DObjects as a text renderer instead
const meshMat = [mat, mat, ...twoFaceBoxFaceMaterials]
objs[n.id] = new THREE.Mesh(mesh, meshMat)
})
break
case 'image/png':
case 'image/jpg':
case 'image/jpeg': {
const onImgLoad = tex => {
// console.info(tex)
// Prevent stretching texture to nearest 2^n
// apparently, this fixes itself with WebGL2 (just omit & it doesn't resize)
tex.minFilter = THREE.LinearFilter
n = {...n, tex}
// console.info(n)
const meshWidth = tex.image.width / config.meshScale
const meshHeight = tex.image.height / config.meshScale
// Create mesh
const mesh = new THREE.BoxGeometry(config.imageDepth, meshHeight, meshWidth)
const mat = new THREE.MeshBasicMaterial({ map: n.tex })
const meshMat = [mat, mat, ...twoFaceBoxFaceMaterials]
objs[n.id] = new THREE.Mesh(mesh, meshMat)
}
const onImgError = err => {
console.error(err)
}
textureLoader.load(o.path, onImgLoad, undefined, onImgError)
break
}
default:
console.error('Unknown mime type:', mime, o.path)
//const mesh = new THREE.TorusKnotGeometry(2, 1)
//objs[n.id] = new THREE.Mesh(mesh, torusMaterial)
}
break
}
case 'directory': {
for (const c of o.children) { // Add all children for next iteration
// Create link
links = [...links, { source: nodeData(o).id, target: nodeData(c).id }]
q.push(c)
}
const mesh = new THREE.TorusKnotGeometry(6, 1)
objs[n.id] = new THREE.Mesh(mesh, torusMaterial)
break
}
}
}
return { nodes, links }
}
/*
TODO
npm scripts should enable:
- git clone to a temp dir
- run directory-tree against temp dir
- pipe output to webapp input for rendering
- git cleanup?
usage:
- `npm run clone-and-start gh-username/repo-name`
- `npm run start [dir-root-path]`
*/
// Note: Pain Point: `directory-tree` doesn't work in a web browser context, even with Browserify.
// Instead, local files can be configured via the npm scripts.
// (Otherwise, we would just be able to: `import dirTree from 'directory-tree'`)
const readDirectoryTree = async (path) => {
// Check expected location of npm script `list-directory` output
// Default: `scripts/output/currentDirectoryTree.txt`
const res = await fetch(path)
return await res.json()
}
const load = async () => {
// Read in the directory listing.
const tree = await readDirectoryTree('scripts/output/currentDirectoryTree.txt') // TODO vary based on config.path
console.info('Directory Tree:\n', tree)
const loadingElem = document.querySelector('#loading')
const progressBarElem = loadingElem.querySelector('.progressbar')
// Overall steps:
// 1. for filetypes of interest (images), load as texture asynchronously
// 2. capture width, height info
// 3. build mesh from texture dimensions
// 4. otherwise, build default mesh for filetype/dir
const graphData = await buildGraphData(tree)
//console.log('graphData:', graphData)
const threeObj = (n) => objs[n.path]
/* Load textures */
loadManager.onLoad = () => {
console.log('Textures loaded.')
loadingElem.style.display = 'none'
ReactDOM.render(
<ForceGraphVR
graphData={graphData}
nodeThreeObject={threeObj}
/>,
document.getElementById('graph')
)
}
loadManager.onProgress = (urlOfLastItemLoaded, itemsLoaded, itemsTotal) => {
console.info('Texture loaded: ', urlOfLastItemLoaded)
const progress = itemsLoaded / itemsTotal
progressBarElem.style.transform = `scaleX(${progress})`
}
}
//setTimeout(() => {
(async () => {
const ok = await load()
//console.info(ok)
})()
//}, 500)