-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshader.html
More file actions
519 lines (406 loc) · 15.8 KB
/
shader.html
File metadata and controls
519 lines (406 loc) · 15.8 KB
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
<!DOCTYPE html>
<HTML>
<HEAD>
<title>Shader Tricks: Retrieving Triangle Location and Edges in Pixel Shader and More - Alexandr Poltavsky, software developer</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/common.css" />
<link rel="stylesheet" href="highlight/styles/hybrid.css">
</HEAD>
<BODY>
<div id="wrap">
<!-- header part -->
<div id="header">
<a href="/color-throne.html"><img class="ad" src="images/color-throne-logo-promo.png" title="Color Throne Game"/></a>
<div class="avatar">
<a href="/">
<img class="avatar" width="160" src="images/alexandr-poltavsky-avatar.jpeg" title="Alexandr Poltavsky" align="left"/>
</a>
</div>
<div class="text">
<span class="bio">
Alexandr Poltavsky <br/>
Software Developer <br/>
Location: Russia, Moscow <br/>
<span class="email">
<a href="mailto:poltavsky.alexandr@gmail.com">poltavsky.alexandr@gmail.com</a><br/>
</span>
</span>
<div class="break"></div>
<span class="links">
<a href="/">Blog</a>
<a href="https://github.com/alexpolt/">Github</a>
<a href="https://www.shadertoy.com/user/alexpolt">Shadertoy</a>
<a href="https://twitter.com/poltavsky_alex">Twitter</a>
</span>
</div>
</div>
<div id="content" style="clear: left">
<!-- here goes the main content -->
<div id="main-menu">
<a id="main-menu-0" href="index.html">Programming</a>
<a id="main-menu-1" href="index-gfx.html">Graphics</a>
<a id="main-menu-2" href="index-off.html">Off-topic</a>
</div>
<h2>Shader Tricks: Retrieving Triangle Location and Edges in Pixel Shader and More</h2>
<p>In this post I'm going to talk about:</p>
<ul>
<li><p><a href="#triangle">Getting triangle (primitive) location in screen space and its edge vectors</a></p></li>
<li><p><a href="#noperspective">Non-perspective interpolation in WebGL</a></p></li>
<li><p><a href="#derivatives">Using partial derivatives for peeking into another shader</a></p></li>
</ul>
<!-- end list -->
<p><a name="triangle"></a></p>
<h3>Triangle Info</h3>
<p><a href="barycentric.html">
<img src="images/barycentric-screenspace.png" style="display:block;float:right;max-width:25%;"/>
</a></p>
<p>Every once in while there is a need to get full info about the rasterized primitive in a pixel
shader: location in screen space and edge vectors. And it's an easy thing with the help of
barycentrics. Check out a <a href="barycentric.html" title="Barycentric Coordinates">blog post</a> I made on them with a Javascript interactive demo.</p>
<p>So the first step is to take partial derivatives (I use GLSL syntax but it's easy to translate
to HLSL):</p>
<div class="clear">
</div>
<pre><code>vec2 uvdx = dFdx( uv );
vec2 uvdy = dFdy( uv );
mat2 scr2uv = mat2( uvdx, uvdy );
</code></pre>
<p>uv - is interpolated barycentrics, uvdx and uvdy form a 2x2 matrix that takes from screen space
to barycentric space. Taking the inverse of that matrix produces a matrix that transforms uv
coordinates to screen space. Because a uv of [1,0] is one edge of the triangle and [0,1] is
another, this inverse matrix has as its columns (or rows, depending on your math) the edge
vectors. </p>
<pre><code>float D = 1.0 / ( uvdx.x*uvdy.y - uvdx.y*uvdy.x );
vec2 xydu = vec2( uvdy.y, -uvdx.y ) * D;
vec2 xydv = vec2( -uvdy.x, uvdx.x ) * D;
mat2 uv2scr = mat2( xydu, xydv );
//starting with OpenGL 3.1 (GLSL 1.4) there is inverse(...) intrinsic
</code></pre>
<p>Okay. The first step is done. Now we need to find the location of uv=[0,0] on screen. Remember
that uv is an interpolated barycentric, so we can use the above uv2scr to find the screen space
position of the shaded fragment within the primitive. Then we subtract that from the global
screen space fragment position (gl_FragCoord or SV_POSITION) to get the desired result:</p>
<pre><code>vec2 pos_tri = gl_FragCoord.xy - uv2scr*uv;
</code></pre>
<p>Below is a WebGL demonstration. On the sides of the triangle are screen dimensions of its edges
together with screen position of the origin point. Three digits are printed so make sure your
browser window is reasonable in size. Most of the code in pixel shader is for outputting the
text in the right place. To pause rotation just hit space bar.</p>
<div class="webgl" webgl_version="1" webgl_div="shader0" init="load_demo_tri">
<img class="link" src="images/triangle-info.png" title="Click to show WebGL demo" alt="WebGL demo"/><br/>
<span>Click to show WebGL demo</span>
</div>
<div class="shader hidden" id="shader0" js="" fn="">
<ul class="close">
<li title="Info" class="help">?</li>
<li title="Close Demo" class="close">Close</li>
</ul>
<ul class="menu">
<li title="WebGL Canvas" class="canvas">Canvas</li>
<li title="Vertex Shader" class="vs">VS</li>
<li title="Pixel Shader" class="ps">PS</li>
</ul>
<div class="canvas">
<canvas hide class="canvas"></canvas>
<textarea hide class="vs hidden" spellcheck="false" fromid="shader0vs"></textarea>
<textarea hide class="ps hidden" spellcheck="false" fromid="shader0ps"></textarea>
<div hide class="help hidden"></div>
</div>
<div class="buttons">
<button title="Reload Shaders" class="reload">Reload</button>
<button title="Output WebGL Info in Console" class="log">Log</button>
<button title="Pause Rendering" class="pause">Pause</button>
<button title="Go Fullscreen" class="fscreen">FS</button>
</div>
</div>
<div class="clear">
</div>
<p>Retrieving tri info is helpful in <a href="dfaa.html" title="DFAA Antialiasing Algorithm">DFAA</a> antialiasing: the edge vectors are used to determine
sampling direction.</p>
<p><a name="noperspective"></a></p>
<h3>Non-perspective interpolation in WebGL</h3>
<p>In WebGL (both 1 and 2) there is no <em>noperspective</em> qualifier and that's a problem because our
barycentric coordinates need to be interpolated in screen space linearly. No worries, it can be
done by hand: we need to multiply by gl_Position.w in the vertex shader and then divide by
1\gl_FragCoord.w in the pixel shader (if the z is constant then we don't need to do anything).
This effectively has the same effect as <em>noperspective</em> interpolation.</p>
<p><a name="derivatives"></a></p>
<h3>Using partial derivatives for peeking into another shader</h3>
<p>Derivatives can be exploited to peek into what's happening in a neighbor fragment.</p>
<pre><code>float value;
float value_in_right_fragment = value + dFdx( value );
float value_in_up_fragment = value + dFdy( value );
//up in OpenGL, down in DirectX
</code></pre>
<p>While this looks alluring it has a number of problems. First, it's limited to right and up
fragments. Second, derivatives are calculated for a quad of fragments ( 2x2 ), so it essentially
halves the resolution. If you have linear data then it is all, obviously, no problem.
Another problem we have to check for out-of-primitive fragments and it can be done with
barycentrics (by checking for u>=0, v>=0, u+v <=1 in neighbor fragments).</p>
<div>
<script src="js/common.js"></script>
<script src="js/loader.js"></script>
<script src="js/math.js"></script>
<script src="js/camera.js"></script>
<script src="js/webgl-quad.js"></script>
<script src="js/webgl.js"></script>
<script>
var images = ["images/fixedfont.png", "images/triangle-info-bg.png"];
var loader_img = load_images( images );
function run_demo_tri (cb) {
var opts = {
bgcolor: [ 1, 1, 1, 1 ],
textures: {
font: { tex2d: 1, format: "RGB", magf: "NEAREST", minf: "NEAREST",
genmipmap: 0, flip: 1, data: loader_img.data[0] },
bg: { tex2d: 1, format: "RGB", magf: "LINEAR", minf: "LINEAR_MIPMAP_LINEAR",
genmipmap: 1, flip: 1, data: loader_img.data[1] },
},
extensions: [ "OES_standard_derivatives" ]
};
cb (opts);
}
function load_demo_tri(cb) {
var span = this.querySelector("span");
var div = this;
var fn = function(){
if( loader_img.failed )
alert("Loading texture " + loader_img.failed_src + " failed. Try realoading the page.");
else if( ! loader_img.loaded )
alert("Textures not loaded. Check console output (ctrl+shift+j or F12) and try reloading the page.");
else {
div.load_animation = true;
run_demo_tri (cb);
}
};
if( ! this.load_animation )
load_animation (loader_img, span, fn);
else fn ();
}
document.addEventListener( "DOMContentLoaded", function() {
var tas = document.querySelectorAll("div.shader textarea");
if( tas ) foreach( tas, function( e ) {
var fromid = e.getAttribute( "fromid" );
if( fromid ) {
var from = document.getElementById( fromid );
if( !from || from.nodeName !== "TEXTAREA" ) throw "id " + fromid +" not found";
e.value = from.value;
}
} );
} );
</script>
<textarea class="hidden" id="shader0vs">//<!--
attribute vec2 v_in;
attribute vec2 uv_in;
attribute float vid_in;
varying vec2 uvt;
varying vec2 uvb;
uniform float t;
uniform vec2 screen;
void main() {
uvt = v_in;
uvb = uv_in;
vec4 p = vec4(0,0,0,1);
vec4 ar = vec4(1);
if( screen.x > screen.y )
ar = vec4(screen.y/screen.x,1,1,1);
else
ar = vec4(1,screen.x/screen.y,1,1);
float tt = fract(t/32.);
float a = 2.*3.14159265*tt;
mat2 m = mat2( vec2(cos(a),sin(a)), vec2(-sin(a),cos(a)) );
if( vid_in < 3. ) {
p = ar * vec4( m*vec2( 1.4*v_in-.7 ), 0, 1 );
}
gl_Position = p;
}
//-->
</textarea>
<textarea class="hidden" id="shader0ps">//<!--
#extension GL_OES_standard_derivatives : enable
precision highp float;
varying vec2 uvt;
varying vec2 uvb;
uniform sampler2D font;
uniform sampler2D bg;
float print_coords( vec2, vec2 );
float compute_digit( float, vec2 );
float load_digit( float, vec2 );
bool inbox( inout vec2, vec4 );
mat2 inverse( mat2 );
const float numd = 4.;
void main() {
//getting tri info
vec2 uvdx = dFdx( uvb );
vec2 uvdy = dFdy( uvb );
mat2 scr2uv = mat2( uvdx, uvdy );
mat2 uv2scr = inverse( scr2uv );
vec2 pos_tri = gl_FragCoord.xy - uv2scr*uvb;
//the rest is printing digits
vec2 uv;
float c = .0;
uv = uvb;
vec4 boxu = vec4( 0.5, 0.9, .0, .1 );
if( inbox( uv, boxu ) ) {
c = print_coords( uv2scr[0], uv );
}
uv = uvb;
vec4 boxv = vec4( 0., 0.1, .5, .9 );
if( inbox( uv, boxv ) ) {
uv.xy = uv.yx;
uv.y = 1.-uv.y;
c = print_coords( uv2scr[1], uv );
}
uv = uvb;
vec4 boxcx = vec4( 0, 0.2, .0, .1 );
if( inbox( uv, boxcx ) ) {
c = compute_digit( pos_tri.x, uv );
}
uv = uvb;
vec4 boxcy = vec4( 0., 0.1, .11, .31 );
if( inbox( uv, boxcy ) ) {
uv.xy = uv.yx;
uv.y = 1.-uv.y;
c = compute_digit( pos_tri.y, uv );
}
vec4 color = texture2D( bg, uvb );
if( c > .0 )
color = vec4(1,1,1,1);
gl_FragData[0] = color;
}
float compute_digit( float n, vec2 uv ) {
float digit = floor(numd*uv.x);
uv.x = fract(numd*uv.x);
if( digit == .0 ) {
if( n < .0 ) return load_digit( 15., uv );
else return load_digit( 14., uv );
}
digit = digit - 1.;
float d = abs(n)/pow(10.,numd-1.);
for( float n = .0; n < numd-1.; n++ ) {
if(n <= digit) d = 10.*fract(d);
else break;
}
return load_digit( floor(d), uv );
}
float load_digit( float d, vec2 uv ) {
float line = 4.;
vec2 luv = vec2( fract(d/line), floor(d/line)/line );
luv = luv+uv/line;
return texture2D( font, luv ).r;
}
bool inbox( inout vec2 uv, vec4 box ) {
float s0 = sign(uv.x-box.x)+sign(box.y-uv.x);
float s1 = sign(uv.y-box.z)+sign(box.w-uv.y);
if( s0*s1 > .0 ) {
uv.x = (uv.x-box.x)/(box.y-box.x);
uv.y = (uv.y-box.z)/(box.w-box.z);
return true;
}
return false;
}
float print_coords( vec2 coords, vec2 uv ) {
float dd = 2.*numd + 1.;
float d = floor(dd*uv.x);
float c = .0;
if( d < numd ) {
vec2 uv2 = vec2( fract(dd*uv.x/numd), uv.y );
c = compute_digit( coords.x, uv2 );
} else if( d == numd ) {
vec2 uv2 = vec2( fract(dd*uv.x), uv.y );
c = load_digit( 11., uv2 );
} else {
vec2 uv2 = vec2( fract((dd*uv.x-1.-numd)/numd), uv.y );
c = compute_digit( coords.y, uv2 );
}
return c;
}
mat2 inverse( mat2 m ) {
vec2 uvdx = m[0];
vec2 uvdy = m[1];
float D = 1.0 / ( uvdx.x*uvdy.y - uvdx.y*uvdy.x );
vec2 xydu = vec2( uvdy.y, -uvdx.y ) * D;
vec2 xydv = vec2( -uvdy.x, uvdx.x ) * D;
return mat2( xydu, xydv );
}
//-->
</textarea>
</div>
<script>
document.addEventListener( "DOMContentLoaded", function() {
if( /iPhone|iPad|iPod|Android|Windows Phone/i.test(navigator.userAgent) ) {
document.getElementById("wrap").classList.add("mobile");
}
} );
</script>
<script src="highlight/highlight.pack.js"></script>
<script>
//hljs.configure({languages: ["C++"]});
hljs.initHighlightingOnLoad();
</script>
<div id="disqus_comments"><a href="javascript: run_disqus()">read and write commentaries</a></div>
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
function run_disqus() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//alexpolt-github-io.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
d.getElementById("disqus_comments").innerHTML = ""; // alexpolt
return undefined;
};
if( location.hash.indexOf("comment") != -1 ) run_disqus();
</script>
<!--noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments
powered by Disqus.</a></noscript-->
</div> <!-- end content -->
</div> <!-- end wrap -->
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-75341409-1', 'auto');
ga('send', 'pageview');
</script>
<!-- Yandex.Metrika counter -->
<script type="text/javascript">
(function (d, w, c) {
(w[c] = w[c] || []).push(function() {
try {
w.yaCounter43425229 = new Ya.Metrika({
id:43425229,
clickmap:true,
trackLinks:true,
accurateTrackBounce:true
});
} catch(e) { }
});
var n = d.getElementsByTagName("script")[0],
s = d.createElement("script"),
f = function () { n.parentNode.insertBefore(s, n); };
s.type = "text/javascript";
s.async = true;
s.src = "https://mc.yandex.ru/metrika/watch.js";
if (w.opera == "[object Opera]") {
d.addEventListener("DOMContentLoaded", f, false);
} else { f(); }
})(document, window, "yandex_metrika_callbacks");
</script>
<noscript><div><img src="https://mc.yandex.ru/watch/43425229" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
<!-- /Yandex.Metrika counter -->
</BODY>