summaryrefslogtreecommitdiff
path: root/src/changes/main.c
blob: b5e4ffe1ef9ac2d9d79008cfafd975ea32c8f46c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/**

Copyright (c) Scott Gasch

Module Name:

    main.c

Abstract:

    Program entry point and setup code.

Author:

    Scott Gasch ([email protected]) 8 Apr 2004

Revision History:

    $Id: main.c 351 2008-06-28 04:21:53Z scott $

**/

#include "chess.h"

FILE *g_pfLogfile = NULL;
GAME_OPTIONS g_Options;
CHAR g_szInitialCommand[SMALL_STRING_LEN_CHAR];
ULONG g_uInputThreadHandle = (ULONG)-1;

void
Banner(void)
/**

Routine description:

    Describe the compile/build options and program version.

Parameters:

    void

Return value:

    void

**/
{
    char *p;

    Trace("Typhoon %s (built on %s %s):\n", VERSION, __DATE__, __TIME__);
    Trace("    Copyright (C) 2000-2007, Scott Gasch ([email protected])\n");
    Trace("    " REVISION);
    Trace("    " COMPILER_STRING);
    Trace("    Make profile used: %s\n", PROFILE);
#ifdef MP
    Trace("    Multiprocessor enabled; %u searcher thread%s\n",
          g_Options.uNumProcessors, (g_Options.uNumProcessors > 1) ? "s" : "");
#else
    Trace("    Single processor version\n");
#endif
#ifdef DEBUG
    Trace("    DEBUG build\n");
#endif
#ifdef TEST
    Trace("    Testcode compiled in\n");
#endif
#ifdef EVAL_DUMP
    Trace("    Evaluation terms\n");
#endif
#ifdef EVAL_TIME
    Trace("    Evaluation timing\n");
#endif
#ifdef PERF_COUNTERS
    Trace("    Performance counters\n");
#ifdef TEST_NULL
    Trace("    Testing nullmove prediction algorithms\n");
#endif
#endif
#ifdef DUMP_TREE
    Trace("    Search tree dumpfile generation enabled\n");
#endif
    Trace("    Hash sizes: %u Mb (main), %u Mb / thread (pawn), %u Mb / thread (eval)\n", 
          (g_uHashTableSizeEntries * sizeof(HASH_ENTRY)) / MB,
          PAWN_HASH_TABLE_SIZE * sizeof(PAWN_HASH_ENTRY) / MB,
          EVAL_HASH_TABLE_SIZE * sizeof(EVAL_HASH_ENTRY) / MB);
    Trace("    QCheckPlies: %u\n", QPLIES_OF_NON_CAPTURE_CHECKS);
    Trace("    FutilityBase: %u\n", FUTILITY_BASE_MARGIN);
    p = ExportEvalDNA();
    Trace("    Logging Eval DNA.\n");
    Log(p);
    free(p);
#ifdef DO_IID
    Trace("    IID R-factor: %u ply\n", IID_R_FACTOR / ONE_PLY);
#endif
}


void
EndLogging(void)
/**

Routine description:

    Close the main logfile.

Parameters:

    void

Return value:

    void

**/
{
    if (NULL != g_pfLogfile)
    {
        fflush(g_pfLogfile);
        fflush(stdout);
        fclose(g_pfLogfile);
        g_pfLogfile = NULL;
    }
}


FLAG
BeginLogging(void)
/**

Routine description:

    Open the main logfile.

Parameters:

    void

Return value:

    FLAG

**/
{
    if (NULL != g_pfLogfile)
    {
        EndLogging();
    }
    ASSERT(g_pfLogfile == NULL);
    ASSERT(strlen(g_Options.szLogfile));

    //
    // If the logfile we want to write already exists, back it up.
    //
    if (TRUE == SystemDoesFileExist(g_Options.szLogfile))
    {
        VERIFY(BackupFile(g_Options.szLogfile));
    }
    ASSERT(FALSE == SystemDoesFileExist(g_Options.szLogfile));

    g_pfLogfile = fopen(g_Options.szLogfile, "wb+");
    if (NULL == g_pfLogfile)
    {
        UtilPanic(INITIALIZATION_FAILURE,
                  (void *)"Can't open logfile", 
                  (void *)&(g_Options.szLogfile), 
                  (void *)"write", 
                  NULL,
                  __FILE__, __LINE__);
    }
    return(TRUE);
}


FLAG
PreGameReset(FLAG fResetBoard)
/**

Routine description:

    Reset internal state between games.

Parameters:

    void

Return value:

    FLAG

**/
{
    if (TRUE == fResetBoard)
    {
        SetRootToInitialPosition();
    }
    SetMyName();
    ClearDynamicMoveOrdering();
    ClearHashTable();
    ResetOpeningBook();
    return(TRUE);
}


