ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
(Generate patch)

Comparing deliantra/server/lib/cf.pm (file contents):
Revision 1.482 by root, Sun Oct 11 05:31:54 2009 UTC vs.
Revision 1.513 by root, Mon Apr 12 05:22:38 2010 UTC

1# 1#
2# This file is part of Deliantra, the Roguelike Realtime MMORPG. 2# This file is part of Deliantra, the Roguelike Realtime MMORPG.
3# 3#
4# Copyright (©) 2006,2007,2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team 4# Copyright (©) 2006,2007,2008,2009,2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5# 5#
6# Deliantra is free software: you can redistribute it and/or modify 6# Deliantra is free software: you can redistribute it and/or modify it under
7# it under the terms of the GNU General Public License as published by 7# the terms of the Affero GNU General Public License as published by the
8# the Free Software Foundation, either version 3 of the License, or 8# Free Software Foundation, either version 3 of the License, or (at your
9# (at your option) any later version. 9# option) any later version.
10# 10#
11# This program is distributed in the hope that it will be useful, 11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of 12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details. 14# GNU General Public License for more details.
15# 15#
16# You should have received a copy of the GNU General Public License 16# You should have received a copy of the Affero GNU General Public License
17# along with this program. If not, see <http://www.gnu.org/licenses/>. 17# and the GNU General Public License along with this program. If not, see
18# <http://www.gnu.org/licenses/>.
18# 19#
19# The authors can be reached via e-mail to <support@deliantra.net> 20# The authors can be reached via e-mail to <support@deliantra.net>
20# 21#
21 22
22package cf; 23package cf;
23 24
24use 5.10.0; 25use 5.10.0;
25use utf8; 26use utf8;
31use EV; 32use EV;
32use Opcode; 33use Opcode;
33use Safe; 34use Safe;
34use Safe::Hole; 35use Safe::Hole;
35use Storable (); 36use Storable ();
37use Carp ();
36 38
37use Guard (); 39use Guard ();
38use Coro (); 40use Coro ();
39use Coro::State; 41use Coro::State;
40use Coro::Handle; 42use Coro::Handle;
51use Coro::Util (); 53use Coro::Util ();
52 54
53use JSON::XS 2.01 (); 55use JSON::XS 2.01 ();
54use BDB (); 56use BDB ();
55use Data::Dumper; 57use Data::Dumper;
56use Digest::MD5;
57use Fcntl; 58use Fcntl;
58use YAML (); 59use YAML::XS ();
59use IO::AIO (); 60use IO::AIO ();
60use Time::HiRes; 61use Time::HiRes;
61use Compress::LZF; 62use Compress::LZF;
62use Digest::MD5 (); 63use Digest::MD5 ();
63 64
107our $PIDFILE = "$LOCALDIR/pid"; 108our $PIDFILE = "$LOCALDIR/pid";
108our $RUNTIMEFILE = "$LOCALDIR/runtime"; 109our $RUNTIMEFILE = "$LOCALDIR/runtime";
109 110
110our %RESOURCE; 111our %RESOURCE;
111 112
113our $OUTPUT_RATE_MIN = 4000;
114our $OUTPUT_RATE_MAX = 100000;
115
112our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 116our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
113our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 117our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
114our $NEXT_TICK; 118our $NEXT_TICK;
115our $USE_FSYNC = 1; # use fsync to write maps - default on 119our $USE_FSYNC = 1; # use fsync to write maps - default on
116 120
227returns directly I<after> the tick processing (and consequently, can only wake one process 231returns directly I<after> the tick processing (and consequently, can only wake one process
228per tick), while cf::wait_for_tick wakes up all waiters after tick processing. 232per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
229 233
230=item @cf::INVOKE_RESULTS 234=item @cf::INVOKE_RESULTS
231 235
232This array contains the results of the last C<invoke ()> call. When 236This array contains the results of the last C<invoke ()> call. When
233C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of 237C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of
234that call. 238that call.
235 239
236=item %cf::REFLECT 240=item %cf::REFLECT
237 241
288)) { 292)) {
289 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 293 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
290} 294}
291 295
292$EV::DIED = sub { 296$EV::DIED = sub {
293 warn "error in event callback: @_"; 297 Carp::cluck "error in event callback: @_";
294}; 298};
295 299
296############################################################################# 300#############################################################################
297 301
298=head2 UTILITY FUNCTIONS 302=head2 UTILITY FUNCTIONS
422 426
423=cut 427=cut
424 428
425our @SLOT_QUEUE; 429our @SLOT_QUEUE;
426our $SLOT_QUEUE; 430our $SLOT_QUEUE;
431our $SLOT_DECAY = 0.9;
427 432
428$SLOT_QUEUE->cancel if $SLOT_QUEUE; 433$SLOT_QUEUE->cancel if $SLOT_QUEUE;
429$SLOT_QUEUE = Coro::async { 434$SLOT_QUEUE = Coro::async {
430 $Coro::current->desc ("timeslot manager"); 435 $Coro::current->desc ("timeslot manager");
431 436
432 my $signal = new Coro::Signal; 437 my $signal = new Coro::Signal;
438 my $busy;
433 439
434 while () { 440 while () {
435 next_job: 441 next_job:
442
436 my $avail = cf::till_tick; 443 my $avail = cf::till_tick;
437 if ($avail > 0.01) { 444
438 for (0 .. $#SLOT_QUEUE) { 445 for (0 .. $#SLOT_QUEUE) {
439 if ($SLOT_QUEUE[$_][0] < $avail) { 446 if ($SLOT_QUEUE[$_][0] <= $avail) {
447 $busy = 0;
440 my $job = splice @SLOT_QUEUE, $_, 1, (); 448 my $job = splice @SLOT_QUEUE, $_, 1, ();
441 $job->[2]->send; 449 $job->[2]->send;
442 Coro::cede; 450 Coro::cede;
443 goto next_job; 451 goto next_job;
444 } 452 } else {
453 $SLOT_QUEUE[$_][0] *= $SLOT_DECAY;
445 } 454 }
446 } 455 }
447 456
448 if (@SLOT_QUEUE) { 457 if (@SLOT_QUEUE) {
449 # we do not use wait_for_tick() as it returns immediately when tick is inactive 458 # we do not use wait_for_tick() as it returns immediately when tick is inactive
450 push @cf::WAIT_FOR_TICK, $signal; 459 push @cf::WAIT_FOR_TICK, $signal;
451 $signal->wait; 460 $signal->wait;
452 } else { 461 } else {
462 $busy = 0;
453 Coro::schedule; 463 Coro::schedule;
454 } 464 }
455 } 465 }
456}; 466};
457 467
458sub get_slot($;$$) { 468sub get_slot($;$$) {
459 return if tick_inhibit || $Coro::current == $Coro::main; 469 return if tick_inhibit || $Coro::current == $Coro::main;
460 470
461 my ($time, $pri, $name) = @_; 471 my ($time, $pri, $name) = @_;
462 472
463 $time = $TICK * .6 if $time > $TICK * .6; 473 $time = clamp $time, 0.01, $TICK * .6;
474
464 my $sig = new Coro::Signal; 475 my $sig = new Coro::Signal;
465 476
466 push @SLOT_QUEUE, [$time, $pri, $sig, $name]; 477 push @SLOT_QUEUE, [$time, $pri, $sig, $name];
467 @SLOT_QUEUE = sort { $b->[1] <=> $a->[1] } @SLOT_QUEUE; 478 @SLOT_QUEUE = sort { $b->[1] <=> $a->[1] } @SLOT_QUEUE;
468 $SLOT_QUEUE->ready; 479 $SLOT_QUEUE->ready;
495 506
496sub sync_job(&) { 507sub sync_job(&) {
497 my ($job) = @_; 508 my ($job) = @_;
498 509
499 if ($Coro::current == $Coro::main) { 510 if ($Coro::current == $Coro::main) {
500 my $time = EV::time; 511 my $time = AE::time;
501 512
502 # this is the main coro, too bad, we have to block 513 # this is the main coro, too bad, we have to block
503 # till the operation succeeds, freezing the server :/ 514 # till the operation succeeds, freezing the server :/
504 515
505 LOG llevError, Carp::longmess "sync job";#d# 516 LOG llevError, Carp::longmess "sync job";#d#
522 } else { 533 } else {
523 EV::loop EV::LOOP_ONESHOT; 534 EV::loop EV::LOOP_ONESHOT;
524 } 535 }
525 } 536 }
526 537
527 my $time = EV::time - $time; 538 my $time = AE::time - $time;
528 539
529 $TICK_START += $time; # do not account sync jobs to server load 540 $TICK_START += $time; # do not account sync jobs to server load
530 541
531 wantarray ? @res : $res[0] 542 wantarray ? @res : $res[0]
532 } else { 543 } else {
1302} 1313}
1303 1314
1304use File::Glob (); 1315use File::Glob ();
1305 1316
1306cf::player->attach ( 1317cf::player->attach (
1307 on_command => sub { 1318 on_unknown_command => sub {
1308 my ($pl, $name, $params) = @_; 1319 my ($pl, $name, $params) = @_;
1309 1320
1310 my $cb = $COMMAND{$name} 1321 my $cb = $COMMAND{$name}
1311 or return; 1322 or return;
1312 1323
1391 . "\n};\n1"; 1402 . "\n};\n1";
1392 1403
1393 $todo{$base} = \%ext; 1404 $todo{$base} = \%ext;
1394 } 1405 }
1395 1406
1407 my $pass = 0;
1396 my %done; 1408 my %done;
1397 while (%todo) { 1409 while (%todo) {
1398 my $progress; 1410 my $progress;
1399 1411
1412 ++$pass;
1413
1414 ext:
1400 while (my ($k, $v) = each %todo) { 1415 while (my ($k, $v) = each %todo) {
1401 for (split /,\s*/, $v->{meta}{depends}) { 1416 for (split /,\s*/, $v->{meta}{depends}) {
1402 goto skip 1417 next ext
1403 unless exists $done{$_}; 1418 unless exists $done{$_};
1404 } 1419 }
1405 1420
1406 warn "... loading '$k' into '$v->{pkg}'\n"; 1421 warn "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1407 1422
1408 unless (eval $v->{source}) { 1423 my $active = eval $v->{source};
1424
1425 if (length $@) {
1409 my $msg = $@ ? "$v->{path}: $@\n" 1426 warn "$v->{path}: $@\n";
1410 : "$v->{base}: extension inactive.\n";
1411 1427
1412 if (exists $v->{meta}{mandatory}) {
1413 warn $msg;
1414 cf::cleanup "mandatory extension failed to load, exiting."; 1428 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1415 } 1429 if exists $v->{meta}{mandatory};
1416 1430 } else {
1417 warn $msg; 1431 $done{$k} = delete $todo{$k};
1432 push @EXTS, $v->{pkg};
1433 $progress = 1;
1434
1435 warn "$v->{base}: extension inactive.\n"
1436 unless $active;
1418 } 1437 }
1419
1420 $done{$k} = delete $todo{$k};
1421 push @EXTS, $v->{pkg};
1422 $progress = 1;
1423 } 1438 }
1424 1439
1425 skip: 1440 unless ($progress) {
1426 die "cannot load " . (join ", ", keys %todo) . ": unable to resolve dependencies\n" 1441 warn "cannot load " . (join ", ", keys %todo) . ": unable to resolve dependencies\n";
1427 unless $progress; 1442
1443 while (my ($k, $v) = each %todo) {
1444 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting."
1445 if exists $v->{meta}{mandatory};
1446 }
1447 }
1428 } 1448 }
1429 }; 1449 };
1430} 1450}
1431 1451
1432############################################################################# 1452#############################################################################
1516 $cf::PLAYER{$login} = $pl 1536 $cf::PLAYER{$login} = $pl
1517 } 1537 }
1518 } 1538 }
1519} 1539}
1520 1540
1541cf::player->attach (
1542 on_load => sub {
1543 my ($pl, $path) = @_;
1544
1545 # restore slots saved in save, below
1546 my $slots = delete $pl->{_slots};
1547
1548 $pl->ob->current_weapon ($slots->[0]);
1549 $pl->combat_ob ($slots->[1]);
1550 $pl->ranged_ob ($slots->[2]);
1551 },
1552);
1553
1521sub save($) { 1554sub save($) {
1522 my ($pl) = @_; 1555 my ($pl) = @_;
1523 1556
1524 return if $pl->{deny_save}; 1557 return if $pl->{deny_save};
1525 1558
1530 1563
1531 aio_mkdir playerdir $pl, 0770; 1564 aio_mkdir playerdir $pl, 0770;
1532 $pl->{last_save} = $cf::RUNTIME; 1565 $pl->{last_save} = $cf::RUNTIME;
1533 1566
1534 cf::get_slot 0.01; 1567 cf::get_slot 0.01;
1568
1569 # save slots, to be restored later
1570 local $pl->{_slots} = [$pl->ob->current_weapon, $pl->combat_ob, $pl->ranged_ob];
1535 1571
1536 $pl->save_pl ($path); 1572 $pl->save_pl ($path);
1537 cf::cede_to_tick; 1573 cf::cede_to_tick;
1538} 1574}
1539 1575
1752 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM 1788 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1753 1789
1754 # mit "rum" bekleckern, nicht 1790 # mit "rum" bekleckern, nicht
1755 $self->_create_random_map ( 1791 $self->_create_random_map (
1756 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle}, 1792 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1757 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, 1793 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, $rmp->{miningstyle},
1758 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map}, 1794 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1759 $rmp->{exit_on_final_map}, 1795 $rmp->{exit_on_final_map},
1760 $rmp->{xsize}, $rmp->{ysize}, 1796 $rmp->{xsize}, $rmp->{ysize},
1761 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3}, 1797 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3},
1762 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase}, 1798 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase},
2008 2044
2009 $cf::MAP{$path} = $map 2045 $cf::MAP{$path} = $map
2010 } 2046 }
2011} 2047}
2012 2048
2013sub pre_load { } 2049sub pre_load { }
2014sub post_load { } 2050#sub post_load { } # XS
2015 2051
2016sub load { 2052sub load {
2017 my ($self) = @_; 2053 my ($self) = @_;
2018 2054
2019 local $self->{deny_reset} = 1; # loading can take a long time 2055 local $self->{deny_reset} = 1; # loading can take a long time
2076 } 2112 }
2077 2113
2078 $self->post_load; 2114 $self->post_load;
2079} 2115}
2080 2116
2117# customize the map for a given player, i.e.
2118# return the _real_ map. used by e.g. per-player
2119# maps to change the path to ~playername/mappath
2081sub customise_for { 2120sub customise_for {
2082 my ($self, $ob) = @_; 2121 my ($self, $ob) = @_;
2083 2122
2084 return find "~" . $ob->name . "/" . $self->{path} 2123 return find "~" . $ob->name . "/" . $self->{path}
2085 if $self->per_player; 2124 if $self->per_player;
2340 : normalise $_ 2379 : normalise $_
2341 } @{ aio_readdir $UNIQUEDIR or [] } 2380 } @{ aio_readdir $UNIQUEDIR or [] }
2342 ] 2381 ]
2343} 2382}
2344 2383
2384=item cf::map::static_maps
2385
2386Returns an arrayref if paths of all static maps (all preinstalled F<.map>
2387file in the shared directory excluding F</styles> and F</editor>). May
2388block.
2389
2390=cut
2391
2392sub static_maps() {
2393 my @dirs = "";
2394 my @maps;
2395
2396 while (@dirs) {
2397 my $dir = shift @dirs;
2398
2399 next if $dir eq "/styles" || $dir eq "/editor";
2400
2401 my ($dirs, $files) = Coro::AIO::aio_scandir "$MAPDIR$dir", 2
2402 or return;
2403
2404 for (@$files) {
2405 s/\.map$// or next;
2406 utf8::decode $_;
2407 push @maps, "$dir/$_";
2408 }
2409
2410 push @dirs, map "$dir/$_", @$dirs;
2411 }
2412
2413 \@maps
2414}
2415
2345=back 2416=back
2346 2417
2347=head3 cf::object 2418=head3 cf::object
2348 2419
2349=cut 2420=cut
2544 ($x, $y) = (-1, -1) 2615 ($x, $y) = (-1, -1)
2545 unless (defined $x) && (defined $y); 2616 unless (defined $x) && (defined $y);
2546 2617
2547 # use -1 or undef as default coordinates, not 0, 0 2618 # use -1 or undef as default coordinates, not 0, 0
2548 ($x, $y) = ($map->enter_x, $map->enter_y) 2619 ($x, $y) = ($map->enter_x, $map->enter_y)
2549 if $x <=0 && $y <= 0; 2620 if $x <= 0 && $y <= 0;
2550 2621
2551 $map->load; 2622 $map->load;
2552 $map->load_neighbours; 2623 $map->load_neighbours;
2553 2624
2554 return unless $self->contr->active; 2625 return unless $self->contr->active;
2753 2824
2754 utf8::encode $text; 2825 utf8::encode $text;
2755 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text); 2826 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text);
2756} 2827}
2757 2828
2829=item $client->send_big_packet ($pkt)
2830
2831Like C<send_packet>, but tries to compress large packets, and fragments
2832them as required.
2833
2834=cut
2835
2836our $MAXFRAGSIZE = cf::MAXSOCKBUF - 64;
2837
2838sub cf::client::send_big_packet {
2839 my ($self, $pkt) = @_;
2840
2841 # try lzf for large packets
2842 $pkt = "lzf " . Compress::LZF::compress $pkt
2843 if 1024 <= length $pkt and $self->{can_lzf};
2844
2845 # split very large packets
2846 if ($MAXFRAGSIZE < length $pkt and $self->{can_lzf}) {
2847 $self->send_packet ("frag $_") for unpack "(a$MAXFRAGSIZE)*", $pkt;
2848 $pkt = "frag";
2849 }
2850
2851 $self->send_packet ($pkt);
2852}
2853
2758=item $client->send_msg ($channel, $msg, $color, [extra...]) 2854=item $client->send_msg ($channel, $msg, $color, [extra...])
2759 2855
2760Send a drawinfo or msg packet to the client, formatting the msg for the 2856Send a drawinfo or msg packet to the client, formatting the msg for the
2761client if neccessary. C<$type> should be a string identifying the type of 2857client if neccessary. C<$type> should be a string identifying the type of
2762the message, with C<log> being the default. If C<$color> is negative, suppress 2858the message, with C<log> being the default. If C<$color> is negative, suppress
2764 2860
2765=cut 2861=cut
2766 2862
2767# non-persistent channels (usually the info channel) 2863# non-persistent channels (usually the info channel)
2768our %CHANNEL = ( 2864our %CHANNEL = (
2865 "c/motd" => {
2866 id => "infobox",
2867 title => "MOTD",
2868 reply => undef,
2869 tooltip => "The message of the day",
2870 },
2769 "c/identify" => { 2871 "c/identify" => {
2770 id => "infobox", 2872 id => "infobox",
2771 title => "Identify", 2873 title => "Identify",
2772 reply => undef, 2874 reply => undef,
2773 tooltip => "Items recently identified", 2875 tooltip => "Items recently identified",
2775 "c/examine" => { 2877 "c/examine" => {
2776 id => "infobox", 2878 id => "infobox",
2777 title => "Examine", 2879 title => "Examine",
2778 reply => undef, 2880 reply => undef,
2779 tooltip => "Signs and other items you examined", 2881 tooltip => "Signs and other items you examined",
2882 },
2883 "c/shopinfo" => {
2884 id => "infobox",
2885 title => "Shop Info",
2886 reply => undef,
2887 tooltip => "What your bargaining skill tells you about the shop",
2780 }, 2888 },
2781 "c/book" => { 2889 "c/book" => {
2782 id => "infobox", 2890 id => "infobox",
2783 title => "Book", 2891 title => "Book",
2784 reply => undef, 2892 reply => undef,
2900 my $pkt = "msg " 3008 my $pkt = "msg "
2901 . $self->{json_coder}->encode ( 3009 . $self->{json_coder}->encode (
2902 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra] 3010 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra]
2903 ); 3011 );
2904 3012
2905 # try lzf for large packets
2906 $pkt = "lzf " . Compress::LZF::compress $pkt
2907 if 1024 <= length $pkt and $self->{can_lzf};
2908
2909 # split very large packets
2910 if (8192 < length $pkt and $self->{can_lzf}) {
2911 $self->send_packet ("frag $_") for unpack "(a8192)*", $pkt;
2912 $pkt = "frag";
2913 }
2914
2915 $self->send_packet ($pkt); 3013 $self->send_big_packet ($pkt);
2916} 3014}
2917 3015
2918=item $client->ext_msg ($type, @msg) 3016=item $client->ext_msg ($type, @msg)
2919 3017
2920Sends an ext event to the client. 3018Sends an ext event to the client.
2923 3021
2924sub cf::client::ext_msg($$@) { 3022sub cf::client::ext_msg($$@) {
2925 my ($self, $type, @msg) = @_; 3023 my ($self, $type, @msg) = @_;
2926 3024
2927 if ($self->extcmd == 2) { 3025 if ($self->extcmd == 2) {
2928 $self->send_packet ("ext " . $self->{json_coder}->encode ([$type, @msg])); 3026 $self->send_big_packet ("ext " . $self->{json_coder}->encode ([$type, @msg]));
2929 } elsif ($self->extcmd == 1) { # TODO: remove 3027 } elsif ($self->extcmd == 1) { # TODO: remove
2930 push @msg, msgtype => "event_$type"; 3028 push @msg, msgtype => "event_$type";
2931 $self->send_packet ("ext " . $self->{json_coder}->encode ({@msg})); 3029 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
2932 } 3030 }
2933} 3031}
2934 3032
2935=item $client->ext_reply ($msgid, @msg) 3033=item $client->ext_reply ($msgid, @msg)
2936 3034
2940 3038
2941sub cf::client::ext_reply($$@) { 3039sub cf::client::ext_reply($$@) {
2942 my ($self, $id, @msg) = @_; 3040 my ($self, $id, @msg) = @_;
2943 3041
2944 if ($self->extcmd == 2) { 3042 if ($self->extcmd == 2) {
2945 $self->send_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg])); 3043 $self->send_big_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg]));
2946 } elsif ($self->extcmd == 1) { 3044 } elsif ($self->extcmd == 1) {
2947 #TODO: version 1, remove 3045 #TODO: version 1, remove
2948 unshift @msg, msgtype => "reply", msgid => $id; 3046 unshift @msg, msgtype => "reply", msgid => $id;
2949 $self->send_packet ("ext " . $self->{json_coder}->encode ({@msg})); 3047 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
2950 } 3048 }
2951} 3049}
2952 3050
2953=item $success = $client->query ($flags, "text", \&cb) 3051=item $success = $client->query ($flags, "text", \&cb)
2954 3052
3055 3153
3056 $coro 3154 $coro
3057} 3155}
3058 3156
3059cf::client->attach ( 3157cf::client->attach (
3060 on_destroy => sub { 3158 on_client_destroy => sub {
3061 my ($ns) = @_; 3159 my ($ns) = @_;
3062 3160
3063 $_->cancel for values %{ (delete $ns->{_coro}) || {} }; 3161 $_->cancel for values %{ (delete $ns->{_coro}) || {} };
3064 }, 3162 },
3065); 3163);
3081our $safe_hole = new Safe::Hole; 3179our $safe_hole = new Safe::Hole;
3082 3180
3083$SIG{FPE} = 'IGNORE'; 3181$SIG{FPE} = 'IGNORE';
3084 3182
3085$safe->permit_only (Opcode::opset qw( 3183$safe->permit_only (Opcode::opset qw(
3086 :base_core :base_mem :base_orig :base_math 3184 :base_core :base_mem :base_orig :base_math :base_loop
3087 grepstart grepwhile mapstart mapwhile 3185 grepstart grepwhile mapstart mapwhile
3088 sort time 3186 sort time
3089)); 3187));
3090 3188
3091# here we export the classes and methods available to script code 3189# here we export the classes and methods available to script code
3143 $qcode =~ s/"/‟/g; # not allowed in #line filenames 3241 $qcode =~ s/"/‟/g; # not allowed in #line filenames
3144 $qcode =~ s/\n/\\n/g; 3242 $qcode =~ s/\n/\\n/g;
3145 3243
3146 %vars = (_dummy => 0) unless %vars; 3244 %vars = (_dummy => 0) unless %vars;
3147 3245
3246 my @res;
3148 local $_; 3247 local $_;
3149 local @safe::cf::_safe_eval_args = values %vars;
3150 3248
3151 my $eval = 3249 my $eval =
3152 "do {\n" 3250 "do {\n"
3153 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 3251 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
3154 . "#line 0 \"{$qcode}\"\n" 3252 . "#line 0 \"{$qcode}\"\n"
3155 . $code 3253 . $code
3156 . "\n}" 3254 . "\n}"
3157 ; 3255 ;
3158 3256
3257 if ($CFG{safe_eval}) {
3159 sub_generation_inc; 3258 sub_generation_inc;
3259 local @safe::cf::_safe_eval_args = values %vars;
3160 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval); 3260 @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
3161 sub_generation_inc; 3261 sub_generation_inc;
3262 } else {
3263 local @cf::_safe_eval_args = values %vars;
3264 @res = wantarray ? eval eval : scalar eval $eval;
3265 }
3162 3266
3163 if ($@) { 3267 if ($@) {
3164 warn "$@"; 3268 warn "$@";
3165 warn "while executing safe code '$code'\n"; 3269 warn "while executing safe code '$code'\n";
3166 warn "with arguments " . (join " ", %vars) . "\n"; 3270 warn "with arguments " . (join " ", %vars) . "\n";
3185=cut 3289=cut
3186 3290
3187sub register_script_function { 3291sub register_script_function {
3188 my ($fun, $cb) = @_; 3292 my ($fun, $cb) = @_;
3189 3293
3190 no strict 'refs'; 3294 $fun = "safe::$fun" if $CFG{safe_eval};
3191 *{"safe::$fun"} = $safe_hole->wrap ($cb); 3295 *$fun = $safe_hole->wrap ($cb);
3192} 3296}
3193 3297
3194=back 3298=back
3195 3299
3196=cut 3300=cut
3217 3321
3218 $facedata->{version} == 2 3322 $facedata->{version} == 2
3219 or cf::cleanup "$path: version mismatch, cannot proceed."; 3323 or cf::cleanup "$path: version mismatch, cannot proceed.";
3220 3324
3221 # patch in the exptable 3325 # patch in the exptable
3326 my $exp_table = $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]);
3222 $facedata->{resource}{"res/exp_table"} = { 3327 $facedata->{resource}{"res/exp_table"} = {
3223 type => FT_RSRC, 3328 type => FT_RSRC,
3224 data => $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]), 3329 data => $exp_table,
3330 hash => (Digest::MD5::md5 $exp_table),
3225 }; 3331 };
3226 cf::cede_to_tick; 3332 cf::cede_to_tick;
3227 3333
3228 { 3334 {
3229 my $faces = $facedata->{faceinfo}; 3335 my $faces = $facedata->{faceinfo};
3231 while (my ($face, $info) = each %$faces) { 3337 while (my ($face, $info) = each %$faces) {
3232 my $idx = (cf::face::find $face) || cf::face::alloc $face; 3338 my $idx = (cf::face::find $face) || cf::face::alloc $face;
3233 3339
3234 cf::face::set_visibility $idx, $info->{visibility}; 3340 cf::face::set_visibility $idx, $info->{visibility};
3235 cf::face::set_magicmap $idx, $info->{magicmap}; 3341 cf::face::set_magicmap $idx, $info->{magicmap};
3236 cf::face::set_data $idx, 0, $info->{data32}, Digest::MD5::md5 $info->{data32}; 3342 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32};
3237 cf::face::set_data $idx, 1, $info->{data64}, Digest::MD5::md5 $info->{data64}; 3343 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64};
3238 3344
3239 cf::cede_to_tick; 3345 cf::cede_to_tick;
3240 } 3346 }
3241 3347
3242 while (my ($face, $info) = each %$faces) { 3348 while (my ($face, $info) = each %$faces) {
3266 3372
3267 cf::anim::invalidate_all; # d'oh 3373 cf::anim::invalidate_all; # d'oh
3268 } 3374 }
3269 3375
3270 { 3376 {
3271 # TODO: for gcfclient pleasure, we should give resources
3272 # that gcfclient doesn't grok a >10000 face index.
3273 my $res = $facedata->{resource}; 3377 my $res = $facedata->{resource};
3274 3378
3275 while (my ($name, $info) = each %$res) { 3379 while (my ($name, $info) = each %$res) {
3276 if (defined $info->{type}) { 3380 if (defined $info->{type}) {
3277 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3381 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3278 my $data;
3279 3382
3280 if ($info->{type} & 1) { 3383 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3281 # prepend meta info
3282
3283 my $meta = $enc->encode ({
3284 name => $name,
3285 %{ $info->{meta} || {} },
3286 });
3287
3288 $data = pack "(w/a*)*", $meta, $info->{data};
3289 } else {
3290 $data = $info->{data};
3291 }
3292
3293 cf::face::set_data $idx, 0, $data, Digest::MD5::md5 $data;
3294 cf::face::set_type $idx, $info->{type}; 3384 cf::face::set_type $idx, $info->{type};
3295 } else { 3385 } else {
3296 $RESOURCE{$name} = $info; 3386 $RESOURCE{$name} = $info;
3297 } 3387 }
3298 3388
3382 3472
3383 warn "finished reloading resource files\n"; 3473 warn "finished reloading resource files\n";
3384} 3474}
3385 3475
3386sub reload_config { 3476sub reload_config {
3477 warn "reloading config file...\n";
3478
3387 open my $fh, "<:utf8", "$CONFDIR/config" 3479 open my $fh, "<:utf8", "$CONFDIR/config"
3388 or return; 3480 or return;
3389 3481
3390 local $/; 3482 local $/;
3391 *CFG = YAML::Load <$fh>; 3483 *CFG = YAML::XS::Load scalar <$fh>;
3392 3484
3393 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37]; 3485 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37];
3394 3486
3395 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3487 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
3396 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset}; 3488 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3400 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()" 3492 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
3401 and die "WARNING: m(un)lockall failed: $!\n"; 3493 and die "WARNING: m(un)lockall failed: $!\n";
3402 }; 3494 };
3403 warn $@ if $@; 3495 warn $@ if $@;
3404 } 3496 }
3497
3498 warn "finished reloading resource files\n";
3405} 3499}
3406 3500
3407sub pidfile() { 3501sub pidfile() {
3408 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3502 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3409 or die "$PIDFILE: $!"; 3503 or die "$PIDFILE: $!";
3457 }; 3551 };
3458 3552
3459 evthread_start IO::AIO::poll_fileno; 3553 evthread_start IO::AIO::poll_fileno;
3460 3554
3461 cf::sync_job { 3555 cf::sync_job {
3556 cf::load_settings;
3557 cf::load_materials;
3558
3462 reload_resources; 3559 reload_resources;
3463 reload_config; 3560 reload_config;
3464 db_init; 3561 db_init;
3465 3562
3466 cf::load_settings;
3467 cf::load_materials;
3468 cf::init_uuid; 3563 cf::init_uuid;
3469 cf::init_signals; 3564 cf::init_signals;
3470 cf::init_commands;
3471 cf::init_skills; 3565 cf::init_skills;
3472 3566
3473 cf::init_beforeplay; 3567 cf::init_beforeplay;
3474 3568
3475 atomic; 3569 atomic;
3493 3587
3494# install some emergency cleanup handlers 3588# install some emergency cleanup handlers
3495BEGIN { 3589BEGIN {
3496 our %SIGWATCHER = (); 3590 our %SIGWATCHER = ();
3497 for my $signal (qw(INT HUP TERM)) { 3591 for my $signal (qw(INT HUP TERM)) {
3498 $SIGWATCHER{$signal} = EV::signal $signal, sub { 3592 $SIGWATCHER{$signal} = AE::signal $signal, sub {
3499 cf::cleanup "SIG$signal"; 3593 cf::cleanup "SIG$signal";
3500 }; 3594 };
3501 } 3595 }
3502} 3596}
3503 3597
3504sub write_runtime_sync { 3598sub write_runtime_sync {
3599 my $t0 = AE::time;
3600
3505 # first touch the runtime file to show we are still running: 3601 # first touch the runtime file to show we are still running:
3506 # the fsync below can take a very very long time. 3602 # the fsync below can take a very very long time.
3507 3603
3508 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef; 3604 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef;
3509 3605
3510 my $guard = cf::lock_acquire "write_runtime"; 3606 my $guard = cf::lock_acquire "write_runtime";
3511 3607
3512 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT, 0644 3608 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT | O_TRUNC, 0644
3513 or return; 3609 or return;
3514 3610
3515 my $value = $cf::RUNTIME + 90 + 10; 3611 my $value = $cf::RUNTIME + 90 + 10;
3516 # 10 is the runtime save interval, for a monotonic clock 3612 # 10 is the runtime save interval, for a monotonic clock
3517 # 60 allows for the watchdog to kill the server. 3613 # 60 allows for the watchdog to kill the server.
3530 or return; 3626 or return;
3531 3627
3532 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3628 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3533 and return; 3629 and return;
3534 3630
3535 warn "runtime file written.\n"; 3631 warn sprintf "runtime file written (%gs).\n", AE::time - $t0;
3536 3632
3537 1 3633 1
3538} 3634}
3539 3635
3540our $uuid_lock; 3636our $uuid_lock;
3678 return; 3774 return;
3679 } 3775 }
3680 3776
3681 return if $RELOAD++; 3777 return if $RELOAD++;
3682 3778
3683 my $t1 = EV::time; 3779 my $t1 = AE::time;
3684 3780
3685 while ($RELOAD) { 3781 while ($RELOAD) {
3686 warn "reloading..."; 3782 warn "reloading...";
3687 3783
3688 warn "entering sync_job"; 3784 warn "entering sync_job";
3759 3855
3760 warn "unload completed, starting to reload now"; 3856 warn "unload completed, starting to reload now";
3761 3857
3762 warn "reloading cf.pm"; 3858 warn "reloading cf.pm";
3763 require cf; 3859 require cf;
3764 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt 3860 cf::_connect_to_perl_1;
3765 3861
3766 warn "loading config and database again"; 3862 warn "loading config and database again";
3767 cf::reload_config; 3863 cf::reload_config;
3768 3864
3769 warn "loading extensions"; 3865 warn "loading extensions";
3791 3887
3792 warn "reloaded"; 3888 warn "reloaded";
3793 --$RELOAD; 3889 --$RELOAD;
3794 } 3890 }
3795 3891
3796 $t1 = EV::time - $t1; 3892 $t1 = AE::time - $t1;
3797 warn "reload completed in ${t1}s\n"; 3893 warn "reload completed in ${t1}s\n";
3798}; 3894};
3799 3895
3800our $RELOAD_WATCHER; # used only during reload 3896our $RELOAD_WATCHER; # used only during reload
3801 3897
3804 # coro crashes during coro_state_free->destroy here. 3900 # coro crashes during coro_state_free->destroy here.
3805 3901
3806 $RELOAD_WATCHER ||= cf::async { 3902 $RELOAD_WATCHER ||= cf::async {
3807 Coro::AIO::aio_wait cache_extensions; 3903 Coro::AIO::aio_wait cache_extensions;
3808 3904
3809 $RELOAD_WATCHER = EV::timer $TICK * 1.5, 0, sub { 3905 $RELOAD_WATCHER = AE::timer $TICK * 1.5, 0, sub {
3810 do_reload_perl; 3906 do_reload_perl;
3811 undef $RELOAD_WATCHER; 3907 undef $RELOAD_WATCHER;
3812 }; 3908 };
3813 }; 3909 };
3814} 3910}
3831 3927
3832our @WAIT_FOR_TICK; 3928our @WAIT_FOR_TICK;
3833our @WAIT_FOR_TICK_BEGIN; 3929our @WAIT_FOR_TICK_BEGIN;
3834 3930
3835sub wait_for_tick { 3931sub wait_for_tick {
3836 return if tick_inhibit || $Coro::current == $Coro::main; 3932 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3837 3933
3838 my $signal = new Coro::Signal; 3934 my $signal = new Coro::Signal;
3839 push @WAIT_FOR_TICK, $signal; 3935 push @WAIT_FOR_TICK, $signal;
3840 $signal->wait; 3936 $signal->wait;
3841} 3937}
3842 3938
3843sub wait_for_tick_begin { 3939sub wait_for_tick_begin {
3844 return if tick_inhibit || $Coro::current == $Coro::main; 3940 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3845 3941
3846 my $signal = new Coro::Signal; 3942 my $signal = new Coro::Signal;
3847 push @WAIT_FOR_TICK_BEGIN, $signal; 3943 push @WAIT_FOR_TICK_BEGIN, $signal;
3848 $signal->wait; 3944 $signal->wait;
3849} 3945}
3854 unless ++$bug_warning > 10; 3950 unless ++$bug_warning > 10;
3855 return; 3951 return;
3856 } 3952 }
3857 3953
3858 cf::server_tick; # one server iteration 3954 cf::server_tick; # one server iteration
3955
3956 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d#
3859 3957
3860 if ($NOW >= $NEXT_RUNTIME_WRITE) { 3958 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3861 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 3959 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
3862 Coro::async_pool { 3960 Coro::async_pool {
3863 $Coro::current->{desc} = "runtime saver"; 3961 $Coro::current->{desc} = "runtime saver";
3886} 3984}
3887 3985
3888{ 3986{
3889 # configure BDB 3987 # configure BDB
3890 3988
3891 BDB::min_parallel 8; 3989 BDB::min_parallel 16;
3892 BDB::max_poll_reqs $TICK * 0.1; 3990 BDB::max_poll_reqs $TICK * 0.1;
3893 $AnyEvent::BDB::WATCHER->priority (1); 3991 $AnyEvent::BDB::WATCHER->priority (1);
3894 3992
3895 unless ($DB_ENV) { 3993 unless ($DB_ENV) {
3896 $DB_ENV = BDB::db_env_create; 3994 $DB_ENV = BDB::db_env_create;
3977 } 4075 }
3978} 4076}
3979 4077
3980# load additional modules 4078# load additional modules
3981require "cf/$_.pm" for @EXTRA_MODULES; 4079require "cf/$_.pm" for @EXTRA_MODULES;
4080cf::_connect_to_perl_2;
3982 4081
3983END { cf::emergency_save } 4082END { cf::emergency_save }
3984 4083
39851 40841
3986 4085

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines