-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnormalmap.html
executable file
·537 lines (355 loc) · 14.2 KB
/
normalmap.html
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
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="three.js"></script>
<script type="text/javascript" src="dat.gui.min.js"></script>
<script src="TrackballControls.js"></script>
</head>
<body style="background:#ececec; margin:0px; padding:0px" onmousemove="update()">
<canvas id="imgCanvas" style="position: absolute; visibility:hidden;"></canvas>
<div id="container"></div>
<!-- ----- VERTEX SHADER ----- -->
<script id="vertex_shader" type="x-shader/x-vertex">
attribute vec4 tangent;
attribute float amplitude;
attribute float displacement;
varying vec3 vTangent;
varying vec3 vBinormal;
varying vec3 vNormal;
varying vec2 vUv;
varying vec3 vPointLightVector;
varying vec3 vViewPosition;
uniform vec3 uPointLightPos;
#ifdef VERTEX_TEXTURES
uniform sampler2D tDisplacement;
uniform float uDisplacementScale;
uniform float uDisplacementBias;
uniform float uDisplacementPostScale;
#endif
void main() {
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
vViewPosition = -mvPosition.xyz; // ah HA
vNormal = normalize( normalMatrix * normal );
//tangent and binormal vectors
vTangent = normalize( normalMatrix * tangent.xyz );
vBinormal = cross( vNormal, vTangent ) * tangent.w;
vBinormal = normalize( vBinormal );
vUv = uv;
// point light
vec4 lPosition = viewMatrix * vec4( uPointLightPos, 1.0 );
vPointLightVector = normalize( lPosition.xyz - mvPosition.xyz );
#ifdef VERTEX_TEXTURES
vec3 dv = texture2D( tDisplacement, vUv ).xyz;
float df = uDisplacementScale * dv.x + uDisplacementBias;
vec4 displacedPosition = vec4( vNormal.xyz * df * uDisplacementPostScale/100.0, 0.0 ) + mvPosition;
gl_Position = projectionMatrix * displacedPosition;
#else
gl_Position = projectionMatrix * mvPosition;
#endif
}
</script>
<!-- ----- FRAGMENT SHADER ----- -->
<script id="fragment_shader" type="x-shader/x-fragment">
#extension GL_OES_standard_derivatives : enable
uniform vec3 uPointLightPos;
uniform vec3 uAmbientLightColor;
uniform vec3 uPointLightColor;
uniform vec3 uAmbientColor;
uniform vec3 uDiffuseColor;
uniform vec3 uSpecularColor;
uniform float uShininess; //
uniform sampler2D tDiffuse;
uniform sampler2D tDisplacement;
uniform sampler2D tNormal;
uniform sampler2D tSpec; //
uniform sampler2D tOcc; //
uniform float tDiffuseOpacity;
uniform float uNormalScale; //
uniform float specToggle; //
uniform float normalToggle; //
uniform float displacementToggle; //
uniform float texToggle; //
varying vec3 vTangent;
varying vec3 vBinormal;
varying vec3 vNormal;
varying vec2 vUv;
varying vec3 vPointLightVector;
varying vec3 vViewPosition;
uniform float uDisplacementPostScale;
uniform float bumpScale;
// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
vec2 dHdxy_fwd() {
vec2 dSTdx = dFdx( vUv );
vec2 dSTdy = dFdy( vUv );
float hll = bumpScale * texture2D( tDisplacement, vUv ).x;
float dBx = bumpScale * texture2D( tDisplacement, vUv + dSTdx ).x - hll;
float dBy = bumpScale * texture2D( tDisplacement, vUv + dSTdy ).x - hll;
return vec2( dBx, dBy );
}
vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {
vec3 vSigmaX = dFdx( surf_pos );
vec3 vSigmaY = dFdy( surf_pos );
vec3 vN = surf_norm; // normalized
vec3 R1 = cross( vSigmaY, vN );
vec3 R2 = cross( vN, vSigmaX );
float fDet = dot( vSigmaX, R1 );
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
return normalize( abs( fDet ) * surf_norm - vGrad );
}
void main() {
vec4 diffuseTex = texture2D( tDiffuse, vUv ) * tDiffuseOpacity;
diffuseTex.a = tDiffuseOpacity;
// vec3 specTex = texture2D( tSpec, vUv ).xyz;
// vec3 occTex = texture2D( tOcc, vUv ).xyz;
vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;
mat3 tsb = mat3( vTangent, vBinormal, vNormal );
vec3 finalNormal = tsb * normalTex.rgb;
vec3 normal = normalize( finalNormal );
vec3 normal2 = normalize( finalNormal );
vec3 viewPosition = normalize( vViewPosition );
// normals from displacement map
if (normalToggle == 1.0) normal = perturbNormalArb( -vViewPosition, normal * vec3(100.0/(uDisplacementPostScale+1.0)), dHdxy_fwd() );
normal = normalize(normal);
// point light
vec4 pointDiffuse = vec4( 0.0, 0.0, 0.0, 0.0 );
vec4 pointSpecular = vec4( 0.0, 0.0, 0.0, 0.0 ); //
vec3 pointVector = normalize( vPointLightVector );
float dotProduct = dot( normal, pointVector );
float pointDiffuseWeight = max( dotProduct, 0.0 );
vec3 pointHalfVector = normalize( vPointLightVector + viewPosition );
// specular
float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );
float pointSpecularWeight = 0.0; //
pointSpecularWeight += max( pow( pointDotNormalHalf, uShininess ), 0.0 );
pointSpecular += vec4( uSpecularColor, 1.0 ) * vec4( uPointLightColor, 1.0 ) * pointSpecularWeight * pointDiffuseWeight;
if ( pointDotNormalHalf >= 0.0 ) pointSpecularWeight = pow( pointDotNormalHalf, uShininess ); // no spectex
pointDiffuse += vec4( uDiffuseColor, 1.0 ) * vec4( uPointLightColor, 1.0 ) * pointDiffuseWeight;
// all lights contribution summation
vec4 totalLight = vec4( uAmbientLightColor * uAmbientColor , 1.0 ); // orig
// with spec
totalLight += vec4( uPointLightColor, 1.0 ) * ( pointDiffuse + pointSpecular * specToggle );
// without spec
// totalLight += vec4( uPointLightColor, 1.0 ) * ( pointDiffuse );
// with texture
// gl_FragColor = vec4( diffuseTex.xyz * texToggle + totalLight.xyz, 1.0 );
// without texture
gl_FragColor = vec4( totalLight.xyz, 1.0 );
}
</script>
<!-- ----- MAIN THREE.JS CODE ----- -->
<script type="text/javascript">
var camera, scene, renderer, container;
var light, ambientLight, pointLight, geometry, mesh;
var uniforms, attributes, material;
var heightmap, diffTexture, dispTexture;
var t = 0;
var diameter = 1200;
var dist_x = 0;
var step = 0;
var imgc=document.getElementById("imgCanvas");
var ictx=imgc.getContext("2d");
function start() {
container = document.getElementById( 'container' );
// --- WebGl render
try {
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
container.appendChild( renderer.domElement );
}
catch (e) {
alert(e);
}
scene = new THREE.Scene();
// --- Camera
var fov = 15; // camera field-of-view in degrees
var width = renderer.domElement.width;
var height = renderer.domElement.height;
var aspect = width / height; // view aspect ratio
camera = new THREE.PerspectiveCamera( fov, aspect );
camera.position.x = 300;
camera.position.y = -100;
camera.position.z = -1200;
camera.lookAt(scene.position);
camera.updateMatrix();
controls = new THREE.TrackballControls( camera, renderer.domElement );
controls.rotateSpeed = 3.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
controls.addEventListener( 'change', render );
// --- Lights
ambientLight = new THREE.AmbientLight( 0xffffff );
scene.add( ambientLight );
pointLight = new THREE.PointLight( 0xffffff, 0.0 );
scene.add( pointLight );
pointLight.position.set(0, 100, -200);
var sphere = new THREE.SphereGeometry( 100, 8, 8 );
light = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color:0xffffff } ) );
light.position = pointLight.position;
light.scale.x = light.scale.y = light.scale.z = 0.05;
scene.add(light);
// MATERIAL
var ambient = 0x000000, diffuse = 0xffffff, specular = 0xffffff, shininess = 50.0;
diffTexture = new THREE.Texture(imgc);
dispTexture = new THREE.Texture(imgc);
heightmap = new Image();
heightmap.src = 'moon.jpg';
heightmap.onload = function() {
imgc.width = heightmap.width;
imgc.height = heightmap.height;
ictx.drawImage(heightmap, 0, 0, heightmap.width, heightmap.height);
diffTexture.needsUpdate = true;
dispTexture.needsUpdate = true;
update();
};
var shader = THREE.ShaderLib[ "normalmap" ];
uniforms = THREE.UniformsUtils.clone( shader.uniforms );
uniforms[ "enableDisplacement" ] = { type: 'i', value: 1 };
uniforms[ "enableDiffuse" ] = { type: 'i', value: 0 };
uniforms[ "tDiffuseOpacity" ] = { type: 'f', value: 1.0 };
uniforms[ "tDisplacement" ] = { type: 't', value: dispTexture };
uniforms[ "uDisplacementScale" ] = { type: 'f', value: 20 };
uniforms[ "tNormal" ] = { type: 't', value: new THREE.ImageUtils.loadTexture( 'flat.png' )};
uniforms[ "uDiffuseColor" ].value = new THREE.Color( diffuse );
uniforms[ "uSpecularColor" ].value = new THREE.Color( specular );
uniforms[ "uAmbientColor" ].value = new THREE.Color( ambient );
uniforms[ "uShininess" ].value = shininess;
uniforms[ "uPointLightPos"] = { type: "v3", value: pointLight.position },
uniforms[ "uPointLightColor" ] = {type: "c", value: new THREE.Color( pointLight.color )};
uniforms[ "uAmbientLightColor" ] = {type: "c", value: new THREE.Color( ambientLight.color )};
uniforms[ "uDisplacementPostScale" ] = {type: 'f', value: 100 };
uniforms[ "bumpScale" ] = { type: "f", value: 10 };
uniforms[ "specToggle" ] = { type: 'f', value: 1.0 };
uniforms[ "normalToggle" ] = { type: 'f', value: 1.0 };
material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: document.getElementById( 'vertex_shader' ).textContent,
fragmentShader: document.getElementById( 'fragment_shader' ).textContent,
side: THREE.DoubleSide
} );
// GEOMETRY
geometry = new THREE.SphereGeometry(100, 128, 128)
geometry.computeTangents();
mesh = new THREE.Mesh( geometry, material);
mesh.rotation.y = Math.PI;
scene.add(mesh);
t = 0;
update();
setInterval(function() {
mesh.rotation.y += .01;
update();
}, 30);
}
function update() {
render();
controls.update(); // trackball interaction
}
function render() {
renderer.clear();
renderer.render(scene, camera);
}
//
// JAVASCRIPT IMAGE MANIPULATION
//
function log(n) {
console.log(n);
}
function imageFromCanvas(canvas) {
var m = canvas.width
var n = canvas.height
var data = canvas.getContext('2d').getImageData(0, 0, m, n).data
var image = new Array(m*n)
for (var i=0; i<n*m; i++) {
image[i] = data[i*4]
}
return image
}
function drawImage(image, canvas) {
// set destination canvas
c = document.getElementById(canvas+"Canvas");
context = c.getContext('2d')
var m = c.width
var n = c.height
// find range
minimum = 1000000000000000000
maximum = 0
first = true
var d = 0
for (var i=0; i<n*m; i++) {
try {d = image[i]}
catch(e) {log(e); log("i: "+i); log("image: "+image); break}
minimum = Math.min(minimum, d)
maximum = Math.max(maximum, d)
if (i == m*n-1) {
first = false
}
}
var finalImage = ictx.createImageData(m, n);
var data = finalImage.data // pixel data array of (width*height*4) elements
var contrast = 2
var distanceColor = { r : 255*contrast/255, g : 255*contrast/255, b : 255*contrast/255 }
var ceil = 255
var floor = 0
newmin = 1000000000000000
newmax = 0
// Convert to visible
for (var i=0; i<n*m; i++) {
d = image[i]
normd = ((ceil - floor) * (d - minimum))/(maximum - minimum) + floor
newmin = Math.min(newmin, normd)
newmax = Math.max(newmax, normd)
data[i*4+0] = normd
data[i*4+1] = normd
data[i*4+2] = normd
data[i*4+3] = 255
}
context.putImageData(finalImage, 0, 0)
geometry.normalsNeedUpdate = true;
geometry.tangentsNeedUpdate = true;
diffTexture.needsUpdate = true;
dispTexture.needsUpdate = true;
geometry.computeTangents();
update();
}
//
// GUI
//
var initDisp = function() {
this.displacement = true;
this.specular = true;
this.normals = true;
this.scale = 100;
}
window.onload = function() {
var disp = new initDisp();
var gui = new dat.GUI();
var scaleVal = 100.0;
dControl = gui.add(disp, "displacement");
dControl.onChange(function(value) {
uniforms[ "uDisplacementScale" ].value = ( value == true ) ? scaleVal : 0.0;
});
sControl = gui.add(disp, "specular");
sControl.onChange(function(value) {
uniforms[ "specToggle" ].value = ( value == true ) ? 1.0 : 0.0;
});
nControl = gui.add(disp, "normals");
nControl.onChange(function(value) {
uniforms[ "normalToggle" ].value = ( value == true ) ? 1.0 : 0.0;
});
scControl = gui.add(disp, "scale", 0, 200);
scControl.onChange(function(value) {
scaleVal = value;
uniforms[ "uDisplacementScale" ].value = value;
});
start();
controls.update();
}
</script>
</body>
</html>