floormap.in 30.5 KB
Newer Older
1 2 3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2005 University of Utah and the Flux Group.
5 6 7 8
# All rights reserved.
#
use English;
use Getopt::Std;
9
use File::Basename;
10

11 12 13
#
# TODO: Deal with multiple buildings? Currently defaults to MEB! 
# 
14
sub usage {
Timothy Stack's avatar
 
Timothy Stack committed
15
    print STDERR "Usage: floormap [-tvnx] [-T] [-g] [-o <prefix>] ";
16 17 18
    print STDERR "[-s <scale>] | [-c <map_x>,<_y>] ";
    print STDERR "[-S <last_scale> -C <last_x>,<_y>] -O <last_x_off>,<_y>] ";
    print STDERR "[-f <floor>] [<building>]";
19
    print STDERR "\nor\n";
Timothy Stack's avatar
 
Timothy Stack committed
20
    print STDERR "Usage: floormap [-tvnx] [-T] [-g] [-o <prefix>] ";
21 22
    print STDERR "[-s <scale>] | [-c <map_x>,<_y>] ";
    print STDERR "[-S <last_scale> -C <last_x>,<_y>] -O <last_x_off>,<_y>] ";
23
    print STDERR "[-e <pid,eid>] [<building>]\n";
24 25
    print STDERR "\nor\n";
    print STDERR "Usage: floormap [-k] [-o <prefix>] ";
26 27
    exit(-1);
}
28 29 30 31 32 33 34 35 36 37

# Debugging.
my $debug = 0;
sub dprint($) {
    my ($msg) = @_;
    
    print STDERR $msg
	if ($debug);
}

38
my $optlist  = "df:o:s:c:S:C:O:e:tTakgzvnxy";
39
my $notitles = 0;       # This suppresses titles surrounding the output map.
40
my $showany  = 0;	# When showing specific floor, showany is turned on.
41
my $mereuser = 1;
42
my $cleanup  = 0;
43
my $nozoom   = 0;
44
my $ghost    = 0;	#  Overlay ghost nodes from all floors onto each map.
45

Timothy Stack's avatar
 
Timothy Stack committed
46 47 48 49
# Display options
my $show_vnames    = 0;
my $show_cameras   = 0;
my $show_exclusion = 0;
50
my $show_nodes     = 1;
Timothy Stack's avatar
 
Timothy Stack committed
51

52
my $building;
53 54
my $floor;
my $image;
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

# These result from clicking on zoom/pan controls outside.
my $scale      = 1;	# From clicking on one of the scale buttons.
my $scale_arg  = 1;     # Scale by half-integer factors: 1=>1, 2=>1.5, 3=>2, etc.
my $map_x      = 0;	# From clicking on the (possibly scaled and offset) map.
my $map_y      = 0;

# Calculated from the scale and click coords.
my $x_offset   = 0;	# Offset on the upper-left corner of the image.
my $y_offset   = 0;
my $curr_x     = 0;	# The UNZOOMED, and hence un-offset, click point.
my $curr_y     = 0;

# We get previous scale, offsets, etc. to help interpret new click coords.
my $last_scale_arg = 1;
my $last_scale = 1;
my $last_x_off = 0;
my $last_y_off = 0;
my $last_x  = 0;  # The UNZOOMED, and hence un-offset, previous click point.
my $last_y  = 0;
my $last_notitles = 0;  # This says there were no titles around the previous images.

77 78 79 80
# The image produced for each floor will be this size, except when
# using thumbnails.
#
# XXX What is this! 
81 82 83
my $out_width  = 792;
my $out_height = 492;

84 85 86 87
# Max x,y of image to go into state file.
my $max_x = 0;
my $max_y = 0;

88 89
# Unless we suppress titles, there will be a header/trailer around each floor image.
my $head_height = 50;
90
my $head_pointsize = 32;
91 92
my $tail_height = 15;

93 94 95 96 97 98 99 100 101 102 103 104 105
# Thumbnail images are 40% as big.  Use smaller header/trailer as well.
my $thumb_head_height = 25;
my $thumb_head_pointsize = 16;
my $thumb_width = 316;
my $thumb_height = 196;
my $thumb_tail_height = 5;

# Assume non-thumbnail images last time, unless told otherwise by $last_scale == 0.
my $last_head_height = $head_height;
my $last_head_pointsize = $head_pointsize;
my $last_height = $out_height;
my $last_tail_height = $tail_height;

106 107
my $pid;
my $eid;
108 109
my @areamaps   = ();
my %baseimages = ();
110 111 112 113 114 115
my $prefix = "/tmp/floormap";

#
# Configure variables
#
my $TB		= "@prefix@";
116
my $WWWPAGE     = "@TBBASE@/shownode.php3";
117 118 119 120 121
my $ICONDIR     = "$TB/www";

# Load libraries.
use lib '@prefix@/lib';
use libdb;
122 123 124 125 126 127

# See http://www.imagemagick.org/www/perl.html .
# Also man ImageMagick, identify, display, convert, etc.
use Image::Magick;
my $images = new Image::Magick;
my $img_n  = -1;
128

Timothy Stack's avatar
 
Timothy Stack committed
129 130
my $excl = Image::Magick->new;

131 132
# Admin people get extra info
$mereuser = 0
133
    if (TBAdmin($UID));