static ULONG
_ParseHashOption(char *p,
                 ULONG uEntrySize)
{
    ULONG u, v;
    CHAR c;

    if ((!STRCMPI(p, "none")) || (!STRCMPI(p, "no"))) return(0);
    if (2 == sscanf(p, "%u%1c", &u, &c))
    {
        v = u;
        switch(c)
        {
            case 'K':
            case 'k':
                u *= 1024;
                break;
            case 'M':
            case 'm':
                u *= 1024 * 1024;
                break;
            case 'G':
            case 'g':
                u *= 1024 * 1024 * 1024;
                break;
            default:
                Trace("Error (unrecognized size): \"%s\"\n", p);
                break;
        }
        if (u < v)
        {
            Trace("Error (size too large): \"%s\"\n", p);
            u = v;
        }
        u /= uEntrySize;
    }
    else
    {
        u = (ULONG)atoi(p);
    }

    while(!IS_A_POWER_OF_2(u))
    {
        u &= (u - 1);
    }
    return(u);
}



void
InitializeOptions(int argc, char *argv[])
/**

Routine description:

    Set global options to their initial state.  This code also is
    responsible for parsing the commandline in order to override the
    default state of global options.

Parameters:

    int argc,
    char *argv[]

Return value:

    void

**/
{
    int i;

    //
    // Defaults
    //
    memset(&g_Options, 0, sizeof(g_Options));
    g_szInitialCommand[0] = '\0';
    g_Options.uMyClock = g_Options.uOpponentsClock = 600;
    g_Options.fGameIsRated = FALSE;
    g_Options.fOpponentIsComputer = FALSE;
    g_Options.uSecPerMove = 0;
    g_Options.uMaxDepth = MAX_PLY_PER_SEARCH - 1;
    g_Options.fShouldPonder = TRUE;
    g_Options.fPondering = g_Options.fThinking = FALSE;
    g_Options.mvPonder.uMove = 0;
    g_Options.fShouldPost = TRUE;
    g_Options.fForceDrawWorthZero = FALSE;
    g_Options.uMyIncrement = 0;
    g_Options.uMovesPerTimePeriod = 0;
    g_Options.szAnalyzeProgressReport[0] = '\0';
    g_Options.fShouldAnnounceOpening = TRUE;
    g_Options.eClock = CLOCK_NONE;
    g_Options.eGameType = GAME_UNKNOWN;
    g_Options.ePlayMode = FORCE_MODE;
    g_Options.fNoInputThread = FALSE;
    g_Options.fVerbosePosting = TRUE;
    strcpy(g_Options.szEGTBPath, "/egtb/three;/etc/four;/egtb/five");
    strcpy(g_Options.szLogfile, "typhoon.log");
    strcpy(g_Options.szBookName, "book.bin");
    g_Options.uNumHashTableEntries = 0x10000;
    g_Options.uNumProcessors = 1;
    g_Options.fStatusLine = TRUE;
    g_Options.fShouldResign = FALSE;
    g_Options.u64MaxNodeCount = 0ULL;

    i = 1;
    while(i < argc)
    {
#ifdef MP
        if ((!STRCMPI(argv[i], "--cpus")) && (argc > i))
        {
            g_Options.uNumProcessors = (ULONG)atoi(argv[i+1]);
            if ((g_Options.uNumProcessors == 0) ||
                (g_Options.uNumProcessors > 64))
            {
                g_Options.uNumProcessors = 2;
            }
            i++;
        }
        else
#endif
        if ((!STRCMPI(argv[i], "--command")) && (argc > i))
        {
            strncpy(g_szInitialCommand,
                    argv[i+1],
                    SMALL_STRING_LEN_CHAR - 2);
            strcat(g_szInitialCommand, "\r\n");
            i++;
        }
        else if ((!STRCMPI(argv[i], "--hash")) && (argc > i))
        {
            g_Options.uNumHashTableEntries =
                _ParseHashOption(argv[i+1],
                                 sizeof(HASH_ENTRY));
            i++;
        }
        else if ((!STRCMPI(argv[i], "--egtbpath")) && (argc > i))
        {
            g_Options.szEGTBPath[0] = '\0';
            strncpy(g_Options.szEGTBPath, argv[i+1], SMALL_STRING_LEN_CHAR);
            i++;
        }
        else if (!STRCMPI(argv[i], "--batch"))
        {
            g_Options.fNoInputThread = TRUE;
        }
        else if ((!STRCMPI(argv[i], "--dnafile")) && (argc > i)) 
        {
            if (!ReadEvalDNA(argv[i+1])) 
            {
                UtilPanic(INITIALIZATION_FAILURE,
                          (void *)"Bad DNA file",
                          (void *)&(argv[i+1]),
                          (void *)"read",
                          NULL,
                          __FILE__, __LINE__);
            }
            i++;
        }
        else if ((!STRCMPI(argv[i], "--logfile")) && (argc > i)) 
        {
            strncpy(g_Options.szLogfile, argv[i+1],
                    SMALL_STRING_LEN_CHAR);
            i++;
        }
        else if (!STRCMPI(argv[i], "--help")) {
            Trace("Usage: %s [--batch] [--command arg] [--logfile arg] [--egtbpath arg]\n"
                  "                [--dnafile arg] [--cpus arg] [--hash arg]\n\n"
                  "    --batch    : operate the engine without an input thread\n"
                  "    --command  : specify initial command(s) (requires arg)\n"
                  "    --cpus     : indicate the number of cpus to use (requires arg, MP build)\n"
                  "    --hash     : indicate desired hash size (requires arg)\n"
                  "    --egtbpath : supplies the egtb path to engine (requires arg)\n"
                  "    --logfile  : indicate desired output logfile name (requires arg)\n"
                  "    --dnafile  : indicate desired eval profile input (requres arg)\n\n"
                  "Example: %s --hash 256m --cpus 2\n"
                  "         %s --logfile test.out --batch --command \"test\" --dnafile test.in\n", argv[0], argv[0], argv[0]);
            exit(-1);
        }
        else
        {
            Trace("Error (unknown argument): \"%s\"; try --help\n", argv[i]);
        }

        //
        // TODO: parse other commandline options and override above
        //

        i++;
    }
}


