% RenderDemo
%
% Illustrates calibration interface for simple task of
% producing a uniform color patch of desired CIE xyY
% coordinates.
%
% The calculation is done with respect to the current
% calibration for screen whichScreen.  We provide a default
% with the toolbox, but it won't match your monitor.
%
% If the RGB values contain 0 or 255, the coordinates
% requested may have been out of gamut.
%
% A 64 by 64 image is left in the clipboard as a PICT
% and may be pasted into Photoshop, Word, etc.

% 4/26/97  dhb  Wrote it.
% 7/25/97  dhb  Better initialization.
% 3/12/98  dgp  Use Ask.
% 3/14/02  dhb  Update for OpenWindow.
% 4/03/02  awi  Merged in Windows changes.  On Windows we do not
%				copy the result to the clipboard. 
% 4/13/02  awi	Changed "SetColorSpace" to new name "SetSensorColorSpace".
%					 			Changed "LinearToSettings" to new name "SensorToSettings".
% 12/21/02 dhb  Remove reliance on now obsolete OpenWindow/CloseWindow.

% Clear out workspace if we haven't run this.
% This step tries to avoid name space collision
% with other programs that use the variable 
% cal to hold calibraiton data.
if (exist('RenderDemoInit') ~= 1)
	clear
	RenderDemoInit = 1;
end

% Set screen
whichScreen = 0;

% Load calibration file
if (exist('cal') ~= 1)
	cal = LoadCalFile(whichScreen);
	load T_xyz1931
	T_xyz1931 = 683*T_xyz1931;
	cal = SetSensorColorSpace(cal,T_xyz1931,S_xyz1931);
	cal = SetGammaMethod(cal,0);
end

% Get xyY, render, and report.
xyY = input('Enter xyY (as a row vector): ')';
XYZ = xyYtoXYZ(xyY);
RGB = SensorToSettings(cal,XYZ);
fprintf('Computed RGB: [%g %g %g]\n',RGB(1),RGB(2),RGB(3));

% Show the image
[window,rect] = Screen(whichScreen,'OpenWindow',255,[],8);
Screen(window,'FillRect',254,CenterRect([0 0 64 64],rect));
SetColor(window,254,RGB);
%Screen(window,'SetClut',RGB',254);
if strcmp(computer, 'PCWIN')
    % Win:Psychtoolbox needs a delay here, for mysterious reasons having to do with 
    % the way that the following call to Ask() interferes with the preceeding call to SetColor.  
    WaitSecs(0.1); 
end
Ask(window,'Here''s the color.  Click to proceed',0,255);
Screen(window,'Close');

if strcmp(computer,'MAC2')
  % Convert to image and leave in clipboard
	cImage = ones(64*64,1)*RGB';
	CopyCImage(cImage/255);
	fprintf('\nThe image is now in the clipboard as a 24-bit PICT.\n');
	fprintf('You can paste it into your favorite graphics-savvy application,\n');
	fprintf('e.g. Photoshop or Word.\n');
end

