6 use POSIX qw/floor ceil/;
8 my @lumpname = qw/entities textures planes nodes leafs leaffaces leafbrushes models brushes brushsides vertices triangles effects faces lightmaps lightgrid pvs advertisements/;
9 my %lumpid = map { $lumpname[$_] => $_ } 0..@lumpname-1;
15 if(!@ARGV || $ARGV[0] eq '-h' || $ARGV[0] eq '--help')
19 $0 filename.bsp [operations...]
23 -i print info about the BSP file
24 -xlumpname extract a lump (see -i)
27 -dlumpname delete a lump (see -i)
28 -rlumpname replace a lump (see -i) by the data from standard input
29 -gfilename.tga save the lightgrid as filename.tga (debugging)
30 -Gratio scale down the lightgrid to reduce BSP file size
31 -ljpgNNN externalize the lightmaps as JPEG, quality NNN (number from 1 to 100)
32 -lpng externalize the lightmaps as PNG
33 -ltga externalize the lightmaps as TGA
34 -mMESSAGE set the BSP file comment message
37 -o actually apply the changes to the BSP
38 -ofilename2.bsp save the changes to a new BSP file
45 or die "invalid input file name (must be a .bsp): $fn";
50 read $fh, my $header, 8;
52 die "Invalid BSP format"
53 if $header ne "IBSP\x2e\x00\x00\x00";
57 read $fh, my $lump, 8;
58 my ($offset, $length) = unpack "VV", $lump;
60 push @bsp, [$offset, $length, undef];
65 my ($offset, $length, $data) = @$_;
67 read $fh, $data, $length;
68 length $data == $length
69 or die "Incomplete BSP lump at $offset\n";
79 my ($lump, @fields) = @_;
91 if(/^(\w*)=(.*?)(\d*)$/)
98 push @decoders, sub { $item->{$f} = $data[$idx++]; };
102 push @decoders, sub { $item->{$f} = [ map { $data[$idx++] } 1..$n ]; };
107 my $itemlen = length pack $spec, ();
108 my $len = length $lump;
110 die "Invalid lump size: $len not divisible by $itemlen"
113 my $items = $len / $itemlen;
116 @data = unpack $spec, substr $lump, $_ * $itemlen, $itemlen;
119 $_->() for @decoders;
120 push @decoded, $item;
127 my ($items, @fields) = @_;
139 if(/^(\w*)=(.*?)(\d*)$/)
146 push @encoders, sub { $data .= pack $spec, $item->{$f}; };
150 push @encoders, sub { $data .= pack $spec, @{$item->{$f}}; };
158 $_->() for @encoders;
164 sub EncodeDirection(@)
166 my ($x, $y, $z) = @_;
169 map { ($_ / 0.02454369260617025967) & 0xFF }
171 atan2(sqrt($x * $x + $y * $y), $z),
177 sub DecodeDirection($)
181 my ($pitch, $yaw) = map { $_ * 0.02454369260617025967 } @$dir; # maps 256 to 2pi
184 cos($yaw) * sin($pitch),
185 sin($yaw) * sin($pitch),
190 sub IntervalIntersection($$$$)
192 my ($a, $al, $b, $bl) = @_;
193 my $a0 = $a - 0.5 * $al;
194 my $a1 = $a + 0.5 * $al;
195 my $b0 = $b - 0.5 * $bl;
196 my $b1 = $b + 0.5 * $bl;
197 my $left = ($a0 > $b0) ? $a0 : $b0;
198 my $right = ($a1 > $b1) ? $b1 : $a1;
199 die "Non-intersecting intervals $a $al $b $bl"
201 return $right - $left;
204 sub BoxIntersection(@)
206 my ($x, $y, $z, $w, $h, $d, $x2, $y2, $z2, $w2, $h2, $d2) = @_;
208 IntervalIntersection($x, $w, $x2, $w2)
210 IntervalIntersection($y, $h, $y2, $h2)
212 IntervalIntersection($z, $d, $z2, $d2);
221 my $msgalign = [0, 3, 2, 1]->[length($msg) % 4];
222 my $total = 17 * 8 + 8 + length($msg) + $msgalign;
226 my $nl = length $bsp[$_]->[2];
227 my $align = [0, 3, 2, 1]->[$nl % 4];
228 $total += $nl + $align;
229 print "BSP lump $_ ($lumpname[$_]): offset $bsp[$_]->[0] length $bsp[$_]->[1] newlength $nl\n";
230 my $endpos = $bsp[$_]->[0] + $bsp[$_]->[1];
231 $max = $endpos if $max < $endpos;
233 print "BSP file size will change from $max to $total bytes\n";
235 elsif(/^-d(.+)$/) # delete a lump
237 my $id = $lumpid{$1};
238 die "invalid lump $1 to remove"
242 elsif(/^-r(.+)$/) # replace a lump
244 my $id = $lumpid{$1};
245 die "invalid lump $1 to replace"
247 $bsp[$id]->[2] = do { undef local $/; scalar <STDIN>; };
249 elsif(/^-m(.*)$/) # change the message
253 elsif(/^-l(jpg|png|tga)(\d+)?$/) # externalize lightmaps (deleting the internal ones)
258 my $faces = $bsp[$lumpid{faces}]->[2];
259 my $lightmaps = $bsp[$lumpid{lightmaps}]->[2];
260 my @values = DecodeLump $faces,
261 qw/texture=V effect=V type=V vertex=V n_vertexes=V meshvert=V n_meshverts=V lm_index=V lm_start=f2 lm_size=f2 lm_origin=f3 lm_vec_0=f3 lm_vec_1=f3 normal=f3 size=V2/;
265 my $l = $_->{lm_index};
266 next if $l >= 2**31; # signed
273 $lightmaps{$_+1} = $lightmaps{$_} for keys %lightmaps;
275 for(sort { $a <=> $b } keys %lightmaps)
277 print STDERR "Lightmap $_ was used $lightmaps{$_} times\n";
279 # export that lightmap
280 my $lmsize = 128 * 128 * 3;
281 next if length $lightmaps < ($_ + 1) * $lmsize;
282 my $lmdata = substr $lightmaps, $_ * $lmsize, $lmsize;
283 my $img = Image::Magick->new(size => '128x128', depth => 8, magick => 'RGB');
284 $img->BlobToImage($lmdata);
285 my $outfn = sprintf "%s/lm_%04d.$ext", $basename, $_;
287 $img->Set(quality => $quality)
289 my $err = $img->Write($outfn);
292 print STDERR "Wrote $outfn\n";
295 # nullify the lightmap lump
296 $bsp[$lumpid{lightmaps}]->[2] = "";
298 elsif(/^-g(.+)$/) # export light grid as an image (for debugging)
301 my @models = DecodeLump $bsp[$lumpid{models}]->[2],
302 qw/mins=f3 maxs=f3 face=V n_faces=V brush=V n_brushes=V/;
303 my $entities = $bsp[$lumpid{entities}]->[2];
304 my @entitylines = split /\r?\n/, $entities;
305 my $gridsize = "64 64 128";
309 /^\s*"_?gridsize"\s+"(.*)"$/
312 my @scale = map { 1 / $_ } split / /, $gridsize;
313 my @imins = map { ceil($models[0]{mins}[$_] * $scale[$_]) } 0..2;
314 my @imaxs = map { floor($models[0]{maxs}[$_] * $scale[$_]) } 0..2;
315 my @isize = map { $imaxs[$_] - $imins[$_] + 1 } 0..2;
316 my $isize = $isize[0] * $isize[1] * $isize[2];
317 my @gridcells = DecodeLump $bsp[$lumpid{lightgrid}]->[2],
318 qw/ambient=C3 directional=C3 dir=C2/;
319 die "Cannot decode light grid"
320 unless $isize == @gridcells;
322 # sum up the "ambient" light over all pixels
325 for my $y(0..$isize[1]-1)
327 for my $x(0..$isize[0]-1)
329 my ($r, $g, $b) = (0, 0, 0);
330 for my $z(0..$isize[2]-1)
332 my $cell = $gridcells[$x + $y * $isize[0] + $z * $isize[0] * $isize[1]];
333 $r += $cell->{ambient}->[0];
334 $g += $cell->{ambient}->[1];
335 $b += $cell->{ambient}->[2];
337 push @pixels, [$r, $g, $b];
338 $max = $r if $max < $r;
339 $max = $g if $max < $g;
340 $max = $b if $max < $b;
346 $pixeldata .= pack "CCC", map { 255 * $p->[$_] / $max } 0..2;
349 my $img = Image::Magick->new(size => sprintf("%dx%d", $isize[0], $isize[1]), depth => 8, magick => 'RGB');
350 $img->BlobToImage($pixeldata);
351 $img->Write($filename);
352 print STDERR "Wrote $filename\n";
354 elsif(/^-G(.+)$/) # decimate light grid
357 my $filter = 1; # 0 = nearest, 1 = box filter
359 my @models = DecodeLump $bsp[$lumpid{models}]->[2],
360 qw/mins=f3 maxs=f3 face=V n_faces=V brush=V n_brushes=V/;
361 my $entities = $bsp[$lumpid{entities}]->[2];
362 my @entitylines = split /\r?\n/, $entities;
363 my $gridsize = "64 64 128";
364 my $gridsizeindex = undef;
365 for(0..@entitylines-1)
367 my $l = $entitylines[$_];
369 if($l =~ /^\s*"_?gridsize"\s+"(.*)"$/)
375 my @scale = map { 1 / $_ } split / /, $gridsize;
376 my @imins = map { ceil($models[0]{mins}[$_] * $scale[$_]) } 0..2;
377 my @imaxs = map { floor($models[0]{maxs}[$_] * $scale[$_]) } 0..2;
378 my @isize = map { $imaxs[$_] - $imins[$_] + 1 } 0..2;
379 my $isize = $isize[0] * $isize[1] * $isize[2];
380 my @gridcells = DecodeLump $bsp[$lumpid{lightgrid}]->[2],
381 qw/ambient=C3 directional=C3 dir=C2/;
382 die "Cannot decode light grid"
383 unless $isize == @gridcells;
385 # get the new grid size values
386 my @newscale = map { $_ / $decimate } @scale;
387 my $newgridsize = join " ", map { 1 / $_ } @newscale;
388 my @newimins = map { ceil($models[0]{mins}[$_] * $newscale[$_]) } 0..2;
389 my @newimaxs = map { floor($models[0]{maxs}[$_] * $newscale[$_]) } 0..2;
390 my @newisize = map { $newimaxs[$_] - $newimins[$_] + 1 } 0..2;
393 my @newgridcells = ();
394 for my $z($newimins[2]..$newimaxs[2])
396 # the coords are MIDPOINTS of the grid cells!
397 my @oldz = grep { $_ >= $imins[2] && $_ <= $imaxs[2] } floor(($z - 0.5) * $decimate + 0.5) .. ceil(($z + 0.5) * $decimate - 0.5);
398 my $innerz_raw = $z * $decimate;
399 my $innerz = floor($innerz_raw + 0.5);
400 $innerz = $imins[2] if $innerz < $imins[2];
401 $innerz = $imaxs[2] if $innerz > $imaxs[2];
402 for my $y($newimins[1]..$newimaxs[1])
404 my @oldy = grep { $_ >= $imins[1] && $_ <= $imaxs[1] } floor(($y - 0.5) * $decimate + 0.5) .. ceil(($y + 0.5) * $decimate - 0.5);
405 my $innery_raw = $y * $decimate;
406 my $innery = floor($innery_raw + 0.5);
407 $innery = $imins[1] if $innery < $imins[1];
408 $innery = $imaxs[1] if $innery > $imaxs[1];
409 for my $x($newimins[0]..$newimaxs[0])
411 my @oldx = grep { $_ >= $imins[0] && $_ <= $imaxs[0] } floor(($x - 0.5) * $decimate + 0.5) .. ceil(($x + 0.5) * $decimate - 0.5);
412 my $innerx_raw = $x * $decimate;
413 my $innerx = floor($innerx_raw + 0.5);
414 $innerx = $imins[0] if $innerx < $imins[0];
415 $innerx = $imaxs[0] if $innerx > $imaxs[0];
421 my $innercell = $gridcells[($innerx - $imins[0]) + $isize[0] * ($innery - $imins[1]) + $isize[0] * $isize[1] * ($innerz - $imins[2])];
428 my $cell = $gridcells[($X - $imins[0]) + $isize[0] * ($Y - $imins[1]) + $isize[0] * $isize[1] * ($Z - $imins[2])];
430 my $cellweight = BoxIntersection(
432 map { $_ * $decimate } $x, $y, $z, 1, 1, 1
435 $dir[$_] += $cellweight * $cell->{directional}->[$_] for 0..2;
436 $amb[$_] += $cellweight * $cell->{ambient}->[$_] for 0..2;
437 my @norm = DecodeDirection $cell->{dir};
438 $vec[$_] += $cellweight * $norm[$_] for 0..2;
439 $weight += $cellweight;
445 $dir[$_] /= $weight for 0..2;
446 $dir[$_] *= $filter for 0..2;
447 $dir[$_] += (1 - $filter) * $innercell->{directional}->[$_] for 0..2;
449 $amb[$_] /= $weight for 0..2;
450 $amb[$_] *= $filter for 0..2;
451 $amb[$_] += (1 - $filter) * $innercell->{ambient}->[$_] for 0..2;
453 my @norm = DecodeDirection $innercell->{dir};
454 $vec[$_] /= $weight for 0..2;
455 $vec[$_] *= $filter for 0..2;
456 $vec[$_] += (1 - $filter) * $norm[$_] for 0..2;
460 directional => \@dir,
461 dir => EncodeDirection @norm
465 push @newgridcells, $innercell;
470 $bsp[$lumpid{lightgrid}]->[2] = EncodeLump \@newgridcells,
471 qw/ambient=C3 directional=C3 dir=C2/;
472 splice @entitylines, $gridsizeindex, 1, ()
473 if defined $gridsizeindex;
474 splice @entitylines, 1, 0, qq{"gridsize" "$newgridsize"};
475 $bsp[$lumpid{entities}]->[2] = join "\n", @entitylines;
477 elsif(/^-x(.+)$/) # extract lump to stdout
479 my $id = $lumpid{$1};
480 die "invalid lump $1 to extract"
482 print $bsp[$id]->[2];
484 elsif(/^-o(.+)?$/) # write the final BSP file
488 if not defined $outfile;
489 open my $fh, ">", $outfile
490 or die "$outfile: $!";
492 my $msgalign = [0, 3, 2, 1]->[length($msg) % 4];
493 my $pos = 17 * 8 + tell($fh) + length($msg) + $msgalign;
496 my $align = [0, 3, 2, 1]->[length($_->[2]) % 4];
498 $_->[1] = length $_->[2];
499 $pos += $_->[1] + $align;
500 print $fh pack "VV", $_->[0], $_->[1];
503 print $fh "\x00" x $msgalign;
506 my $align = [0, 3, 2, 1]->[length($_->[2]) % 4];
508 print $fh "\x00" x $align;
511 print STDERR "Wrote $outfile\n";
515 die "Invalid option: $_";
521 # decimate light grid
522 # edit lightmaps/grid