#!/usr/local/bin/perl -w
# Query for adjacent objects
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<BR>buildings along streets</H1>\n";
    print $query->startform(-action=>"$script_name/response",
-TARGET=>"response");


    print "<P><BR>ID STREET: <BR>(identifier 1)  ", 
    $query->textfield(-name=>'id1', 
			-default=>'1',
			-size=>10,
			-maxlength=>120),"</P>";

    
    print "<P><BR>ID BUILDING: <BR> (identifier 2)  ",
    $query->textfield(-name=>'id2', 
			-default=>'2',
			-size=>10,
			-maxlength=>120),"</P>"; 
   
    print "<BR><BR>",$query->submit (' Submit query ');
    print $query->endform;

    print "<P><I><FONT COLOR=red><FONT SIZE=0>Note: an asterisk(*) initiates a search among all the object</FONT></I></P>";



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;
    }

$id1 = $query->param('id1');
$id2 = $query->param('id2');

print "<P><B><FONT COLOR=red>STREET: $id1<BR> BUILDING: $id2</FONT></B></P>";
     
    &qdb_check_nodes;
    
    print "<BR>street building <BR> ";
    for ($jj=0; $jj<$n_com; $jj++) {
          
       print "$b[$jj]     $s[$jj]";
       print "<BR>";
    }


    print $query->startform;
    print $query->hidden(-name=>'id1',
                         -default=>$id1);
    print $query->hidden(-name=>'id2',
                         -default=>$id1);

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

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

sub qdb_check_nodes {

$dbh = DBI->connect ("DBI:mysql:$database:$hostname", $user,$password);
  
  $n_body=$dbh->do ("select * from bodyt");
  $n_com=0;   

  if ($id1 eq "*") {$begi=1; $endi=$n_body+1;}
  else {$begi=$id1; $endi=$id1+1;} 

  for ($i=$begi; $i<$endi; $i++){
 
    $sth = $dbh->prepare("select nidf from surfg,face where sidg=$i and fids=fid");
    $sth->execute;

    $num_n1=0;
    while ($field = $sth->fetchrow) {   
      $all[$num_n1]=$field;
      $num_n1++;
    }
    $sth->finish;
    $body_1[$i]=[@all];   

    if ($id2 eq "*") {$begj=1; $endj=$n_body+1;}
    else {$begj=$id2; $endj=$id2+1;} 

  
    for ($j=$begj; $j<$endj;$j++){
      for ($kk=0;$kk<$num_n1;$kk++){

        $sth = $dbh->prepare("select nidf from bodyg,face where bidg=$j and fidb=fid and nidf=$body_1[$i]->[$kk]");
        $sth->execute;

      
        if ($field = $sth->fetchrow) {
           $b[$n_com] = $i;
           $s[$n_com] = $j;
           $n_com++;
        } 
        $sth->finish;      
      
      } # comparison faces body1/body2 
       
    } #one and more body2

  }#one and more body1


$dbh->disconnect; 

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

$id1 = $query->param('id1');
$id2 = $query->param('id2');
          
   &print_vrml_header;
   
   &qdb_check_nodes;
    
   $obj=0;
   for ($jj=0; $jj<$n_com; $jj++) {
       if ($b1[$jj] != $obj) {
           $obj=$b1[$jj];   
           &query_database_VRML;
           &print_vrml_surface;
       }
    }
   $obj=0;
   for ($jj=0; $jj<$n_com; $jj++) {
       if ($b2[$jj] != $obj) {
           $obj=$b2[$jj];   
           &query_database_VRML;
           &print_vrml_surface;
       }
    }

   &print_vrml_end;

   return;
}
#----------------------------------------------------------

sub query_database_VRML{

$fields = 'fid,enoseqf,nid,xc,yc,zc,bidg';
$tables = 'bodyg,face,node';
$condition = 'fid=fidb and nid=nidf';
$order = 'fid,enoseqf';

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


$sth = $dbh->prepare("select $fields from $tables where bidg=$obj and $condition order by $order");

$sth->execute;

$num=0;

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

$sth->finish;

$dbh->disconnect; 

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

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
#---------------------------------------------------------------



