% script to do some texture mapping 
% transformations
% 11/7/00 Dorian Miller
function M = texturemap(uv,xy)

% Solving by Gaussian ellinination 
hold on

% original box (u,v)
%uv = [0 0 1; 0 1 1; 1 1 1; 1 0 1]';
%uv = [0 0 1; 0 1 1; 1 2 1; 0.5 0 1]';
%plot3(uv(1,:),uv(2,:),uv(3,:),'b');
%xy = rotationXXX(uv,-60);
%xy = [-0.5 0 1; 0 1 1; 1 1 1; 1.5 0 1]'
%xy = [0 0 1; 0 1 1; 1 1 1; 1 0 1]';
%xy = uv+1;
%plot3(xy(1,:),xy(2,:),xy(3,:),'r');

% Construct equations to solve
% scale by x-coordinate
xuv = -repmat(xy(1,:),3,1)';
temp  =[uv(1,:);uv(2,:);ones(1,4)]';
xuv = xuv.*[uv(1,:);uv(2,:);ones(1,4)]';
xequations = [uv;zeros(3,4);xuv']';

yuv = -repmat(xy(2,:),3,1)';
temp  =[uv(1,:);uv(2,:);ones(1,4)]';
yuv = yuv.*[uv(1,:);uv(2,:);ones(1,4)]';
yequations = [zeros(3,4);uv;yuv']';

% concatenate matrix and add scaling row.
scaleRow = zeros(1,9);
scaleRow(1,9) = 1;
solve = [xequations;yequations;scaleRow];
solution = zeros(1,9);
solution(1,9) = 1; % This is the scale factor

abc = solve\solution';

M = [abc(1:3,1)';abc(4:6,1)';abc(7:9,1)'];

% rotation about y,z-plane pointing straight up
% angle given in degrees
% rotation in horizontal plane
function newM = rotationXXX(m, angle)
m = [m; ones(1,size(m,2))];
cosA = cos(angle*pi/180);
sinA = sin(angle*pi/180);

rotate = [cosA  sinA 0 0;...
          -sinA cosA 0 0;...
         0      0    1 0;...
       	0      0    0 1];
newM = rotate*m;
newM= newM(1:3,:);	