134

135 136 137 138 139 140 141 142 143 144 145
# Ha.
my @floortags = ();
$floortags[1] = "1st floor";
$floortags[2] = "2nd floor";   
$floortags[3] = "3rd floor";
$floortags[4] = "4th floor";
$floortags[5] = "5th floor";
$floortags[6] = "6th floor";
$floortags[7] = "7th floor";
$floortags[8] = "8th floor";
$floortags[9] = "9th floor";
146

147 148 149 150 151
#
# Turn off line buffering on output
#
$| = 1;

152
# Forward declarations.
153 154 155
sub dofloor($$);
sub writefiles($@);
sub adjustmap($$$);
156 157
sub adjust_map_y($$);
sub calc_offsets($$$$$);
158 159 160 161 162 163 164 165 166

#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
167 168 169
if (defined($options{"a"})) {
    $showany = 1;
}
170 171
if (defined($options{"z"})) {
    $nozoom = 1;
172 173 174 175

    # XXX For the robot maps. Bogus.
    $out_width  = 1280;
    $out_height = 1024;
176
}
177 178 179
if (defined($options{"d"})) {
    $debug = 1;
}
180 181 182
if (defined($options{"k"})) {
    $cleanup = 1;
}
183 184 185
if (defined($options{"t"})) {
    $notitles = 1;
}
186 187 188
if (defined($options{"T"})) {
    $last_notitles = 1;
}
189 190 191
if (defined($options{"g"})) {
    $ghost = 1;
}
192
if (defined($options{"f"})) {
193 194
    $floor   = $options{"f"};
    $showany = 1;
195
}
196 197
if (defined($options{"s"})) {
    $scale_arg = $options{"s"};
198 199 200 201 202 203 204
    if ($scale_arg > 0) {
	# Scale by half-integer factors: 1=>1, 2=>1.5, 3=>2, etc.
	$scale = ( $scale_arg + 1 ) / 2;
    }
    else {
	# Scale_arg 0 means to use the 40% size thumbnail images.
	$scale = 0.4;
205 206 207 208 209

	# Skinny down the head/tail heights as well.
	$head_height = $thumb_head_height;
	$head_pointsize = $thumb_head_pointsize;
	$tail_height = $thumb_tail_height;
210
    }
211 212 213 214
    dprint "scale arg $scale_arg, scaling factor $scale\n";
}
if (defined($options{"S"})) {
    $last_scale_arg = $options{"S"};
215 216 217 218 219 220 221
    if ($last_scale_arg > 0) {
	# Scale by half-integer factors: 1=>1, 2=>1.5, 3=>2, etc.
	$last_scale = ( $last_scale_arg + 1 ) / 2;
    }
    else {
	# Scale_arg 0 means to use the 40% size thumbnail images.
	$last_scale = 0.4;
222 223 224 225 226 227

	# Skinny down the head/tail heights as well.
	$last_head_height = $thumb_head_height;
	$last_head_pointsize = $thumb_head_pointsize;
	$last_height = $thumb_height;
	$last_tail_height = $thumb_tail_height;
228
    }
229 230 231 232 233 234 235
    dprint "last_scale arg $last_scale_arg, last scaling factor $last_scale\n";

    # Do this now so $scale is defined when reading in images.
    if (!defined($options{"s"})) {
	# If we didn't specify a new scale, keep it the same as the last time.
	$scale_arg = $last_scale_arg;
	$scale = $last_scale;
236 237 238 239 240 241

	# Skinny down the head/tail heights as well.
	$head_height = $last_head_height;
	$head_pointsize = $last_head_pointsize;
	$tail_height = $last_tail_height;

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	dprint "scale from last_scale_arg $last_scale_arg, last_scale $scale\n";
    }
}
if (defined($options{"c"})) {
    if ($options{"c"} =~ /([-\w]*),([-\w]*)/) {
	$map_x = $1;
	$map_y = $2;
        dprint "click point $map_x, $map_y\n";
    }
    else {
	die("*** $0:\n".
	    "    Invalid argument to -c option!\n");
    }
}
if (defined($options{"C"})) {
    if ($options{"C"} =~ /([-\w]*),([-\w]*)/) {
	$last_x = $1;
	$last_y = $2;
        dprint "last click $last_x, $last_y\n";
    }
    else {
	die("*** $0:\n".
	    "    Invalid argument to -C option!\n");
    }
}
if (defined($options{"O"})) {
    if ($options{"O"} =~ /([-\w]*),([-\w]*)/) {
	$last_x_off = $1;
	$last_y_off = $2;
        dprint "last offset $last_x_off, $last_y_off\n";
    }
    else {
	die("*** $0:\n".
	    "    Invalid argument to -C option!\n");
    }
}
278 279
if (defined($options{"o"})) {
    $prefix = $options{"o"};
280
    if ($cleanup) {
281
	unlink $prefix, "${prefix}.jpg", "${prefix}.map", "${prefix}.state";
282 283
	exit(0);
    }
284
}
285 286 287
if (defined($options{"y"})) {
    $show_nodes = 0;
}
Timothy Stack's avatar
 
