Reset Repo structure.

This commit is contained in:
Bill
2021-05-19 02:41:33 +08:00
commit 4c104a8c26
211 changed files with 34936 additions and 0 deletions
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 336 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 803 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

+235
View File
@@ -0,0 +1,235 @@
#define _DEBUG_BREAK {gl_FragColor=vec4(1,0,0,1); return;}
#define REFRACTION (c2 >= 0.? (eta*W + (eta*c1 - sqrt(c2))*N) : ((W + c1*N)/sqrt(1.-c1*c1)))
vec3 foregroundColor = vec3(.0841, .5329, .9604);
vec3 groundColor = vec3(.2, .3, .5);
vec4 groundSpecular = vec4(.71, .71, .71, 10.);
uniform float uTime;// TIME, IN SECONDS
uniform vec3 Ambient[ns], Diffuse[ns];
uniform vec4 Specular[ns];
uniform float ks[ns], kr[ns], kf[ns];
uniform vec4 Sph[ns];
uniform sampler2D uSampler[ns];
uniform vec3 V0;
uniform int sel;
const float kf_air = 1.000293;
varying vec3 trPos;
const float pi=3.14159265359;
const float _2pi=2.*pi;
/***********PLEASE DO INCREASE n_ref(RT DEPTH) FOR BETTER RESULTS************/
/*---->*/const int n_ref=7; //2^n-1 because each hit now spawn at most 2 rays.
/**BUT BE CAUTIOUS IF YOU DON'T HAVE A DECENT GRAPHICS CARD (below GTX 950M)**/
const int max_stack = (n_ref+1)/4;
vec3 scolor = vec3(0,0,0);
struct Ray{
vec3 V;
vec3 W;
float kf, cumulativeK;
} stack1[max_stack], stack2[max_stack];
bool modulo2(int n){
return n-2*(n/2) == 1;
}
vec2 getTextCoord(vec3 tex_sph, float R){
float tex_x=atan(tex_sph.z,tex_sph.x)/_2pi + 0.5;//*Correct aspect ratio of texture 2:1 -> 2pir:2r
tex_x=fract(tex_x+uTime/20.);
return vec2(tex_x,-asin(tex_sph.y/R)/pi + 0.5);
}
void main(){
vec3 LDir=vec3(.5,.5,.5);
vec3 LCol=vec3(1.,1.,1.);
float currKf = kf_air;
vec3 color=vec3(.2, .3, .5);
vec3 V = V0;
vec3 W=(trPos-V);
bool rtxoff = false, showtexture = true, selected = false;
float currentK = 1.;
int curr_ptr = 0, curr_top = 0, next_top = 0;
bool final = false, stackswap = false, stop = false;
for(int j=0;j<n_ref;j++)
{
for(int curr = 0; curr < max_stack; ++curr){
if(curr == curr_ptr){
bool skip = false;
if(j > 0){
Ray currR;
if(stackswap)
currR = stack1[curr];
else
currR = stack2[curr];
currKf = currR.kf;
currentK = currR.cumulativeK;
if(currKf <= 0.001 || currentK <= 0.001)
skip = true;
V = currR.V;
W = currR.W;
}
else
W = normalize(W);
if(!skip){
float tMin=10000.;
int iMin = -1;
for(int i=0;i<cns;i++){
vec3 Vp=V-Sph[i].xyz;
float B=dot(W,Vp);
float C=dot(Vp,Vp)-Sph[i].w*Sph[i].w;
float D=B*B-C;
if(D>0.){
float t=-B-sqrt(D);
if(t >= 0.01 && t < tMin){
tMin = t; // This is an optimization, we don't have to do lighting/tex
iMin = i; // for objects that are occuluded, which is expensive!
}
else if (t >= -0.01 && t <0.01){
t = -(t + 2.*B);
if(t > 0.01 && t < tMin){
tMin = t;
iMin = i;
}
}
}
}
if(iMin >= 0){
if(j == 0 && iMin == sel)
selected = true;
float t = tMin;
vec3 S=V+t*W;
for(int i = 0; i < cns; ++ i)
if(i == iMin)
{
vec3 texture_color;
if(showtexture)
{
vec3 tex_sph = (S-Sph[i].xyz);
texture_color=texture2D(uSampler[i],getTextCoord(tex_sph, Sph[i].w)).xyz;
}
else texture_color = foregroundColor;
vec3 N=normalize(S-Sph[i].xyz);
vec3 realLDir=normalize(LDir-S);
float c1 =dot(N, W);
float eta, nextkf;
if(c1<0.){
color=(Ambient[i]+Diffuse[i]*max(0.,dot(N,realLDir))*LCol)*texture_color;
if(rtxoff || final) //if it's the last hit
{
color += Specular[i].xyz*pow(max(0.,
dot(-2.*c1*N-realLDir,realLDir)),Specular[i].w);
scolor += color * currentK;
break;
}
else{
c1 = -c1;
eta = currKf/kf[i];
nextkf = kf[i];
}
}
else{
N = -N;
eta = currKf/kf_air;
nextkf = kf_air;
color = Ambient[i];
}
float c2 = (1.-eta*eta*(1.-c1*c1));
float nextks = currentK * ks[i], nextkr = currentK * kr[i];
bool refl = nextks > 0.01, refr = nextkr > 0.01;
if(refl || refr)
for(int k = 0; k < max_stack; ++k)
if(k == next_top){
if(stackswap){
if(refl)
{
stack2[k] = Ray(S, 2. * c1 * N + W, currKf, nextks); //reflection
currentK -= nextks;
next_top ++;
}
if(refr)
{
if(refl)
stack2[k+1] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
else
stack2[k] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
currentK -= nextkr;
next_top ++;
}
}else{
if(refl)
{ //remember, c1 = -NW now
stack1[k] = Ray(S, 2. * c1 * N + W, currKf, nextks); //reflection
currentK -= nextks;
next_top ++;
}
if(refr)
{
if(refl)
stack1[k+1] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
else
stack1[k] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
currentK -= nextkr;
next_top ++;
}
}
break;
}
scolor += color * currentK;
break;
}
}
else {
float t = -(.2+V.y)/W.y;
float sx = V.x + t* W.x, sz = V.z + t * W.z;
if(t >= 0. && abs(sx) < 1.5 && abs(sz) < 3.)
{
vec3 S = vec3(sx, -.2, sz);
vec3 realLDir=normalize(LDir - S);
color=(0.5+0.5*max(0.,realLDir.y)*LCol)*texture2D(uSampler[4],vec2((sx+1.4)/3., (sz+1.5)/4.)).xyz;
if(rtxoff || final&&abs(sx)<1.5 && abs(sz+.6)<3.)
{
color += groundSpecular.xyz* //specular for ground.
pow(max(0., dot(vec3(-realLDir.x, realLDir.y,-realLDir.z),-W)),groundSpecular.w);
scolor += currentK * color;
}
else
{
for(int k = 0; k < max_stack; ++k)
if(k == next_top){
if(stackswap)
stack2[k] = Ray(S, vec3(W.x, -W.y, W.z), kf_air, currentK * 0.15); //reflection
else
stack1[k] = Ray(S, vec3(W.x, -W.y, W.z), kf_air, currentK * 0.15); //reflection
next_top ++;
break;
}
scolor += (currentK*.85)*color;
}
}
else{
if(j > 0)
scolor += currentK * (pow(max(0.,dot(W, normalize(LDir - V))), 10.) * vec3(3.,3.,3.) + foregroundColor*0.1);
else scolor = foregroundColor*0.6;
}
}
}
if(++curr_ptr >= curr_top){
if(next_top <= 0)
stop = true;
if(next_top * 2 > max_stack)
final = true;
curr_top = next_top;
next_top = 0;
curr_ptr = 0;
stackswap = !stackswap;
}
break;
}
}
if(stop)
break;
}
if(selected)
scolor.x += 0.5;
gl_FragColor=vec4(sqrt(scolor),1.);
}
+16
View File
@@ -0,0 +1,16 @@
attribute vec3 aPos;
varying vec3 trPos;
uniform mat3 transformation;
//I used mat3 instead of the augmented mat4 matrix because we
//are not doing complex projections yet. I implemented simple
//perspective projection back in hw2 by changing focal length
//and adjusting the size of the projected surface accrodingly.
//New surface = distance(surface, old viewpoint)/ distance(surface, new viewpoint) * old surface
// = (deltaFl + fl + 1)/(fl + 1) * old surface
//This is implemented by vPos = (dFl + fl + 1)/(fl + 1) * vPos;
//Because we will multiply the resulting vPos by the transformation matrix
//anyway, I smashed the ratio into the matrix into avoid doing this in shaders.
void main() {
gl_Position = vec4(aPos, 1.);
trPos = transformation *vec3(aPos.xy, -1);
}
+105
View File
@@ -0,0 +1,105 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 906 215" style="enable-background:new 0 0 906 215;" xml:space="preserve">
<style type="text/css">
.st0{fill:#75B943;}
.st1{fill:#1D1E1D;}
.st2{fill:#FFFFFF;}
.st3{fill:#FFFFFF;stroke:#FFFFFF;stroke-miterlimit:10;}
</style>
<rect x="601.61" y="-0.13" class="st0" width="306" height="215"/>
<g id="surface1">
<path class="st0" d="M604.9,214.84H-2.43V0.18h662L604.9,214.84z"/>
<path class="st1" d="M307.9,0.18l-57.16,214.67h341.99L646.9,0.18H307.9z"/>
<path class="st2" d="M323.71,65.38V39.35c0-1.81,0.64-3.35,1.9-4.62c1.27-1.27,2.8-1.91,4.61-1.91h24.72v6.93h-21.79
c-0.54,0-1,0.2-1.38,0.59s-0.57,0.85-0.57,1.37v21.29c0,0.54,0.19,1,0.57,1.37c0.38,0.37,0.84,0.55,1.38,0.55h13.51
c0.54,0,1-0.18,1.39-0.55c0.38-0.38,0.57-0.83,0.57-1.37v-7.29h-9.33v-6.93h16.93v16.61c0,1.77-0.64,3.29-1.91,4.56
c-1.28,1.27-2.82,1.9-4.62,1.9h-19.48c-1.8,0-3.34-0.63-4.61-1.9C324.35,68.67,323.71,67.15,323.71,65.38"/>
<path class="st2" d="M363.69,71.84V32.81h27.34v6.93h-19.75v9.16h15.86v6.93h-15.86v9.08h19.75v6.93"/>
<path class="st2" d="M396.45,71.84V32.81h27.34v6.93h-19.75v9.16h15.86v6.93h-15.86v16.01"/>
<path class="st2" d="M436.14,62.98c0,0.54,0.19,1,0.57,1.37c0.38,0.37,0.84,0.55,1.38,0.55h13.52c0.54,0,1-0.18,1.39-0.55
c0.38-0.38,0.57-0.83,0.57-1.37V41.75c0-0.54-0.19-1.01-0.57-1.41c-0.38-0.4-0.84-0.6-1.39-0.6H438.1c-0.54,0-1,0.2-1.38,0.6
c-0.38,0.4-0.57,0.87-0.57,1.41V62.98z M428.65,65.38V39.35c0-1.81,0.63-3.35,1.89-4.62c1.27-1.27,2.78-1.91,4.54-1.91h19.5
c1.76,0,3.29,0.64,4.55,1.91c1.27,1.28,1.91,2.82,1.91,4.62v26.03c0,1.79-0.63,3.31-1.89,4.57c-1.27,1.26-2.79,1.89-4.57,1.89
h-19.5c-1.79,0-3.3-0.63-4.55-1.89C429.28,68.69,428.65,67.17,428.65,65.38"/>
<path class="st2" d="M475.47,49.02h12.73c0.54,0,1-0.19,1.38-0.57c0.39-0.38,0.57-0.84,0.57-1.38v-5.3c0-0.54-0.19-1.01-0.57-1.41
c-0.38-0.4-0.84-0.6-1.38-0.6h-12.73V49.02z M467.98,71.84V32.82h23.39c1.8,0,3.34,0.64,4.6,1.91c1.27,1.28,1.9,2.82,1.9,4.62
v10.05c0,1.8-0.63,3.35-1.9,4.62c-1.27,1.28-2.8,1.91-4.61,1.91h-0.48l9.55,15.89h-8.16l-9.65-15.89h-7.16v15.89"/>
<path class="st2" d="M504.77,65.38V39.35c0-1.81,0.63-3.35,1.9-4.62c1.27-1.27,2.8-1.91,4.61-1.91h19.5v6.93h-16.56
c-0.54,0-1.01,0.2-1.39,0.59c-0.38,0.39-0.57,0.85-0.57,1.37v21.29c0,0.54,0.19,1,0.57,1.37c0.38,0.37,0.84,0.55,1.39,0.55h16.56
v6.93h-19.5c-1.8,0-3.34-0.63-4.61-1.9C505.4,68.67,504.77,67.15,504.77,65.38"/>
<path class="st2" d="M537.34,71.84V32.81h27.34v6.93h-19.75v9.16h15.86v6.93h-15.86v9.08h19.75v6.93"/>
<path class="st2" d="M573.1,36.84h-0.82V35.3h0.82c1,0,1,0.57,1,0.76C574.1,36.25,574.1,36.84,573.1,36.84 M575.19,36.06
c0-1.14-0.8-1.86-2.09-1.86h-1.91v5.18h1.09v-1.44h0.82c0.05,0,0.1,0,0.15,0l1.05,1.45h1.36l-1.29-1.76
C574.9,37.29,575.19,36.74,575.19,36.06 M573.21,40.68c-2,0-3.63-1.63-3.63-3.64s1.63-3.63,3.63-3.63s3.63,1.63,3.63,3.63
S575.21,40.68,573.21,40.68 M573.21,32.82c-2.33,0-4.23,1.89-4.23,4.23s1.9,4.23,4.23,4.23s4.23-1.9,4.23-4.23
S575.54,32.82,573.21,32.82"/>
<path class="st2" d="M341.65,118.07h30.51c1.3,0,2.41-0.46,3.32-1.37c0.92-0.91,1.38-2.02,1.38-3.31v-12.72
c0-1.29-0.46-2.42-1.38-3.38c-0.91-0.96-2.03-1.44-3.32-1.44h-30.51V118.07z M323.72,172.75v-93.5h56.03
c4.33,0,8.01,1.53,11.04,4.59c3.03,3.05,4.55,6.75,4.55,11.08v24.09c0,4.33-1.52,8.02-4.55,11.08c-3.04,3.05-6.72,4.59-11.05,4.59
h-1.14l22.89,38.08h-19.54l-23.12-38.08h-17.17v38.08"/>
<path class="st2" d="M408.39,95.58V79.25h71.75v16.33h-26.77v77.17h-18.21V95.58"/>
<path class="st2" d="M484.82,172.75l30.99-47.19l-29.18-46.45h21.95l18.47,29.52l18.81-29.52h20.15l-29.52,44.44l31.12,49.2h-21.89
l-20.35-31.93l-20.55,31.93"/>
<path class="st2" d="M221.13,167.89v-1.14h0.73c0.4,0,0.95,0.03,0.95,0.52c0,0.53-0.28,0.62-0.75,0.62H221.13 M221.13,168.7h0.49
l1.14,2h1.25l-1.26-2.09c0.65-0.05,1.19-0.36,1.19-1.23c0-1.09-0.75-1.45-2.03-1.45h-1.84v4.77h1.06V168.7 M226.49,168.33
c0-2.8-2.17-4.42-4.59-4.42c-2.44,0-4.61,1.62-4.61,4.42c0,2.8,2.18,4.43,4.61,4.43C224.32,172.75,226.49,171.12,226.49,168.33
M225.16,168.33c0,2.04-1.5,3.41-3.27,3.41v-0.01c-1.82,0.01-3.29-1.36-3.29-3.39c0-2.04,1.47-3.4,3.29-3.4
C223.67,164.93,225.16,166.29,225.16,168.33"/>
<path class="st2" d="M110.83,137.83l0,33.49h9.46v-33.49H110.83z M36.43,137.78v33.54h9.54v-25.46l7.39,0
c2.45,0,4.2,0.61,5.37,1.87c1.5,1.59,2.11,4.17,2.11,8.87v14.73h9.25v-18.53c0-13.22-8.43-15.01-16.68-15.01H36.43z M126.06,137.83
v33.49h15.34c8.17,0,10.84-1.36,13.73-4.41c2.04-2.14,3.36-6.84,3.36-11.97c0-4.71-1.11-8.91-3.06-11.52
c-3.5-4.68-8.55-5.59-16.09-5.59H126.06z M135.44,145.12h4.06c5.9,0,9.71,2.65,9.71,9.52c0,6.88-3.81,9.53-9.71,9.53h-4.06V145.12z
M97.2,137.83l-7.89,26.54l-7.56-26.54l-10.21,0l10.8,33.49h13.63l10.89-33.49H97.2z M162.88,171.32h9.46v-33.48l-9.46,0V171.32z
M189.4,137.84l-13.21,33.46h9.33l2.09-5.91h15.63l1.97,5.91h10.12l-13.3-33.47L189.4,137.84z M195.54,143.95l5.73,15.68h-11.64"/>
<path class="st2" d="M61.86,71.16c0,0,12.17-17.96,36.47-19.81v-6.52c-26.91,2.16-50.22,24.96-50.22,24.96s13.2,38.16,50.22,41.65
v-6.93C71.16,101.09,61.86,71.16,61.86,71.16"/>
<path class="st2" d="M98.33,90.74v6.34c-20.53-3.66-26.23-25-26.23-25s9.86-10.92,26.23-12.69v6.96c-0.01,0-0.02,0-0.03,0
c-8.59-1.03-15.3,7-15.3,7S86.75,86.86,98.33,90.74"/>
<path class="st2" d="M98.33,32.81v12.02c0.79-0.06,1.58-0.11,2.38-0.14c30.6-1.03,50.54,25.1,50.54,25.1s-22.9,27.84-46.75,27.84
c-2.19,0-4.23-0.21-6.16-0.54v7.43c1.64,0.21,3.35,0.33,5.13,0.33c22.2,0,38.25-11.34,53.8-24.75c2.58,2.07,13.13,7.09,15.3,9.28
c-14.78,12.38-49.23,22.35-68.75,22.35c-1.88,0-3.69-0.11-5.47-0.29v10.44h84.38V32.81"/>
<path class="st2" d="M98.33,59.39v-8.05c0.78-0.05,1.57-0.1,2.38-0.12c22-0.69,36.44,18.91,36.44,18.91s-15.59,21.65-32.31,21.65
c-2.41,0-4.56-0.38-6.5-1.04V66.35c8.57,1.04,10.29,4.82,15.44,13.4l11.46-9.66c0,0-8.36-10.96-22.46-10.96
C101.23,59.12,99.76,59.23,98.33,59.39"/>
</g>
<g>
<path class="st3" d="M768.65,113.4c0,32.02-19.46,48.99-43.19,48.99c-24.56,0-41.81-19.04-41.81-47.2
c0-29.53,18.35-48.85,43.19-48.85C752.22,66.34,768.65,85.8,768.65,113.4z M696.47,114.92c0,19.87,10.76,37.67,29.67,37.67
c19.04,0,29.81-17.53,29.81-38.64c0-18.49-9.66-37.81-29.67-37.81C706.41,76.14,696.47,94.49,696.47,114.92z"/>
<path class="st3" d="M784.24,160.87V67.86h13.11l29.81,47.06c6.9,10.9,12.28,20.7,16.7,30.22l0.28-0.14
c-1.1-12.42-1.38-23.74-1.38-38.23V67.86h11.32v93.01h-12.14l-29.53-47.2c-6.49-10.35-12.7-20.98-17.39-31.05l-0.41,0.14
c0.69,11.73,0.97,22.91,0.97,38.36v39.74H784.24z"/>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.7 KiB

+111
View File
@@ -0,0 +1,111 @@
<!--<video src="pjsk.mp4" id="pjsk" muted="muted" loop="true" style="position:fixed; left:0; top:0;max-width:100%;min-width:100%;min-height: 100%;z-index: -100;"></video>!-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ext-language_tools.js" crossorigin="anonymous"></script>
<script src=lib4.header.js></script>
<script src=lib4.js></script>
<style>
.ace_gutter-layer {
/* original width is 48px */
width: 25px !important;
}
.ace_gutter-layer > * {
/* 48 - 32 = 16 */
margin-left: 0;
}
.ace_gutter-cell {
padding-left: 0 !important;
padding-right: 3px !important;
}
.code{
font-family: "monaco, menlo, ubuntu mono, consolas, source-code-pro" ;
}
</style>
<!!-------- VERTEX SHADER: YOU PROBABLY DON'T WANT TO CHANGE THIS RIGHT NOW -------->
<!!-------- FRAGMENT SHADER: THIS IS WHERE YOU WILL DO YOUR WORK -------->
<!!-------- FRAGMENT SHADER: MOVED TO ./shader.frag!! LOADED IN lib2.js -------->
<font size=7 color=#909090>
Space Walk
<img id="rtx" style="float:right;" src="./RTXon.svg" type="image/svg+xml"
alt="Turn Ray Tracing On/OFF" title="Turn Ray Tracing On/OFF" height=60px /img>
<div id="fps" style="font-size:25;float:right;margin-right:18px;"></div>
<TABLE cellspacing=0 cellpadding=0><TR>
<td><font color=red size=5><div id=errorMessage></div></font></td>
</TR><TR>
<table cellspacing=0>
<tr>
<td valign=top>
<div id="ace" style="opacity:90%;width:800px;height:2200px;"></div>
</td><td valign=top style="background-color:azure;opacity: 95%;">
<body bgcolor=white text=black link=black alink=blue vlink=blue>
<center>
<!!--- SUPER SAMPLING THE W/H PARAMS FOR CANVAS ARE RENDER SIZE, IN THE CSS IS ACTUAL(DISPLAY) SIZE.--->
<canvas id='canvas1' style=" overflow: hidden !important; width: 600px !important; height:600px !important;" width=599 height=599></canvas>
</center>
</body>
<div id="controls">
<input type="number" id="ins" style="margin-left:0px;font-size:24px;width:35px;height:45px" value="5" max="5" min = "1">
<button id="bns" style="margin-left:0px;font-size:24px;width:105px;height:45px">Spheres</button>
<input type="number" id="insamp" style="margin-left:2px;font-size:24px;width:60px;height:45px" value="1" max="4" min = "0.25" step="0.2">
<button id="bnsamp" style="margin-left:0px;font-size:24px;width:190px;height:45px">Super Sampling</button>
<button id="bnfs" style="margin-left:2px;font-size:24px;width:180px;height:45px">Fullscreen</button>
<button id="clrsel" style="margin-left:0px;font-size:24px;width:180px;height:45px">Clear Selection</button>
<button id="reset" style="margin-left:0px;font-size:24px;width:100px;height:45px">Reset</button>
<button id="mov" style="margin-left:0px;font-size:24px;width:280px;height:45px">Move Lighting & Texture</button>
<div style='font-size:25px;'>
<font color=#909090>
<i style="font-size:25px;">What's new: </i>
<p style="font-size:20px;">
&nbsp;&nbsp;&nbsp;&nbsp;I created a little figure that can walk. First, press "Fullscreen" button. In fullscreen mode, <a style="font-size:25px;color:red;"><strong>the figure is able to walk
in four directions when pressing corresponding arrow keys.</strong></a><br>
&nbsp;&nbsp;&nbsp;&nbsp; I added normal calculation to every shape I created and then I added phong shading to the scene. <br>
&nbsp;&nbsp;&nbsp;&nbsp; As before, you can rotate the scene by dragging on the canvas.<br>
&nbsp;&nbsp;&nbsp;&nbsp;I added new shapes such as torus and cubes.</strong><br>
&nbsp;&nbsp;&nbsp;&nbsp;<strong>If you found the scene somehow clipped, it seems to be a bug of chromium, please simply click on 'Super Sampling' button
or refresh the page. .</strong>
</p>
<div id="howitworks">
<br>
<i style="font-size:25px;">How it works:</i><br>
<p style="font-size:20px;">
I used the matrix stack to push and pop transformations to create the figure and move it around. The entire scene is then transformed to apply movements and global rotations.<br>
The mesh creation functions and transformation methods are implemented in <a href="./lib4.header.js">lib4.header.js</a><br>
Animating function and are in <a href="./lib4.ext.js">lib4.ext.js</a><br>
<a href="./shader.vert">shader.vert</a> is the vertex shader.<br>
<a href="./lib4.js">lib4.js</a> most contains initialization methods for the renderer. You can also see how I passes more attributes like surface normal and
object id to the shaders.<br>
<a href="./index.html">index.html</a> is almost pure html.<br>
</p>
</div>
<p>
</div>
</div></td>
</tr></table>
</TR></TABLE>
<!!-------- YOU PROBABLY WANT TO CHANGE ANYTHING BELOW RIGHT NOW -------->
<script src="lib4.ext.js"></script>
<script>
setInterval(() => {
if(window.vs != null && window.fs != null&& canvas1.setShaders === undefined)
gl_start(canvas1, vs, fs);
}, 200);
</script>
+593
View File
@@ -0,0 +1,593 @@
let ctrl = false, alt = false, shift = false, fpson = true, moving = false, over = false;
let lastClick = undefined;
let animating = true;
let flags = 0x0;
var startTime = Date.now();
let lastTime = Date.now();
var lastFrameTime = 0;
let oldDocument;
let fullscreen = false, btntoggled = false;
let movescene = true;
let oldparents = {};
var tr, div;
let canvas_originalsize;
let Sph = [];
let SphTr = [];
let SphDletaR = []
let selected = false, selection = -1, dragging = false;
let overall_trans = matrix_identity();
let rebuild = true, presentation = true, sRotation = matrix_identity();
let facing = 1, running = 0;
for(let i = 0; i < ns; ++i)
{
SphTr[i]=matrix_identity();
SphDletaR[i] = 0;
}
function toggleFullscreen(element){
if(fullscreen)
{
if (document.exitFullscreen)
document.exitFullscreen();
else if (document.webkitExitFullscreen)
document.webkitExitFullscreen();
else if (document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.msExitFullscreen)
document.msExitFullscreen();
fullscreen = false;
bnfs.innerText = "Fullscreen";
}
else{
if(element.requestFullscreen)
element.requestFullscreen();
else if (element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
else if(element.msRequestFullscreen)
element.msRequestFullscreen();
fullscreen = true;
bnfs.innerText = "Exit Fullscreen";
}
}
bnfs.onclick = function(e){
if(e === "no")
;
else
btntoggled = true;
if(fullscreen){
oldparents[controls].appendChild(controls);
oldparents[canvas1].appendChild(canvas1);
canvas1.style.width = canvas_originalsize[0];
canvas1.style.height = canvas_originalsize[1];
howitworks.hidden = false;
}else{
div = document.createElement("div");
tr = document.createElement("table").insertRow();
tr.style.backgroundColor="white";
let size = Math.min(screen.availHeight, screen.availWidth);
canvas_originalsize = [canvas1.style.width, canvas1.style.height, canvas1.width, canvas1.height];
canvas1.style.height = canvas1.style.width = size;
howitworks.hidden=true;
oldparents[controls] = controls.parentNode;
oldparents[canvas1] = canvas1.parentNode;
let td1 = tr.insertCell();
td1.appendChild(canvas1);
let td2;
td2 = tr.insertCell();
td2.style.verticalAlign="top";
td2.appendChild(controls);
div.appendChild(tr);
document.body.appendChild(div);
}
toggleFullscreen(div);
}
mov.onclick=function(_){
movescene = !movescene;
if(!movescene)
{
mov.innerText= "Move Scene";
mov.style.width = "170px";
}
else
{
mov.innerText = "Move Lighting&Texture";
mov.style.width = "280px";
}
}
document.addEventListener("webkitfullscreenchange", ()=>{if(!btntoggled && fullscreen)bnfs.onclick("no");btntoggled = false;});
document.addEventListener("fullscreenchange", ()=>{if(!btntoggled && fullscreen)bnfs.onclick("no");btntoggled = false;});
clrsel.onclick=function(_){
setUniform("1i", "sel", -1);
selected = false;
selection = -1;
}
reset.onclick = function(_){
clrsel.onclick();
if(!animating)
pause_resume();
flags = 0;
moving = false;
mousedx = mousedy = mousedz = 0;
positionsupdated = true;
for(let i = 0; i < ns; ++i)
{
SphTr[i]=matrix_identity();
SphDletaR[i] = 0;
}
rtx.src='./RTXon.svg';
setUniform('1i', 'flags', flags);
}
bns.onclick=function(e){
if(ins.value>0 &&ins.value<=ns &&cns!=ins.value)
{
cns = ins.value;
fragmentShaderDefs = '\n const int cns = ' + cns + ';';
if(typeof canvas1.setShaders === "function")
canvas1.setShaders(vs, editor.getSession().getValue());
}
}
bnsamp.onclick=function(e){
let multiplier = insamp.value;
let w = parseInt(canvas1.style.width)*multiplier;
let h = parseInt(canvas1.style.height)*multiplier;
canvas1.height = h;
canvas1.width = w;
gl.viewport(0, 0, w, h);
//gl.clearRect(0, 0, w, h);
}
// SET UP THE EDITABLE TEXT AREA ON THE LEFT SIDE.
ace.require("ace/ext/language_tools");
var editor = ace.edit("ace", {
mode:"ace/mode/glsl",
theme:"ace/theme/crimson_editor"
});
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true,
fontSize: 14,
fontFamily: "monaco, menlo, ubuntu mono, consolas, source-code-pro",
fixedWidthGutter: true,
showGutter: true,
showPrintMargin: false,
});
editor.setAutoScrollEditorIntoView(true);
if(fs != undefined)
editor.getSession().setValue(fs);
editor.session.on('change', function(delta) {
if(typeof canvas1.setShaders === "function")
{
canvas1.setShaders(vs, editor.getSession().getValue());
setUniform('1i', 'flags', flags);
}
});
// REPARSE THE SHADER PROGRAM AFTER EVERY KEYSTROKE.
delete editor.KeyBinding;
let pause_resume = function(){
if(animating)
lastTime = Date.now();
else
startTime += Date.now() - lastTime;
animating = !animating;
};
canvas1.addEventListener('click',function(ev){
if(!(shift && alt) && lastClick&& Date.now()-lastClick<400)
pause_resume();
lastClick = Date.now();
});
canvas1.addEventListener('mouseover', function(e){
over = true;
const mask = 0x8;
flags |= mask;
setUniform('1i', 'flags', flags);
});
canvas1.addEventListener('mousedown', function(e){
moving = true
mouselastX = mouselastY = undefined;
let i = hitTest([2*e.offsetX/ parseInt(canvas1.style.width)-1,
1-2*e.offsetY/ parseInt(canvas1.style.height), -1]);
if(i >= 0)
{
dragging = true;
selected = true;
setUniform("1i", "sel", i);
selection = i;
}
else if(selected = true){
dragging = false;
selected = false;
setUniform("1i", "sel", i);
selection = i;
}
});
canvas1.addEventListener('mousemove', function(e){
if(!(mouselastX==undefined || mouselastY == undefined)&&moving){
let dx = (mouselastX - e.offsetX),
dy = (mouselastY - e.offsetY);
if(movescene){
sRotation = matrix_multiply(sRotation, matrix_rotateY(-dy/60));
sRotation = matrix_multiply(sRotation, matrix_rotateX(-dx/60));
}
else if(!selected)
{
mousedx -= dx/60;
mousedy -= dy/60;
positionsupdated = true;
}else if(dragging){
let m = matrix_rotateY(-mousedx);
m = matrix_multiply(m, matrix_rotateX(-mousedy));
let dv = matrix_multiply(m, [2*-dx/ parseInt(canvas1.style.width),
2*dy/ parseInt(canvas1.style.height), 0, 1]).slice(0,3);
SphTr[selection] = matrix_multiply(SphTr[selection], matrix_translate(dv[0], dv[1], dv[2]));
}
}
mouselastX = e.offsetX;
mouselastY = e.offsetY;
});
canvas1.addEventListener('mouseup', function(e){
moving = false;
dragging = false;
});
canvas1.addEventListener('mouseout', function(e){
const mask = 0x8;
flags &= !mask;
setUniform('1i', 'flags', flags);
over = false;
moving = false;
});
canvas1.addEventListener('wheel', function(e){
if(!selected){
mousedz += e.wheelDelta/600;
positionsupdated = true;
}
else{
SphDletaR[selection] += e.wheelDelta / 800;
}
});
canvas1.scroll(function(e) {e.stopPropagation();});
rtx.style.cursor="pointer";
let rtswitch = function(){
alert('Ray Tracing is always on. See hw2 where rt can be toggled on/off.')
rtx.src='./RTXon.svg';
}
rtx.addEventListener('click', rtswitch);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
let fpscounter = function(time){
if (start === undefined)
start = time;
else
fps.innerHTML = Math.round(10000/(time-start))/10 + ' fps';
start = time;
if(fpson)
;//requestAnimationFrame(fpscounter);
else{
start = undefined;
fps.innerHTML = '';
}
};
document.addEventListener('keydown',(e)=>{
if(e.code.startsWith('Shift'))
shift = true;
if(e.code.startsWith('Control'))
ctrl = true;
if(e.code.startsWith('Alt'))
alt = true;
else if(ctrl && alt && e.code == 'KeyT'){
const mask = 0x1;
flags = flags&!mask | (!(flags&mask)?mask:0);
setUniform('1i', 'flags', flags);
}
else if (ctrl &&e.code == 'KeyS'){
let a = document.createElement('a');
a.href = "data:text/plain,"+encodeURIComponent(editor.getSession().getValue());
a.download = 'shader.frag';
a.click();
}
else if(ctrl && alt&&e.code == 'KeyR')
rtswitch();
else if(ctrl && alt&&e.code == 'KeyN')
{
reset.onclick();
}
else if(ctrl && alt&&e.code == 'KeyP')
pause_resume();
else if(ctrl && alt&&e.code == 'KeyF')
if(!fpson)
{
fpson = true;
requestAnimationFrame(fpscounter);
}
else
fpson = false;
if(e.code == 'ArrowUp' || e.code == 'ArrowDown' || e.code =='ArrowLeft'
||e.code == 'ArrowRight' || e.code =='KeyW'||e.code =='KeyS')
{
switch(e.code){
case 'ArrowUp':
facing = -2;
break;
case 'ArrowDown':
facing = 2;
break;
case 'ArrowLeft':
facing = -1;
break;
case 'ArrowRight':
facing = 1;
break;
case 'KeyW':
break;
case 'KeyS':
break;
}
running = 20;
rebuild = true;
}
if(fullscreen && selected ){
if(e.code =='KeyF'||e.code =='KeyB'){
let m = matrix_rotateY(-mousedx);
m = matrix_multiply(m, matrix_rotateX(-mousedy));
m = const_multiply((fl + 1 + mousedz)/(fl+1), m);
switch(e.code){
case 'KeyB':
var dv = matrix_multiply(m, [0,0, -0.1, 1]).slice(0,3);
m = matrix_translate(dv[0], dv[1], dv[2]);
break;
case 'KeyF':
var dv = matrix_multiply(m, [0,0, 0.1, 1]).slice(0,3);
m = matrix_translate(dv[0], dv[1], dv[2]);
break;
}
SphTr[selection] = matrix_multiply(SphTr[selection], m);
}
}
});
document.addEventListener('keyup',(e)=>{
if(e.code.startsWith('Control'))
ctrl = false;
if(e.code.startsWith('Alt'))
alt = false;
if(e.code.startsWith('Shift'))
shift = false;
});
let squareMesh = new Float32Array([ -1,-1,1,0,0,0,0,0,-1, 1,1,0,0,0,0,0,-1, -1,-1,0,0,0,0,0, -1,1,-1,0 ,0,0,0,0]);
let sphereMesh = createMesh(32, 32, uvToSphere);
let tubeMesh = createMesh(32, 2, uvToTube,0,1);
let diskMesh = createMesh(32, 2, uvToDisk,0,1);
let tubeMesh2 = createMesh(32, 2, uvToTube,0,2);
let diskNMesh2 = createMesh(32, 2, uvToDisk, -1,2);
let diskPMesh2 = createMesh(32, 2, uvToDisk, 1,2);
let tubeMesh3 = createMesh(32, 2, uvToTube,0,3);
let diskNMesh3 = createMesh(32, 2, uvToDisk, -1,3);
let diskPMesh3 = createMesh(32, 2, uvToDisk, 1,3);
let diskNMesh = createMesh(32, 2, uvToDisk, -1,1);
let diskPMesh = createMesh(32, 2, uvToDisk, 1,1);
let cylinderMesh = glueMeshes(glueMeshes(tubeMesh, diskPMesh), diskNMesh);
let cylinderMesh2 = glueMeshes(glueMeshes(tubeMesh2, diskPMesh2), diskNMesh2);
let cylinderMesh3 = glueMeshes(glueMeshes(tubeMesh3, diskPMesh3), diskNMesh3);
let torusMash = createMesh(32, 32, uvToTorus, 1, 5);
let head = createCube(1.5,1,1, 4);
let objects = [];
let addObject = (obj, mat) => {
objects.push([obj, mat]);
};
let clearObject = () => {delete objects; objects = [];};
let delta_height = 0, delta_l = [0,0];
class State{
constructor() {
this.leg = true;
this.progress = 0;
this.rh = this.lh = .5*pi;
this.lf = this.rf = 0;
}
initialize(){
this.leg = true;
this.progress = 0;
}
next(){
//return this.presentation();
if(running <= 0)
return {rh:.5*pi, lh:.5*pi, rf:0, lf:0, dh:0,dl:0}
running --;
const steps = 100;
let dl = 0;
if(this.progress >= steps/2)
{
this.progress = 0;
this.leg = !this.leg;
}
let delta = [-pi/5, 0.5*pi, 0.44*pi, 0.55*pi];
for (let i = 0; i < 4; ++i) delta[i] /= steps;
if(this.leg)
{
if(this.progress < steps/4)
{
this.lh += delta[0];
this.rh += delta[3];
this.lf += delta[1];
this.rf += delta[2];
}
else{
this.lh -= delta[0];
this.rh -= delta[3];
this.lf -= delta[1];
this.rf-= delta[2];
}
}
else{
if(this.progress < steps/4)
{
this.lh += delta[3];
this.rh += delta[0];
this.lf += delta[2];
this.rf += delta[1];
}
else{
this.lh -= delta[3];
this.rh -= delta[0];
this.lf -= delta[2];
this.rf-= delta[1];
}
}
let delta_h = Math.max((1-cos(abs(this.lh - pi/2)))*.5+(1-cos(abs(this.lf)))*.6,(1-cos(abs(this.rh - pi/2)))*.5+(1-cos(abs(this.rf)))*.6);
this.progress++;
return {lh:this.lh, lf:this.lf, rh:this.rh,rf:this.rf, dh:delta_h, dl:1.8522/steps};
}
// presentation(){
// return {lh:.4*pi, lf:pi/6,rh:.7*pi, rf:pi/8, dh:0};
// }
};
let build_objects = (state)=>{
if(running === 0)
rebuild = false;
let {lh, lf, rh, rf, dh, dl} = state.next();
delta_l[abs(facing)-1] += 0.3* Math.sign(facing) * dl;
delta_height = dh;
clearObject();
M.save();
M.save();
M.rotateX(pi/2);
M.scale(0.5, 0.5, 1);
addObject(cylinderMesh, M.value());
M.restore();
M.save();
M.translate(0,1,0);
addObject(head, M.value());
M.restore();
M.save();
M.translate(0.5, 0.2, 0.3);
M.rotateX(pi/4);
M.translate(0,0,.5);
M.save();
M.translate(0,0,.4);
M.rotateX(-0.53*pi);
M.scale(0.2, 0.2, 0.4);
M.translate(0,0,1);
addObject(cylinderMesh2, M.value());
M.restore();
M.scale(0.2, 0.2, 0.5);
addObject(cylinderMesh2, M.value());
M.restore();
M.save();
M.translate(-0.5, 0.2, 0.3);
M.rotateX(pi/4);
M.translate(0,0,.5);
M.save();
M.translate(0,0,.4);
M.rotateX(-0.55*pi);
M.scale(0.2, 0.2, 0.4);
M.translate(0,0,1);
addObject(cylinderMesh2, M.value());
M.restore();
M.scale(0.2, 0.2, 0.5);
addObject(cylinderMesh2, M.value());
M.restore();
M.save();
M.translate(0.3, -1, 0.);
M.rotateX(lh);
M.translate(0,0,.5);
M.save();
M.translate(0,0,.45);
M.rotateX(lf);
M.scale(0.2, 0.2, 0.6);
M.translate(0,0,1);
addObject(cylinderMesh3, M.value());
M.restore();
M.scale(0.2, 0.2, 0.5);
addObject(cylinderMesh3, M.value());
M.restore();
M.save();
M.translate(-0.3, -1, 0.);
M.rotateX(rh);
M.translate(0,0,.5);
M.save();
M.translate(0,0,.45);
M.rotateX(rf);
M.scale(0.2, 0.2, 0.6);
M.translate(0,0,1);
addObject(cylinderMesh3, M.value());
M.restore();
M.scale(0.2, 0.2, 0.5);
addObject(cylinderMesh3, M.value());
M.restore();
M.restore();
//rebuild = false;
};
let state = new State();
var M = new Matrix();
function animate(gl) {
let uTime;
if(animating)
{
uTime = (Date.now() - startTime) / 1000;
setUniform('1f', 'uTime', uTime);
}
else
{
uTime = (lastTime - startTime) / 1000;
setUniform('1f', 'uTime', uTime);
}
Sph[0] = [0,0.05*Math.cos(uTime + 1.),.045*Math.cos(uTime), 1,.15];
Sph[1] = [0,0,0,1,.25];
Sph[2] = [.22*Math.sin(uTime*1.2),0.05,.22*Math.cos(uTime*1.2),1,.05];
Sph[3] = [.9*Math.sin(uTime*.4),0.,.9*Math.cos(uTime*.4),1,.25];
Sph[4] = [0.5*Math.sin(uTime*1.),0.08*Math.sin(uTime *0.9),.5*Math.cos(uTime*1.),1,.12];
for(let i = 0; i < ns; ++ i)
{
let trsph = matrix_multiply(SphTr[i], Sph[i]);
trsph[3] = Sph[i][4];
setUniform('4fv', 'Sph['+ i + ']', trsph);
}
if(presentation){
M.save();
M.scale(0.3);
M.rotateY(uTime/5);
M.rotateX(1);
M.translate(delta_l[0], -delta_height, delta_l[1]);
if(facing !=2)
M.rotateY(pi*(facing/2));
//M.translate(0, -delta_height, 0);
overall_trans = M.value();
M.restore();
}else{
M.save();
// M.rotateY(2);
M.rotateX(1);
M.scale(0.3);
M.translate(delta_l[0], -delta_height, delta_l[1]);
overall_trans = M.value();
M.restore();
}
if(rebuild)
build_objects(state);
for(const [obj, mat] of objects){
drawMesh(obj, matrix_multiply(sRotation,matrix_multiply(overall_trans, mat)));
}
M.save();
M.scale(0.1);
M.translate(6,0,1);
M.rotateX(1);
M.rotateY(uTime/4);
drawMesh(torusMash, M.value());
M.restore();
if(positionsupdated)
updatePositions();
}
requestAnimationFrame(fpscounter);
//pjsk.play();
+332
View File
@@ -0,0 +1,332 @@
//Header file, contains global variable definitions,
// asynchronized shader loading and utility functions
var mousedx = 0, mousedy = 0, mousedz = 0;
let seldx = 0, seldy = 0, seldz = 0;
var enableSelection = false;
var cx = 1, cy = 1, sx = 0, sy = 0;
var mouselastX, mouselastY;
const fl = 3;
let start;
var vs, fs;
var vsfetch = new XMLHttpRequest();
var editor = undefined
var cos = Math.cos, sin = Math.sin, tan = Math.tan,
acos = Math.acos, asin = Math.asin, atan = Math.atan,
sqrt = Math.sqrt, pi = Math.PI, abs = Math.abs;
var positionsupdated = true;
vsfetch.open('GET', './shader.vert');
vsfetch.onloadend = function () {
vs = vsfetch.responseText;
};
vsfetch.send();
//* LOADING FRAGMENT SHADER
var client = new XMLHttpRequest();
client.open('GET', './shader.frag');
client.onloadend = function () {
fs = (client.responseText);
//* START EVERYTHING AFTER FRAGMENT SHADER IS DOWNLOADED.
if (editor != undefined)
editor.getSession().setValue(fs);
};
client.send();
// I HAVE IMPLEMENTED THESE FUNCTIONS FOR YOU
let matrix_identity = () => {
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
let matrix_translate = (x, y, z) => {
let m = matrix_identity();
m[12] = x;
m[13] = y;
m[14] = z;
return m;
}
// YOU NEED TO PROPERLY IMPLEMENT THE FOLLOWING FIVE FUNCTIONS:
let matrix_rotateX = theta => {
let m = matrix_identity();
m[5] = cos(theta);
m[6] = sin(theta);
m[9] = -sin(theta);
m[10] = cos(theta);
return m;
}
let matrix_rotateY = theta => {
let m = matrix_identity();
m[0] = cos(theta);
m[2] = -sin(theta);
m[8] = sin(theta);
m[10] = cos(theta);
return m;
}
let matrix_rotateZ= theta => {
let m = matrix_identity();
m[0] = cos(theta);
m[1] = sin(theta);
m[4] = -sin(theta);
m[5] = cos(theta);
return m;
}
let matrix_scale = (x, y, z) => {
if (y === undefined)
y = z = x;
let m = matrix_identity();
m[0] = x;
m[5] = y;
m[10] = z;
return m;
}
let matrix_multiply = (a, b, m = 4, n = 4) => { //dim=mn*nm=mm
let res = [];
if (b.length < m*n) { //mat-vec multiply (i did this for my convenience)
for (let i = 0; i < m; ++i) {
res[i] = 0;
for (let j = 0; j < n; ++j)
res[i] += b[j] * a[m * j + i];
}
return res;
} //otherwise mm multiply
for (let i = 0; i < m; ++i)
for (let j = 0; j < m; ++j) {
var t = 0;
for (let k = 0; k < n; ++k)
t += a[k * m + j] * b[i * n + k];
res.push(t);
}
return res;
}
let const_multiply = (c, a) => {
let m = [];
for(let i = 0; i < a.length; ++ i)
m[i] = a[i] * c;
return m;
}
function dot(a, b){
let m = 0;
for(let i = 0; i < a.length; ++i)
m += a[i] * b[i];
return m;
}
function plus(a, b){
let m = [];
for(let i = 0; i < a.length; ++i)
m[i] = a[i] + b[i];
return m;
}
function minus(a, b){
let m = [];
for(let i = 0; i < a.length; ++i)
m[i] = a[i] - b[i];
return m;
}
function normalize(v){
let res = [];
sum = 0;
for(let i = 0; i < v.length; ++ i)
sum += v[i] * v[i];
sum = sqrt(sum);
for(let i = 0; i < v.length; ++ i)
res[i] = v[i] / sum;
return res;
}
let Matrix = function() {
let top = 0, m = [ matrix_identity() ];
this.identity = () => m[top] = matrix_identity();
this.translate = (x,y,z) => m[top] = matrix_multiply(m[top], matrix_translate(x,y,z));
this.rotateX = theta => m[top] = matrix_multiply(m[top], matrix_rotateX(theta));
this.rotateY = theta => m[top] = matrix_multiply(m[top], matrix_rotateY(theta));
this.rotateZ = theta => m[top] = matrix_multiply(m[top], matrix_rotateZ(theta));
this.scale = (x,y,z) => m[top] = matrix_multiply(m[top], matrix_scale(x,y,z));
this.value = () => m[top];
this.save = () => { m[top+1] = m[top].slice(); top++; }
this.restore = () => --top;
}
//------ CREATING MESH SHAPES
// CREATE A MESH FROM A PARAMETRIC FUNCTION
let createMesh = (nu, nv, f, data, oid = 0) => {
let tmp = [];
for (let v = 0 ; v < 1 ; v += 1/nv) {
for (let u = 0 ; u <= 1 ; u += 1/nu) {
tmp = tmp.concat(f(u,v,oid,data));
tmp = tmp.concat(f(u,v+1/nv,oid,data));
}
tmp = tmp.concat(f(1,v,oid,data));
tmp = tmp.concat(f(0,v+1/nv,oid,data));
}
return new Float32Array(tmp);
}
// GLUE TWO MESHES TOGETHER INTO A SINGLE MESH
let glueMeshes = (a, b) => {
let c = [];
for (let i = 0 ; i < a.length ; i++)
c.push(a[i]); // a
for (let i = 0 ; i < VERTEX_SIZE ; i++)
c.push(a[a.length - VERTEX_SIZE + i]); // + last vertex of a
for (let i = 0 ; i < VERTEX_SIZE ; i++)
c.push(b[i]); // + first vertex of b
for (let i = 0 ; i < b.length ; i++)
c.push(b[i]); // + b
return new Float32Array(c);
}
let uvToSphere = (u,v, i) => {
let theta = 2 * Math.PI * u;
let phi = Math.PI * (v - .5);
let x = Math.cos(theta) * Math.cos(phi);
let y = Math.sin(theta) * Math.cos(phi);
let z = Math.sin(phi);
return [i, x,y,z].concat(normalize([x, y, z]));
}
let uvToTube = (u,v,i) => {
let theta = 2 * Math.PI * u;
let x = Math.cos(theta);
let y = Math.sin(theta);
let z = 2 * v - 1;
return [i,x,y,z].concat(normalize([x,y,0]));
}
let uvToDisk = (u,v,i,dz) => {
if (dz === undefined)
dz = 0;
let theta = 2 * Math.PI * u;
let x = Math.cos(theta) * v;
let y = Math.sin(theta) * v;
let z = dz;
return [i,x,y,z].concat([0,0,Math.sign(z)]);
}
let uvToTorus = (u,v,i,r) => {
let theta = 2 * pi;
let phi = theta * v;
theta *= u;
let x = 1 + r * cos(phi);
let y = sin(theta)*x;
x *=cos(theta);
let z = r * sin(phi);
let tx = -sin(theta), ty = cos(theta),tsx = sin(phi), tsy = tsx*tx, tsz = cos(phi);
tsx*=-ty;
return [i,x, y, z].concat(normalize([ty*tsz*0.5, -tx*tsz, tx*tsy-ty*tsx]));
}
let createCube = (w, h, l,id) => {
let mesh = [];
mesh=mesh.concat([id, -w/2,-h/2,-l/2,0,-1,0]);
mesh=mesh.concat([id, -w/2,-h/2,l/2,0,-1,0]);
mesh=mesh.concat([id, w/2,-h/2,-l/2,0,-1,0]);
mesh=mesh.concat([id, w/2,-h/2,l/2,0,-1,0]);
mesh=mesh.concat([id, w/2,-h/2,l/2,0,-1,0]);
mesh=mesh.concat([id, w/2,-h/2,l/2,0,0,1]);
mesh=mesh.concat([id, w/2,-h/2,l/2,0,0,1]);
mesh=mesh.concat([id, w/2,h/2,l/2,0,0,1]);
mesh=mesh.concat([id, -w/2,-h/2,l/2,0,0,1]);
mesh=mesh.concat([id, -w/2,h/2,l/2,0,0,1]);
mesh=mesh.concat([id, -w/2,h/2,l/2,0,0,1]);
mesh=mesh.concat([id, -w/2,h/2,l/2,-1,0,0]);
mesh=mesh.concat([id, -w/2,h/2,l/2,-1,0,0]);
mesh=mesh.concat([id, -w/2,-h/2,l/2,-1,0,0]);
mesh=mesh.concat([id, -w/2,h/2,-l/2,-1,0,0]);
mesh=mesh.concat([id, -w/2,-h/2,-l/2,-1,0,0]);
mesh=mesh.concat([id, -w/2,-h/2,-l/2,-1,0,0]);
mesh=mesh.concat([id, -w/2,-h/2,-l/2,0,0,-1]);
mesh=mesh.concat([id, -w/2,-h/2,-l/2,0,0,-1]);
mesh=mesh.concat([id, -w/2,h/2,-l/2,0,0,-1]);
mesh=mesh.concat([id, w/2,-h/2,-l/2,0,0,-1]);
mesh=mesh.concat([id, w/2,h/2,-l/2,0,0,-1]);
mesh=mesh.concat([id, w/2,h/2,-l/2,0,0,-1]);
mesh=mesh.concat([id, w/2,h/2,-l/2,1,0,0]);
mesh=mesh.concat([id, w/2,h/2,-l/2,1,0,0]);
mesh=mesh.concat([id, w/2,h/2,l/2,1,0,0]);
mesh=mesh.concat([id, w/2,-h/2,-l/2,1,0,0]);
mesh=mesh.concat([id, w/2,-h/2,l/2,1,0,0]);
mesh=mesh.concat([id, w/2,-h/2,l/2,1,0,0]);
mesh=mesh.concat([id, w/2,h/2,l/2,0,1,0]);
mesh=mesh.concat([id, w/2,h/2,l/2,0,1,0]);
mesh=mesh.concat([id, w/2,h/2,-l/2,0,1,0]);
mesh=mesh.concat([id, -w/2,h/2,l/2,0,1,0]);
mesh=mesh.concat([id, -w/2,h/2,-l/2,0,1,0]);
return new Float32Array(mesh);
// let verts = [];
// for(let i = -w/2; i < w; i += w)
// for(let j = -h/2; j < h; j += h)
// for (let k = -l/2; k < l; k += l)
// verts.push([id, i, j, k]);
// let mesh = [];
// let n = 0;
// for(let j = 0; j < 4; ++ j)
// mesh = mesh.concat(verts[j]);
// for(let i = 0; i < 2; ++ i)
// for(let j = 0; j < 2; ++ j)
// mesh = mesh.concat(verts[6 - i*2 + j]);
// for(let j = 0; j < 2; ++ j)
// mesh = mesh.concat(verts[j]);
// mesh = mesh.concat(verts[5]);
// mesh = mesh.concat(verts[3]);
// mesh = mesh.concat(verts[7]);
// mesh = mesh.concat(verts[7]);
// mesh = mesh.concat(verts[6]);
// mesh = mesh.concat(verts[6]);
// mesh = mesh.concat(verts[4]);
// mesh = mesh.concat(verts[2]);
// mesh = mesh.concat(verts[0]);
// return new Float32Array(mesh);
//CREATING CUBES THIS WAY REDUCES VERTICES BUT MAKES IT HARDER TO DO LIGHTING
}
function updatePositions() {
let m = matrix_rotateY(-mousedx);
m = matrix_multiply(m, matrix_rotateX(-mousedy));
setUniform('3f', 'V0', m[8] * (fl + mousedz), m[9] * (fl + mousedz), m[10] * (fl + mousedz));
m = const_multiply((fl + 1 + mousedz)/(fl+1), m);
setUniform('Matrix3fv', 'transformation', false, [m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]]);
positionsupdated = false;
}
function hitTest(pos){
if(!enableSelection)
return -1;
let m = matrix_rotateY(-mousedx);
m = matrix_multiply(m, matrix_rotateX(-mousedy));
let V = [m[8] * (fl + mousedz), m[9] * (fl + mousedz), m[10] * (fl + mousedz)];
m = const_multiply((fl + 1 + mousedz)/(fl+1), m);
let trPos = matrix_multiply([m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]], pos, 3,3);
let W=normalize(minus(trPos, V));
let tMin=10000.;
let iMin = -1;
for(let i=0;i<cns;i++){
let Vp=minus(V, matrix_multiply(SphTr[i], Sph[i]));
let B=dot(W,Vp);
let C=dot(Vp,Vp)-Sph[i][4]*Sph[i][4];
let D=B*B-C;
if(D>0.){
let t=-B-sqrt(D);
if(t > 0.0 && t < tMin){
tMin = t; // This is an optimization, we don't have to do lighting/tex
iMin = i; // for objects that are occuluded, which is expensive!
}
}
}
return iMin;
}
+211
View File
@@ -0,0 +1,211 @@
//////////////////////////////////////////////////////////////////////////////////////////
//
// THIS IS THE SUPPORT LIBRARY. YOU PROBABLY DON'T WANT TO CHANGE ANYTHING HERE JUST YET.
//
//////////////////////////////////////////////////////////////////////////////////////////
let fragmentShaderHeader = ['' // WHATEVER CODE WE WANT TO PREDEFINE FOR FRAGMENT SHADERS
, 'precision highp float;'
, 'float noise(vec3 point) { float r = 0.; for (int i=0;i<16;i++) {'
, ' vec3 D, p = point + mod(vec3(i,i/4,i/8) , vec3(4.0,2.0,2.0)) +'
, ' 1.7*sin(vec3(i,5*i,8*i)), C=floor(p), P=p-C-.5, A=abs(P);'
, ' C += mod(C.x+C.y+C.z,2.) * step(max(A.yzx,A.zxy),A) * sign(P);'
, ' D=34.*sin(987.*float(i)+876.*C+76.*C.yzx+765.*C.zxy);P=p-C-.5;'
, ' r+=sin(6.3*dot(P,fract(D)-.5))*pow(max(0.,1.-2.*dot(P,P)),4.);'
, '} return .5 * sin(r); }'
].join('\n');
var ns = 5, cns = 5;
fragmentShaderHeader+= 'const int ns = ' + ns + ';\n';
var fragmentShaderDefs = 'const int cns = ' + cns + ';\n';
let nfsh = fragmentShaderHeader.split('\n').length + 1; // NUMBER OF LINES OF CODE IN fragmentShaderHeader
let isFirefox = navigator.userAgent.indexOf('Firefox') > 0;
function getBlob(data) {
let bytes = new Array(data.length);
for (let i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
return new Blob([new Uint8Array(bytes)]);
}
let texture = [], gl, program;
let textures = [];
let lock = false;
function loadTexture(gl, url, i) {
const level = 0;
const internalFormat = gl.RGBA;
const width = 1;
const height = 1;
const border = 0;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
if (texture[i] == null)
{
texture[i] = gl.createTexture();
const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue
gl.activeTexture(gl.TEXTURE0+i);
gl.bindTexture(gl.TEXTURE_2D, texture[i]);
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
width, height, border, srcFormat, srcType,
pixel);
}
const image = new Image();
image.onload = function () {
gl.activeTexture(gl.TEXTURE0+i);
gl.bindTexture(gl.TEXTURE_2D, texture[i]);
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
srcFormat, srcType, image);
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
} else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
};
image.src = url;
}
function isPowerOf2(value) {
return (value & (value - 1)) == 0;
}
function gl_start(canvas, vertexShader, fragmentShader) { // START WEBGL RUNNING IN A CANVAS
console.log('glstart');
setTimeout(function () {
try {
canvas.gl = canvas.getContext('experimental-webgl'); // Make sure WebGl is supported. IT WOULD BE GREAT TO USE WEBGL2 INSTEAD.
} catch (e) { throw 'Sorry, your browser does not support WebGL.'; }
canvas.setShaders = function (vertexShader, fragmentShader) { // Add the vertex and fragment shaders:
gl = this.gl;
program = gl.createProgram(); // Create the WebGL program.
function addshader(type, src) { // Create and attach a WebGL shader.
function spacer(color, width, height) {
return '<table bgcolor=' + color +
' width=' + width +
' height=' + height + '><tr><td>&nbsp;</td></tr></table>';
}
errorMessage.innerHTML = 'Build Your Own Universe!';
// errorMarker.innerHTML = spacer('white', 1, 1) + '<font size=1 color=white>\u25B6</font>';
let shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
let msg = gl.getShaderInfoLog(shader);
console.log('Cannot compile shader:\n\n' + msg);
let a = msg.substring(6, msg.length);
let line = 0;
if (a.substring(0, 3) == ' 0:') {
a = a.substring(3, a.length);
line = parseInt(a) - nfsh;
editor.session.setAnnotations([{
row: line,
column: 0,
text: msg,
type: "error"
}]);
}
let j = a.indexOf(':');
a = 'line ' + (line+1) + a.substring(j, a.length);
if ((j = a.indexOf('\n')) > 0)
a = a.substring(0, j);
errorMessage.innerHTML = a;
}
else
editor.session.clearAnnotations();
gl.attachShader(program, shader);
};
addshader(gl.VERTEX_SHADER, vertexShader); // Add the vertex and fragment shaders.
addshader(gl.FRAGMENT_SHADER, fragmentShaderHeader +fragmentShaderDefs+ fragmentShader);
gl.linkProgram(program); // Link the program, report any errors.
if (!gl.getProgramParameter(program, gl.LINK_STATUS))
console.log('Could not link the shader program!');
gl.useProgram(program);
gl.program = program;
for(let i = 0; i < ns; ++i){
loadTexture(gl, './'+(i+1)+'.jpg', i); //Texture loading.
textures[i] = i;
}
gl.uniform1iv(gl.getUniformLocation(program, 'uSampler'), textures);
positionsupdated = true;
let attribs = [
.05,.05,.1, .5,.5,1., 1.,.5,.5,20., 0., .0, 1.3,
.1,.05,.05, 1.,.5,.5, 1.,.5,.5,10., .3,1.,1.3,
.1,.05,.05, .71,.71,.71, .71,.71,.71,10., 0.3,.0,1.5,
.1,.1,.1, .71,.71,.71, .71,.71,.71,10., 0.05,0., 1.,
.0,.0,.0, .0,.0,.0, .0,.0,.0,40., 0.,.85,1.5
]
var offset = 0;
for(let i = 0; i < ns; i++){
setUniform('3fv', 'Ambient['+i+']', attribs.slice(offset, offset += 3));
setUniform('3fv', 'Diffuse['+i+']', attribs.slice(offset, offset += 3));
setUniform('4fv', 'Specular['+i+']', attribs.slice(offset, offset += 4));
setUniform('1fv', 'ks['+i+']', attribs.slice(offset, offset += 1));
setUniform('1fv', 'kr['+i+']', attribs.slice(offset, offset += 1));
setUniform('1fv', 'kf['+i+']', attribs.slice(offset, offset += 1));
}
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); // Create a square as a triangle strip
// gl.bufferData(gl.ARRAY_BUFFER, new Float32Array( // consisting of two triangles.
// [-1, 1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]), gl.STATIC_DRAW);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearDepth(-1);
let oid = gl.getAttribLocation(program, 'oid'); // Set aPos attribute for each vertex.
gl.enableVertexAttribArray(oid);
gl.vertexAttribPointer(oid, 1, gl.FLOAT, false, 4*7, 0);
let aPos = gl.getAttribLocation(program, 'aPos'); // Set aPos attribute for each vertex.
gl.enableVertexAttribArray(aPos);
gl.vertexAttribPointer(aPos, 3, gl.FLOAT, false, 4*7, 4);
let normal = gl.getAttribLocation(program, 'normal'); // Set aPos attribute for each vertex.
gl.enableVertexAttribArray(normal);
gl.vertexAttribPointer(normal, 3, gl.FLOAT, false, 4*7, 4*4);
}
canvas.setShaders(vertexShader, fragmentShader); // Initialize everything,
setInterval(function () { // Start the animation loop.
gl = canvas.gl;
if (gl.startTime === undefined) // First time through,
gl.startTime = Date.now(); // record the start time.
animate(gl);
//gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); // Render the square.
}, 30);
}, 100); // Wait 100 milliseconds after page has loaded before starting WebGL.
}
// THE animate() CALLBACK FUNCTION CAN BE REDEFINED IN index.html.
function animate() { }
function setUniform(type, name, a, b, c, d, e, f) {
if(gl)
{
let loc = gl.getUniformLocation(gl.program, name);
(gl['uniform' + type])(loc, a, b, c, d, e, f);
}
}
//let VERTEX_SIZE = 3;
let VERTEX_SIZE = 7;
let drawMesh = (mesh, m) => {
setUniform('Matrix4fv', 'uMatrix', false, m);
gl.bufferData(gl.ARRAY_BUFFER, mesh, gl.STATIC_DRAW);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, mesh.length / VERTEX_SIZE);
}
BIN
View File
Binary file not shown.
+253
View File
@@ -0,0 +1,253 @@
#define _DEBUG_BREAK {gl_FragColor=vec4(1,0,0,1); return;}
#define REFRACTION (c2 >= 0.? (eta*W + (eta*c1 - sqrt(c2))*N) : ((W + c1*N)/sqrt(1.-c1*c1)))
vec3 foregroundColor = vec3(.0841, .5329, .9604);
vec3 groundColor = vec3(.2, .3, .5);
vec4 groundSpecular = vec4(.71, .71, .71, 10.);
uniform float uTime;// TIME, IN SECONDS
uniform vec3 Ambient[ns], Diffuse[ns];
uniform vec4 Specular[ns];
uniform float ks[ns], kr[ns], kf[ns];
uniform vec4 Sph[ns];
uniform sampler2D uSampler[ns];
uniform vec3 V0;
uniform int sel;
const float kf_air = 1.000293;
varying vec3 trPos;
varying vec3 norm;
varying float id;
varying vec3 glpos;
varying vec3 apos;
const float pi=3.14159265359;
const float _2pi=2.*pi;
vec3 LDir=vec3(.5,.5,.5);
vec3 LCol=vec3(1.,1.,1.);
/***********PLEASE DO INCREASE n_ref(RT DEPTH) FOR BETTER RESULTS************/
/*---->*/const int n_ref=15; //2^n-1 because each hit now spawn at most 2 rays.
/**BUT BE CAUTIOUS IF YOU DON'T HAVE A DECENT GRAPHICS CARD (below GTX 950M)**/
const int max_stack = (n_ref+1)/4;
vec3 scolor = vec3(0,0,0);
struct Ray{
vec3 V;
vec3 W;
float kf, cumulativeK;
} stack1[max_stack], stack2[max_stack];
bool modulo2(int n){
return n-2*(n/2) == 1;
}
vec2 getTextCoord(vec3 tex_sph, float R){
float tex_x=atan(tex_sph.z,tex_sph.x)/_2pi + 0.5;//*Correct aspect ratio of texture 2:1 -> 2pir:2r
tex_x=fract(tex_x+uTime/20.);
return vec2(tex_x,-asin(tex_sph.y/R)/pi + 0.5);
}
void rtx(){
float currKf = kf_air;
vec3 color=vec3(.2, .3, .5);
vec3 V = V0;
vec3 W=(trPos-V);
bool rtxoff = false, showtexture = true, selected = false;
float currentK = 1.;
int curr_ptr = 0, curr_top = 0, next_top = 0;
bool final = false, stackswap = false, stop = false;
for(int j=0;j<n_ref;j++)
{
for(int curr = 0; curr < max_stack; ++curr){
if(curr == curr_ptr){
bool skip = false;
if(j > 0){
Ray currR;
if(stackswap)
currR = stack1[curr];
else
currR = stack2[curr];
currKf = currR.kf;
currentK = currR.cumulativeK;
if(currKf <= 0.001 || currentK <= 0.001)
skip = true;
V = currR.V;
W = currR.W;
}
else
W = normalize(W);
if(!skip){
float tMin=10000.;
int iMin = -1;
for(int i=0;i<cns;i++){
vec3 Vp=V-Sph[i].xyz;
float B=dot(W,Vp);
float C=dot(Vp,Vp)-Sph[i].w*Sph[i].w;
float D=B*B-C;
if(D>0.){
float t=-B-sqrt(D);
if(t >= 0.01 && t < tMin){
tMin = t; // This is an optimization, we don't have to do lighting/tex
iMin = i; // for objects that are occuluded, which is expensive!
}
else if (t >= -0.01 && t <0.01){
t = -(t + 2.*B);
if(t > 0.01 && t < tMin){
tMin = t;
iMin = i;
}
}
}
}
if(iMin >= 0){
if(j == 0 && iMin == sel)
selected = true;
float t = tMin;
vec3 S=V+t*W;
for(int i = 0; i < cns; ++ i)
if(i == iMin)
{
vec3 texture_color;
if(showtexture)
{
vec3 tex_sph = (S-Sph[i].xyz);
texture_color=texture2D(uSampler[i],getTextCoord(tex_sph, Sph[i].w)).xyz;
}
else texture_color = foregroundColor;
vec3 N=normalize(S-Sph[i].xyz);
vec3 realLDir=normalize(LDir-S);
float c1 =dot(N, W);
float eta, nextkf;
if(c1<0.){
color=(Ambient[i]+Diffuse[i]*max(0.,dot(N,realLDir))*LCol)*texture_color;
if(rtxoff || final) //if it's the last hit
{
color += Specular[i].xyz*pow(max(0.,
dot(-2.*c1*N-realLDir,realLDir)),Specular[i].w);
scolor += color * currentK;
break;
}
else{
c1 = -c1;
eta = currKf/kf[i];
nextkf = kf[i];
}
}
else{
N = -N;
eta = currKf/kf_air;
nextkf = kf_air;
color = Ambient[i];
}
float c2 = (1.-eta*eta*(1.-c1*c1));
float nextks = currentK * ks[i], nextkr = currentK * kr[i];
bool refl = nextks > 0.01, refr = nextkr > 0.01;
if(refl || refr)
for(int k = 0; k < max_stack; ++k)
if(k == next_top){
if(stackswap){
if(refl)
{
stack2[k] = Ray(S, 2. * c1 * N + W, currKf, nextks); //reflection
currentK -= nextks;
next_top ++;
}
if(refr)
{
if(refl)
stack2[k+1] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
else
stack2[k] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
currentK -= nextkr;
next_top ++;
}
}else{
if(refl)
{ //remember, c1 = -NW now
stack1[k] = Ray(S, 2. * c1 * N + W, currKf, nextks); //reflection
currentK -= nextks;
next_top ++;
}
if(refr)
{
if(refl)
stack1[k+1] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
else
stack1[k] = Ray(S, REFRACTION, nextkf, nextkr); //refraction
currentK -= nextkr;
next_top ++;
}
}
break;
}
scolor += color * currentK;
break;
}
}
else {
float t = -(.2+V.y)/W.y;
float sx = V.x + t* W.x, sz = V.z + t * W.z;
if(t >= 0. && abs(sx) < 1.5 && abs(sz) < 3.)
{
vec3 S = vec3(sx, -.2, sz);
vec3 realLDir=normalize(LDir - S);
color=(0.5+0.5*max(0.,realLDir.y)*LCol)*texture2D(uSampler[4],vec2((sx+1.4)/3., (sz+1.5)/4.)).xyz;
if(rtxoff || final&&abs(sx)<1.5 && abs(sz+.6)<3.)
{
color += groundSpecular.xyz* //specular for ground.
pow(max(0., dot(vec3(-realLDir.x, realLDir.y,-realLDir.z),-W)),groundSpecular.w);
scolor += currentK * color;
}
else
{
for(int k = 0; k < max_stack; ++k)
if(k == next_top){
if(stackswap)
stack2[k] = Ray(S, vec3(W.x, -W.y, W.z), kf_air, currentK * 0.15); //reflection
else
stack1[k] = Ray(S, vec3(W.x, -W.y, W.z), kf_air, currentK * 0.15); //reflection
next_top ++;
break;
}
scolor += (currentK*.85)*color;
}
}
else{
if(j > 0)
scolor += currentK * (pow(max(0.,dot(W, normalize(LDir - V))), 10.) * vec3(3.,3.,3.) + foregroundColor*0.1);
else scolor = foregroundColor*0.6;
}
}
}
if(++curr_ptr >= curr_top){
if(next_top <= 0)
stop = true;
if(next_top * 2 > max_stack)
final = true;
curr_top = next_top;
next_top = 0;
curr_ptr = 0;
stackswap = !stackswap;
}
break;
}
}
if(stop)
break;
}
if(selected)
scolor.x += 0.5;
gl_FragColor=vec4((scolor),1.);
}
void main(){
vec3 color =foregroundColor.xyz;
float sp = 0.4, df = 0.4, amb = 0.4;
if(id == 4.) {rtx();color = gl_FragColor.xyz;}
else if (id == 1.) color = vec3(1.,.4,.6);
else if (id == 5.) {color = vec3(1, .9375,.7329);sp = .5; df=.8; amb = .05;}
vec3 V = V0;
vec3 W=normalize(glpos-V);
vec3 realLDir=normalize(LDir - glpos);
color = color*(amb+ df*max(0.,dot(norm,realLDir)))//specular for ground.
+ sp*pow(max(0., dot(2.*dot(norm, realLDir)*norm-realLDir, -W)),5.)*vec3(1,1,1);
gl_FragColor=vec4(sqrt(color), 1.);
}
+20
View File
@@ -0,0 +1,20 @@
uniform mat4 uMatrix;
uniform mat3 transformation;
attribute float oid;
attribute vec3 aPos;
attribute vec3 normal;
varying vec3 trPos;
varying float id;
varying vec3 norm;
varying vec3 glpos;
varying vec3 apos;
void main() {
vec4 pos = uMatrix * vec4(aPos, 1.);
gl_Position = pos * vec4(1., 1., -1., 1.);
id = oid;
norm = normalize((uMatrix*vec4(normal,0.)).xyz);
trPos = transformation *vec3(pos.xy, -1);
apos = aPos;
glpos = gl_Position.xyz;
}