void
CleanupOptions(void)
/**

Routine description:

    Cleanup options...

Parameters:

    void

Return value:

    void

**/
{
    NOTHING;
}


FLAG
MainProgramInitialization(int argc, char *argv[])
/**

Routine description:

    Perform main program initialization.  This includes stuff like:
    precomputing some data structures, resetting the global options,
    parsing the commandline to override said options, and calling out
    to other modules to tell them to initialize themselves.

Parameters:

    int argc,
    char *argv[]

Return value:

    FLAG

**/
{
    srand((unsigned int)time(0));
    InitializeOptions(argc, argv);
    InitializeTreeDump();
    InitializeEGTB();
    InitializeSigSystem();
    InitializeInteriorNodeRecognizers();
    InitializeSearchDepthArray();
    InitializeWhiteSquaresTable();
    InitializeVectorDeltaTable();
    InitializeSwapTable();
    InitializeDistanceTable();
    InitializeOpeningBook();
    InitializeDynamicMoveOrdering();
    InitializeHashSystem();
    InitializePositionHashSystem();
#ifdef MP
    InitializeParallelSearch();
#endif
    VERIFY(PreGameReset(TRUE));
    return(BeginLogging());
}


FLAG
MainProgramCleanup(void)
/**

Routine description:

    Perform main program cleanup.  Tear down the stuff we set up in
    MainProgramInitialization.

Parameters:

    void

Return value:

    FLAG

**/
{
    CleanupOpeningBook();
    CleanupEGTB();
    CleanupDynamicMoveOrdering();
#ifdef MP
    CleanupParallelSearch();
#endif
    CleanupPositionHashSystem();
    CleanupHashSystem();
    CleanupTreeDump();
    CleanupOptions();
    EndLogging();
    return(TRUE);
}


#ifdef TEST
FLAG
RunStartupProgramTest(void)
/**

Routine description:

    If we built this version with -DTEST then this code is the start
    of the self-test that runs at program startup time.

Parameters:

    void

Return value:

    FLAG

**/
{
    ULONG u, x, y;

#ifdef _X86_
    Trace("Testing CPP macros...\n");
    for (u = 0; u < 1000000; u++)
    {
        x = rand() * rand();
        y = rand() * rand();
        x = x & ~(0x80000000);
        y = y & ~(0x80000000);

        if (MAX(x, y) != MAXU(x, y))
        {
            UtilPanic(TESTCASE_FAILURE,
                      NULL, "max maxu", NULL, NULL, __FILE__, __LINE__);
        }

        if (MAXU(x, y) != MAXU(y, x))
        {
            UtilPanic(TESTCASE_FAILURE,
                      NULL, "maxu assoc", NULL, NULL, __FILE__, __LINE__);
        }

        if (MIN(x, y) != MINU(x, y))
        {
            UtilPanic(TESTCASE_FAILURE,
                      NULL, "min minu", NULL, NULL, __FILE__, __LINE__);
        }

        if (MINU(x, y) != MINU(y, x))
        {
            UtilPanic(TESTCASE_FAILURE,
                      NULL, "minu assoc", NULL, NULL, __FILE__, __LINE__);
        }

        if (abs(x - y) != ABS_DIFF(x, y))
        {
            UtilPanic(TESTCASE_FAILURE,
                      NULL, "abs_diff", NULL, NULL, __FILE__, __LINE__);
        }

        if (ABS_DIFF(x, y) != ABS_DIFF(y, x))
        {
            UtilPanic(TESTCASE_FAILURE,
                      NULL, "abs_diff assoc", NULL, NULL, __FILE__, __LINE__);
        }
    }
#endif

    TestDraw();
#ifdef EVAL_DUMP
    TestEval();
#endif
    TestBitboards();
    TestSan();
    TestIcs();
    TestGetAttacks();
    TestMoveGenerator();
    TestLegalMoveGenerator();
    TestFenCode();
    TestLiftPlaceSlidePiece();
    TestExposesCheck();
    TestIsAttacked();
    TestMakeUnmakeMove();
    TestSearch();

    return(TRUE);
}
#endif // TEST



