#! /usr/bin/perl -w
#
# $Id: wrl2smf 190 2003-08-18 13:54:52Z garland $
#

=head1 NAME

wrl2smf - Extract line and polygonal geometry from VRML files to SMF format

=head1 SYNOPSIS

B<wrl2smf> model.wrl > model.smf

=head1 DESCRIPTION

This is a very simple minded script for extracting line and polygonal
geometry from VRML files.  Once extracted, it is written out in SMF
format.  Specifically, this script attempts to decode B<IndexedLineSet>
and B<IndexedFaceSet> elements of the VRML input.  It does not apply any
transformations, materials, etc.  It merely extracts the raw geometry.

This script is in all probability quite B<brittle>.  I wrote it to
process a couple of VRML files that I happened to have.  It works on
them.  However, it may or may not work on any other VRML file.  And
since I didn't consult any VRML specs while I was writing it, who knows
what might be wrong with it.

=head1 VERSION

This is wrl2smf v1.0.

=head1 AUTHOR

Michael Garland <garland@cs.uiuc.edu>

=cut

my $vbase = 1;

undef $/;
while( <> )
{
    while( /geometry \s* Indexed(Line|Face)Set \s* \{
	    (?:.*?)  # Junk we don't care about
	    point \s* \[\s* ([^\]]*) \s* \]
	    (?:.*?)  # Junk we don't care about
	    coordIndex \s* \[ \s* ([^\]]*) \s* \]/sgx )
	{
	    my $smftag = "#";

	    $smftag = "e" if $1 eq "Line";
	    $smftag = "f" if $1 eq "Face";

	    output_elements($smftag, $2, $3);
	}
}

sub output_elements
{
    my ($tag, $vstring, $estring) = @_;

    my @vertices;

    if( index($vstring, ",") >= 0 )
    {
	# Normally, the [x y z] coordinates are separated by commas ...
	@vertices = split /\s*,\s*/, $vstring;
    }
    else
    {
	# ... but I've seen some that aren't.  Is this actually legal?
	@vertices = ($vstring =~ m/([-.\d]+\s+[-.\d]+\s+[-.\d]+)/g);
    }

    foreach my $v (@vertices)
    {
	print "v $v\n";
    }

    $estring =~ s/,//gm;

    my @elements = split /\s*-1\s*/, $estring;
    foreach my $e (@elements)
    {

	my @ids = split ' ',$e;
	my $idcount = @ids;

	foreach my $id (@ids) { $id += $vbase; }

	if( $tag eq "e" and $idcount>2 )
	{
	    my $i;
	    for($i=0; $i<$idcount-1; $i++)
	    {
		print "$tag ", $ids[$i], " ", $ids[$i+1], "\n";
	    }
	}
	else
	{
	    print "$tag @ids\n";
	}
    }

    $vbase += @vertices;
}