Timothy Stack committed
288 289 290 291 292 293 294 295 296
if (defined($options{"v"})) {
    $show_cameras = 1;
}
if (defined($options{"n"})) {
    $show_vnames = 1;
}
if (defined($options{"x"})) {
    $show_exclusion = 1;
}
297

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
if (defined($options{"e"})) {
    if ($options{"e"} =~ /([-\w]*),([-\w]*)/) {
	$pid = $1;
	$eid = $2;
    }
    else {
	die("*** $0:\n".
	    "    Invalid argument to -e option!\n");
    }

    #
    # Verify permission to view this experiment.
    #
    if ($UID && !TBAdmin($UID) &&
	! TBExptAccessCheck($UID, $pid, $eid, TB_EXPT_READINFO)) {
	die("*** $0:\n".
	    "    You do not have permission to view $pid/$eid!\n");
    }
316

317 318 319 320 321 322 323 324 325
    #
    # Optional building and floor (see above) for a specific experiment.
    #
    usage()
	if (@ARGV > 1);
    if (@ARGV) {
	$building = $ARGV[0];
    }
}
326 327
elsif (@ARGV == 1) {
    $building = $ARGV[0];
328
}
329

330 331 332
#
# Gather image data from DB.
#
333 334 335
# Scale_arg 0 means to use the 40% size thumbnail images.
my $path_col = ($scale_arg == 0 ? "thumb_path" : "image_path");
my $db_scale = max($scale_arg, 1);
336
my $query_result =
Timothy Stack's avatar
 
Timothy Stack committed
337 338
    DBQueryFatal("select b.building,b.title,f.floor,f.$path_col,".
		 "f.pixels_per_meter ".
339 340
		 "   from buildings as b ".
		 "left join floorimages as f on f.building=b.building ".
341
		 "where f.scale=$db_scale");
342 343 344 345 346 347

if (!$query_result->numrows) {
    die("*** $0:\n".
	"    There is no building/floor data in the DB!\n");
}

Timothy Stack's avatar
 
Timothy Stack committed
348 349
while (my ($building,$title,$floor,$image,$ppm) = 
       $query_result->fetchrow_array()) {
350 351 352 353
    ##dprint "building $building, floor $floor, image $image\n";
    if (!exists($baseimages{$building})) {
	$baseimages{$building} = {};
	$baseimages{$building}->{"title"}  = $title;
Timothy Stack's avatar
 
Timothy Stack committed
354
	$baseimages{$building}->{"ppm"}  = $ppm;
355 356 357
	$baseimages{$building}->{"floors"} = {};
    }

358
    $image = "$TB/www/floormap/$image"
359 360 361 362 363 364 365 366 367 368
	if (dirname($image) eq ".");
    dprint "image $image\n";

    if (! -e $image) {
	die("*** $0:\n".
	    "    $image does not exist!\n");
    }
    $baseimages{$building}->{"floors"}->{$floor} = $image;
}

369 370 371 372
# Must specify a building with a floor.
if (defined($floor) && !defined($building)) {
    die("*** $0:\n".
	"    Must supply a building name!\n");
373 374
}

375 376
# Building must exist.
if (defined($building) && !exists($baseimages{$building})) {
377 378
    die("*** $0:\n".
	"    No such building: $building\n");
379
}
380 381 382 383 384

#
# If a floor specified, then do just that floor and spit it out.
#
if (defined($floor)) {
385
    if (!exists($baseimages{$building}->{"floors"}->{$floor})) {
386 387 388
	die("No such floor '$floor' in building: $building\n");
    }
    
389 390 391
    my ($floorimage, $areamap) = dofloor($building, $floor);
    $image    = $floorimage;
    @areamaps = ($areamap);
392 393 394

    $max_x = $floorimage->Get('width');
    $max_y = $floorimage->Get('height');
395 396 397 398 399 400 401
}
else {
    #
    # Need to find all the floors in this building and generate them all.
    #
    my @floors = ();

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    if (defined($building)) {
	foreach my $floor (sort(keys(%{ $baseimages{$building}->{"floors"} }))) {
	    my ($floorimage, $areamap) = dofloor($building, $floor);

	    push(@floors, [ $floorimage, $areamap ])
		if (defined($floorimage));
	}
    }
    else {
	#
	# XXX We need to be fancier for multiple buildings at some point!
	# Not much of a worry right now.
	#
	foreach my $building (sort(keys(%baseimages))) {
	    my @floorlist = sort(keys(%{ $baseimages{$building}->{"floors"} }));
	    
	    foreach my $floor (@floorlist) {
		my ($floorimage, $areamap) = dofloor($building, $floor);
420

421 422 423 424
		push(@floors, [ $floorimage, $areamap ])
		    if (defined($floorimage));
	    }
	}
425 426 427 428 429 430 431
    }

    #
    # Now generate a superimage from all the base images. We just line
    # them up; nothing fancy at all.
    #
    my $running_y = 0;
432 433 434
    foreach my $ref (@floors) {
	my ($floorimage, $areamap) = @$ref;
	
435
	# Move all the map references down by adjusted amount.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
436
	adjustmap($areamap, 0, $running_y);
437 438
	push(@areamaps, $areamap);
	
439
	$running_y += $floorimage->Get('height');
440
    }
441 442 443 444 445 446 447 448 449 450
    dprint "images ".($img_n+1)."\n";
    ## Append and Coalesce get this error - 
    ##    Image::Magick=ARRAY(0x84116b8) at ./floormap.in line 266.
    ## Instead, do it from the shell after writing the component images below.
    ##$err = $images->Append();
    ##warn "$err" if "$err";
}
writefiles($images->[0], @areamaps);