void DeclareTerminalStates(GAME_RESULT result) {
    switch(result.eResult) {
    case RESULT_IN_PROGRESS:
        return;
    case RESULT_BLACK_WON:
        Trace("0-1 {%s}\n", result.szDescription);
        SetGameResultAndDescription(result.eResult, result.szDescription);
        DumpPgn();
        g_Options.ePlayMode = FORCE_MODE;
        break;
    case RESULT_WHITE_WON:
        Trace("1-0 {%s}\n", result.szDescription);
        SetGameResultAndDescription(result.eResult, result.szDescription);
        DumpPgn();
        g_Options.ePlayMode = FORCE_MODE;
        break;
    case RESULT_DRAW:
        Trace("1/2-1/2 {%s}\n", result.szDescription);
        Trace("tellics draw\n");
        SetGameResultAndDescription(result.eResult, result.szDescription);
        DumpPgn();
        g_Options.ePlayMode = FORCE_MODE;
        break;
    case RESULT_ABANDONED:
    case RESULT_UNKNOWN:
        ASSERT(FALSE);
        SetGameResultAndDescription(result.eResult, result.szDescription);
        DumpPgn();
        g_Options.ePlayMode = FORCE_MODE;
        break;
    }
}


// Main work loop
void MainProgramLoop() {
    POSITION pos;
    GAME_RESULT result;
    FLAG fThink;
    FLAG fPonder;

    while(!g_fExitProgram) {
        
        // Prepare to search or ponder
        memcpy(&pos, GetRootPosition(), sizeof(POSITION));
        fThink = fPonder = FALSE;
        result.eResult = RESULT_IN_PROGRESS;
        result.szDescription[0] = '\0';
        
        // What should we do?
        switch(g_Options.ePlayMode) {
        case I_PLAY_WHITE:
            fThink = (pos.uToMove == WHITE);
            fPonder = (pos.uToMove == BLACK);
            break;
        case I_PLAY_BLACK:
            fThink = (pos.uToMove == BLACK);
            fPonder = (pos.uToMove == WHITE);
            break;
        case FORCE_MODE:
        default:
            MakeStatusLine();
            ParseUserInput(FALSE);
            continue;
        }

        if (fThink) {
            result = Think(&pos);
            if ((NumberOfPendingInputEvents() != 0) &&
                (FALSE == g_fExitProgram))
            {
                MakeStatusLine();
                ParseUserInput(FALSE);
            }
        } else if (fPonder) {
            if (g_Options.fShouldPonder) {
                result = Ponder(&pos);
            }
            if (FALSE == g_fExitProgram)
            {
                MakeStatusLine();
                ParseUserInput(FALSE);
            }
        }
        DeclareTerminalStates(result);
    }
}


int CDECL
main(int argc, char *argv[])
/**

Routine description:

    Chess engine entry point and main loop.

Parameters:

    int argc,
    char *argv[]

Return value:

    int CDECL

**/
{
    // Initial setup work...
    Trace("Setting up, please wait...\n");
    if (FALSE == SystemDependentInitialization())
    {
        Trace("main: Operating system dependent init code failed, "
              "aborting.\n");
        exit(-1);
    }
    if (FALSE == MainProgramInitialization(argc, argv))
    {
        Trace("main: Main program init code failed, aborting.\n");
        exit(-1);
    }
    Banner();
#ifdef TEST
    (void)RunStartupProgramTest();
#endif
    if (TRUE == g_Options.fNoInputThread)
    {
        InitInputSystemInBatchMode();
    }
    else
    {
        g_uInputThreadHandle = InitInputSystemWithDedicatedThread();
    }
    
    // Enter the main work loop code...
    MainProgramLoop();  
    
    // If we get here g_fExitProgram is set -- clean up.
    Trace("MAIN THREAD: thread terminating.\n");
    if (FALSE == MainProgramCleanup())
    {
        Trace("main: Main program cleanup code failed, aborting.\n");
        exit(-1);
    }
    exit(0); 
}