#!/bin/bash
###################################
# author: Matthieu Hendriks
# date: 01-2024
# license: free to use and adept, no warranty grom the author
# title: scad2mp4
# description:
# this script generates a lot of png file, every picture is taken from a different camera view, all png files are added to a mp4 file to create a simple movie
# the run_all module is used to create the objects.
echo "Convert scad to mp4"
pwd
#
fnum=1000;		# fo serial numbering the different pictures
x=1;			# starting x,y,z position for camera
y=0;
z=0;
string=$1;
file=${string%.*};		# skip extension
maxproc=5;
####################
# routine for creating a png file
####################
create_png() {
#echo "Create $fnum x:$x y:$y z:$z "
if [  $(pgrep -c openscad) -ge $maxproc ]
then 
	openscad -q -D 'run="run_all"' $file.scad  --viewall --camera=0,0,0,$x,$y,$z,30 -o "tmp$fnum.png" 
else 
	openscad -q -D 'run="run_all"' $file.scad  --viewall --camera=0,0,0,$x,$y,$z,30 -o "tmp$fnum.png" &
	sleep 0.01
fi 

}
#
# first create cwsingle png file for every print_ module

grep module $file.scad | awk '{print $2}' | awk -F '(' '{print $1}' | while read -r line ; do

if [[  "$line" ==  "print_"* ]] || [ "$line" == "all" ]; then
	openscad -q -D 'run="'$line'"' $file.scad  -o "$line.png" &
fi
done
#echo "Done  print_module files";

# create gif file
# now create from different angles the png file these are a lot of files, but don't worry the script will clean up after

for x in {0..180..1} 
do 
	((fnum=fnum+1))
	create_png
done
x=180;
for y in {0..360..1} 
do 
	((fnum=fnum+1))
	create_png
done
y=0;
for x in {181..360..1} 
do 
	((fnum=fnum+1))
	create_png
done
until [ -f tmp$fnum.png ]
do 
	sleep 1
done
sleep 5		# wait a moment to let every thing finish
date
echo "Start converting to mp4"
rm -f $file.mp4		# delete old or previous file
ffmpeg -framerate 30 -pattern_type glob -i 'tmp*.png' -c:v libx264 -pix_fmt yuv420p $file.mp4
date
echo "Start cleaning temporary file"
rm tmp*.png
echo "Done"

