clear

h=0.16;

% interpolation
%-----------------------------------------------------------


my_d = @(P) ( max(abs( P(:,1)-0.5), abs(P(:,2) - 0.5)) -0.5 );
[P,T]=distmesh2d(my_d,@huniform,h,[-1 -1; 2 2;],[0 0; 1 1; 0 1; 1 0]);
%u = @(x,y) x.^4 + y.^4;
u=@(x,y) exp(x.^2 + y.^2);

% P1 is easy, just compute the value of u on the nodes of the mesh
figure
u_vert = u(P(:,1),P(:,2));
trimesh(T,P(:,1),P(:,2),u_vert)

% P0 requires more work: in detail, we need to compute baricenter of each triangle and create a matrix where
% each column contains the x and y coordinates of the three vertices of each triangle. 
nb_t = size(T,1);
x_bar = zeros(nb_t,1);
y_bar = zeros(nb_t,1);
x_tr = zeros(3,nb_t);
y_tr = zeros(3,nb_t);

% loop over triangles
for t=1:nb_t
    % the baricenter is the mean of the vertices of a triangle. I access the vertices of a triangle as T(t,:)
    the_verts = T(t,:);
    x_bar(t) = mean( P(the_verts,1) );
    y_bar(t) = mean( P(the_verts,2) );
    x_tr(:,t) = P(the_verts,1);
    y_tr(:,t) = P(the_verts,2);
end

% now evaluate u in the baricenter. We need it to be a row vector, hence use '
u_bar = u(x_bar,y_bar)';

% the plot of P0 is a constant value on each triangle. thus, we need the z coordinate of the vertices of each
% triangle, i.e. a matrix like x_tr and y_tr. Clearly, the three coordinates are constant.
z = u_bar;
z_tr= [z; z; z];

% now, plot. The fourth input says that the color of the triangle is proportional to the height of the
% triangle
figure
patch(x_tr,y_tr,z_tr,u_bar)
