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.561 by root, Fri Apr 22 06:10:33 2011 UTC vs.
Revision 1.624 by root, Sat Nov 17 23:40:02 2018 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 (©) 2018 Marc Alexander Lehmann / the Deliantra team
4# Copyright (©) 2006,2007,2008,2009,2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team 5# Copyright (©) 2006,2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5# 6#
6# Deliantra is free software: you can redistribute it and/or modify it under 7# Deliantra is free software: you can redistribute it and/or modify it under
7# the terms of the Affero GNU General Public License as published by the 8# the terms of the Affero GNU General Public License as published by the
8# Free Software Foundation, either version 3 of the License, or (at your 9# Free Software Foundation, either version 3 of the License, or (at your
9# option) any later version. 10# option) any later version.
10# 11#
11# This program is distributed in the hope that it will be useful, 12# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of 13# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details. 15# GNU General Public License for more details.
15# 16#
16# You should have received a copy of the Affero GNU General Public License 17# You should have received a copy of the Affero GNU General Public License
17# and the GNU General Public License along with this program. If not, see 18# and the GNU General Public License along with this program. If not, see
18# <http://www.gnu.org/licenses/>. 19# <http://www.gnu.org/licenses/>.
19# 20#
20# The authors can be reached via e-mail to <support@deliantra.net> 21# The authors can be reached via e-mail to <support@deliantra.net>
21# 22#
22 23
23package cf; 24package cf;
24 25
32use Safe; 33use Safe;
33use Safe::Hole; 34use Safe::Hole;
34use Storable (); 35use Storable ();
35use Carp (); 36use Carp ();
36 37
37use Guard (); 38use AnyEvent ();
39use AnyEvent::IO ();
40use AnyEvent::DNS ();
41
38use Coro (); 42use Coro ();
39use Coro::State; 43use Coro::State;
40use Coro::Handle; 44use Coro::Handle;
41use Coro::EV; 45use Coro::EV;
42use Coro::AnyEvent; 46use Coro::AnyEvent;
48use Coro::AIO; 52use Coro::AIO;
49use Coro::BDB 1.6; 53use Coro::BDB 1.6;
50use Coro::Storable; 54use Coro::Storable;
51use Coro::Util (); 55use Coro::Util ();
52 56
57use Guard ();
53use JSON::XS 2.01 (); 58use JSON::XS 2.01 ();
54use BDB (); 59use BDB ();
55use Data::Dumper; 60use Data::Dumper;
56use Fcntl; 61use Fcntl;
57use YAML::XS (); 62use YAML::XS ();
63use CBOR::XS ();
58use IO::AIO (); 64use IO::AIO ();
59use Time::HiRes;
60use Compress::LZF; 65use Compress::LZF;
61use Digest::MD5 (); 66use Digest::MD5 ();
62 67
63AnyEvent::detect; 68AnyEvent::detect;
64 69
83our %COMMAND = (); 88our %COMMAND = ();
84our %COMMAND_TIME = (); 89our %COMMAND_TIME = ();
85 90
86our @EXTS = (); # list of extension package names 91our @EXTS = (); # list of extension package names
87our %EXTCMD = (); 92our %EXTCMD = ();
93our %EXTACMD = ();
88our %EXTICMD = (); 94our %EXTICMD = ();
95our %EXTIACMD = ();
89our %EXT_CORO = (); # coroutines bound to extensions 96our %EXT_CORO = (); # coroutines bound to extensions
90our %EXT_MAP = (); # pluggable maps 97our %EXT_MAP = (); # pluggable maps
91 98
92our $RELOAD; # number of reloads so far, non-zero while in reload 99our $RELOAD; # number of reloads so far, non-zero while in reload
93our @EVENT; 100our @EVENT;
108our $RANDOMDIR = "$LOCALDIR/random"; 115our $RANDOMDIR = "$LOCALDIR/random";
109our $BDBDIR = "$LOCALDIR/db"; 116our $BDBDIR = "$LOCALDIR/db";
110our $PIDFILE = "$LOCALDIR/pid"; 117our $PIDFILE = "$LOCALDIR/pid";
111our $RUNTIMEFILE = "$LOCALDIR/runtime"; 118our $RUNTIMEFILE = "$LOCALDIR/runtime";
112 119
113our %RESOURCE; # unused 120#our %RESOURCE; # unused
114 121
115our $OUTPUT_RATE_MIN = 3000; 122our $OUTPUT_RATE_MIN = 3000;
116our $OUTPUT_RATE_MAX = 1000000; 123our $OUTPUT_RATE_MAX = 1000000;
117 124
118our $MAX_LINKS = 32; # how many chained exits to follow 125our $MAX_LINKS = 32; # how many chained exits to follow
129our $DB_ENV; 136our $DB_ENV;
130 137
131our @EXTRA_MODULES = qw(pod match mapscript incloader); 138our @EXTRA_MODULES = qw(pod match mapscript incloader);
132 139
133our %CFG; 140our %CFG;
141our %EXT_CFG; # cfgkeyname => [var-ref, defaultvalue]
134 142
135our $UPTIME; $UPTIME ||= time; 143our $UPTIME; $UPTIME ||= time;
136our $RUNTIME; 144our $RUNTIME = 0;
145our $SERVER_TICK = 0;
137our $NOW; 146our $NOW;
138 147
139our (%PLAYER, %PLAYER_LOADING); # all users 148our (%PLAYER, %PLAYER_LOADING); # all users
140our (%MAP, %MAP_LOADING ); # all maps 149our (%MAP, %MAP_LOADING ); # all maps
141our $LINK_MAP; # the special {link} map, which is always available 150our $LINK_MAP; # the special {link} map, which is always available
150 159
151our @POST_INIT; 160our @POST_INIT;
152 161
153our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow) 162our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow)
154our $REALLY_UNLOOP; # never set to true, please :) 163our $REALLY_UNLOOP; # never set to true, please :)
164
165our $WAIT_FOR_TICK = new Coro::Signal;
166our @WAIT_FOR_TICK_BEGIN;
155 167
156binmode STDOUT; 168binmode STDOUT;
157binmode STDERR; 169binmode STDERR;
158 170
159# read virtual server time, if available 171# read virtual server time, if available
193 205
194=over 4 206=over 4
195 207
196=item $cf::UPTIME 208=item $cf::UPTIME
197 209
198The timestamp of the server start (so not actually an uptime). 210The timestamp of the server start (so not actually an "uptime").
211
212=item $cf::SERVER_TICK
213
214An unsigned integer that starts at zero when the server is started and is
215incremented on every tick.
216
217=item $cf::NOW
218
219The (real) time of the last (current) server tick - updated before and
220after tick processing, so this is useful only as a rough "what time is it
221now" estimate.
222
223=item $cf::TICK
224
225The interval between each server tick, in seconds.
199 226
200=item $cf::RUNTIME 227=item $cf::RUNTIME
201 228
202The time this server has run, starts at 0 and is increased by $cf::TICK on 229The time this server has run, starts at 0 and is increased by $cf::TICK on
203every server tick. 230every server tick.
204 231
205=item $cf::CONFDIR $cf::DATADIR $cf::LIBDIR $cf::PODDIR 232=item $cf::CONFDIR $cf::DATADIR $cf::LIBDIR $cf::PODDIR
206$cf::MAPDIR $cf::LOCALDIR $cf::TMPDIR $cf::UNIQUEDIR 233$cf::MAPDIR $cf::LOCALDIR $cf::TMPDIR $cf::UNIQUEDIR
207$cf::PLAYERDIR $cf::RANDOMDIR $cf::BDBDIR 234$cf::PLAYERDIR $cf::RANDOMDIR $cf::BDBDIR
208 235
209Various directories - "/etc", read-only install directory, perl-library 236Various directories - "/etc", read-only install directory, perl-library
210directory, pod-directory, read-only maps directory, "/var", "/var/tmp", 237directory, pod-directory, read-only maps directory, "/var", "/var/tmp",
211unique-items directory, player file directory, random maps directory and 238unique-items directory, player file directory, random maps directory and
212database environment. 239database environment.
213 240
214=item $cf::NOW
215
216The time of the last (current) server tick.
217
218=item $cf::TICK
219
220The interval between server ticks, in seconds.
221
222=item $cf::LOADAVG 241=item $cf::LOADAVG
223 242
224The current CPU load on the server (alpha-smoothed), as a value between 0 243The current CPU load on the server (alpha-smoothed), as a value between 0
225(none) and 1 (overloaded), indicating how much time is spent on processing 244(none) and 1 (overloaded), indicating how much time is spent on processing
226objects per tick. Healthy values are < 0.5. 245objects per tick. Healthy values are < 0.5.
234Configuration for the server, loaded from C</etc/deliantra-server/config>, or 253Configuration for the server, loaded from C</etc/deliantra-server/config>, or
235from wherever your confdir points to. 254from wherever your confdir points to.
236 255
237=item cf::wait_for_tick, cf::wait_for_tick_begin 256=item cf::wait_for_tick, cf::wait_for_tick_begin
238 257
239These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only 258These are functions that inhibit the current coroutine one tick.
240returns directly I<after> the tick processing (and consequently, can only wake one thread 259cf::wait_for_tick_begin only returns directly I<after> the tick
260processing (and consequently, can only wake one thread per tick), while
241per tick), while cf::wait_for_tick wakes up all waiters after tick processing. 261cf::wait_for_tick wakes up all waiters after tick processing.
262
263Note that cf::wait_for_tick will immediately return when the server is not
264ticking, making it suitable for small pauses in threads that need to run
265when the server is paused. If that is not applicable (i.e. you I<really>
266want to wait, use C<$cf::WAIT_FOR_TICK>).
267
268=item $cf::WAIT_FOR_TICK
269
270Note that C<cf::wait_for_tick> is probably the correct thing to use. This
271variable contains a L<Coro::Signal> that is broadcats after every server
272tick. Calling C<< ->wait >> on it will suspend the caller until after the
273next server tick.
242 274
243=cut 275=cut
244 276
245sub wait_for_tick(); 277sub wait_for_tick();
246sub wait_for_tick_begin(); 278sub wait_for_tick_begin();
312)) { 344)) {
313 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 345 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
314} 346}
315 347
316$EV::DIED = sub { 348$EV::DIED = sub {
317 Carp::cluck "error in event callback: @_"; 349 warn "error in event callback: $@";
318}; 350};
319 351
320############################################################################# 352#############################################################################
321 353
322sub fork_call(&@); 354sub fork_call(&@);
349 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge; 381 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge;
350 $d 382 $d
351 } || "[unable to dump $_[0]: '$@']"; 383 } || "[unable to dump $_[0]: '$@']";
352} 384}
353 385
354=item $scalar = load_file $path 386=item $scalar = cf::load_file $path
355 387
356Loads the given file from path and returns its contents. Croaks on error 388Loads the given file from path and returns its contents. Croaks on error
357and can block. 389and can block.
358 390
359=cut 391=cut
363 or Carp::croak "$_[0]: $!"; 395 or Carp::croak "$_[0]: $!";
364 396
365 $data 397 $data
366} 398}
367 399
400=item $success = cf::replace_file $path, $data, $sync
401
402Atomically replaces the file at the given $path with new $data, and
403optionally $sync the data to disk before replacing the file.
404
405=cut
406
407sub replace_file($$;$) {
408 my ($path, $data, $sync) = @_;
409
410 my $lock = cf::lock_acquire ("replace_file:$path");
411
412 my $fh = aio_open "$path~", Fcntl::O_WRONLY | Fcntl::O_CREAT | Fcntl::O_TRUNC, 0644
413 or return;
414
415 $data = $data->() if ref $data;
416
417 length $data == aio_write $fh, 0, (length $data), $data, 0
418 or return;
419
420 !$sync
421 or !aio_fsync $fh
422 or return;
423
424 aio_close $fh
425 and return;
426
427 aio_rename "$path~", $path
428 and return;
429
430 if ($sync) {
431 $path =~ s%/[^/]*$%%;
432 aio_pathsync $path;
433 }
434
435 1
436}
437
368=item $ref = cf::decode_json $json 438=item $ref = cf::decode_json $json
369 439
370Converts a JSON string into the corresponding perl data structure. 440Converts a JSON string into the corresponding perl data structure.
371 441
372=item $json = cf::encode_json $ref 442=item $json = cf::encode_json $ref
394 464
395=cut 465=cut
396 466
397sub decode_yaml($) { 467sub decode_yaml($) {
398 fork_call { YAML::XS::Load $_[0] } @_ 468 fork_call { YAML::XS::Load $_[0] } @_
469}
470
471=item $scalar = cf::decode_cbor $scalar
472
473Same as CBOR::XS::decode_cbor, but takes server ticks into account, so
474blocks. For small amounts of data, C<CBOR::XS::decode_cbor> is the better
475alternative.
476
477=cut
478
479sub decode_cbor($) {
480 # we assume 10mb/s minimum decoding speed (on a ~2ghz machine)
481 cf::get_slot +(length $_[0]) / 10_000_000, 0, "decode_cbor";
482 CBOR::XS::decode_cbor $_[0]
399} 483}
400 484
401=item $scalar = cf::unlzf $scalar 485=item $scalar = cf::unlzf $scalar
402 486
403Same as Compress::LZF::compress, but takes server ticks into account, so 487Same as Compress::LZF::compress, but takes server ticks into account, so
442 } 526 }
443} 527}
444 528
445=item cf::lock_wait $string 529=item cf::lock_wait $string
446 530
447Wait until the given lock is available. See cf::lock_acquire. 531Wait until the given lock is available. See cf::lock_acquire.
448 532
449=item my $lock = cf::lock_acquire $string 533=item my $lock = cf::lock_acquire $string
450 534
451Wait until the given lock is available and then acquires it and returns 535Wait until the given lock is available and then acquires it and returns
452a L<Guard> object. If the guard object gets destroyed (goes out of scope, 536a L<Guard> object. If the guard object gets destroyed (goes out of scope,
505Allocate $time seconds of blocking CPU time at priority C<$priority> 589Allocate $time seconds of blocking CPU time at priority C<$priority>
506(default: 0): This call blocks and returns only when you have at least 590(default: 0): This call blocks and returns only when you have at least
507C<$time> seconds of cpu time till the next tick. The slot is only valid 591C<$time> seconds of cpu time till the next tick. The slot is only valid
508till the next cede. 592till the next cede.
509 593
510Background jobs should use a priority les than zero, interactive jobs 594Background jobs should use a priority less than zero, interactive jobs
511should use 100 or more. 595should use 100 or more.
512 596
513The optional C<$name> can be used to identify the job to run. It might be 597The optional C<$name> can be used to identify the job to run. It might be
514used for statistical purposes and should identify the same time-class. 598used for statistical purposes and should identify the same time-class.
515 599
528 my $signal = new Coro::Signal; 612 my $signal = new Coro::Signal;
529 my $busy; 613 my $busy;
530 614
531 while () { 615 while () {
532 next_job: 616 next_job:
617
618 Coro::cede;
533 619
534 my $avail = cf::till_tick; 620 my $avail = cf::till_tick;
535 621
536 for (0 .. $#SLOT_QUEUE) { 622 for (0 .. $#SLOT_QUEUE) {
537 if ($SLOT_QUEUE[$_][0] <= $avail) { 623 if ($SLOT_QUEUE[$_][0] <= $avail) {
538 $busy = 0; 624 $busy = 0;
539 my $job = splice @SLOT_QUEUE, $_, 1, (); 625 my $job = splice @SLOT_QUEUE, $_, 1, ();
540 $job->[2]->send; 626 $job->[2]->send;
541 Coro::cede;
542 goto next_job; 627 goto next_job;
543 } else { 628 } else {
544 $SLOT_QUEUE[$_][0] *= $SLOT_DECAY; 629 $SLOT_QUEUE[$_][0] *= $SLOT_DECAY;
545 } 630 }
546 } 631 }
547 632
548 if (@SLOT_QUEUE) { 633 if (@SLOT_QUEUE) {
549 # we do not use wait_for_tick() as it returns immediately when tick is inactive 634 wait_for_tick;
550 push @cf::WAIT_FOR_TICK, $signal;
551 $signal->wait;
552 } else { 635 } else {
553 $busy = 0; 636 $busy = 0;
554 Coro::schedule; 637 Coro::schedule;
555 } 638 }
556 } 639 }
582BEGIN { *async = \&Coro::async_pool } 665BEGIN { *async = \&Coro::async_pool }
583 666
584=item cf::sync_job { BLOCK } 667=item cf::sync_job { BLOCK }
585 668
586The design of Deliantra requires that the main coroutine ($Coro::main) 669The design of Deliantra requires that the main coroutine ($Coro::main)
587is always able to handle events or runnable, as Deliantra is only 670is always able to handle events or is runnable, as Deliantra is only
588partly reentrant. Thus "blocking" it by e.g. waiting for I/O is not 671partly reentrant. Thus "blocking" it by e.g. waiting for I/O is not
589acceptable. 672acceptable.
590 673
591If it must be done, put the blocking parts into C<sync_job>. This will run 674If it must be done, put the blocking parts into C<sync_job>. This will run
592the given BLOCK in another coroutine while waiting for the result. The 675the given BLOCK in another coroutine while waiting for the result. The
620 703
621 while ($busy) { 704 while ($busy) {
622 if (Coro::nready) { 705 if (Coro::nready) {
623 Coro::cede_notself; 706 Coro::cede_notself;
624 } else { 707 } else {
625 EV::loop EV::LOOP_ONESHOT; 708 EV::run EV::RUN_ONCE;
626 } 709 }
627 } 710 }
628 711
629 my $time = AE::time - $time; 712 my $time = AE::time - $time;
630 713
671 reset_signals; 754 reset_signals;
672} 755}
673 756
674sub fork_call(&@) { 757sub fork_call(&@) {
675 my ($cb, @args) = @_; 758 my ($cb, @args) = @_;
676
677 # we seemingly have to make a local copy of the whole thing,
678 # otherwise perl prematurely frees the stuff :/
679 # TODO: investigate and fix (likely this will be rather laborious)
680 759
681 my @res = Coro::Util::fork_eval { 760 my @res = Coro::Util::fork_eval {
682 cf::post_fork; 761 cf::post_fork;
683 &$cb 762 &$cb
684 } @args; 763 } @args;
834 913
835 return db_get cache => "$id/data"; 914 return db_get cache => "$id/data";
836 } 915 }
837 } 916 }
838 917
839 my $t1 = Time::HiRes::time; 918 my $t1 = EV::time;
840 my $data = $process->(\@data); 919 my $data = $process->(\@data);
841 my $t2 = Time::HiRes::time; 920 my $t2 = EV::time;
842 921
843 info "cache: '$id' processed in ", $t2 - $t1, "s\n"; 922 info "cache: '$id' processed in ", $t2 - $t1, "s\n";
844 923
845 db_put cache => "$id/data", $data; 924 db_put cache => "$id/data", $data;
846 db_put cache => "$id/md5" , $md5; 925 db_put cache => "$id/md5" , $md5;
1366=cut 1445=cut
1367 1446
1368############################################################################# 1447#############################################################################
1369# command handling &c 1448# command handling &c
1370 1449
1371=item cf::register_command $name => \&callback($ob,$args); 1450=item cf::register_command $name => \&callback($ob,$args)
1372 1451
1373Register a callback for execution when the client sends the user command 1452Register a callback for execution when the client sends the user command
1374$name. 1453$name.
1375 1454
1376=cut 1455=cut
1382 #warn "registering command '$name/$time' to '$caller'"; 1461 #warn "registering command '$name/$time' to '$caller'";
1383 1462
1384 push @{ $COMMAND{$name} }, [$caller, $cb]; 1463 push @{ $COMMAND{$name} }, [$caller, $cb];
1385} 1464}
1386 1465
1387=item cf::register_extcmd $name => \&callback($pl,$packet); 1466=item cf::register_extcmd $name => \&callback($pl,@args)
1388 1467
1389Register a callback for execution when the client sends an (synchronous) 1468Register a callback for execution when the client sends an (synchronous)
1390extcmd packet. Ext commands will be processed in the order they are 1469extcmd packet. Ext commands will be processed in the order they are
1391received by the server, like other user commands. The first argument is 1470received by the server, like other user commands. The first argument is
1392the logged-in player. Ext commands can only be processed after a player 1471the logged-in player. Ext commands can only be processed after a player
1393has logged in successfully. 1472has logged in successfully.
1394 1473
1395If the callback returns something, it is sent back as if reply was being 1474The values will be sent back to the client.
1396called.
1397 1475
1476=item cf::register_async_extcmd $name => \&callback($pl,$reply->(...),@args)
1477
1478Same as C<cf::register_extcmd>, but instead of returning values, the
1479callback needs to clal the C<$reply> function.
1480
1398=item cf::register_exticmd $name => \&callback($ns,$packet); 1481=item cf::register_exticmd $name => \&callback($ns,@args)
1399 1482
1400Register a callback for execution when the client sends an (asynchronous) 1483Register a callback for execution when the client sends an (asynchronous)
1401exticmd packet. Exti commands are processed by the server as soon as they 1484exticmd packet. Exti commands are processed by the server as soon as they
1402are received, i.e. out of order w.r.t. other commands. The first argument 1485are received, i.e. out of order w.r.t. other commands. The first argument
1403is a client socket. Exti commands can be received anytime, even before 1486is a client socket. Exti commands can be received anytime, even before
1404log-in. 1487log-in.
1405 1488
1406If the callback returns something, it is sent back as if reply was being 1489The values will be sent back to the client.
1407called.
1408 1490
1409=cut 1491=item cf::register_async_exticmd $name => \&callback($ns,$reply->(...),@args)
1410 1492
1493Same as C<cf::register_extcmd>, but instead of returning values, the
1494callback needs to clal the C<$reply> function.
1495
1496=cut
1497
1411sub register_extcmd { 1498sub register_extcmd($$) {
1412 my ($name, $cb) = @_; 1499 my ($name, $cb) = @_;
1413 1500
1414 $EXTCMD{$name} = $cb; 1501 $EXTCMD{$name} = $cb;
1415} 1502}
1416 1503
1417sub register_exticmd { 1504sub register_async_extcmd($$) {
1418 my ($name, $cb) = @_; 1505 my ($name, $cb) = @_;
1419 1506
1507 $EXTACMD{$name} = $cb;
1508}
1509
1510sub register_exticmd($$) {
1511 my ($name, $cb) = @_;
1512
1420 $EXTICMD{$name} = $cb; 1513 $EXTICMD{$name} = $cb;
1514}
1515
1516sub register_async_exticmd($$) {
1517 my ($name, $cb) = @_;
1518
1519 $EXTIACMD{$name} = $cb;
1421} 1520}
1422 1521
1423use File::Glob (); 1522use File::Glob ();
1424 1523
1425cf::player->attach ( 1524cf::player->attach (
1439 my ($pl, $buf) = @_; 1538 my ($pl, $buf) = @_;
1440 1539
1441 my $msg = eval { $pl->ns->{json_coder}->decode ($buf) }; 1540 my $msg = eval { $pl->ns->{json_coder}->decode ($buf) };
1442 1541
1443 if (ref $msg) { 1542 if (ref $msg) {
1444 my ($type, $reply, @payload) = 1543 my ($type, $reply, @payload) = @$msg; # version 1 used %type, $id, %$hash
1445 "ARRAY" eq ref $msg
1446 ? @$msg
1447 : ($msg->{msgtype}, $msg->{msgid}, %$msg); # TODO: version 1, remove
1448 1544
1449 my @reply;
1450
1451 if (my $cb = $EXTCMD{$type}) { 1545 if (my $cb = $EXTACMD{$type}) {
1546 $cb->(
1547 $pl,
1548 sub {
1549 $pl->ext_msg ("reply-$reply", @_)
1550 if $reply;
1551 },
1552 @payload
1553 );
1554 } else {
1555 my @reply;
1556
1557 if (my $cb = $EXTCMD{$type}) {
1452 @reply = $cb->($pl, @payload); 1558 @reply = $cb->($pl, @payload);
1559 }
1560
1561 $pl->ext_msg ("reply-$reply", @reply)
1562 if $reply;
1453 } 1563 }
1454
1455 $pl->ext_reply ($reply, @reply)
1456 if $reply;
1457 1564
1458 } else { 1565 } else {
1459 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 1566 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
1460 } 1567 }
1461 1568
1474 }; 1581 };
1475 1582
1476 $grp 1583 $grp
1477} 1584}
1478 1585
1586sub _ext_cfg_reg($$$$) {
1587 my ($rvar, $varname, $cfgname, $default) = @_;
1588
1589 $cfgname = lc $varname
1590 unless length $cfgname;
1591
1592 $EXT_CFG{$cfgname} = [$rvar, $default];
1593
1594 $$rvar = exists $CFG{$cfgname} ? $CFG{$cfgname} : $default;
1595}
1596
1479sub load_extensions { 1597sub load_extensions {
1480 info "loading extensions..."; 1598 info "loading extensions...";
1599
1600 %EXT_CFG = ();
1481 1601
1482 cf::sync_job { 1602 cf::sync_job {
1483 my %todo; 1603 my %todo;
1484 1604
1485 for my $path (<$LIBDIR/*.ext>) { 1605 for my $path (<$LIBDIR/*.ext>) {
1528 unless exists $done{$_}; 1648 unless exists $done{$_};
1529 } 1649 }
1530 1650
1531 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n"; 1651 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1532 1652
1653 my $source = $v->{source};
1654
1655 # support "CONF varname :confname = default" pseudo-statements
1656 $source =~ s{
1657 ^ CONF \s+ ([^\s:=]+) \s* (?:: \s* ([^\s:=]+) \s* )? = ([^\n#]+)
1658 }{
1659 "our \$$1; BEGIN { cf::_ext_cfg_reg \\\$$1, q\x00$1\x00, q\x00$2\x00, $3 }";
1660 }gmxe;
1661
1533 my $active = eval $v->{source}; 1662 my $active = eval $source;
1534 1663
1535 if (length $@) { 1664 if (length $@) {
1536 error "$v->{path}: $@\n"; 1665 error "$v->{path}: $@\n";
1537 1666
1538 cf::cleanup "mandatory extension '$k' failed to load, exiting." 1667 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1825} 1954}
1826 1955
1827=item $protocol_xml = $player->expand_cfpod ($cfpod) 1956=item $protocol_xml = $player->expand_cfpod ($cfpod)
1828 1957
1829Expand deliantra pod fragments into protocol xml. 1958Expand deliantra pod fragments into protocol xml.
1830
1831=item $player->ext_reply ($msgid, @msg)
1832
1833Sends an ext reply to the player.
1834
1835=cut
1836
1837sub ext_reply($$@) {
1838 my ($self, $id, @msg) = @_;
1839
1840 $self->ns->ext_reply ($id, @msg)
1841}
1842 1959
1843=item $player->ext_msg ($type, @msg) 1960=item $player->ext_msg ($type, @msg)
1844 1961
1845Sends an ext event to the client. 1962Sends an ext event to the client.
1846 1963
2069 $self->{load_path} = $path; 2186 $self->{load_path} = $path;
2070 2187
2071 1 2188 1
2072} 2189}
2073 2190
2191# used to laod the header of an original map
2074sub load_header_orig { 2192sub load_header_orig {
2075 my ($self) = @_; 2193 my ($self) = @_;
2076 2194
2077 $self->load_header_from ($self->load_path) 2195 $self->load_header_from ($self->load_path)
2078} 2196}
2079 2197
2198# used to laod the header of an instantiated map
2080sub load_header_temp { 2199sub load_header_temp {
2081 my ($self) = @_; 2200 my ($self) = @_;
2082 2201
2083 $self->load_header_from ($self->save_path) 2202 $self->load_header_from ($self->save_path)
2084} 2203}
2085 2204
2205# called after loading the header from an instantiated map
2086sub prepare_temp { 2206sub prepare_temp {
2087 my ($self) = @_; 2207 my ($self) = @_;
2088 2208
2089 $self->last_access ((delete $self->{last_access}) 2209 $self->last_access ((delete $self->{last_access})
2090 || $cf::RUNTIME); #d# 2210 || $cf::RUNTIME); #d#
2091 # safety 2211 # safety
2092 $self->{instantiate_time} = $cf::RUNTIME 2212 $self->{instantiate_time} = $cf::RUNTIME
2093 if $self->{instantiate_time} > $cf::RUNTIME; 2213 if $self->{instantiate_time} > $cf::RUNTIME;
2094} 2214}
2095 2215
2216# called after loading the header from an original map
2096sub prepare_orig { 2217sub prepare_orig {
2097 my ($self) = @_; 2218 my ($self) = @_;
2098 2219
2099 $self->{load_original} = 1; 2220 $self->{load_original} = 1;
2100 $self->{instantiate_time} = $cf::RUNTIME; 2221 $self->{instantiate_time} = $cf::RUNTIME;
2126sub find { 2247sub find {
2127 my ($path, $origin) = @_; 2248 my ($path, $origin) = @_;
2128 2249
2129 cf::cede_to_tick; 2250 cf::cede_to_tick;
2130 2251
2131 $path = normalise $path, $origin && $origin->path; 2252 $path = normalise $path, $origin;
2132 2253
2133 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove 2254 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove
2134 my $guard2 = cf::lock_acquire "map_find:$path"; 2255 my $guard2 = cf::lock_acquire "map_find:$path";
2135 2256
2136 $cf::MAP{$path} || do { 2257 $cf::MAP{$path} || do {
2167 2288
2168 { 2289 {
2169 my $guard = cf::lock_acquire "map_data:$path"; 2290 my $guard = cf::lock_acquire "map_data:$path";
2170 2291
2171 return unless $self->valid; 2292 return unless $self->valid;
2172 return unless $self->in_memory == cf::MAP_SWAPPED; 2293 return unless $self->state == cf::MAP_SWAPPED;
2173
2174 $self->in_memory (cf::MAP_LOADING);
2175 2294
2176 $self->alloc; 2295 $self->alloc;
2177 2296
2178 $self->pre_load; 2297 $self->pre_load;
2179 cf::cede_to_tick; 2298 cf::cede_to_tick;
2180 2299
2300 if (exists $self->{load_path}) {
2181 my $f = new_from_file cf::object::thawer $self->{load_path}; 2301 my $f = new_from_file cf::object::thawer $self->{load_path};
2182 $f->skip_block; 2302 $f->skip_block;
2183 $self->_load_objects ($f) 2303 $self->_load_objects ($f)
2184 or return; 2304 or return;
2185 2305
2186 $self->post_load_original 2306 $self->post_load_original
2187 if delete $self->{load_original}; 2307 if delete $self->{load_original};
2188 2308
2189 if (my $uniq = $self->uniq_path) { 2309 if (my $uniq = $self->uniq_path) {
2190 utf8::encode $uniq; 2310 utf8::encode $uniq;
2191 unless (aio_stat $uniq) { 2311 unless (aio_stat $uniq) {
2192 if (my $f = new_from_file cf::object::thawer $uniq) { 2312 if (my $f = new_from_file cf::object::thawer $uniq) {
2193 $self->clear_unique_items; 2313 $self->clear_unique_items;
2194 $self->_load_objects ($f); 2314 $self->_load_objects ($f);
2195 $f->resolve_delayed_derefs; 2315 $f->resolve_delayed_derefs;
2316 }
2196 } 2317 }
2197 } 2318 }
2198 }
2199 2319
2200 $f->resolve_delayed_derefs; 2320 $f->resolve_delayed_derefs;
2321 } else {
2322 $self->post_load_original
2323 if delete $self->{load_original};
2324 }
2325
2326 $self->state (cf::MAP_INACTIVE);
2201 2327
2202 cf::cede_to_tick; 2328 cf::cede_to_tick;
2203 # now do the right thing for maps 2329 # now do the right thing for maps
2204 $self->link_multipart_objects; 2330 $self->link_multipart_objects;
2205 $self->difficulty ($self->estimate_difficulty) 2331 $self->difficulty ($self->estimate_difficulty)
2209 unless ($self->{deny_activate}) { 2335 unless ($self->{deny_activate}) {
2210 $self->decay_objects; 2336 $self->decay_objects;
2211 $self->fix_auto_apply; 2337 $self->fix_auto_apply;
2212 $self->update_buttons; 2338 $self->update_buttons;
2213 cf::cede_to_tick; 2339 cf::cede_to_tick;
2214 $self->activate; 2340 #$self->activate; # no longer activate maps automatically
2215 } 2341 }
2216 2342
2217 $self->{last_save} = $cf::RUNTIME; 2343 $self->{last_save} = $cf::RUNTIME;
2218 $self->last_access ($cf::RUNTIME); 2344 $self->last_access ($cf::RUNTIME);
2219
2220 $self->in_memory (cf::MAP_ACTIVE);
2221 } 2345 }
2222 2346
2223 $self->post_load; 2347 $self->post_load;
2224 2348
2225 1 2349 1
2238# if $self->per_party; 2362# if $self->per_party;
2239 2363
2240 $self 2364 $self
2241} 2365}
2242 2366
2243# find and load all maps in the 3x3 area around a map
2244sub load_neighbours {
2245 my ($map) = @_;
2246
2247 my @neigh; # diagonal neighbours
2248
2249 for (0 .. 3) {
2250 my $neigh = $map->tile_path ($_)
2251 or next;
2252 $neigh = find $neigh, $map
2253 or next;
2254 $neigh->load;
2255
2256 # now find the diagonal neighbours
2257 push @neigh,
2258 [$neigh->tile_path (($_ + 3) % 4), $neigh],
2259 [$neigh->tile_path (($_ + 1) % 4), $neigh];
2260 }
2261
2262 for (grep defined $_->[0], @neigh) {
2263 my ($path, $origin) = @$_;
2264 my $neigh = find $path, $origin
2265 or next;
2266 $neigh->load;
2267 }
2268}
2269
2270sub find_sync { 2367sub find_sync {
2271 my ($path, $origin) = @_; 2368 my ($path, $origin) = @_;
2272 2369
2370 # it's a bug to call this from the main context
2273 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync" 2371 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2274 if $Coro::current == $Coro::main; 2372 if $Coro::current == $Coro::main;
2275 2373
2276 find $path, $origin 2374 find $path, $origin
2277} 2375}
2278 2376
2279sub do_load_sync { 2377sub do_load_sync {
2280 my ($map) = @_; 2378 my ($map) = @_;
2281 2379
2380 # it's a bug to call this from the main context
2282 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync" 2381 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2283 if $Coro::current == $Coro::main; 2382 if $Coro::current == $Coro::main;
2284 2383
2285 $map->load; 2384 $map->load;
2286} 2385}
2289our $MAP_PREFETCHER = undef; 2388our $MAP_PREFETCHER = undef;
2290 2389
2291sub find_async { 2390sub find_async {
2292 my ($path, $origin, $load) = @_; 2391 my ($path, $origin, $load) = @_;
2293 2392
2294 $path = normalise $path, $origin && $origin->{path}; 2393 $path = normalise $path, $origin;
2295 2394
2296 if (my $map = $cf::MAP{$path}) { 2395 if (my $map = $cf::MAP{$path}) {
2297 return $map if !$load || $map->in_memory == cf::MAP_ACTIVE; 2396 return $map if !$load || $map->linkable;
2298 } 2397 }
2299 2398
2300 $MAP_PREFETCH{$path} |= $load; 2399 $MAP_PREFETCH{$path} |= $load;
2301 2400
2302 $MAP_PREFETCHER ||= cf::async { 2401 $MAP_PREFETCHER ||= cf::async {
2303 $Coro::current->{desc} = "map prefetcher"; 2402 $Coro::current->{desc} = "map prefetcher";
2304 2403
2305 while (%MAP_PREFETCH) { 2404 while (%MAP_PREFETCH) {
2306 while (my ($k, $v) = each %MAP_PREFETCH) { 2405 for my $k (keys %MAP_PREFETCH) {
2307 if (my $map = find $k) { 2406 if (my $map = find $k) {
2308 $map->load if $v; 2407 $map->load if $MAP_PREFETCH{$k};
2309 } 2408 }
2310 2409
2311 delete $MAP_PREFETCH{$k}; 2410 delete $MAP_PREFETCH{$k};
2312 } 2411 }
2313 } 2412 }
2361sub swap_out { 2460sub swap_out {
2362 my ($self) = @_; 2461 my ($self) = @_;
2363 2462
2364 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2463 my $lock = cf::lock_acquire "map_data:$self->{path}";
2365 2464
2366 return if $self->in_memory != cf::MAP_ACTIVE; 2465 return if !$self->linkable;
2367 return if $self->{deny_save}; 2466 return if $self->{deny_save};
2368 return if $self->players; 2467 return if $self->players;
2369 2468
2370 # first deactivate the map and "unlink" it from the core 2469 # first deactivate the map and "unlink" it from the core
2371 $self->deactivate; 2470 $self->deactivate;
2372 $_->clear_links_to ($self) for values %cf::MAP; 2471 $_->clear_links_to ($self) for values %cf::MAP;
2373 $self->in_memory (cf::MAP_SWAPPED); 2472 $self->state (cf::MAP_SWAPPED);
2374 2473
2375 # then atomically save 2474 # then atomically save
2376 $self->_save; 2475 $self->_save;
2377 2476
2378 # then free the map 2477 # then free the map
2404 2503
2405 return if $self->players; 2504 return if $self->players;
2406 2505
2407 cf::trace "resetting map ", $self->path, "\n"; 2506 cf::trace "resetting map ", $self->path, "\n";
2408 2507
2409 $self->in_memory (cf::MAP_SWAPPED); 2508 $self->state (cf::MAP_SWAPPED);
2410 2509
2411 # need to save uniques path 2510 # need to save uniques path
2412 unless ($self->{deny_save}) { 2511 unless ($self->{deny_save}) {
2413 my $uniq = $self->uniq_path; utf8::encode $uniq; 2512 my $uniq = $self->uniq_path; utf8::encode $uniq;
2414 2513
2567 2666
2568Creates and returns a persistent reference to an object that can be stored as a string. 2667Creates and returns a persistent reference to an object that can be stored as a string.
2569 2668
2570=item $ob = cf::object::deref ($refstring) 2669=item $ob = cf::object::deref ($refstring)
2571 2670
2572returns the objetc referenced by refstring. may return undef when it cnanot find the object, 2671returns the objetc referenced by refstring. may return undef when it cannot find the object,
2573even if the object actually exists. May block. 2672even if the object actually exists. May block.
2574 2673
2575=cut 2674=cut
2576 2675
2577sub deref { 2676sub deref {
2659=item $player_object->may ("access") 2758=item $player_object->may ("access")
2660 2759
2661Returns wether the given player is authorized to access resource "access" 2760Returns wether the given player is authorized to access resource "access"
2662(e.g. "command_wizcast"). 2761(e.g. "command_wizcast").
2663 2762
2763This is implemented by checking a config setting of C<may_access> where
2764C<access> is replaced by the access string. The following alternatives are
2765possible (and are tested in order):
2766
2767=over 4
2768
2769=item * Player is DM
2770
2771The request will succeed.
2772
2773=item * may_access is an array reference
2774
2775If either the player nickname or UUID is in the array, the request will
2776succeed, otherwise it will fail.
2777
2778=item * may_access is a true value
2779
2780The request will succeed.
2781
2782=item * may_access is missing or false
2783
2784The request will fail.
2785
2786=back
2787
2664=cut 2788=cut
2665 2789
2666sub cf::object::player::may { 2790sub cf::object::player::may {
2667 my ($self, $access) = @_; 2791 my ($self, $access) = @_;
2668 2792
2669 $self->flag (cf::FLAG_WIZ) || 2793 $self->flag (cf::FLAG_WIZ) ||
2670 (ref $cf::CFG{"may_$access"} 2794 (ref $cf::CFG{"may_$access"}
2671 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}} 2795 ? scalar grep $self->name eq $_ || $self->uuid eq $_, @{$cf::CFG{"may_$access"}}
2672 : $cf::CFG{"may_$access"}) 2796 : $cf::CFG{"may_$access"})
2673} 2797}
2674 2798
2675=item $player_object->enter_link 2799=item $player_object->enter_link
2676 2800
2679The player should be reasonably safe there for short amounts of time (e.g. 2803The player should be reasonably safe there for short amounts of time (e.g.
2680for loading a map). You I<MUST> call C<leave_link> as soon as possible, 2804for loading a map). You I<MUST> call C<leave_link> as soon as possible,
2681though, as the player cannot control the character while it is on the link 2805though, as the player cannot control the character while it is on the link
2682map. 2806map.
2683 2807
2684Will never block. 2808This method will never block, which is the whole reaosn for it's
2809existance: you can I<always> put a player onto the link map, which is the
2810only place to put objects that is guaranteed to exist.
2811
2812A typical usage pattern is to call C<enter_link> synchronously from the
2813server, then start a new thread, do your blocking stuff there and then
2814call C<leave_link> from that thread.
2685 2815
2686=item $player_object->leave_link ($map, $x, $y) 2816=item $player_object->leave_link ($map, $x, $y)
2687 2817
2688Moves the player out of the special C<{link}> map onto the specified 2818Moves the player out of the special C<{link}> map onto the specified
2689map. If the map is not valid (or omitted), the player will be moved back 2819map. If the map is not valid (or omitted), the player will be moved back
2744 # use -1 or undef as default coordinates, not 0, 0 2874 # use -1 or undef as default coordinates, not 0, 0
2745 ($x, $y) = ($map->enter_x, $map->enter_y) 2875 ($x, $y) = ($map->enter_x, $map->enter_y)
2746 if $x <= 0 && $y <= 0; 2876 if $x <= 0 && $y <= 0;
2747 2877
2748 $map->load; 2878 $map->load;
2749 $map->load_neighbours;
2750 2879
2751 return unless $self->contr->active; 2880 return unless $self->contr->active;
2752 2881
2753 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2882 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2754 if ($self->enter_map ($map, $x, $y)) { 2883 if ($self->enter_map ($map, $x, $y)) {
2810 ($path, $x, $y) = (undef, undef, undef); 2939 ($path, $x, $y) = (undef, undef, undef);
2811 } 2940 }
2812 } 2941 }
2813 2942
2814 my $map = eval { 2943 my $map = eval {
2815 my $map = defined $path ? cf::map::find $path : undef; 2944 my $map = defined $path ? cf::map::find $path, $self->map : undef;
2816 2945
2817 if ($map) { 2946 if ($map) {
2818 $map = $map->customise_for ($self); 2947 $map = $map->customise_for ($self);
2819 $map = $check->($map, $x, $y, $self) if $check && $map; 2948 $map = $check->($map, $x, $y, $self) if $check && $map;
2820 } else { 2949 } else {
2910 $Coro::current->{desc} = "enter_exit"; 3039 $Coro::current->{desc} = "enter_exit";
2911 3040
2912 unless (eval { 3041 unless (eval {
2913 $self->deactivate_recursive; # just to be sure 3042 $self->deactivate_recursive; # just to be sure
2914 3043
2915 # random map handling
2916 {
2917 my $guard = cf::lock_acquire "exit_prepare:$exit";
2918
2919 prepare_random_map $exit
2920 if $exit->slaying eq "/!";
2921 }
2922
2923 my $map = cf::map::normalise $exit->slaying, $exit->map && $exit->map->path; 3044 my $map = cf::map::normalise $exit->slaying, $exit->map;
2924 my $x = $exit->stats->hp; 3045 my $x = $exit->stats->hp;
2925 my $y = $exit->stats->sp; 3046 my $y = $exit->stats->sp;
3047
3048 # special map handling
3049 my $slaying = $exit->slaying;
3050
3051 # special map handling
3052 if ($slaying eq "/!") {
3053 my $guard = cf::lock_acquire "exit_prepare:$exit";
3054
3055 prepare_random_map $exit
3056 if $exit->slaying eq "/!"; # need to re-check after getting the lock
3057
3058 $map = $exit->slaying;
3059
3060 } elsif ($slaying eq '!up') {
3061 $map = $exit->map->tile_path (cf::TILE_UP);
3062 $x = $exit->x;
3063 $y = $exit->y;
3064
3065 } elsif ($slaying eq '!down') {
3066 $map = $exit->map->tile_path (cf::TILE_DOWN);
3067 $x = $exit->x;
3068 $y = $exit->y;
3069 }
2926 3070
2927 $self->goto ($map, $x, $y); 3071 $self->goto ($map, $x, $y);
2928 3072
2929 # if exit is damned, update players death & WoR home-position 3073 # if exit is damned, update players death & WoR home-position
2930 $self->contr->savebed ($map, $x, $y) 3074 $self->contr->savebed ($map, $x, $y)
2945 3089
2946=head3 cf::client 3090=head3 cf::client
2947 3091
2948=over 4 3092=over 4
2949 3093
2950=item $client->send_drawinfo ($text, $flags)
2951
2952Sends a drawinfo packet to the client. Circumvents output buffering so
2953should not be used under normal circumstances.
2954
2955=cut
2956
2957sub cf::client::send_drawinfo {
2958 my ($self, $text, $flags) = @_;
2959
2960 utf8::encode $text;
2961 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text);
2962}
2963
2964=item $client->send_big_packet ($pkt) 3094=item $client->send_big_packet ($pkt)
2965 3095
2966Like C<send_packet>, but tries to compress large packets, and fragments 3096Like C<send_packet>, but tries to compress large packets, and fragments
2967them as required. 3097them as required.
2968 3098
2986 $self->send_packet ($pkt); 3116 $self->send_packet ($pkt);
2987} 3117}
2988 3118
2989=item $client->send_msg ($channel, $msg, $color, [extra...]) 3119=item $client->send_msg ($channel, $msg, $color, [extra...])
2990 3120
2991Send a drawinfo or msg packet to the client, formatting the msg for the 3121Send a msg packet to the client, formatting the msg for the client if
2992client if neccessary. C<$type> should be a string identifying the type of 3122necessary. C<$type> should be a string identifying the type of the
2993the message, with C<log> being the default. If C<$color> is negative, suppress 3123message, with C<log> being the default. If C<$color> is negative, suppress
2994the message unless the client supports the msg packet. 3124the message unless the client supports the msg packet.
2995 3125
2996=cut 3126=cut
2997 3127
2998# non-persistent channels (usually the info channel) 3128# non-persistent channels (usually the info channel)
3041 }, 3171 },
3042 "c/body" => { 3172 "c/body" => {
3043 id => "infobox", 3173 id => "infobox",
3044 title => "Body Parts", 3174 title => "Body Parts",
3045 reply => undef, 3175 reply => undef,
3046 tooltip => "Shows which body parts you posess and are available", 3176 tooltip => "Shows which body parts you possess and are available",
3047 }, 3177 },
3048 "c/statistics" => { 3178 "c/statistics" => {
3049 id => "infobox", 3179 id => "infobox",
3050 title => "Statistics", 3180 title => "Statistics",
3051 reply => undef, 3181 reply => undef,
3103 id => "death", 3233 id => "death",
3104 title => "Death", 3234 title => "Death",
3105 reply => undef, 3235 reply => undef,
3106 tooltip => "Reason for and more info about your most recent death", 3236 tooltip => "Reason for and more info about your most recent death",
3107 }, 3237 },
3238 "c/fatal" => {
3239 id => "fatal",
3240 title => "Fatal Error",
3241 reply => undef,
3242 tooltip => "Reason for the server disconnect",
3243 },
3108 "c/say" => $SAY_CHANNEL, 3244 "c/say" => $SAY_CHANNEL,
3109 "c/chat" => $CHAT_CHANNEL, 3245 "c/chat" => $CHAT_CHANNEL,
3110); 3246);
3111 3247
3112sub cf::client::send_msg { 3248sub cf::client::send_msg {
3155=cut 3291=cut
3156 3292
3157sub cf::client::ext_msg($$@) { 3293sub cf::client::ext_msg($$@) {
3158 my ($self, $type, @msg) = @_; 3294 my ($self, $type, @msg) = @_;
3159 3295
3160 if ($self->extcmd == 2) {
3161 $self->send_big_packet ("ext " . $self->{json_coder}->encode ([$type, @msg])); 3296 $self->send_big_packet ("ext " . $self->{json_coder}->encode ([$type, @msg]));
3162 } elsif ($self->extcmd == 1) { # TODO: remove
3163 push @msg, msgtype => "event_$type";
3164 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
3165 }
3166}
3167
3168=item $client->ext_reply ($msgid, @msg)
3169
3170Sends an ext reply to the client.
3171
3172=cut
3173
3174sub cf::client::ext_reply($$@) {
3175 my ($self, $id, @msg) = @_;
3176
3177 if ($self->extcmd == 2) {
3178 $self->send_big_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg]));
3179 } elsif ($self->extcmd == 1) {
3180 #TODO: version 1, remove
3181 unshift @msg, msgtype => "reply", msgid => $id;
3182 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
3183 }
3184} 3297}
3185 3298
3186=item $success = $client->query ($flags, "text", \&cb) 3299=item $success = $client->query ($flags, "text", \&cb)
3187 3300
3188Queues a query to the client, calling the given callback with 3301Queues a query to the client, calling the given callback with
3208 3321
3209 $self->send_packet ($self->{query_queue}[0][0]) 3322 $self->send_packet ($self->{query_queue}[0][0])
3210 if @{ $self->{query_queue} } == 1; 3323 if @{ $self->{query_queue} } == 1;
3211 3324
3212 1 3325 1
3326}
3327
3328=item $client->update_command_faces
3329
3330=cut
3331
3332our %COMMAND_FACE;
3333
3334sub cf::client::update_command_faces {
3335 my ($self) = @_;
3336
3337 my @faces = grep $_,
3338 $COMMAND_FACE{preferred},
3339 $COMMAND_FACE{standard},
3340 $COMMAND_FACE{skill},
3341 $self->pl->ob->flag (cf::FLAG_WIZ) ? $COMMAND_FACE{dm} : (),
3342 $COMMAND_FACE{emote},
3343 ;
3344
3345 $self->send_face ($_)
3346 for @faces;
3347 $self->flush_fx;
3348
3349 $self->ext_msg (command_list => @faces);
3350}
3351
3352=item cf::client::set_command_face $type, $commands
3353
3354=cut
3355
3356sub cf::client::set_command_face {
3357 my ($type, $list) = @_;
3358
3359 my $idx = &cf::face::set ( #d# ugly forward reference
3360 "command_list/$type" => cf::FT_RSRC,
3361 JSON::XS->new->utf8->encode ([ sort @$list ])
3362 );
3363
3364 $COMMAND_FACE{$type} = $idx;
3213} 3365}
3214 3366
3215cf::client->attach ( 3367cf::client->attach (
3216 on_connect => sub { 3368 on_connect => sub {
3217 my ($ns) = @_; 3369 my ($ns) = @_;
3243 my ($ns, $buf) = @_; 3395 my ($ns, $buf) = @_;
3244 3396
3245 my $msg = eval { $ns->{json_coder}->decode ($buf) }; 3397 my $msg = eval { $ns->{json_coder}->decode ($buf) };
3246 3398
3247 if (ref $msg) { 3399 if (ref $msg) {
3248 my ($type, $reply, @payload) = 3400 my ($type, $reply, @payload) = @$msg; # version 1 used %type, $id, %$hash
3249 "ARRAY" eq ref $msg
3250 ? @$msg
3251 : ($msg->{msgtype}, $msg->{msgid}, %$msg); # TODO: version 1, remove
3252 3401
3253 my @reply;
3254
3255 if (my $cb = $EXTICMD{$type}) { 3402 if (my $cb = $EXTIACMD{$type}) {
3403 $cb->(
3404 $ns,
3405 sub {
3406 $ns->ext_msg ("reply-$reply", @_)
3407 if $reply;
3408 },
3409 @payload
3410 );
3411 } else {
3412 my @reply;
3413
3414 if (my $cb = $EXTICMD{$type}) {
3256 @reply = $cb->($ns, @payload); 3415 @reply = $cb->($ns, @payload);
3416 }
3417
3418 $ns->ext_msg ("reply-$reply", @reply)
3419 if $reply;
3257 } 3420 }
3258
3259 $ns->ext_reply ($reply, @reply)
3260 if $reply;
3261
3262 } else { 3421 } else {
3263 error "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n"; 3422 error "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n";
3264 } 3423 }
3265 3424
3266 cf::override; 3425 cf::override;
3434=cut 3593=cut
3435 3594
3436############################################################################# 3595#############################################################################
3437# the server's init and main functions 3596# the server's init and main functions
3438 3597
3598{
3599 package cf::face;
3600
3601 our %HASH; # hash => idx
3602 our @DATA; # dynamically-created facedata, only faceste 0 used
3603 our @FOFS; # file offset, if > 0
3604 our @SIZE; # size of face, in octets
3605 our @META; # meta hash of face, if any
3606 our $DATAFH; # facedata filehandle
3607
3608 # internal api, not finalised
3609 sub set {
3610 my ($name, $type, $data) = @_;
3611
3612 my $idx = cf::face::find $name;
3613
3614 if ($idx) {
3615 delete $HASH{cf::face::get_csum $idx};
3616 } else {
3617 $idx = cf::face::alloc $name;
3618 }
3619
3620 my $hash = cf::face::mangle_csum Digest::MD5::md5 $data;
3621
3622 cf::face::set_type $idx, $type;
3623 cf::face::set_csum $idx, 0, $hash;
3624
3625 # we need to destroy the SV itself, not just modify it, as a running ix
3626 # might hold a reference to it: "delete" achieves that.
3627 delete $FOFS[0][$idx];
3628 delete $DATA[0][$idx];
3629 $DATA[0][$idx] = $data;
3630 $SIZE[0][$idx] = length $data;
3631 delete $META[$idx];
3632 $HASH{$hash} = $idx;#d#
3633
3634 $idx
3635 }
3636
3637 sub _get_data($$$) {
3638 my ($idx, $set, $cb) = @_;
3639
3640 if (defined $DATA[$set][$idx]) {
3641 $cb->($DATA[$set][$idx]);
3642 } elsif (my $fofs = $FOFS[$set][$idx]) {
3643 my $size = $SIZE[$set][$idx];
3644 my $buf;
3645 IO::AIO::aio_read $DATAFH, $fofs, $size, $buf, 0, sub {
3646 if ($_[0] == $size) {
3647 #cf::debug "read face $idx, $size from $fofs as ", length $buf;#d#
3648 $cb->($buf);
3649 } else {
3650 cf::error "INTERNAL ERROR: unable to read facedata for face $idx#$set ($size, $fofs), ignoring request.";
3651 }
3652 };
3653 } else {
3654 cf::error "requested facedata for unknown face $idx#$set, ignoring.";
3655 }
3656 }
3657
3658 # rather ineffient
3659 sub cf::face::get_data($;$) {
3660 my ($idx, $set) = @_;
3661
3662 _get_data $idx, $set, Coro::rouse_cb;
3663 Coro::rouse_wait
3664 }
3665
3666 sub cf::face::ix {
3667 my ($ns, $set, $idx, $pri) = @_;
3668
3669 _get_data $idx, $set, sub {
3670 $ns->ix_send ($idx, $pri, $_[0]);
3671 };
3672 }
3673}
3674
3439sub load_facedata($) { 3675sub load_facedata($) {
3440 my ($path) = @_; 3676 my ($path) = @_;
3441 3677
3442 # HACK to clear player env face cache, we need some signal framework
3443 # for this (global event?)
3444 %ext::player_env::MUSIC_FACE_CACHE = ();
3445
3446 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3678 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3447 3679
3448 trace "loading facedata from $path\n"; 3680 trace "loading facedata from $path\n";
3449 3681
3450 my $facedata = decode_storable load_file $path; 3682 my $facedata = decode_storable load_file "$path/faceinfo";
3451 3683
3452 $facedata->{version} == 2 3684 $facedata->{version} == 2
3453 or cf::cleanup "$path: version mismatch, cannot proceed."; 3685 or cf::cleanup "$path/faceinfo: version mismatch, cannot proceed.";
3454 3686
3455 # patch in the exptable 3687 my $fh = aio_open "$DATADIR/facedata", IO::AIO::O_RDONLY, 0
3456 my $exp_table = $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]); 3688 or cf::cleanup "$path/facedata: $!, cannot proceed.";
3457 $facedata->{resource}{"res/exp_table"} = { 3689
3458 type => FT_RSRC, 3690 get_slot 1, -100, "load_facedata"; # make sure we get a very big slot
3459 data => $exp_table, 3691
3460 hash => (Digest::MD5::md5 $exp_table), 3692 # BEGIN ATOMIC
3461 }; 3693 # from here on, everything must be atomic - no thread switch allowed
3462 cf::cede_to_tick; 3694 my $t1 = EV::time;
3463 3695
3464 { 3696 {
3465 my $faces = $facedata->{faceinfo}; 3697 my $faces = $facedata->{faceinfo};
3466 3698
3467 while (my ($face, $info) = each %$faces) { 3699 for my $face (sort keys %$faces) {
3700 my $info = $faces->{$face};
3468 my $idx = (cf::face::find $face) || cf::face::alloc $face; 3701 my $idx = (cf::face::find $face) || cf::face::alloc $face;
3469 3702
3470 cf::face::set_visibility $idx, $info->{visibility}; 3703 cf::face::set_visibility $idx, $info->{visibility};
3471 cf::face::set_magicmap $idx, $info->{magicmap}; 3704 cf::face::set_magicmap $idx, $info->{magicmap};
3472 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32}; 3705 cf::face::set_csum $idx, 0, $info->{hash64}; $cf::face::SIZE[0][$idx] = $info->{size64}; $cf::face::FOFS[0][$idx] = $info->{fofs64};
3473 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64}; 3706 cf::face::set_csum $idx, 1, $info->{hash32}; $cf::face::SIZE[1][$idx] = $info->{size32}; $cf::face::FOFS[1][$idx] = $info->{fofs32};
3474 cf::face::set_data $idx, 2, $info->{glyph} , $info->{glyph} ; 3707 cf::face::set_csum $idx, 2, $info->{glyph}; $cf::face::DATA[2][$idx] = $info->{glyph};
3475 3708 $cf::face::HASH{$info->{hash64}} = $idx;
3476 cf::cede_to_tick; 3709 delete $cf::face::META[$idx];
3477 } 3710 }
3478 3711
3479 while (my ($face, $info) = each %$faces) { 3712 while (my ($face, $info) = each %$faces) {
3480 next unless $info->{smooth}; 3713 next unless $info->{smooth};
3481 3714
3486 cf::face::set_smooth $idx, $smooth; 3719 cf::face::set_smooth $idx, $smooth;
3487 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3720 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3488 } else { 3721 } else {
3489 error "smooth face '$info->{smooth}' not found for face '$face'"; 3722 error "smooth face '$info->{smooth}' not found for face '$face'";
3490 } 3723 }
3491
3492 cf::cede_to_tick;
3493 } 3724 }
3494 } 3725 }
3495 3726
3496 { 3727 {
3497 my $anims = $facedata->{animinfo}; 3728 my $anims = $facedata->{animinfo};
3498 3729
3499 while (my ($anim, $info) = each %$anims) { 3730 while (my ($anim, $info) = each %$anims) {
3500 cf::anim::set $anim, $info->{frames}, $info->{facings}; 3731 cf::anim::set $anim, $info->{frames}, $info->{facings};
3501 cf::cede_to_tick;
3502 } 3732 }
3503 3733
3504 cf::anim::invalidate_all; # d'oh 3734 cf::anim::invalidate_all; # d'oh
3505 } 3735 }
3506 3736
3507 { 3737 {
3508 my $res = $facedata->{resource}; 3738 my $res = $facedata->{resource};
3509 3739
3510 while (my ($name, $info) = each %$res) { 3740 while (my ($name, $info) = each %$res) {
3511 if (defined $info->{type}) { 3741 if (defined (my $type = $info->{type})) {
3742 # TODO: different hash - must free and use new index, or cache ixface data queue
3512 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3743 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3513 3744
3514 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3515 cf::face::set_type $idx, $info->{type}; 3745 cf::face::set_type $idx, $type;
3746 cf::face::set_csum $idx, 0, $info->{hash};
3747 $cf::face::SIZE[0][$idx] = $info->{size};
3748 $cf::face::FOFS[0][$idx] = $info->{fofs};
3749 $cf::face::META[$idx] = $type & 1 ? undef : $info->{meta}; # preserve meta unless prepended already
3750 $cf::face::HASH{$info->{hash}} = $idx;
3516 } else { 3751 } else {
3517 $RESOURCE{$name} = $info; # unused 3752# $RESOURCE{$name} = $info; # unused
3518 } 3753 }
3519
3520 cf::cede_to_tick;
3521 } 3754 }
3522 } 3755 }
3756
3757 ($fh, $cf::face::DATAFH) = ($cf::face::DATAFH, $fh);
3758
3759 # HACK to clear player env face cache, we need some signal framework
3760 # for this (global event?)
3761 %ext::player_env::MUSIC_FACE_CACHE = ();
3762
3763 # END ATOMIC
3764
3765 cf::debug "facedata atomic update time ", EV::time - $t1;
3523 3766
3524 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3767 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3768
3769 aio_close $fh if $fh; # close old facedata
3525 3770
3526 1 3771 1
3527} 3772}
3528 3773
3529register_exticmd fx_want => sub { 3774register_exticmd fx_want => sub {
3540 my $status = load_resource_file_ $_[0]; 3785 my $status = load_resource_file_ $_[0];
3541 get_slot 0.1, 100; 3786 get_slot 0.1, 100;
3542 cf::arch::commit_load; 3787 cf::arch::commit_load;
3543 3788
3544 $status 3789 $status
3790}
3791
3792sub reload_exp_table {
3793 _reload_exp_table;
3794
3795 cf::face::set
3796 "res/exp_table" => FT_RSRC,
3797 JSON::XS->new->utf8->canonical->encode (
3798 [map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]
3799 );
3800}
3801
3802sub reload_materials {
3803 _reload_materials;
3545} 3804}
3546 3805
3547sub reload_regions { 3806sub reload_regions {
3548 # HACK to clear player env face cache, we need some signal framework 3807 # HACK to clear player env face cache, we need some signal framework
3549 # for this (global event?) 3808 # for this (global event?)
3557 if exists $_->{match}; 3816 if exists $_->{match};
3558 } 3817 }
3559} 3818}
3560 3819
3561sub reload_facedata { 3820sub reload_facedata {
3562 load_facedata "$DATADIR/facedata" 3821 load_facedata $DATADIR
3563 or die "unable to load facedata\n"; 3822 or die "unable to load facedata\n";
3564} 3823}
3565 3824
3566sub reload_archetypes { 3825sub reload_archetypes {
3567 load_resource_file "$DATADIR/archetypes" 3826 load_resource_file "$DATADIR/archetypes"
3568 or die "unable to load archetypes\n"; 3827 or die "unable to load archetypes\n";
3828
3829 cf::face::set
3830 "res/skill_info" => FT_RSRC,
3831 JSON::XS->new->utf8->canonical->encode (
3832 [map [cf::arch::skillvec ($_)->name], 0 .. cf::arch::skillvec_size - 1]
3833 );
3834
3835 cf::face::set
3836 "res/spell_paths" => FT_RSRC,
3837 JSON::XS->new->utf8->canonical->encode (
3838 [map [cf::spellpathnames ($_)], 0 .. NRSPELLPATHS - 1]
3839 );
3840
3841 # command completion
3842 my @commands;
3843
3844 for (0..cf::arch::skillvec_size - 1) {
3845 my $skill = cf::arch::skillvec $_;
3846 my $name = $skill->name;
3847 my $flags = cf::skill_flags $skill->subtype;
3848
3849 push @commands, "ready_skill $name" if $flags & (SF_COMBAT | SF_RANGED | SF_GRACE);
3850 push @commands, "use_skill $name" if $flags & (SF_USE | SF_AUTARK | SF_GRACE);
3851 }
3852
3853 cf::client::set_command_face skill => \@commands;
3569} 3854}
3570 3855
3571sub reload_treasures { 3856sub reload_treasures {
3572 load_resource_file "$DATADIR/treasures" 3857 load_resource_file "$DATADIR/treasures"
3573 or die "unable to load treasurelists\n"; 3858 or die "unable to load treasurelists\n";
3594} 3879}
3595 3880
3596sub reload_resources { 3881sub reload_resources {
3597 trace "reloading resource files...\n"; 3882 trace "reloading resource files...\n";
3598 3883
3599 reload_exp_table;
3600 reload_materials; 3884 reload_materials;
3601 reload_facedata; 3885 reload_facedata;
3886 reload_exp_table;
3602 reload_sound; 3887 reload_sound;
3603 reload_archetypes; 3888 reload_archetypes;
3604 reload_regions; 3889 reload_regions;
3605 reload_treasures; 3890 reload_treasures;
3606 3891
3646 seek $fh, 0, 0; 3931 seek $fh, 0, 0;
3647 print $fh $$; 3932 print $fh $$;
3648} 3933}
3649 3934
3650sub main_loop { 3935sub main_loop {
3651 trace "EV::loop starting\n"; 3936 trace "EV::run starting\n";
3652 if (1) { 3937 if (1) {
3653 EV::loop; 3938 EV::run;
3654 } 3939 }
3655 trace "EV::loop returned\n"; 3940 trace "EV::run returned\n";
3656 goto &main_loop unless $REALLY_UNLOOP; 3941 goto &main_loop unless $REALLY_UNLOOP;
3657} 3942}
3658 3943
3659sub main { 3944sub main {
3660 cf::init_globals; # initialise logging 3945 cf::init_globals; # initialise logging
3661 3946
3662 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3947 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3948 LOG llevInfo, "Copyright (C) 2017-2018 Marc Alexander Lehmann / the Deliantra team.";
3663 LOG llevInfo, "Copyright (C) 2005-2011 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3949 LOG llevInfo, "Copyright (C) 2005-2016 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3664 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3950 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3665 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3951 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3666 3952
3667 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3953 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3668 3954
3669 # we must not ever block the main coroutine 3955 # we must not ever block the main coroutine
3670 local $Coro::idle = sub { 3956 $Coro::idle = sub {
3671 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d# 3957 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d#
3672 (async { 3958 (async {
3673 $Coro::current->{desc} = "IDLE BUG HANDLER"; 3959 $Coro::current->{desc} = "IDLE BUG HANDLER";
3674 EV::loop EV::LOOP_ONESHOT; 3960 EV::run EV::RUN_ONCE;
3675 })->prio (Coro::PRIO_MAX); 3961 })->prio (Coro::PRIO_MAX);
3676 }; 3962 };
3677 3963
3678 evthread_start IO::AIO::poll_fileno; 3964 evthread_start IO::AIO::poll_fileno;
3679 3965
3680 cf::sync_job { 3966 cf::sync_job {
3681 cf::incloader::init (); 3967 cf::incloader::init ();
3968
3969 db_init;
3682 3970
3683 cf::init_anim; 3971 cf::init_anim;
3684 cf::init_attackmess; 3972 cf::init_attackmess;
3685 cf::init_dynamic; 3973 cf::init_dynamic;
3686 3974
3687 cf::load_settings; 3975 cf::load_settings;
3688 3976
3689 reload_resources; 3977 reload_resources;
3690 reload_config; 3978 reload_config;
3691 db_init;
3692 3979
3693 cf::init_uuid; 3980 cf::init_uuid;
3694 cf::init_signals; 3981 cf::init_signals;
3695 cf::init_skills; 3982 cf::init_skills;
3696 3983
3710 }; 3997 };
3711 3998
3712 cf::object::thawer::errors_are_fatal 0; 3999 cf::object::thawer::errors_are_fatal 0;
3713 info "parse errors in files are no longer fatal from this point on.\n"; 4000 info "parse errors in files are no longer fatal from this point on.\n";
3714 4001
3715 my $free_main; $free_main = EV::idle sub { 4002 AE::postpone {
3716 undef $free_main;
3717 undef &main; # free gobs of memory :) 4003 undef &main; # free gobs of memory :)
3718 }; 4004 };
3719 4005
3720 goto &main_loop; 4006 goto &main_loop;
3721} 4007}
3878 4164
3879 cf::write_runtime_sync; # external watchdog should not bark 4165 cf::write_runtime_sync; # external watchdog should not bark
3880 4166
3881 trace "emergency_perl_save: flushing outstanding aio requests"; 4167 trace "emergency_perl_save: flushing outstanding aio requests";
3882 while (IO::AIO::nreqs || BDB::nreqs) { 4168 while (IO::AIO::nreqs || BDB::nreqs) {
3883 Coro::EV::timer_once 0.01; # let the sync_job do it's thing 4169 Coro::AnyEvent::sleep 0.01; # let the sync_job do it's thing
3884 } 4170 }
3885 4171
3886 cf::write_runtime_sync; # external watchdog should not bark 4172 cf::write_runtime_sync; # external watchdog should not bark
3887 }; 4173 };
3888 4174
4069 4355
4070############################################################################# 4356#############################################################################
4071 4357
4072my $bug_warning = 0; 4358my $bug_warning = 0;
4073 4359
4074our @WAIT_FOR_TICK;
4075our @WAIT_FOR_TICK_BEGIN;
4076
4077sub wait_for_tick() { 4360sub wait_for_tick() {
4078 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4361 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
4079 4362
4080 my $signal = new Coro::Signal; 4363 $WAIT_FOR_TICK->wait;
4081 push @WAIT_FOR_TICK, $signal;
4082 $signal->wait;
4083} 4364}
4084 4365
4085sub wait_for_tick_begin() { 4366sub wait_for_tick_begin() {
4086 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4367 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
4087 4368
4088 my $signal = new Coro::Signal; 4369 my $signal = new Coro::Signal;
4089 push @WAIT_FOR_TICK_BEGIN, $signal; 4370 push @WAIT_FOR_TICK_BEGIN, $signal;
4090 $signal->wait; 4371 $signal->wait;
4091} 4372}
4095 Carp::cluck "major BUG: server tick called outside of main coro, skipping it" 4376 Carp::cluck "major BUG: server tick called outside of main coro, skipping it"
4096 unless ++$bug_warning > 10; 4377 unless ++$bug_warning > 10;
4097 return; 4378 return;
4098 } 4379 }
4099 4380
4100 cf::server_tick; # one server iteration 4381 cf::one_tick; # one server iteration
4101 4382
4102 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d# 4383 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d#
4103 4384
4104 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4385 if ($NOW >= $NEXT_RUNTIME_WRITE) {
4105 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 4386 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
4111 } 4392 }
4112 4393
4113 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4394 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
4114 $sig->send; 4395 $sig->send;
4115 } 4396 }
4116 while (my $sig = shift @WAIT_FOR_TICK) { 4397 $WAIT_FOR_TICK->broadcast;
4117 $sig->send;
4118 }
4119 4398
4120 $LOAD = ($NOW - $TICK_START) / $TICK; 4399 $LOAD = ($NOW - $TICK_START) / $TICK;
4121 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25; 4400 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25;
4122 4401
4123 if (0) { 4402 if (0) {
4129 } 4408 }
4130} 4409}
4131 4410
4132{ 4411{
4133 # configure BDB 4412 # configure BDB
4413 info "initialising database";
4134 4414
4135 BDB::min_parallel 16; 4415 BDB::min_parallel 16;
4136 BDB::max_poll_reqs $TICK * 0.1; 4416 BDB::max_poll_reqs $TICK * 0.1;
4137 $AnyEvent::BDB::WATCHER->priority (1); 4417 #$AnyEvent::BDB::WATCHER->priority (1);
4138 4418
4139 unless ($DB_ENV) { 4419 unless ($DB_ENV) {
4140 $DB_ENV = BDB::db_env_create; 4420 $DB_ENV = BDB::db_env_create;
4141 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT); 4421 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT);
4142 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7; 4422 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7;
4167 BDB::db_env_txn_checkpoint $DB_ENV, 0, 0, 0, sub { }; 4447 BDB::db_env_txn_checkpoint $DB_ENV, 0, 0, 0, sub { };
4168 }; 4448 };
4169 $BDB_TRICKLE_WATCHER = EV::periodic 0, 10, 0, sub { 4449 $BDB_TRICKLE_WATCHER = EV::periodic 0, 10, 0, sub {
4170 BDB::db_env_memp_trickle $DB_ENV, 20, 0, sub { }; 4450 BDB::db_env_memp_trickle $DB_ENV, 20, 0, sub { };
4171 }; 4451 };
4452
4453 info "database initialised";
4172} 4454}
4173 4455
4174{ 4456{
4175 # configure IO::AIO 4457 # configure IO::AIO
4176 4458
4459 info "initialising aio";
4177 IO::AIO::min_parallel 8; 4460 IO::AIO::min_parallel 8;
4178 IO::AIO::max_poll_time $TICK * 0.1; 4461 IO::AIO::max_poll_time $TICK * 0.1;
4179 undef $AnyEvent::AIO::WATCHER; 4462 undef $AnyEvent::AIO::WATCHER;
4463 info "aio initialised";
4180} 4464}
4181 4465
4182our $_log_backtrace; 4466our $_log_backtrace;
4183our $_log_backtrace_last; 4467our $_log_backtrace_last;
4184 4468

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines