#!/usr/local/bin/perl -w
# Select and visualise
use DBI;

use CGI;


$database = '***';
$hostname = '***';
$user = '***';
$password = '***';
$TITLE="Query Form";


$query = new CGI;

$path_info = $query->path_info;

if ($query->param ('Get the VRML document')){
    
   print $query->header('x-world/x-vrml');
 
   &print_VRML;
}
else {

   print $query->header;

# If no path information is provided, then we create 
# a side-by-side frame set
   if (!$path_info) {
      &print_frameset;
      exit 0;
   }


#Start HTML page

   &print_html_header;
   &print_query if $path_info=~/query/;
   &print_response if $path_info=~/response/;
   &print_html_end;
}

exit;

#----------------------------------------
# Subroutines
#-----------------------------------------

sub print_html_header {
    print $query->start_html($TITLE);
}
#-----------------------------------------
sub print_html_end {
       print $query->end_html;
}
#-----------------------------------------
sub print_frameset {
    $script_name = $query->script_name;

    print <<EOF;
<html><head><title>$TITLE</title></head>
<frameset cols="40,60">

<frame src="$script_name/query" name="query">
<frame src="$script_name/response" name="response">

</frameset>
EOF
    ;

   exit 0;
}
#------------------------------------------

sub print_query{
    $script_name = $query->script_name;

    print "<H1>Query</H1>\n";
    print $query->startform(-action=>"$script_name/response",
-TARGET=>"response");

print "<P><B><I><FONT COLOR=blue><FONT SIZE=-1> To create VRML dociment for visualization use: <BR> SELECT fid,enoseqf,nid,xc,yc,zc, bidg(sidg) FROM {tables} WHERE {condition} ORDER BY bidg(sidg),fid,enoseqf </FONT></FONT></I></B></P>";


    print "<P>SELECT: <BR>(fields)  ", 
    $query->textfield(-name=>'fields', 
			-default=>'fid,enoseqf,nid,xc,yc,zc,bidg',
			-size=>30,
			-maxlength=>120);

    
    print "<P> FROM: <BR> (tables)  ",
    $query->textfield(-name=>'tables', 
			-default=>'bodyg,face,node',
			-size=>30,
			-maxlength=>120);
    
    print "<P> WHERE: <BR> (condition) ",
    $query->textfield(-name=>'condition', 
			-default=>'bidg=4 and fid=fidb and nid=nidf',
			-size=>50,
			-maxlength=>120);
    
    print "<P> ORDER BY: <BR> (fields) ",
    $query->textfield(-name=>'order', 
			-default=>'bidg,fid,enoseqf',
			-size=>30,
			-maxlength=>120);


    print "<BR><BR>",$query->submit (' Submit query ');
    print $query->endform;

print qq{<P><A href="http://barley.itc.nl/VRML/START7.html" TARGET= "vrml" >back</A>};

}
#--------------------------------------------
sub print_response {

    $script_name= $query->script_name;
    print "<H1>Result</H1>\n";
    unless ($query->param) {
	print "<b>No query submitted yet.</b>";
	return;
    }

$fields = $query->param('fields');
$tables = $query->param('tables');
$condition = $query->param('condition');
$order = $query->param('order');

print "<P><B><FONT COLOR=red>SELECT $fields FROM $tables WHERE $condition ORDER BY $order</FONT></B></P>";

    print $query->startform;
    print $query->hidden(-name=>'fields',
                         -default=>$fields);
    print $query->hidden(-name=>'tables',
                         -default=>$tables);
    print $query->hidden(-name=>'condition',
                         -default=>$condition);
    print $query->hidden(-name=>'order',
                         -default=>$order);

    print $query->submit('Get the VRML document');
    print $query->endform;

    &query_database;
    
    for ($jj=0; $jj<$num; $jj++) {
       for ($ii=0;$ii<$num_rec[$jj]; $ii++) {
    
         print "$all[$jj]->[$ii]  ";
       }
       print "<BR>";
    }

}
#---------------------------------------------------------

sub query_database{


$dbh = DBI->connect ("DBI:mysql:$database:$hostname", $user,$password);

if ($order ne '') {

   $sth = $dbh->prepare("select $fields from $tables where $condition order by $order");
}
else {

  $sth = $dbh->prepare("select $fields from $tables where $condition ");
}

$sth->execute;

$num=0;

while (@field = $sth->fetchrow) {   
  $all[$num]=[@field];
  $num_rec[$num]=@field;
  $num++;
}

$sth->finish;

$dbh->disconnect; 

}
#--------------------------------------------------------
sub print_VRML {

$fields = $query->param('fields');
$tables = $query->param('tables');
$condition = $query->param('condition');
$order = $query->param('order');
          
   &print_vrml_header;
   &query_database;
   &print_vrml_surface;
   &print_vrml_end;

   return;
}
#----------------------------------------------------------
sub print_vrml_surface {

  $k=0; 
  $surface = $all[$k]->[6];

  while (($k<$num) && ($surface == ($all[$k]->[6]))) {#-start surface

    print <<EOF;
Shape {
   appearance Appearance {
        material Material {
                diffuseColor  0.20 0.40 0.60
                specularColor 0.80 0.80 0.80
        }
EOF
     ;

#--------print IndexFaceSet--------------------------------
    print <<EOF;
   }
   geometry IndexedFaceSet {
	convex FALSE
        coord Coordinate {
               point [
EOF
    ;
#----------------------------------------------------------

    $n_crd =0;
    $n_face = 0;
    $n[0] = 0;
    while (($k<$num) && (($all[$k]->[6])== $surface)) {
      $fid = $all[$k]->[0];
      $nodeinface=0; 
      while ($fid==$all[$k]->[0]) {
   
#------------------existing coordinates ?????-------------
        $exist = -1;
        $p=$n_crd;
  
        $i=0;
        while ($i<$p){
          if ($all[$k]->[1]==$n[$i]) {
            $exist=$i;
          }
          $i++;
        }
#-----------------------------------------------------------
        if ($exist == -1) { 
          $x[$n_crd] = $all[$k]->[3];
          $y[$n_crd] = $all[$k]->[4];
          $z[$n_crd] = $all[$k]->[5];
          $n[$n_crd] = $all[$k]->[2]; 
  
          $descr[$nodeinface]=$n_crd;
          $n_crd++;
    
        }
        else {
          $descr[$nodeinface]=$exist;
       
        }
    
        $nodeinface++;
        $k++;
   
      }

      $facedescr[$n_face]=[@descr];
      $nodedescr[$n_face]=$nodeinface;
 
      $n_face++;

    } #all the faces in a surface
#--------print coordinates----------------------

    $i=0;

    while ($i<$n_crd) {
      print "            $x[$i] $y[$i] $z[$i] \n";
      $i++;
    }  
    print <<EOF;
            ]
        }
        coordIndex [
         
EOF
    ;

#----------print description----------------------
    $i=0;
    while ($i<$n_face) {
  
      $j=0;
      print "      ";
      while ($j<$nodedescr[$i]) {
        print "$facedescr[$i]->[$j], ";
        $j++;
      }
      $i++;
      print " -1, \n";
    }
    print "       ]\n";   


    $surface = $all[$k]->[6];
 
    print <<EOF;
   } #for geometry
} #for shape
 
EOF
    ;

  } #--------end  surface----------------------------------

}
#---------------------------------------------------------
sub print_vrml_header {
  print <<EOF;
#VRML V2.0 utf8
#Sisi Zlatanova June'98
Group{
    children[

Background {
    skyColor [
        0.0 0.2 0.7,
        0.0 0.5 1.0,
        1.0 1.0 1.0,
    ]
   skyAngle [ 1.009, 1.571 ]
},


Viewpoint {
	position    110  20  -210   
	orientation 0 1 0 3.90
               fieldOfView 0.79
               description "ITC - old buildings"
},

Viewpoint {
	position    270  15  -0   
	orientation 0 1 0 0.60
               description "ITC from South"
},

PointLight {
        location 90 80 -230
        radius   1000.0
},

NavigationInfo{
            speed 1.0
            headlight TRUE
},
Transform {
        rotation 1 0 0 -1.571
        children[
EOF
  ;
} #end print_vrml_header
#---------------------------------------------------------------
sub print_vrml_end {

  print <<EOF;

]} # for transform

]} # for Group

EOF
  ;
} #end print_vrml_end
#---------------------------------------------------------------


