#!/usr/bin/env python
"""pso2h

A small python script to generated header files from compiled ARBfp1.0 shaders

Usage: ./pso2h-runtime [options] file.pso

Options:
    -o, --output      header file name
    -n, --name        name of the shader
    -h, --help        display this help
    -v, --verbose     verbose output

    file.pso 		      compiled shader"""

import sys, os, string, getopt

__author__ = "Damien Lespiau <damien.lespiau@intel.com>"
__version__ = "0.1"
__date__ = "20090426"
__copyright__ = "Copyright (c) 2009 Intel Corporation"
__license__ = "GPL v2"

_verbose = 0

_template = """/*
 * This file was generated by pso2h.
 */

#ifndef %s
#define %s

/*
 * This define is the size of the shader in bytes.  More precisely it's the
 * sum of strlen() of every string in the array.
 */
#define %s    %d

static const char *%s[] =
{
%s  NULL
};

#endif
"""

def define(format, filename):
  path, file = os.path.split(filename)
  return format % string.upper(file.replace('.', '_').capitalize())

class PSO:
  def __init__(self, filename=None, name=None):
    self.filename = filename
    self.name = name

  def write_header(self, filename):
    file = open(self.filename)
    header = open(filename, "w")
    __HEADER__ = define("__%s__", filename)
    SIZE = define("%s_SZ", self.name)
    body = ""
    size = 0;

    for line in file:
      # skip comments
      if line.startswith('#'):
        continue
      line = string.strip(line)
      line += '\\n'
      size += len(line) - 1;
      body += "  \"%s\",\n" % line

    header.write(_template % (__HEADER__,
                              __HEADER__,
                              SIZE,
                              size,
                              self.name,
                              body))

def usage():
  print __doc__

def main(argv):
  opt_shader = None
  opt_header = None
  opt_name = None
  try:
    opts, args = getopt.getopt(argv, "hvo:n:", 	\
        ["help", "verbose", "--ouput=", "--name="])
  except getopt.GetoptError:
    usage()
    sys.exit(1)
  for opt, arg in opts:
    if opt in ("-h", "--help"):
      usage()
      sys.exit()
    elif opt in ("-v", "--verbose"):
      global _verbose
      _verbose = 1
    elif opt in ("-o", "-output"):
      opt_header = arg
    elif opt in ("-n", "-name"):
      opt_name = arg
  if args:
    opt_shader = "".join(args)

  #input validation
  if not opt_shader:
    print "error: you must supply a shader file.\n"
    usage()
    sys.exit(1)
  if not os.access(opt_shader, os.F_OK):
    print opt_shader + ": file not found"
    sys.exit(1)
  file, ext = os.path.splitext(opt_shader)
  if not opt_header:
    opt_header = file + ".h"
  if not opt_name:
    path, file = os.path.split(file)
    opt_name = file

  pso = PSO(opt_shader, opt_name)
  pso.write_header(opt_header)

if __name__ == "__main__":
  main(sys.argv[1:])

