This repository was archived by the owner on Nov 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathRayTracingRenderer.es5.js
3699 lines (3093 loc) · 165 KB
/
RayTracingRenderer.es5.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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three')) :
typeof define === 'function' && define.amd ? define(['exports', 'three'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RayTracingRenderer = {}, global.THREE));
}(this, (function (exports, THREE$1) { 'use strict';
var ThinMaterial = 1;
var ThickMaterial = 2;
var ShadowCatcherMaterial = 3;
var constants = /*#__PURE__*/Object.freeze({
__proto__: null,
ThinMaterial: ThinMaterial,
ThickMaterial: ThickMaterial,
ShadowCatcherMaterial: ShadowCatcherMaterial
});
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
var LensCamera = /*#__PURE__*/function (_PerspectiveCamera) {
_inherits(LensCamera, _PerspectiveCamera);
var _super = _createSuper(LensCamera);
function LensCamera() {
var _this;
_classCallCheck(this, LensCamera);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.aperture = 0.01;
return _this;
}
_createClass(LensCamera, [{
key: "copy",
value: function copy(source, recursive) {
_get(_getPrototypeOf(LensCamera.prototype), "copy", this).call(this, source, recursive);
this.aperture = source.aperture;
}
}]);
return LensCamera;
}(THREE$1.PerspectiveCamera);
var SoftDirectionalLight = /*#__PURE__*/function (_DirectionalLight) {
_inherits(SoftDirectionalLight, _DirectionalLight);
var _super = _createSuper(SoftDirectionalLight);
function SoftDirectionalLight(color, intensity) {
var _this;
var softness = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
_classCallCheck(this, SoftDirectionalLight);
_this = _super.call(this, color, intensity);
_this.softness = softness;
return _this;
}
_createClass(SoftDirectionalLight, [{
key: "copy",
value: function copy(source) {
_get(_getPrototypeOf(SoftDirectionalLight.prototype), "copy", this).call(this, source);
this.softness = source.softness;
}
}]);
return SoftDirectionalLight;
}(THREE$1.DirectionalLight);
var EnvironmentLight = /*#__PURE__*/function (_Light) {
_inherits(EnvironmentLight, _Light);
var _super = _createSuper(EnvironmentLight);
function EnvironmentLight(map) {
var _this;
_classCallCheck(this, EnvironmentLight);
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.map = map;
_this.isEnvironmentLight = true;
return _this;
}
_createClass(EnvironmentLight, [{
key: "copy",
value: function copy(source) {
_get(_getPrototypeOf(EnvironmentLight.prototype), "copy", this).call(this, source);
this.map = source.map;
}
}]);
return EnvironmentLight;
}(THREE$1.Light);
var RayTracingMaterial = /*#__PURE__*/function (_MeshStandardMaterial) {
_inherits(RayTracingMaterial, _MeshStandardMaterial);
var _super = _createSuper(RayTracingMaterial);
function RayTracingMaterial() {
var _this;
_classCallCheck(this, RayTracingMaterial);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.solid = false;
_this.shadowCatcher = false;
return _this;
}
_createClass(RayTracingMaterial, [{
key: "copy",
value: function copy(source) {
_get(_getPrototypeOf(RayTracingMaterial.prototype), "copy", this).call(this, source);
this.solid = source.solid;
this.shadowCatcher = source.shadowCatcher;
}
}]);
return RayTracingMaterial;
}(THREE$1.MeshStandardMaterial);
function loadExtensions(gl, extensions) {
var supported = {};
var _iterator = _createForOfIteratorHelper(extensions),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var name = _step.value;
supported[name] = gl.getExtension(name);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return supported;
}
function compileShader(gl, type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (success) {
return shader;
}
var output = source.split('\n').map(function (x, i) {
return "".concat(i + 1, ": ").concat(x);
}).join('\n');
console.log(output);
throw gl.getShaderInfoLog(shader);
}
function createProgram(gl, vertexShader, fragmentShader, transformVaryings, transformBufferMode) {
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
if (transformVaryings) {
gl.transformFeedbackVaryings(program, transformVaryings, transformBufferMode);
}
gl.linkProgram(program);
gl.detachShader(program, vertexShader);
gl.detachShader(program, fragmentShader);
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (success) {
return program;
}
throw gl.getProgramInfoLog(program);
}
function getUniforms(gl, program) {
var uniforms = {};
var count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
for (var i = 0; i < count; i++) {
var _gl$getActiveUniform = gl.getActiveUniform(program, i),
name = _gl$getActiveUniform.name,
type = _gl$getActiveUniform.type;
var location = gl.getUniformLocation(program, name);
if (location) {
uniforms[name] = {
type: type,
location: location
};
}
}
return uniforms;
}
function getAttributes(gl, program) {
var attributes = {};
var count = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (var i = 0; i < count; i++) {
var _gl$getActiveAttrib = gl.getActiveAttrib(program, i),
name = _gl$getActiveAttrib.name;
if (name) {
attributes[name] = gl.getAttribLocation(program, name);
}
}
return attributes;
}
function decomposeScene(scene) {
var meshes = [];
var directionalLights = [];
var ambientLights = [];
var environmentLights = [];
scene.traverse(function (child) {
if (child.isMesh) {
if (!child.geometry) {
console.warn(child, 'must have a geometry property');
} else if (!child.material.isMeshStandardMaterial) {
console.warn(child, 'must use MeshStandardMaterial in order to be rendered.');
} else {
meshes.push(child);
}
} else if (child.isDirectionalLight) {
directionalLights.push(child);
} else if (child.isAmbientLight) {
ambientLights.push(child);
} else if (child.isEnvironmentLight) {
if (environmentLights.length > 1) {
console.warn(environmentLights, 'only one environment light can be used per scene');
} // Valid lights have HDR texture map in RGBEEncoding
if (isHDRTexture(child)) {
environmentLights.push(child);
} else {
console.warn(child, 'environment light does not use color value or map with THREE.RGBEEncoding');
}
}
});
var background = scene.background;
return {
background: background,
meshes: meshes,
directionalLights: directionalLights,
ambientLights: ambientLights,
environmentLights: environmentLights
};
}
function isHDRTexture(texture) {
return texture.map && texture.map.image && (texture.map.encoding === THREE$1.RGBEEncoding || texture.map.encoding === THREE$1.LinearEncoding);
}
function makeFramebuffer(gl, _ref) {
var color = _ref.color,
depth = _ref.depth;
var framebuffer = gl.createFramebuffer();
function bind() {
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
}
function unbind() {
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
function init() {
bind();
var drawBuffers = [];
for (var location in color) {
location = Number(location);
if (location === undefined) {
console.error('invalid location');
}
var tex = color[location];
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + location, tex.target, tex.texture, 0);
drawBuffers.push(gl.COLOR_ATTACHMENT0 + location);
}
gl.drawBuffers(drawBuffers);
if (depth) {
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, depth.target, depth.texture);
}
unbind();
}
init();
return {
color: color,
bind: bind,
unbind: unbind
};
}
var vertex = {
source: "\n layout(location = 0) in vec2 a_position;\n\n out vec2 vCoord;\n\n void main() {\n vCoord = a_position;\n gl_Position = vec4(2. * a_position - 1., 0, 1);\n }\n"
};
var typeMap;
function makeUniformSetter(gl, program) {
var uniformInfo = getUniforms(gl, program);
var uniforms = {};
var needsUpload = [];
for (var name in uniformInfo) {
var _uniformInfo$name = uniformInfo[name],
type = _uniformInfo$name.type,
location = _uniformInfo$name.location;
var uniform = {
type: type,
location: location,
v0: 0,
v1: 0,
v2: 0,
v3: 0
};
uniforms[name] = uniform;
}
var failedUnis = new Set();
function setUniform(name, v0, v1, v2, v3) {
// v0 - v4 are the values to be passed to the uniform
// v0 can either be a number or an array, and v1-v3 are optional
var uni = uniforms[name];
if (!uni) {
if (!failedUnis.has(name)) {
console.warn("Uniform \"".concat(name, "\" does not exist in shader"));
failedUnis.add(name);
}
return;
}
uni.v0 = v0;
uni.v1 = v1;
uni.v2 = v2;
uni.v3 = v3;
needsUpload.push(uni);
}
typeMap = typeMap || initTypeMap(gl);
function upload() {
while (needsUpload.length > 0) {
var _needsUpload$pop = needsUpload.pop(),
_type = _needsUpload$pop.type,
_location = _needsUpload$pop.location,
v0 = _needsUpload$pop.v0,
v1 = _needsUpload$pop.v1,
v2 = _needsUpload$pop.v2,
v3 = _needsUpload$pop.v3;
var glMethod = typeMap[_type];
if (v0.length) {
if (glMethod.matrix) {
var array = v0;
var transpose = v1 || false;
gl[glMethod.matrix](_location, transpose, array);
} else {
gl[glMethod.array](_location, v0);
}
} else {
gl[glMethod.values](_location, v0, v1, v2, v3);
}
}
}
return {
setUniform: setUniform,
upload: upload
};
}
function initTypeMap(gl) {
var _ref;
return _ref = {}, _defineProperty(_ref, gl.FLOAT, glName(1, 'f')), _defineProperty(_ref, gl.FLOAT_VEC2, glName(2, 'f')), _defineProperty(_ref, gl.FLOAT_VEC3, glName(3, 'f')), _defineProperty(_ref, gl.FLOAT_VEC4, glName(4, 'f')), _defineProperty(_ref, gl.INT, glName(1, 'i')), _defineProperty(_ref, gl.INT_VEC2, glName(2, 'i')), _defineProperty(_ref, gl.INT_VEC3, glName(3, 'i')), _defineProperty(_ref, gl.INT_VEC4, glName(4, 'i')), _defineProperty(_ref, gl.SAMPLER_2D, glName(1, 'i')), _defineProperty(_ref, gl.SAMPLER_2D_ARRAY, glName(1, 'i')), _defineProperty(_ref, gl.FLOAT_MAT2, glNameMatrix(2, 2)), _defineProperty(_ref, gl.FLOAT_MAT3, glNameMatrix(3, 3)), _defineProperty(_ref, gl.FLOAT_MAT4, glNameMatrix(4, 4)), _ref;
}
function glName(numComponents, type) {
return {
values: "uniform".concat(numComponents).concat(type),
array: "uniform".concat(numComponents).concat(type, "v")
};
}
function glNameMatrix(rows, columns) {
return {
matrix: rows === columns ? "uniformMatrix".concat(rows, "fv") : "uniformMatrix".concat(rows, "x").concat(columns, "fv")
};
}
function makeRenderPass(gl, params) {
var fragment = params.fragment,
vertex = params.vertex;
var vertexCompiled = vertex instanceof WebGLShader ? vertex : makeVertexShader(gl, params);
var fragmentCompiled = fragment instanceof WebGLShader ? fragment : makeFragmentShader(gl, params);
var program = createProgram(gl, vertexCompiled, fragmentCompiled);
return _objectSpread2(_objectSpread2({}, makeRenderPassFromProgram(gl, program)), {}, {
outputLocs: fragment.outputs ? getOutputLocations(fragment.outputs) : {}
});
}
function makeVertexShader(gl, _ref) {
var defines = _ref.defines,
vertex = _ref.vertex;
return makeShaderStage(gl, gl.VERTEX_SHADER, vertex, defines);
}
function makeFragmentShader(gl, _ref2) {
var defines = _ref2.defines,
fragment = _ref2.fragment;
return makeShaderStage(gl, gl.FRAGMENT_SHADER, fragment, defines);
}
function makeRenderPassFromProgram(gl, program) {
var uniformSetter = makeUniformSetter(gl, program);
var textures = {};
var nextTexUnit = 1;
function setTexture(name, texture) {
if (!texture) {
return;
}
if (!textures[name]) {
var unit = nextTexUnit++;
uniformSetter.setUniform(name, unit);
textures[name] = {
unit: unit,
tex: texture
};
} else {
textures[name].tex = texture;
}
}
function bindTextures() {
for (var name in textures) {
var _textures$name = textures[name],
tex = _textures$name.tex,
unit = _textures$name.unit;
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(tex.target, tex.texture);
}
}
function useProgram() {
var autoBindTextures = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
gl.useProgram(program);
uniformSetter.upload();
if (autoBindTextures) {
bindTextures();
}
}
return {
attribLocs: getAttributes(gl, program),
bindTextures: bindTextures,
program: program,
setTexture: setTexture,
setUniform: uniformSetter.setUniform,
textures: textures,
useProgram: useProgram
};
}
function makeShaderStage(gl, type, shader, defines) {
var str = '#version 300 es\nprecision mediump float;\nprecision mediump int;\n';
if (defines) {
str += addDefines(defines);
}
if (type === gl.FRAGMENT_SHADER && shader.outputs) {
str += addOutputs(shader.outputs);
}
if (shader.includes) {
str += addIncludes(shader.includes, defines);
}
if (typeof shader.source === 'function') {
str += shader.source(defines);
} else {
str += shader.source;
}
return compileShader(gl, type, str);
}
function addDefines(defines) {
var str = '';
for (var name in defines) {
var value = defines[name]; // don't define falsy values such as false, 0, and ''.
// this adds support for #ifdef on falsy values
if (value) {
str += "#define ".concat(name, " ").concat(value, "\n");
}
}
return str;
}
function addOutputs(outputs) {
var str = '';
var locations = getOutputLocations(outputs);
for (var name in locations) {
var location = locations[name];
str += "layout(location = ".concat(location, ") out vec4 out_").concat(name, ";\n");
}
return str;
}
function addIncludes(includes, defines) {
var str = '';
var _iterator = _createForOfIteratorHelper(includes),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var include = _step.value;
if (typeof include === 'function') {
str += include(defines);
} else {
str += include;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return str;
}
function getOutputLocations(outputs) {
var locations = {};
for (var i = 0; i < outputs.length; i++) {
locations[outputs[i]] = i;
}
return locations;
}
function makeFullscreenQuad(gl) {
var vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1]), gl.STATIC_DRAW); // vertex shader should set layout(location = 0) on position attribute
var posLoc = 0;
gl.enableVertexAttribArray(posLoc);
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
var vertexShader = makeVertexShader(gl, {
vertex: vertex
});
function draw() {
gl.bindVertexArray(vao);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
return {
draw: draw,
vertexShader: vertexShader
};
}
var vertex$1 = {
source: "\n in vec3 aPosition;\n in vec3 aNormal;\n in vec2 aUv;\n in ivec2 aMaterialMeshIndex;\n\n uniform mat4 projView;\n\n out vec3 vPosition;\n out vec3 vNormal;\n out vec2 vUv;\n flat out ivec2 vMaterialMeshIndex;\n\n void main() {\n vPosition = aPosition;\n vNormal = aNormal;\n vUv = aUv;\n vMaterialMeshIndex = aMaterialMeshIndex;\n gl_Position = projView * vec4(aPosition, 1);\n }\n"
};
var constants$1 = "\n #define PI 3.14159265359\n #define TWOPI 6.28318530718\n #define INVPI 0.31830988618\n #define INVPI2 0.10132118364\n #define EPS 0.0005\n #define INF 1.0e999\n\n #define ROUGHNESS_MIN 0.03\n";
var materialBuffer = "\n\nuniform Materials {\n vec4 colorAndMaterialType[NUM_MATERIALS];\n vec4 roughnessMetalnessNormalScale[NUM_MATERIALS];\n\n #if defined(NUM_DIFFUSE_MAPS) || defined(NUM_NORMAL_MAPS) || defined(NUM_PBR_MAPS)\n ivec4 diffuseNormalRoughnessMetalnessMapIndex[NUM_MATERIALS];\n #endif\n\n #if defined(NUM_DIFFUSE_MAPS) || defined(NUM_NORMAL_MAPS)\n vec4 diffuseNormalMapSize[NUM_DIFFUSE_NORMAL_MAPS];\n #endif\n\n #if defined(NUM_PBR_MAPS)\n vec2 pbrMapSize[NUM_PBR_MAPS];\n #endif\n} materials;\n\n#ifdef NUM_DIFFUSE_MAPS\n uniform mediump sampler2DArray diffuseMap;\n#endif\n\n#ifdef NUM_NORMAL_MAPS\n uniform mediump sampler2DArray normalMap;\n#endif\n\n#ifdef NUM_PBR_MAPS\n uniform mediump sampler2DArray pbrMap;\n#endif\n\nfloat getMatType(int materialIndex) {\n return materials.colorAndMaterialType[materialIndex].w;\n}\n\nvec3 getMatColor(int materialIndex, vec2 uv) {\n vec3 color = materials.colorAndMaterialType[materialIndex].rgb;\n\n #ifdef NUM_DIFFUSE_MAPS\n int diffuseMapIndex = materials.diffuseNormalRoughnessMetalnessMapIndex[materialIndex].x;\n if (diffuseMapIndex >= 0) {\n color *= texture(diffuseMap, vec3(uv * materials.diffuseNormalMapSize[diffuseMapIndex].xy, diffuseMapIndex)).rgb;\n }\n #endif\n\n return color;\n}\n\nfloat getMatRoughness(int materialIndex, vec2 uv) {\n float roughness = materials.roughnessMetalnessNormalScale[materialIndex].x;\n\n #ifdef NUM_PBR_MAPS\n int roughnessMapIndex = materials.diffuseNormalRoughnessMetalnessMapIndex[materialIndex].z;\n if (roughnessMapIndex >= 0) {\n roughness *= texture(pbrMap, vec3(uv * materials.pbrMapSize[roughnessMapIndex].xy, roughnessMapIndex)).g;\n }\n #endif\n\n return roughness;\n}\n\nfloat getMatMetalness(int materialIndex, vec2 uv) {\n float metalness = materials.roughnessMetalnessNormalScale[materialIndex].y;\n\n #ifdef NUM_PBR_MAPS\n int metalnessMapIndex = materials.diffuseNormalRoughnessMetalnessMapIndex[materialIndex].w;\n if (metalnessMapIndex >= 0) {\n metalness *= texture(pbrMap, vec3(uv * materials.pbrMapSize[metalnessMapIndex].xy, metalnessMapIndex)).b;\n }\n #endif\n\n return metalness;\n}\n\n#ifdef NUM_NORMAL_MAPS\nvec3 getMatNormal(int materialIndex, vec2 uv, vec3 normal, vec3 dp1, vec3 dp2, vec2 duv1, vec2 duv2) {\n int normalMapIndex = materials.diffuseNormalRoughnessMetalnessMapIndex[materialIndex].y;\n if (normalMapIndex >= 0) {\n // http://www.thetenthplanet.de/archives/1180\n // Compute co-tangent and co-bitangent vectors\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 dpdu = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 dpdv = dp2perp * duv1.y + dp1perp * duv2.y;\n float invmax = inversesqrt(max(dot(dpdu, dpdu), dot(dpdv, dpdv)));\n dpdu *= invmax;\n dpdv *= invmax;\n\n vec3 n = 2.0 * texture(normalMap, vec3(uv * materials.diffuseNormalMapSize[normalMapIndex].zw, normalMapIndex)).rgb - 1.0;\n n.xy *= materials.roughnessMetalnessNormalScale[materialIndex].zw;\n\n mat3 tbn = mat3(dpdu, dpdv, normal);\n\n return normalize(tbn * n);\n } else {\n return normal;\n }\n}\n#endif\n";
var fragment = {
outputs: ['position', 'normal', 'faceNormal', 'color', 'matProps'],
includes: [constants$1, materialBuffer],
source: "\n in vec3 vPosition;\n in vec3 vNormal;\n in vec2 vUv;\n flat in ivec2 vMaterialMeshIndex;\n\n vec3 faceNormals(vec3 pos) {\n vec3 fdx = dFdx(pos);\n vec3 fdy = dFdy(pos);\n return cross(fdx, fdy);\n }\n\n void main() {\n int materialIndex = vMaterialMeshIndex.x;\n int meshIndex = vMaterialMeshIndex.y;\n\n vec2 uv = fract(vUv);\n\n vec3 color = getMatColor(materialIndex, uv);\n float roughness = getMatRoughness(materialIndex, uv);\n float metalness = getMatMetalness(materialIndex, uv);\n float materialType = getMatType(materialIndex);\n\n roughness = clamp(roughness, ROUGHNESS_MIN, 1.0);\n metalness = clamp(metalness, 0.0, 1.0);\n\n vec3 normal = normalize(vNormal);\n vec3 faceNormal = normalize(faceNormals(vPosition));\n normal *= sign(dot(normal, faceNormal));\n\n #ifdef NUM_NORMAL_MAPS\n vec3 dp1 = dFdx(vPosition);\n vec3 dp2 = dFdy(vPosition);\n vec2 duv1 = dFdx(vUv);\n vec2 duv2 = dFdy(vUv);\n normal = getMatNormal(materialIndex, uv, normal, dp1, dp2, duv1, duv2);\n #endif\n\n out_position = vec4(vPosition, float(meshIndex) + EPS);\n out_normal = vec4(normal, materialType);\n out_faceNormal = vec4(faceNormal, 0);\n out_color = vec4(color, 0);\n out_matProps = vec4(roughness, metalness, 0, 0);\n }\n"
};
function makeGBufferPass(gl, _ref) {
var materialBuffer = _ref.materialBuffer,
mergedMesh = _ref.mergedMesh;
var renderPass = makeRenderPass(gl, {
defines: materialBuffer.defines,
vertex: vertex$1,
fragment: fragment
});
renderPass.setTexture('diffuseMap', materialBuffer.textures.diffuseMap);
renderPass.setTexture('normalMap', materialBuffer.textures.normalMap);
renderPass.setTexture('pbrMap', materialBuffer.textures.pbrMap);
var geometry = mergedMesh.geometry;
var elementCount = geometry.getIndex().count;
var vao = gl.createVertexArray();
gl.bindVertexArray(vao);
uploadAttributes(gl, renderPass, geometry);
gl.bindVertexArray(null);
var jitterX = 0;
var jitterY = 0;
function setJitter(x, y) {
jitterX = x;
jitterY = y;
}
var currentCamera;
function setCamera(camera) {
currentCamera = camera;
}
function calcCamera() {
projView.copy(currentCamera.projectionMatrix);
projView.elements[8] += 2 * jitterX;
projView.elements[9] += 2 * jitterY;
projView.multiply(currentCamera.matrixWorldInverse);
renderPass.setUniform('projView', projView.elements);
}
var projView = new THREE$1.Matrix4();
function draw() {
calcCamera();
gl.bindVertexArray(vao);
renderPass.useProgram();
gl.enable(gl.DEPTH_TEST);
gl.drawElements(gl.TRIANGLES, elementCount, gl.UNSIGNED_INT, 0);
gl.disable(gl.DEPTH_TEST);
}
return {
draw: draw,
outputLocs: renderPass.outputLocs,
setCamera: setCamera,
setJitter: setJitter
};
}
function uploadAttributes(gl, renderPass, geometry) {
setAttribute(gl, renderPass.attribLocs.aPosition, geometry.getAttribute('position'));
setAttribute(gl, renderPass.attribLocs.aNormal, geometry.getAttribute('normal'));
setAttribute(gl, renderPass.attribLocs.aUv, geometry.getAttribute('uv'));
setAttribute(gl, renderPass.attribLocs.aMaterialMeshIndex, geometry.getAttribute('materialMeshIndex'));
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, geometry.getIndex().array, gl.STATIC_DRAW);
}
function setAttribute(gl, location, bufferAttribute) {
if (location === undefined) {
return;
}
var itemSize = bufferAttribute.itemSize,
array = bufferAttribute.array;
gl.enableVertexAttribArray(location);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, array, gl.STATIC_DRAW);
if (array instanceof Float32Array) {
gl.vertexAttribPointer(location, itemSize, gl.FLOAT, false, 0, 0);
} else if (array instanceof Int32Array) {
gl.vertexAttribIPointer(location, itemSize, gl.INT, 0, 0);
} else {
throw 'Unsupported buffer type';
}
}
function makeUniformBuffer(gl, program, blockName) {
var blockIndex = gl.getUniformBlockIndex(program, blockName);
var blockSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
var uniforms = getUniformBlockInfo(gl, program, blockIndex);
var buffer = gl.createBuffer();
gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
gl.bufferData(gl.UNIFORM_BUFFER, blockSize, gl.STATIC_DRAW);
var data = new DataView(new ArrayBuffer(blockSize));
function set(name, value) {
if (!uniforms[name]) {
// console.warn('No uniform property with name ', name);
return;
}
var _uniforms$name = uniforms[name],
type = _uniforms$name.type,
size = _uniforms$name.size,