## Append the component images in the shell, until the Perl function is fixed.
451
dprint "Last image is $img_n.\n";
452 453 454 455 456 457 458 459 460 461 462
if ($img_n > 0) {
    my @args = ("convert", "${prefix}.jpg.*", "-append", "${prefix}.jpg");
    dprint "@args\n";
    system(@args) == 0
	or die "system @args failed: $?";

    ## Clean up the component image files.
    @args = ("/bin/sh", "-c", "rm ${prefix}.jpg.*");
    dprint "@args\n";
    system(@args) == 0
	or die "system @args failed: $?";
463 464 465 466
}
exit(0);

#
467
# Do a floor. Returns the image object and an "areamap". 
468 469 470 471
#
sub dofloor($$)
{
    my ($building, $floor) = @_;
472
    my $isnew = 0;
473 474 475 476

    #
    # Grab the nodes on this floor in this building. We want to know
    # their allocation status so we know what colors to use.
477
    #
478
    my $query = "select loc.*,r.pid,r.eid,r.vname, ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
479 480
                "  n.battery_voltage,n.battery_percentage, ".
		"  n.destination_x,n.destination_y,n.destination_orientation ".
481 482
		"  from location_info as loc ".
		"left join reserved as r on r.node_id=loc.node_id ".
483
		"left join nodes as n on n.node_id=loc.node_id ".
484 485
		"where loc.building='$building' " .
		(defined($pid) ? " and r.pid='$pid' and r.eid='$eid'" : "");
486 487
    my $query_result = DBQueryFatal($query . " and loc.floor='$floor'");

488
    
489 490 491
    my $newnodes_query = "select * from new_nodes ".
		         "where building='$building'";
    my $newnodes_result = DBQueryFatal($newnodes_query . " and floor='$floor'");
492

493 494 495 496 497 498
    # When ghosting is turned on, get nodes from all floors to be overlaid.
    my ($ghost_result, $ghost_newnodes_result);
    if ($ghost) {
	$ghost_result = DBQueryFatal($query);
	$ghost_newnodes_result = DBQueryFatal($newnodes_query);
    }
499 500 501 502 503 504 505 506 507 508

    if ($mereuser) {
	if (!$query_result->numrows && !$showany) {
	    return (undef, undef);
	}
    }
    else {
	if (!$query_result->numrows && !$newnodes_result->numrows && !$showany) {
	    return (undef, undef);
	}
509 510
    }

511 512 513 514 515 516 517 518 519 520 521 522 523
    #
    # The area map is indexed by nodeid, and contains a list of the
    # x1,y1,x2,y2 (upper left, lower right) coordinates of the "hot"
    # area.  We have to wait till later to actually generate the map
    # cause the coords might need to be adjusted if creating a floor
    # as part of a building (and the floor image gets moved within a
    # bigger image).
    #
    # XXX We make no attempt to deal with overlapping icons (areamaps).
    # This will eventually lead to confusion and incorrect maps.
    # 
    my $areamap = {};

524 525 526
    #
    # Grab the base image for the floor.
    #
527
    if (! exists($baseimages{$building}->{"floors"}->{$floor})) {
528 529 530
	die("*** $0:\n".
	    "    No base image for $building:$floor!\n");
    }
531 532 533 534 535 536 537 538 539 540 541 542 543 544
    
    my $err = $images->Read($baseimages{$building}->{"floors"}->{$floor});
    if ("$err") {
        die("*** $0:\n".
            "$err\n".
            "    Could not get base ".
            $baseimages{$building}->{"floors"}->{$floor}  ."!\n");
    }
    $img_n++;
    my $baseimage = $images->[$img_n];

    # Figure out where the user clicked.  (Use the upper-left corner if no click yet.)
    # We won't have both scale and click coords, because they are separate controls.
    if (defined($options{"c"})) {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
	if ($nozoom) {
	    #
	    # All we want is the crosshair.
	    # 
	    $curr_x = $map_x;
	    $curr_y = $map_y;
	}
	else {
	    # Back out the influence of the previously applied scale and
	    # offsets, so it is as if we are always clicking onto an image
	    # that is not scaled or offset.
	    my $image_x = $map_x;
	    my $image_y = adjust_map_y($map_y, $last_notitles);
	    dprint "recent click coords $image_x, $image_y ($map_y)\n";
	    $curr_x = int(($image_x + $last_x_off) / $last_scale);
	    $curr_y = int(($image_y + $last_y_off) / $last_scale);
	    dprint "new unzoomed center $curr_x, $curr_y\n";
	}
563 564 565 566
    } else {
	$curr_x = $last_x;
	$curr_y = $last_y;
    }
567

568 569 570 571 572 573 574 575 576 577
    # Set up for zoom (scale) and pan (offset center).  Get the offset to the
    # upper-left corner of the output image, based on the desired center point.
    my $in_width = $baseimage->Get('width');
    my $in_height = $baseimage->Get('height');
    dprint "input size $in_width, $in_height\n";
    ($x_offset, $y_offset) = 
	calc_offsets($scale, $curr_x, $curr_y, $in_width, $in_height);
    dprint "new offsets $x_offset, $y_offset\n";

    # Crop the correct rectangle out of the input image.
578 579 580
    my $this_width = min($in_width, $out_width);
    my $this_height = min($in_height, $out_height);
    $err = $baseimage->Crop(width=>$out_width, height=>$this_height, 
581 582 583
			    x=>$x_offset, y=>$y_offset);
    warn "$err" if "$err";

Timothy Stack's avatar
 
Timothy Stack committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597
    if ($show_cameras) {
	my $camera_query = "select * from cameras where building='$building'";
	my $camera_result = DBQueryFatal($camera_query . 
					 " and floor='$floor'");
	
	while (my %crow = $camera_result->fetchhash()) {
	    my $xmin    = $crow{"loc_x"} * $baseimages{$building}->{"ppm"};
	    my $ymin    = $crow{"loc_y"} * $baseimages{$building}->{"ppm"};
	    my $xmax    = ($crow{"loc_x"} + $crow{"width"}) * 
		$baseimages{$building}->{"ppm"};
	    my $ymax    = ($crow{"loc_y"} + $crow{"height"}) *
		$baseimages{$building}->{"ppm"};
	    
	    $err = $baseimage->Draw(stroke=>'orange',
598
				    strokewidth=>'1',
Timothy Stack's avatar
 
Timothy Stack committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
				    primitive=>'rectangle',
				    points=>"$xmin,$ymin $xmax,$ymax");
	    warn "$err" if "$err";
	}

    }
    
    #
    # Stick in obstacles, if any.
    #
    my $obstacles_result =
	DBQueryFatal("select * from obstacles ".
		     "where floor='$floor' and building='$building'");

    while (my %obrow = $obstacles_result->fetchhash()) {
	my $id       = $obrow{"obstacle_id"};
	my $x1       = $obrow{"x1"};
	my $x2       = $obrow{"x2"};
	my $y1       = $obrow{"y1"};
	my $y2       = $obrow{"y2"};
	my $descr    = $obrow{"description"};
	my $props  = {};

	$props->{"X1"}    = $x1;
	$props->{"Y1"}    = $y1;
	$props->{"X2"}    = $x2;
	$props->{"Y2"}    = $y2;
	$props->{"DESCR"} = $descr;
	$props->{"ISOBS"} = 1;
	$areamap->{"$id"} = $props;

	if ($show_exclusion) {
631
	    my $obstacle_buffer = 23; # XXX
Timothy Stack's avatar
 
Timothy Stack committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645
	    my $xmin = $x1 - $obstacle_buffer;
	    my $ymin = $y1 - $obstacle_buffer;
	    my $xmax = $x2 + $obstacle_buffer;
	    my $ymax = $y2 + $obstacle_buffer;

	    $err = $baseimage->Draw(primitive=>'rectangle',
				    points=>"$xmin,$ymin $xmax,$ymax",
				    stroke=>'steelblue',
				    strokewidth=>'1.5',
				    fill=>"#000000dd");
	    warn "$err" if "$err";
	}
    }

646 647 648
    return ($baseimage, $areamap)
	if (!$show_nodes);

649
    # Draw the selected node locations and labels. 
650 651 652
    # Green dot means node is free or owned by pid/eid.
    # Red dot mean node is down.
    # Blue dot means node is allocated
653 654 655 656
    # Gold dot means node is new.
    my $DOT_RAD = 5;	# Offset from center to edge of dot.
    my $LX    = -10;    # Offset from center of dot to label.
    my $LY    = 15;
657 658 659 660 661 662 663
    foreach my $isnew (0, 1) {
	my $table;
	
	if ($isnew) {
	    next
		if ($mereuser);
	    
664
	    $table = ($ghost ? $ghost_newnodes_result : $newnodes_result);
665 666
	}
	else {
667
	    $table = ($ghost ? $ghost_result : $query_result);
668 669 670 671
	}
	
	while (my $rowref = $table->fetchrow_hashref()) {
	    my $nodeid = $rowref->{"node_id"};
672 673
	    my $x      = int($rowref->{"loc_x"} * $scale - $x_offset);
	    my $y      = int($rowref->{"loc_y"} * $scale - $y_offset);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
674 675 676 677
	    my $o      = $rowref->{"orientation"};
	    my $dx     = $rowref->{"destination_x"};
	    my $dy     = $rowref->{"destination_y"};
	    my $do     = $rowref->{"destination_orientation"};
678 679
	    my $rpid   = $rowref->{"pid"};
	    my $reid   = $rowref->{"eid"};
680
	    my $vname  = $rowref->{"vname"};
681
	    my $label  = $nodeid;
682
 	    my $newid  = ($isnew ? $rowref->{"new_node_id"} : 0);
683
	    my $props  = {};
684

685
            my $color;
686
	    if ($isnew) {
687
		$color = 'gold'
688 689 690 691 692
		}
	    elsif ((!defined($pid) && !(defined($rpid))) ||
		   (defined($pid) && defined($rpid) && $pid eq $rpid)) {
		# Without -e option, green means node is free.
		# With -e option, green means node belongs to experiment. 
693
		$color = 'limegreen';
694
		if (defined($vname)) {
Timothy Stack's avatar
 
Timothy Stack committed
695 696 697
		    $props->{'PNAME'} = $nodeid;
		    $label = $vname 
			if ($show_vnames);
698
		}
699 700 701 702 703 704
		if (defined($rowref->{"battery_voltage"})) {
		    $props->{'BATVOLTS'} = $rowref->{"battery_voltage"};
		}
		if (defined($rowref->{"battery_percentage"})) {
		    $props->{'BATPERCENT'} = $rowref->{"battery_percentage"};
		}
705 706
	    }
	    elsif ($rpid eq NODEDEAD_PID() and $reid eq NODEDEAD_EID()) {
707
		$color = 'red';
708 709
	    }
	    else {
710
		$color = 'blue';
711 712 713 714 715 716 717 718 719 720 721 722
		if (!$mereuser) {
		    if (defined($rpid)) {
			$props->{'VNAME'} = $vname;
			$props->{'PID'}   = $rpid;
			$props->{'EID'}   = $reid;
		    }
		    if (defined($rowref->{"battery_voltage"})) {
			$props->{'BATVOLTS'} = $rowref->{"battery_voltage"};
		    }
		    if (defined($rowref->{"battery_percentage"})) {
			$props->{'BATPERCENT'} = $rowref->{"battery_percentage"};
		    }
723
		}
724
	    }
725
            my $x2 = $x + $DOT_RAD;
726 727 728 729 730 731 732 733
	    if ($ghost && $rowref->{"floor"} != $floor) { 
		$err = $baseimage->Draw(stroke=>$color, strokewidth=>'1.5',
					primitive=>'circle', points=>"$x,$y $x2,$y");
	    }
	    else {
		$err = $baseimage->Draw(fill=>$color, 
					primitive=>'circle', points=>"$x,$y $x2,$y");
	    }
734
            warn "$err" if "$err";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
	    if (defined($o)) {
		my ($ox2, $oy2);
		ComputeOrientationLine($x, $y, 15.0, $o, \$ox2, \$oy2);

		$err = $baseimage->Draw(stroke=>$color, 
					primitive=>'line',
					points=>"$x,$y $ox2,$oy2");
		warn "$err" if "$err";
	    }
	    #
	    # Draw hollow circle for the destination (of the robot).
	    # Add an oritentation stick as well, if defined.
	    # 
	    if (defined($dx) && defined($dy)) {
		$dx = int($dx * $scale - $x_offset);
		$dy = int($dy * $scale - $x_offset);
		my $dlx  = $dx+$LX;
		my $dly  = $dy+$LY;
		my $dx2 = $dx + $DOT_RAD;

		$err = $baseimage->Draw(stroke=>$color,
					strokewidth=>'1.5',
					primitive=>'circle',
					points=>"$dx,$dy $dx2,$dy");
		warn "$err" if "$err";

		if (defined($do)) {
		    my ($ox2, $oy2);
		    ComputeOrientationLine($dx, $dy, 15.0, $do, \$ox2, \$oy2);

		    $err = $baseimage->Draw(stroke=>$color, 
					    primitive=>'line',
					    points=>"$dx,$dy $ox2,$oy2");
		    warn "$err" if "$err";

		    # Shift the label above of the orientation line would go
		    # through it.
772
		    $dly = $dy - ($DOT_RAD + 2)
Timothy Stack's avatar
 
Timothy Stack committed
773 774 775 776 777 778 779 780
			if (($do < 0.0 && $do > -180.0) || 
			    ($do > 180.0 && $do < 360.0));
		}
		if (abs($x - $dx) > 20 || abs($y - $dy) > 20) {
		    $err = $baseimage->Annotate(fill=>'black',
						x=>$dlx, y=>$dly,
						text=>"$label");
		    warn "$err" if "$err";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
		}

		#
		# And, draw a light grey line from source to destination
		# to make it very clear.
		#
		$err = $baseimage->Draw(stroke=>'Grey',
					strokewidth=>'1.0',
					primitive=>'line',
					points=>"$x,$y $dx,$dy");
		warn "$err" if "$err";
	    }
	    # Label location;
	    my $lx = $x+$LX;
	    my $ly = $y+$LY;

	    # Shift the label above of the orientation line would go
	    # through it.
	    $ly = $y - ($DOT_RAD + 2)
Timothy Stack's avatar
 
Timothy Stack committed
800 801
		if (defined($o) && (($o < 0.0 && $o > -180.0) || 
				    ($o > 180.0 && $o < 360.0)));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
802 803
	    
            $err = $baseimage->Annotate(fill=>'black', x=>$lx, y=>$ly, 
804 805
					text=>"$label");
            warn "$err" if "$err";            
806

807 808 809 810 811 812
	    $props->{"X1"} = $x - $DOT_RAD;
	    $props->{"Y1"} = $y - $DOT_RAD;
	    $props->{"X2"} = $x + $DOT_RAD;
	    $props->{"Y2"} = $y + $DOT_RAD;
	    $props->{"ISNEW"}   = $newid;
	    $areamap->{$nodeid} = $props;
813
	}
814
    }
815

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    # Add a crosshair if the user specified a center point.
    if ($curr_x || $curr_y) {
	my $CROSS_SIZE = 12;	# Length of each arm of the crosshair.
	my $x0 = int($curr_x * $scale - $x_offset);
	my $y0 = int($curr_y * $scale - $y_offset);
	my $x1 = $x0 - $CROSS_SIZE;
	my $x2 = $x0 + $CROSS_SIZE;
	my $y1 = $y0 - $CROSS_SIZE;
	my $y2 = $y0 + $CROSS_SIZE;
	dprint "cross at $x0,$y0, lft $x1, rt $x2, top $y1, bot $y2\n";
	$err = $baseimage->Draw(stroke=>'red', primitive=>'line',
				points=>"$x1,$y0, $x2,$y0");
	warn "$err" if "$err";
	$err = $baseimage->Draw(stroke=>'red', primitive=>'line',
				points=>"$x0,$y1, $x0,$y2");
	warn "$err" if "$err";
    }

834 835
    if (!$notitles) {
	#
836
	# We want to stick in a label for the floor. To do that we need to make
837 838
	# some white space at the top by expanding the image, and moving it down.
	# 
839 840 841 842 843
	my $floor_label = $baseimages{$building}->{"title"} . 
	    " - "  . $floortags[$floor];
	dprint "head label $floor_label\n";
        $err = $baseimage->Border(fill=>'white', width=>0, height=>$head_height);
        warn "$err" if "$err";
844
        $err = $baseimage->Annotate(fill=>'black', x=>10, y=>$head_height*0.8, 
845
                                    font=>"/usr/testbed/lib/arial.ttf", 
846
				    pointsize=>$head_pointsize,
847 848 849 850
                                    text=>"$floor_label");
	warn "$err" if "$err";            

        # Border adds to both the top and the bottom.  Crop some of it away.
851
        my $y1 = $head_height + $this_height;
852
        my $y2 = $y1 + $tail_height;
853
        $err = $baseimage->Crop(width=>$this_width, height=>$y2);
854 855 856
        warn "$err" if "$err";
        # Fill in a black rectangle at the bottom for a separator.
        $err = $baseimage->Draw(fill=>'black', primitive=>'rectangle',
857
                                points=>"0,$y1, $this_width,$y2");
858
        warn "$err" if "$err";
859 860

	# Have to adjust the maps cause we just moved everything.
861
	adjustmap($areamap, 0, $head_height);
862
    }
863

864 865 866
    return ($baseimage, $areamap);
}

