#!/bin/csh -f

# dice C Shell script written by BJ MacGowan - Alias Assist October 1991
# revised 12 Dec 1991
# revised 02 Feb 1992
# This program is provided free of charge and unsupported by Alias Research Inc.

onintr Clean_up

set program = `basename $0`
if ($#argv < 1) then
	cat << EOF
Usage: $program [-kmprs] <sdl>"

The $program shell script is used for dividing the rendering of an Alias sdl
file over multiple machines.  $program will determine the resolution
of the sdl, and will subdivide that resolution among the intended render
engines.  Supporting pix files will be copied to the render engines and the
render engines will be started.  Once the render engines are finished
the resultant files will be copied back to the local machine and fpasted
together to make a complete image. Unless specified all working files 
including the supporting pix files on the remote machine will be removed upon 
completion. If a render exits abnormally the sdl and pix files that were
created in order to render the image will not be removed.

-k keep original filenames. There are no arguments to this option. The -k
   option will not remove any of the sdl and pix files that were created in
   order to render the image.
-m machine list.  This option must be used for each render engine to be used.
   An ascii file containing a list of render engines can also be used this
   file should contain just the names of the machines and nothing else
   It is possible to use the -m option with an ascii file list as well as
   command line arguments (eg -m render_engines -m localhost)
-p output pix filename.  If not supplied the final output pix filename will 
   be determined from the sdl. The pix filename should be relative to the
   current directory.
-r raytrace .  No further command line options are required. The raytracer
   will be used instead of the renderer.
-s slice sdl and exit. This option is used to cut the sdl into a specified
   amount slices and then exit. This option is useful for doing render tests on
   small portions of an sdl. If a background is associated with the sdl then
   that too will be subdivided. The amount of subdivisions is specifed by
   entering a value after the -s option. ie -s 4 will subdivided the sdl 4 
   times. The resulting subdivisions will be named with the sdl filename with 
   an extension starting from one and starting from the bottom of the image
   area. For example dice -s 4 sdl/test would result in 4 seperate sdl files
   name sdl/test.1 sdl/test.2 sdl/test.3 & sdl.test.4. When rendered sdl/test.1
   would be the very bottom section of the pix file if it were to be fully 
   rendered.
EOF
	exit 1
endif

# Set up the initial defaults

set render_count = ""
set skip_check = ""
set log = "$program.log"
set keep = "FALSE"
set background = ""
set startframe = 1
set renderer = "renderer"
set pix = ""
set sdl = "$argv[$#argv]"
set render_engines = ""
set render_list = ""
set check_engines = ""
set created_pix = ""
set created_sdl = ""
set texture_path = ""
set temp_dir = "/usr/tmp/dice"
set local_host = `hostname`
set has_background = "FALSE"
set missing = ""
set fpaste_list = ""
set slice = ""

# Check to see if some required SGI image tools are present in /usr/sbin
	if (! -x /usr/sbin/subimg) set missing = "subimg"
	if (! -x /usr/sbin/toalias) set missing = "$missing toalias"
	if (! -x /usr/sbin/fromalias) set missing = "$missing fromalias"

	set missing = ($missing)

	if ("$missing" != "") then
		if ($#missing < 2) then
			echo "\nThe file $missing is missing from /usr/sbin." 
			echo "$program can not continue until the file is placed into /usr/sbin\n"
		else
			echo "\nThe following files are missing from /usr/sbin."
			echo " $program can not continue until the files are placed into /usr/sbin\n"
			set count = 1
			while ($count <= $#missing)
				echo $missing[$count]
				@ count ++
			end	
			echo 
		endif
		exit
	endif

# Create a directory to store a variety of files that the program will write

/bin/mkdir $temp_dir >& /dev/null

# Parse through the command line options 

if ($#argv > 1) then

	set count = 1
	set count2 = 2

	while ($count <= $#argv)
		switch ($argv[$count])
			case "-k":
				set keep = "TRUE"
				@ count --
				@ count2 --
			breaksw

			case "-p":
				set pix = "$argv[$count2]"
			breaksw

			case "-s":
				set slice = "$argv[$count2]"
			breaksw

			case "-m":
				set check = $argv[$count2]
				set file_check = `file $check`

				# Test to see if the -m option is an ascii file if it is then 
				#   use that file to determine the render engines

				if ($file_check[2] == "ascii"||$file_check[2] == "commands")then
					set temp = `cat $check`
					set p_count = 1
					while ($p_count <= $#temp)
						set check = $temp[$p_count]
						if ($check == "x" || $check == "X") then
							set t_count = `expr $p_count - 1`
							set check = $temp[$t_count]
							@ p_count ++
							set times = $temp[$p_count]
							set c_count = 2
							set skip_check = `echo "$skip_check $check $times"`
							while ($c_count <= $times)
								set check_engines=`echo "$check_engines $check"`
								@ c_count ++
							end			
						else
							set check_engines = `echo "$check_engines $check"`
						endif
						@ p_count ++
					end
				else 
					set p_count2 = `expr $count2 + 1`
					if ($argv[$p_count2] == "x" || $argv[$p_count2] == "X") then
						@ p_count2 ++
						set times = $argv[$p_count2]
						set c_count = 1	
						set skip_check = `echo "$skip_check $check $times"`

						while ($c_count <= $times)
							set check_engines = `echo "$check_engines $check"`
							@ c_count ++
						end
					endif
				endif
			breaksw

				if ($argv[$p_count2] == "r" || $argv[$p_count2] == "R") then
					set r_type = "raytracer"
					@ p_count2 ++
					@ p_count ++
				else
					set r_type = "renderer"
				endif
				set check_sdl = `echo "$check_sdl $argv[$p_count2]"`
				set check_renderer = `echo "$check_renderer $r_type"`
			breaksw

			case "-r":
				set renderer = "raytracer"
				@ count --
				@ count2 --
			breaksw
		endsw 

		@ count = $count + 2
		@ count2 = $count2 + 2
	end
endif

# Set todays date into the next line of the log file
echo "\n`date`" >> $log

# Verify sdl file

if (! -r $sdl) then
	echo "cannot read $sdl"
	exit
endif

if ($slice != "") then
	set count = 1
	set host = `hostname`
	set render_engines = ""
	while ($count <= $slice)
		set render_engines = `echo "$render_engines $host"`
		@ count ++
	end
	set out_file = `expr //$sdl : '.*/\(.*\)'` 
	goto Slice
endif

# If an output pix name was not given use the sdl file to determine the pix name

if ($pix == "") then
	grep "pix =" $sdl > $temp_dir/grep
	nawk '{FS = "[\"]"; print $2}' $temp_dir/grep > $temp_dir/grep2
	set pix = `nawk '{FS = "/";print $(NF-1)"/"$NF}' $temp_dir/grep2`
endif

# Determine what the outfile name should be

	set out_file = `expr //$pix : '.*/\(.*\)'` 

# If the sdl has a ramp background the resulting combined pix file will be
#   incorrect
	fgrep -s 'background = ramp(' $sdl
	if ($status == 0) then
		echo "\07\n"
		echo "$sdl has a background ramp assigned to it." | tee -a $log
		echo "Background ramps can create incorrect results" | tee -a $log
		echo -n "Do you wish to continue (y/N) "
		set reply = $<
		if ($reply == "n" || $reply == "N" || $reply == "") then
			echo "Exiting from the render process" | tee -a $log
			goto Clean_up
		endif
	endif

# Determine texture pix names that may be required for the rendering

	grep 'image =' $sdl > $temp_dir/grep
	grep 'floor_texture =' $sdl >> $temp_dir/grep
	grep 'cloud_texture =' $sdl >> $temp_dir/grep
	grep 'right = "' $sdl >> $temp_dir/grep
	grep 'left  = "' $sdl >> $temp_dir/grep
	grep 'top   =' $sdl >> $temp_dir/grep
	grep 'bottom =' $sdl >> $temp_dir/grep
	grep 'back =' $sdl >> $temp_dir/grep
	grep 'front =' $sdl >> $temp_dir/grep
	nawk '{FS = "[\"]"; print $2}' $temp_dir/grep > $temp_dir/grep2
	set texture_path = `cat $temp_dir/grep2`
	set texture = `nawk '{FS = "/";print $(NF-1)"/"$NF}' $temp_dir/grep2`

# Verify the render engines to see if they are accessible

if ("$check_engines" != "") then
	set count = 1
	echo -n "Validating Hosts. "
	while ($count <= $#check_engines)
		rsh $check_engines[$count] date >& /dev/null
		if ($status != 0) then
			echo "\n\07Host $check_engines[$count] not validated. $check_engines[$count] will not be used.\n"
		else
			set render_engines = `echo "$render_engines $check_engines[$count]"`
		endif
		set temp = 1
		while ($temp < $#skip_check)
			if ($check_engines[$count] == $skip_check[$temp]) then
				set temp = `expr $temp + 1`
				set times = `expr $skip_check[$temp] - 1`
				@ count = $count + $times
				set temp2 = 1
				while ($temp2 <= $times)
					set render_engines = `echo "$render_engines $check_engines[$count]"`
					@ temp2 ++
				end
			endif
			@ temp ++
		end
		@ count ++
	end
endif

# If no valid render engines were found then use the local host

if ("$render_engines" == "") then
	set render_engines = `hostname`
	echo "No render engines were found defaulting to $render_engines"
endif
echo "Done"

# Test to see if there is a writeable pix and sdl directory on the Host, if not
#    create temporary directories

echo -n "Checking directory paths. "
set count = 1
while ($count <= $#render_engines)
	set host_test = $render_engines[$count]
	set test_pix = `rsh $host_test "if (-d pix && -w pix) echo '$status'"`
	set test_sdl = `rsh $host_test "if (-d sdl && -w sdl) echo '$status'"`

	if ($test_pix != "0") then
		echo "Creating temporary pix directory on Host $host_test"
		rsh $host_test mkdir pix >& /dev/null
		if ($status == 0) then
			set created_pix = `echo "$created_pix $host_test"`
		else
			echo "Could not create a temporary pix directory on $hosts_test. Aborting render process"
			exit
		endif
	endif

	if ($test_sdl != "0") then
		echo "Creating temporary sdl directory on Host $host_test"
		rsh $host_test mkdir sdl >& /dev/null
		if ($status == 0) then
			set created_sdl = `echo "$created_sdl $host_test"`
		else
			echo "Could not create a temporary sdl directory on $host_test. Aborting render process"
			exit
		endif
	endif
	@ count ++
end
echo "Done"

Slice:
# Determine if there is a background pix file. This has to be handled
#    differently since the background image has to be sliced in order to keep it
#    the same size as the area to be rendered

set has_background = "FALSE"
grep 'background = "' $sdl > $temp_dir/bg1
if ($status == 0) set has_background = "TRUE"

if ($has_background == "TRUE") then
	echo -n "Slicing the background file. "
	nawk '{FS = "[\"]"; print $2}' $temp_dir/bg1 > $temp_dir/bg2
	set bg_path = `cat $temp_dir/bg2`
	set background = `nawk '{FS = "/";print $(NF-1)"/"$NF}' $temp_dir/bg2`
	set vi_bg = `nawk '{FS = "/";print $1"\\/"$2}' $temp_dir/bg2`

	# bg_path: is the full path of the background
	# background: is the path for the background on the remote machine
	# vi_bg: places special control characters into the background path so that
	#        when the sdl files are editted the / in the path will be 
	#        interpeted properly.
	
	# Determine the X and Y resolution of the background
	readrl $bg_path | head -1 > $temp_dir/fs
	set xres = `nawk '{print $2}' $temp_dir/fs`
	set yres = `nawk '{print $4}' $temp_dir/fs`

	# Since the original background has to be sliced up we have to determine
	#   how big those slices must be.
	set increment = `echo "$yres / $#render_engines" | bc`

	# The resolution for the slices must start at 0 so the X & Y resolutions
	#   must be decreased by 1  
	set xres = `echo "$xres - 1" | bc`
	set yhigh = `echo "$increment - 1" | bc`

	# Convert the background to SGI RGB format so that it can be sliced
	fromalias $bg_path $background.rgb 

	set count = 1
	set ylow = 0
	while ($count <= $#render_engines)
	
		# subimg is an SGI utility that will take a subsection of an image
		subimg $background.rgb $background.rgb.$render_engines[$count] 0 $xres $ylow $yhigh 
		# Convert the new background slice back to Alias format for rendering
		toalias $background.rgb.$render_engines[$count] $background.$out_file.$count
		@ count ++
		set ylow = `echo "$ylow + $increment" | bc`
		set yhigh = `echo "$yhigh + $increment" | bc`
		if ($count == $#render_engines) set yhigh = `echo "$yres - 1" | bc`
	end

	# Remove any .rgb files that were created
	/bin/rm $background.rgb*
	echo "Done"
endif 

if ($slice != "") then
	set count = 1
	while ($count <= $slice)
		mv $background.$render_engines[$count].$count $background.$out_file.$count >&/dev/null
		@ count ++
	end
endif
	
# Determine the resolution of the original pix file

echo -n "Determining the size of each sdl slice. "
set temp = `sed -n -e /"yhigh"/p -e /""/q $sdl `
echo $temp[$#temp] > $temp_dir/.sdl
set orig_yhigh = `sed -e "s/;//" $temp_dir/.sdl`
/bin/rm $temp_dir/.sdl

# Determine the size of each slice

set increment = `echo "$orig_yhigh / $#render_engines" | bc`
set yhigh = `echo "$increment - 1" | bc`

# Edit the sdl to render the proper slices

set ylow = 0
set count = 1

while ($count <= $#render_engines)

	if ($has_background != "TRUE") then 
		# If the sdl does not have a background pix use this editing sequence
		ex -s $sdl << EOF
   		/yhigh  = $orig_yhigh/s//yhigh  = $yhigh
		/ylow   = 0/s//ylow   = $ylow
		/yhigh)/s//$orig_yhigh)
		/(yhigh/s//($orig_yhigh
		/ylow,/s//0,
		/ylow)/s//0)
		w! sdl/$out_file.$render_engines[$count].$count
		q
EOF
	else
		# If the sdl does have a background pix then use this editing sequence
		ex -s $sdl << EOF
   		/yhigh  = $orig_yhigh/s//yhigh  = $yhigh
		/ylow   = 0/s//ylow   = $ylow
		/yhigh)/s//$orig_yhigh)
		/(yhigh/s//($orig_yhigh
		/ylow,/s//0,
		/ylow)/s//0)
		/$vi_bg/s//$vi_bg.$out_file.$count
		w! sdl/$out_file.$render_engines[$count].$count
		q
EOF
	endif
	set render_list = `echo "$render_list $render_engines[$count]"`
	@ count ++
	set ylow = `echo "$ylow + $increment" | bc`
	set yhigh = `echo "$yhigh + $increment" | bc`
	if ($count == $#render_engines) set yhigh = $orig_yhigh

end
echo "Done"

# If the user just wanted to slice up the sdl this will rename the files,
#   report the files name and then exit
if ($slice != "") then
	set count = 1
	while ($count <= $slice)
		mv sdl/$out_file.$render_engines[$count].$count sdl/$out_file.$count 
		@ count ++
	end

	echo "\n$sdl has been sliced into $slice sdls named:"

	# List the sdl names
	set count = 1
	while ($count <= $slice)
		echo "\t$sdl.$count"
		@ count ++
	end

	if ($has_background == "TRUE") then
		echo "\nThe background file $background has been sliced into $slice pix files named:"
	
		# List the background names
		set count = 1
		while ($count <= $slice)
			echo "\t$background.$out_file.$count"
			@ count ++
		end
	endif
	echo "\07"
	exit	
endif

# Copy the required sdl and pix files to each render engine

echo "Copying required files to Render Engines.\n"
set count = 1
while ($count <= $#render_list)
	set engine = $render_list[$count]
	set to_render = "sdl/$out_file.$engine.$count"
	rcp $to_render $engine":"$to_render

	# Copy over the background pix files if required
	if ($has_background == "TRUE") then
		rcp $background.$out_file.$count $engine":"$background.$out_file.$count
	endif

	if ("$texture_path" != "") then
		set count2 = 1
		while ($count2 <= $#texture_path)

			# Before copying over and pix files test the remote directory to see
			#   if the file exists or not, if it exists then there is no need to
			#   copy the pix files. For each pix file that is to be copied the 
			#   machine name and pix filename are copied into a file so that the
			#   name can be referenced for later removal

			set exist = `rsh $engine "if (-r $texture[$count2]) echo $status"`
			if ($exist != "0") then
				rcp $texture_path[$count2] $engine":"$texture[$count2]
				echo "$engine $texture[$count2]" >> $temp_dir/cp_pix
			endif
			@ count2 ++
		end
	endif	

	# When a c-shell is invoked as a background process the process ID is 
	#   reported to the screen, as well as a message when the process is 
	#   finished.  To get around this the renderer will be invoked under bourne 
	#   shell. However we have to write out required variables to disk and then  	#   cat them back in

	echo $engine > .engine
	echo $renderer > .renderer
	echo $pix > .pix	
	echo $count > .count
	echo $out_file > .out_file
	echo $temp_dir > .temp_dir
	echo $to_render > .to_render


	# First read in the required variables for the Bourne shell and then start
	#    up the renderers.  sh -cf invokes the bourne shell

	sh -cf 'cat="/bin/cat";to_render=`$cat .to_render`;\
	renderer=`$cat .renderer`; out_file=`$cat .out_file`;\
	engine=`$cat .engine`; pix=`$cat .pix`;count=`$cat .count`\
	temp_dir=`$cat .temp_dir`;\
	echo `date` >sdl/out.$engine.$out_file.$count;\
	rsh $engine $renderer -p $pix.$engine.$count $to_render >>sdl/out.$engine.$out_file.$count 2>&1 &' 

	set render_count = `echo "$render_count $count"`
	echo "Starting Render Engine $engine using $renderer." | tee -a $log

	@ count ++
end

set rc = ($render_count)
Start_of_check:
# Run through the list of render engines to see if they are still running

set count = 1

while ($count <= $#render_list)
	set engine = $render_list[$count]
	if ($engine != $local_host) then
		rsh $engine ps -ef | grep $renderer" -p "$pix"."$engine.$rc[$count]" "sdl/"$out_file."$engine.$rc[$count] >& /dev/null
		set Status = $status
	else
		ps -ef | grep $renderer" -p "$pix"."$engine.$rc[$count]" "sdl/"$out_file."$engine.$rc[$count] | grep -v "grep">& /dev/null
		set Status = $status
	endif

	# When a render engine has finished the name is taken off of the list of
	# engines to check.

	if ($Status == "1") then 
		echo "$engine has finished rendering." | tee -a $log
		set out_name = `expr //$pix : '.*/\(.*\)'` 
		set check = "out.$engine.$out_name.$rc[$count]"
		set Done = `fgrep -s done sdl/$check`
		set Status = $status
		if ($Status == 0) then
			echo `date` >> sdl/$check
		else
			echo $engine sdl/$check $check >> $temp_dir/abnormal
		endif
		set render_list[$count] = ""
		set rc[$count] = ""
	endif
	@ count ++
end

set count = 1
set temp_list = ""
set temp_count = ""
while ($count <= $#render_list)
	if ($render_list[$count] != "") then
		set temp_list = `echo "$temp_list $render_list[$count]"`
		set temp_count = `echo "$temp_count $rc[$count]"`
	endif
	@ count ++
end

set render_list = ($temp_list)
set rc = ($temp_count)

sleep 5

if ("$render_list" != "") goto Start_of_check

echo "All renders are finished."

# Once all of the render engines are finished copy their output back to the
#   local machine and then delete the sdl and pix file from the remote machines

echo -n "\nCopying the images back to $local_host. "
set count = 1
while ($count <= $#render_engines)
	set engine = $render_engines[$count]
	set from_render = $pix.$render_engines[$count].$render_count[$count]
	rcp $engine":"$from_render $from_render >& /dev/null
	rsh $engine /bin/rm "sdl/$out_file."$engine.$render_count[$count] >& /dev/null
	rsh $engine /bin/rm $from_render >& /dev/null
	if ($renderer == "raytracer") rsh $engine /bin/rm $from_render".test" >& /dev/null
	if ($has_background == "TRUE" && $keep != "TRUE") then
		rsh $engine /bin/rm $background.$engine.$render_count[$count] >& /dev/null
	endif
	@ count ++
end

# Check to see if any pix files were copied over to any remote machine. If so
#   then remove them from those machines

if (-r $temp_dir/cp_pix) then
	set delete_pix = `cat $temp_dir/cp_pix`
	set count=1
	set count2=2
	while ($count <= $#delete_pix)
		rsh $delete_pix[$count] /bin/rm $delete_pix[$count2] >& /dev/null

		@ count = $count + 2	
		@ count2 = $count2 + 2	
	end
endif

echo "Done"

# Check to see if any of the sdls had exited abnormally
if (-r $temp_dir/abnormal) then
	set abnormal = `cat $temp_dir/abnormal`
	
	if ("$abnormal" != "") then
		set count1 = 1
		set count2 = 2
		set count3 = 3
		set msg = ""
		if ($#abnormal > 3) set msg = "s"
			echo "\nThe following file$msg exited abnormally.\n"| tee  -a $log 
			echo "Render engine\t\tSDL filename\t\tout filename\n" | tee -a $log
		endif
		while ($count1 <= $#abnormal)
			echo "$abnormal[$count1]\t\t\t$abnormal[$count2]\t\t$abnormal[$count3]"|tee -a $log
		@ count1 = $count1 + 3
		@ count2 = $count2 + 3
		@ count3 = $count3 + 3
		end
		echo "\nVerify the sdl$msg before restarting the render process." | tee -a $log
		set count = $#render_engines
		set count2 = 1
		while ($count >= 1)
			cp $pix.$render_engines[$count].$render_count[$count] $pix.$count2 >& /dev/null
			@ count --
			@ count2 ++
		end
	set keep = "TRUE"
	goto Clean_up
	endif
endif

echo -n "\nPasting the image together. "
set count = $#render_engines
set fpaste_list = ""
# The rendered images must be pasted together, so a list must be created in
#   reverse order of how they were rendered
while ($count >= 1)
	set fpaste_list = `echo "$fpaste_list $pix.$render_engines[$count].$render_count[$count]"`
	@ count --
end

# Paste the images together and call the output file the default pix filename

fpaste $fpaste_list $pix

echo "Done"
echo "\07\n$pix has been completed." | tee -a $log

Clean_up: 
# Clean up and remove any work files

if ($keep != "TRUE") then
	set count = 1
	while ($count <= $#render_count)
		/bin/rm "sdl/$out_file.$render_engines[$count].$render_count[$count]" >& /dev/null
		@ count ++
	end
	/bin/rm $fpaste_list >& /dev/null
endif

# If a temporary sdl directory was created on the remote machine then remove it
if ($created_sdl != "") then
	set count = 1
	set count2 = $#created_sdl
	while ($count <= $#render_engines)
	while ($count2 <= $#created_sdl)
		set from_render = $render_engines[$count]
		if ($created_sdl[$count2] == $from_render) rsh $from_render /bin/rmdir sdl >& /dev/null
		@ count2 ++
	end
	@ count ++
	end
endif

# If a temporary pix directory was created on the remote machine then remove it

if ($created_pix != "") then
	set count = 1
	set count2 = $#created_pix
	while ($count <= $#render_engines)
	while ($count2 <= $#created_pix)
		set from_render = $render_engines[$count]
		if ($created_pix[$count2] == $from_render) rsh $from_render /bin/rmdir pix >& /dev/null
		@ count2 ++
	end
	@ count ++
	end
endif

if ($has_background == "TRUE" && $keep != "TRUE") /bin/rm $background.*
/bin/rm -fr $temp_dir >& /dev/null

/bin/rm .engine >& /dev/null
/bin/rm .renderer >& /dev/null
/bin/rm .pix >& /dev/null
/bin/rm .count >& /dev/null
/bin/rm .out_file >& /dev/null
/bin/rm .temp_dir >& /dev/null
/bin/rm .to_render >& /dev/null

exit
