% Copyright (C) 2018 Andreas Bertsatos <andreas.bertsatos@gmail.com>
%
% This program is free software; you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation; either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
% 
function writeMtl(mtl, filename)
% function writeMtl(mtl,filename);
%
% This function stores the material definition elements according to the
% Wavefront file format. All material elements are defined in a data structure
% "mtl" given as input argument, whereas a second input argument defines the
% filename of the .mtl file that will be created.
%
% The function recognizes only material name statements, i.e. newmtl; material
% color and illumination statements, i.e. Ka, Kd, Ks, Tr, d, illum and Ns; as
% well as texture map statements, i.e. map_Kd, map_Kd and map_Ks.
% All other fields that may be present in the data structure used as input
% argument are ignored. If the data structure contains more than one material
% then they are stored in consecutive order as defined by the structure's index.

  fid = fopen(filename, 'wt');
  fdisp(fid,"#\n# MTL File generated by GNU Octave");
  fdisp(fid,"# using 'writeMtl' function\n#");
  
  for i = 1:length(mtl)
    if (isfield(mtl,"newmtl") && !isempty(mtl(i).Ka))
      fprintf(fid, '\nnewmtl %s\n', mtl(i).newmtl);
    endif
    if (isfield(mtl,"Ka") && !isempty(mtl(i).Ka))
      fprintf(fid, 'Ka %f %f %f\n', mtl(i).Ka);
    endif
    if (isfield(mtl,"Kd") && !isempty(mtl(i).Kd))
      fprintf(fid, 'Kd %f %f %f\n', mtl(i).Kd);
    endif
    if (isfield(mtl,"Ks") && !isempty(mtl(i).Ks))
      fprintf(fid, 'Ks %f %f %f\n', mtl(i).Ks);
    endif
    if (isfield(mtl,"Tr") && !isempty(mtl(i).Tr))
      fprintf(fid, 'Tr %f\n', mtl(i).Tr);
    endif
    if (isfield(mtl,"illum") && !isempty(mtl(i).illum))
      fprintf(fid, 'illum %d\n', mtl(i).illum);
    endif
    if (isfield(mtl,"Ns") && !isempty(mtl(i).Ns))
      fprintf(fid, 'Ns %f\n', mtl(i).Ns);
    endif
    if (isfield(mtl,"map_Ka") && !isempty(mtl(i).map_Ka))
      fprintf(fid, 'map_Ka %s\n', mtl(i).map_Ka);
    endif
    if (isfield(mtl,"map_Kd") && !isempty(mtl(i).map_Kd))
      fprintf(fid, 'map_Kd %s\n', mtl(i).map_Kd);
    endif
    if (isfield(mtl,"map_Ks") && !isempty(mtl(i).map_Ks))
      fprintf(fid, 'map_Ks %s\n', mtl(i).map_Ks);
    endif
  endfor
  fclose(fid);
endfunction