867 868 869 870 871 872 873
#
# Common code to adjust a Y coordinate from an image click into a map Y coordinate.
# The image may have multiple floor maps, with optional headers and trailers.
#
sub adjust_map_y($$) {
    my ($_y, $_notitles) = @_;
    
874 875 876
    my $map_height = $last_height + 
	($_notitles ? 0 : $last_head_height + $last_tail_height);
    my $raw_map_y = ($_y % $map_height) - ($_notitles ? 0 : $last_head_height);
877
    # Avoid out-of-bound coords if the header or trailer is clicked.
878
    my $map_y = max(0, min($raw_map_y, $last_height));
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
    dprint "adjust_map_y map_height $map_height, " .
	"_y $_y, raw_map_y $raw_map_y, map_y $map_y\n";

    return $map_y;
}

# 
# Common code to calculate the image offsets from the upper-left corner, given the
# desired image scale, UNZOOMED center point, and the dimensions of the source image.
# 
# At scale 1, the offsets will always be zero because we have to show the whole image.
# At higher scales, there is room in the middle of the image where we are not up
# against the edges, so we can offset to center the clicked point on the map.  Close
# to the edges, the image edges limit the offsets.
# 
sub calc_offsets($$$$$) {
    my ($scale, $curr_x, $curr_y, $in_width, $in_height) = @_;

897 898 899
    return (0, 0)
	if ($nozoom);

900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    my $scaled_click_x = $curr_x * $scale;
    my $scaled_click_y = $curr_y * $scale;

    # Offset limited by the scaled image size; scale 1 will always have zero offsets.
    if ($scaled_click_x > $out_width/2) {
        my $click_limit = $in_width - $out_width/2;
        if ($scaled_click_x > $click_limit) {
            dprint "right limit $click_limit\n";
            $x_offset = $in_width-$out_width;       # Against the right edge.
        }
        else {
            $x_offset = $scaled_click_x - ($out_width/2) # In the middle.
        }
    } else {
	dprint "left limit 0\n";
	my $x_offset = 0;                           # Against the left edge.
    }

    if ($scaled_click_y > $out_height/2) {
        $click_limit = $in_height - $out_height/2;
        if ($scaled_click_y > $click_limit) {
            dprint "bottom limit $click_limit\n"; 
            $y_offset = $in_height-$out_height;     # Against the bottom edge.
        }
        else {
            $y_offset = $scaled_click_y - ($out_height/2) # In the middle.
        }
    } else {
	dprint "top limit 0\n";
	my $y_offset = 0;                           # Against the top edge.
    }

    return (int($x_offset), int($y_offset));
}

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
#
# Adjust map coordinates moving everything by x,y amount. This is used
# when building an image of multiple maps.
#
sub adjustmap($$$)
{
    my ($mapref, $x, $y) = @_;

    foreach my $nodeid (keys(%{ $mapref })) {
	$mapref->{$nodeid}->{"X1"} += $x;
	$mapref->{$nodeid}->{"Y1"} += $y;
	$mapref->{$nodeid}->{"X2"} += $x;
	$mapref->{$nodeid}->{"Y2"} += $y;
    }
}

