forked from Scthe/nanite-webgpu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.deno.ts
228 lines (191 loc) · 6.45 KB
/
index.deno.ts
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
import { getRowPadding, createCapture } from 'std/webgpu';
import { parseArgs } from 'jsr:@std/cli/parse-args';
import { Dimensions, replaceFileExt } from './utils/index.ts';
import { Renderer } from './renderer.ts';
import { SCENES, SceneName, isValidSceneName } from './scene/sceneFiles.ts';
import { createGpuDevice, ensureIntegerDimensions } from './utils/webgpu.ts';
import { OnObjectLoadedCb, loadScene } from './scene/load/loadScene.ts';
import { createErrorSystem } from './utils/errors.ts';
import {
injectMeshoptimizerWASM,
injectMetisWASM,
} from './sys_deno/testUtils.ts';
import { writePngFromGPUBuffer } from './sys_deno/fakeCanvas.ts';
import { CONFIG, MODELS_DIR } from './constants.ts';
import {
textFileReader_Deno,
createTextureFromFile_Deno,
binaryFileReader_Deno,
} from './sys_deno/loadersDeno.ts';
import { ObjectLoadingProgressCb } from './scene/load/types.ts';
import { Scene } from './scene/scene.ts';
import { exportToFile } from './scene/import-export/import-export.ts';
const SCENE_FILE: SceneName = 'jinxCombined';
// const SCENE_FILE: SceneName = 'manyObjects2';
// const SCENE_FILE: SceneName = 'bunnySingle';
injectMeshoptimizerWASM();
injectMetisWASM();
CONFIG.loaders.textFileReader = textFileReader_Deno;
CONFIG.loaders.binaryFileReader = binaryFileReader_Deno;
CONFIG.loaders.createTextureFromFile = createTextureFromFile_Deno;
CONFIG.colors.gamma = 1.0; // I assume the png library does it for us?
const cliArgs = parseArgs(Deno.args, {
boolean: ['export'],
});
// console.log(cliArgs);
const actSceneName = parseSceneName(cliArgs);
// GPUDevice
const device = (await createGpuDevice())!;
if (!device) Deno.exit(1);
const errorSystem = createErrorSystem(device);
errorSystem.startErrorScope('init');
if (cliArgs.export) {
await exportScene(device);
} else {
const scene = await loadSceneFile(device, actSceneName);
renderSceneToFile(device, scene, './output.png');
}
async function renderSceneToFile(
device: GPUDevice,
scene: Scene,
outputPath: string
) {
const VIEWPORT_SIZE: Dimensions = {
width: 1270,
height: 720,
};
const PREFERRED_CANVAS_FORMAT = 'rgba8unorm-srgb';
// create canvas
console.log('Creating output canvas..');
const canvasDimensions = ensureIntegerDimensions(VIEWPORT_SIZE);
const { texture: windowTexture, outputBuffer } = createCapture(
device,
canvasDimensions.width,
canvasDimensions.height
);
const windowTextureView = windowTexture.createView();
// renderer setup
// const profiler = new GpuProfiler(device);
console.log('Creating renderer..');
const renderer = new Renderer(
device,
VIEWPORT_SIZE,
PREFERRED_CANVAS_FORMAT,
undefined //profiler
);
// init ended, report errors
console.log('Checking async WebGPU errors after init()..');
const lastError = await errorSystem.reportErrorScopeAsync();
if (lastError) {
console.error(lastError);
Deno.exit(1);
}
console.log('Init OK!');
const mainCmdBufDesc: GPUCommandEncoderDescriptor = {
label: 'main-frame-cmd-buffer',
};
// START: Render frame
console.log('Frame start!');
errorSystem.startErrorScope('frame');
// profiler.beginFrame();
// const deltaTime = STATS.deltaTimeMS * MILISECONDS_TO_SECONDS;
// const inputState = getInputState();
// renderer.updateCamera(deltaTime, inputState);
// record commands
const cmdBuf = device.createCommandEncoder(mainCmdBufDesc);
renderer.cmdRender(cmdBuf, scene, windowTextureView);
// result to buffer
cmdCopyTextureToBuffer(
cmdBuf,
windowTexture,
outputBuffer,
renderer.viewportSize
);
// submit commands
// profiler.endFrame(cmdBuf);
device.queue.submit([cmdBuf.finish()]);
console.log('Frame submitted, checking errors..');
// frame end
await errorSystem.reportErrorScopeAsync((lastError) => {
console.error(lastError);
throw new Error(lastError);
});
// write output
await writePngFromGPUBuffer(outputBuffer, renderer.viewportSize, outputPath);
}
async function exportScene(device: GPUDevice) {
CONFIG.isExporting = true;
const exportedFiles: string[] = [];
await loadSceneFile(device, actSceneName, async (obj) => {
const fileNameLC = obj.fileName.toLowerCase();
if (!fileNameLC.endsWith('.obj')) {
console.log(`Skipping export for '${obj.fileName}', it is not an .obj file`); // prettier-ignore
return;
}
console.log(`Exporting: '${obj.fileName}'`);
const fileNameNew = replaceFileExt(obj.fileName, '.json');
const exportedFilePath = `${MODELS_DIR}/${fileNameNew}`;
const exportedFilePathBin = replaceFileExt(exportedFilePath, '.bin');
await exportToFile(device, obj, exportedFilePath, exportedFilePathBin);
console.log(`Export success. Result file: '${exportedFilePath}'`);
exportedFiles.push(exportedFilePath, exportedFilePathBin);
});
await errorSystem.reportErrorScopeAsync((lastError) => {
console.error(lastError);
throw new Error(lastError);
});
console.log(`Success! Exported files:`, exportedFiles);
}
/////////////////////
/// UTILS
function cmdCopyTextureToBuffer(
cmdBuf: GPUCommandEncoder,
texture: GPUTexture,
outputBuffer: GPUBuffer,
dimensions: Dimensions
): void {
const { padded } = getRowPadding(dimensions.width);
cmdBuf.copyTextureToBuffer(
{ texture },
{
buffer: outputBuffer,
bytesPerRow: padded,
},
dimensions
);
}
function parseSceneName(cliArgs_: typeof cliArgs): SceneName {
let result: SceneName = SCENE_FILE;
const cliSceneName = cliArgs_._[0];
if (isValidSceneName(cliSceneName)) {
result = cliSceneName;
} else if (cliSceneName != undefined) {
const okNames = Object.keys(SCENES).join(',');
throw new Error(`Invalid scene name '${cliSceneName}', try one of: ${okNames}`); // prettier-ignore
}
return result;
}
function loadSceneFile(
device: GPUDevice,
sceneName: SceneName,
objectLoadedCb?: OnObjectLoadedCb
) {
console.log(`Loading scene '${sceneName}'..`);
const setReportText = (msg: string) => {
console.log(msg);
};
let lastReportedPercent = -1;
// deno-lint-ignore require-await
const progCb: ObjectLoadingProgressCb = async (objName, p): Promise<void> => {
if (typeof p === 'string') {
setReportText(p);
} else {
const percent = Math.floor(p * 100);
if (percent !== lastReportedPercent && percent % 10 === 0) {
lastReportedPercent = percent;
setReportText(`Loading '${objName}': ${percent}%`);
}
}
};
return loadScene(device, sceneName, progCb, objectLoadedCb);
}