% file light3s.m
% almost identical to file light3.m but reduced the number of points
% in linspace and cylinder to make a simple object
% so we can study the surface, vertices and faces in detail

clear all;close all;
p=linspace(0,1,2);
%r=sin(p*pi).*(sin(4*pi*p)+2).*exp(-p/2);
r=cos(2*pi*p);
[xc,yc,zc]=cylinder(r,4); % 4 points around diameter, looks like cube
% xc,yc are matrices the same as would be produced by meshgrid
figure(1)
surf(xc,yc,zc);
shading interp;
material shiny;
l=light('pos',[-3 -3 0.5],'style','local');
colormap cool
axis equal;
axis square;
xlabel('x');ylabel('y');

figure(11);
mesh(xc,yc,zc);
colormap cool
axis equal;
axis square;
xlabel('x');ylabel('y');


fvc=surf2patch(xc,yc,zc,zc);
%fvc = 
%              faces: 
%           vertices: 
%    facevertexcdata:
v=fvc.vertices; %10x3 matrix of 10 vertices (x,y,z)
% there are 8 unique vertices, the last two are duplicates
f=fvc.faces;% 4x4 matrix,
% the cylinder object has 4 faces in this case, no top, no bottom,
% the light can shine on the inside surfaces of the object.
% so there are 4 rows, each row represents the numbers of the vertices which
% make up a face
c=fvc.facevertexcdata;


figure(12);
patch(fvc)
view(3)
colormap(cool)
l=light('position',[-3 -3 0.5],'style','local');
shading interp;
material shiny;
grid on;
axis equal;
axis square;
xlabel('x');ylabel('y');

f=[f;2 4 6 8];% add another face on top of the cylinder, thus add 
% a new row to f to get a 5x4 matrix
fvc.faces=f;
figure(13);
patch(fvc)
view(3)
colormap(cool)
l=light('position',[-3 -3 0.5],'style','local');
shading interp;
material shiny;
grid on;
axis equal;
axis square;
xlabel('x');ylabel('y');
% now the top face prevents the light from getting inside the object

% example transformation 
T=rot3d_pre(pi/2,2);
vsize=size(v);
vh=[v ones(vsize(1),1)];
v2=T*vh';
fvc2.facevertexcdata=c;
fvc2.faces=f;
v2(4,:)=[];
fvc2.vertices=v2';

figure(2);
patch(fvc2)
view(3)
colormap(cool)
l=light('position',[-3 -3 0.5],'style','local');
shading interp;
material shiny;
grid on;
axis equal;
axis square;
xlabel('x');ylabel('y');


figure(3);
% another way to set the material properties
% shows parameters of the patch function, which are related to the
% properties of the material
patch(fvc2,'AmbientStrength',1,'DiffuseStrength',0.5,...
    'SpecularStrength',0,'SpecularExponent',5,'SpecularColorReflectance',0,...
    'FaceLighting','phong','EdgeLighting','phong');
ka=1;kd=0.5;ks=1;n=5;sc=1;
shading interp;
colormap(summer);
material shiny;
view(3);
l=light('position',[-3 -3 0.5]);
%material([ka kd ks n sc]);
%lighting phong;
grid on;
axis equal;
axis square;
xlabel('x');ylabel('y');