#
# Take a list of the areamaps created in the above function, and dump them
# to the output file so that the web page can grab them.
#
sub writefiles($@)
{
    my ($image, @maps) = @_;

959 960 961 962 963 964 965
    # Image.
    my $err = $images->Write("${prefix}.jpg");
    if ("$err") {
        die("*** $0:\n".
            "$err\n".
            "    Could not open ${prefix}.jpg for writing!\n");
    }
966
	
967 968
    # Areamap.
    if (!open(MAP, "> ${prefix}.map")) {
969
	unlink("${prefix}.jpg");
970 971 972 973 974 975 976 977 978 979 980 981 982
	die("*** $0:\n".
	    "    Could not open ${prefix}.map for writing!\n");
    }
    print MAP "<MAP NAME=floormap>\n";

    foreach my $mapref (@maps) {
	my %map = %{ $mapref };
	
	foreach my $nodeid (keys(%map)) {
	    my $x1 = $map{$nodeid}->{"X1"};
	    my $y1 = $map{$nodeid}->{"Y1"};
	    my $x2 = $map{$nodeid}->{"X2"};
	    my $y2 = $map{$nodeid}->{"Y2"};
983 984
	    my $isobs = $map{$nodeid}->{"ISOBS"};
	    my $descr = $map{$nodeid}->{"DESCR"};
985
	    my $isnew = $map{$nodeid}->{"ISNEW"};
986 987 988 989 990 991
	    my $link  = ($isobs ?
			 "showobstacle.php3?id=${nodeid}" :
			 ($isnew ?
			  "newnode_edit.php3?id=${isnew}" :
			  "shownode.php3?node_id=${nodeid}"));
	    my $title = ($isobs ? $descr : $nodeid);
992 993 994 995 996 997

	    $title .= " (vname=" . $map{$nodeid}->{'VNAME'} . ")"
		if (exists($map{$nodeid}->{'VNAME'}));
	    $title .= " " . $map{$nodeid}->{'PID'} . "/" .
		$map{$nodeid}->{'EID'} . ""
		    if (exists($map{$nodeid}->{'PID'}));
998

999 1000 1001 1002 1003 1004
	    $title .= " " . $map{$nodeid}->{'BATVOLTS'} . " volts"
		if (exists($map{$nodeid}->{'BATVOLTS'}));
	    
	    $title .= " " . $map{$nodeid}->{'BATPERCENT'} . "%"
		if (exists($map{$nodeid}->{'BATPERCENT'}));

1005
	    print MAP "<AREA SHAPE=RECT COORDS=\"$x1,$y1,$x2,$y2\" ".
1006
		      "TITLE=\"$title\" HREF=\"${link}\">\n\n";
1007
	}
1008
    }
1009 1010
    print MAP "</MAP>\n";
    close(MAP);
1011
	
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    # HTML items save state.  They are included into the form by PHP and returned to
    # us by HTML-get as page arguments when the map or zoom buttons are clicked on.
    if (!open(STATE, "> ${prefix}.state")) {
	unlink("${prefix}.jpg");
	die("*** $0:\n".
	    "    Could not open ${prefix}.state for writing!\n");
    }
    print STATE "  <input type=\"hidden\" name=\"last_scale\" " .
	"value=\"$scale_arg\">\n";
    print STATE "  <input type=\"hidden\" name=\"last_x_off\" " .
	"value=\"$x_offset\">\n";
    print STATE "  <input type=\"hidden\" name=\"last_y_off\" " .
	"value=\"$y_offset\">\n";
    # Note that the click point is in UNZOOMED, and hence un-offset, coordinates.
    print STATE "  <input type=\"hidden\" name=\"last_x\" " .
	"value=\"$curr_x\">\n";
    print STATE "  <input type=\"hidden\" name=\"last_y\" " .
	"value=\"$curr_y\">\n";
1030 1031
    print STATE "  <input type=\"hidden\" name=\"last_ghost\" " .
	"value=\"$ghost\">\n";
1032 1033 1034 1035
    if ($notitles) {
	print STATE "  <input type=\"hidden\" name=\"last_notitles\" " .
	    "value=\"$notitles\">\n";
    }
1036 1037 1038 1039 1040
    print STATE "  <input type=\"hidden\" name=\"max_x\" " .
	"value=\"$max_x\">\n";
    print STATE "  <input type=\"hidden\" name=\"max_y\" " .
	"value=\"$max_y\">\n";
    
1041
    close(STATE);
1042
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1043 1044 1045 1046 1047 1048 1049 1050

#
# Compute a line segment given a point and a compass heading of a robot.
#
sub ComputeOrientationLine($$$$$$)
{
    my ($x1, $y1, $distance, $angle, $px2, $py2) = @_;

Timothy Stack's avatar
 
Timothy Stack committed
1051 1052
    my $x2 = $x1 + $distance * cos(-$angle * 3.1415926536 / 180.0);
    my $y2 = $y1 + $distance * sin(-$angle * 3.1415926536 / 180.0);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1053 1054 1055 1056 1057

    $$px2 = $x2;
    $$py2 = $y2;
}