main.c 27.8 KB
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 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

/**************************************************************************
 *                                                                        *
 *               Copyright (C) 1995, Silicon Graphics, Inc.               *
 *                                                                        *
 *  These coded instructions, statements, and computer programs  contain  *
 *  unpublished  proprietary  information of Silicon Graphics, Inc., and  *
 *  are protected by Federal copyright  law.  They  may not be disclosed  *
 *  to  third  parties  or copied or duplicated in any form, in whole or  *
 *  in part, without the prior written consent of Silicon Graphics, Inc.  *
 *                                                                        *
 *************************************************************************/

/*---------------------------------------------------------------------*
        Copyright (C) 1998 Nintendo. (Originated by SGI)
        
        $RCSfile: main.c,v $
        $Revision: 1.1.1.1 $
        $Date: 2002/05/02 03:27:22 $
 *---------------------------------------------------------------------*/

/*
 * File:	main.c
 *
 *   This application demonstrates the capabilities of the RSP ucode
 *   and RDP by allowing the user to select attributes, textures, modes,
 *   etc.  while viewing viewing simple geometric objects.
 *
 */

#include <ultra64.h>
#include <em.h>
#include <ramrom.h>
#include <gu.h>
#include "texture.h"
#include "track.h"
#include "spincontrol.h"
#include "spin.h"
#include "fly.h"
#include "vect.h"
#include "os_internal.h"

typedef enum { 
	SPIN_MODEL, 
	FLY_MODEL, 
	SPIN_LAST
} SpinMode;

void fb_movebits(unsigned long *lfbp, int x, int y, int size, int bit);

#define NUM_PI_MSGS	8

/*
 * Symbol genererated by "makerom" to indicate the end of the code segment
 * in virtual (and physical) memory
 */
extern char _codeSegmentEnd[];
extern char _zbufferSegmentEnd[];
extern char _cfbSegmentEnd[];

/*
 * Symbols generated by "makerom" to tell us where the static segment is
 * in ROM.
 */
extern char _staticSegmentRomStart[], _staticSegmentRomEnd[];
extern char _textureSegmentRomStart[], _textureSegmentRomEnd[];

/*
 * Stacks for the threads as well as message queues for synchronization
 */
u64	bootStack[STACKSIZE/8];

static void	main(void *);
static void	spinloop(void *);
static void     hostiohdl(void* );

static OSThread	spinThread;
static u64	spinloopThreadStack[STACKSIZE/8];

static OSThread	mainThread;
static u64	mainThreadStack[STACKSIZE/8];

static OSThread hostioThread;
static u64      hostioThreadStack[STACKSIZE/8];

static OSMesg PiMessages[NUM_PI_MSGS];
static OSMesgQueue PiMessageQ;

OSMesgQueue	dmaMessageQ, rspMessageQ, rdpMessageQ, retraceMessageQ;
OSMesg		dmaMessageBuf, rspMessageBuf, rdpMessageBuf, retraceMessageBuf, dummyMessage;
OSIoMesg	dmaIOMessageBuf;

static OSMesgQueue  UiDataMQ, UiDoneMQ;
static OSMesg       UiDataMesg, UiDoneMesg;

OSPiHandle	*handler;

/*
 * must be in BSS, not on the stack for this to work:
 */
OSTask  tlist;       /* globaltask list */

Gfx	*glistp;
char	*staticSegment;
char	*textureSegment;

Dynamic	dynamicBuffer;

/*
 * necessary for RSP tasks:
 */
u64 dram_stack[SP_DRAM_STACK_SIZE64];
u64 rdp_output_length[10];
u64 rdp_output[4096*16+10];	/* 64K bytes of rdp output (test) */

SpinMode	Spin_mode = SPIN_MODEL;
static int debugflag;
static int initflag = 1;
static int initTrans = 0;
static int dumpImage = 0;

static int BitToUse   = 0;
static int DoFrameBufferShift = 0;

/*
 * global variables for arguments, to control test cases
 */
static int	keep_mem = 1;
static int	frame_count = 0;
static int	rdp_DRAM_io = 0;
static int	cfb_size = G_IM_SIZ_16b;
static int	viDitherFilter = 0;
static int	viAAFilter = 0;
static int	draw_buffer;
static void	*cfb_ptrs[2] = {
    cfb_16_a,
    cfb_16_b
};

static u64 tmpbuf[8];
static u64 ramrombuf[RAMROM_MSG_SIZE/8];
static u64 tmp2buf[8];

static float	model_mat[4][4];
static float	eye_mat[4][4];
static int	wait_frames = 10;

TrapInfo	tp;
/*
 *  Convert float mtrix to fixed point
 */
void fMtxtolMtx(float mf[4][4], Mtx *m)
{
        int     i, j;
        int     e1,e2;
        int     *ai,*af;


        ai=(int *) &m->m[0][0];
        af=(int *) &m->m[2][0];

        for (i=0; i<4; i++)
        for (j=0; j<2; j++) {
                e1=FTOFIX32(mf[i][j*2]);
                e2=FTOFIX32(mf[i][j*2+1]);
                *(ai++) = ( e1 & 0xffff0000 ) | ((e2 >> 16)&0xffff);
                *(af++) = ((e1 << 16) & 0xffff0000) | (e2 & 0xffff);
        }
}

/***************************************
void fMtxtolMtx(float mf[4][4], Mtx *m)
{
    int     i, j;

    for (i=0; i<4; i++)
      for (j=0; j<4; j++)
      	m->m[i][j] = FTOFIX32(mf[i][j]);
}
*****************************************/

void Identity(float mf[4][4])
{
    int     i, j;
    
    for (i=0; i<4; i++)
        for (j=0; j<4; j++)
	    if (i == j) 
		mf[i][j] = 1.0;
	    else 
		mf[i][j] = 0.0;
}


void dumpRGB( int pixSize, int width, int height, unsigned long *fb)
{
    unsigned long	*longPixels;
    unsigned long	pixelValue;
    int			row, column;
    int			channel;
    char		str[32];

    /*
     * checksum calculates 32 bits, so if 16 bit fb, than 2 pixels at a time.
     * if 8 bit fb, than 4 pixels at a time
     */
    osSyncPrintf("START IMAGE\n");

    if ( pixSize == G_IM_SIZ_8b ) 
    {
        osSyncPrintf("Dimensions %d %d 8\n",width,height);
	width >>= 2;
    } 
    else if ( pixSize == G_IM_SIZ_16b ) 
    {
        osSyncPrintf("Dimensions %d %d 16\n",width,height);
	width >>= 1;
    } 
    else  
    {
        osSyncPrintf("Dimensions %d %d 32\n",width,height);
    }

    longPixels = (unsigned long *) (fb);

    for (column = 0; column < height; column++)
    {
	for (row = 0; row < width; row += 8) 
	{
	    osSyncPrintf("0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x ", 
			 longPixels[0],longPixels[1],longPixels[2],longPixels[3],
			 longPixels[4],longPixels[5],longPixels[6],longPixels[7]);
	    longPixels += 8;
        }
        osSyncPrintf("\n");
    }
    
    osSyncPrintf("END IMAGE\n");
}



/*
 *  Build Graphics Task List
 */
static void BuildGraphicsTask( OSTask *tlistp, Dynamic *dynamicp )
{
    /* build graphics task */
    /* this structure must be aligned to 64-bit boundary: */

    tlistp->t.type = M_GFXTASK;
    tlistp->t.flags = OS_TASK_DP_WAIT;
    tlistp->t.ucode_boot = (u64 *) rspbootTextStart;
    tlistp->t.ucode_boot_size = ((u32)rspbootTextEnd - 
				     (u32)rspbootTextStart);
    /*
     * choose which ucode to run:
     */
    if (rdp_DRAM_io) 
    {
	/* re-direct output to DRAM: */
	tlistp->t.ucode = (u64 *) gspFast3D_dramTextStart;
	tlistp->t.ucode_data = (u64 *) gspFast3D_dramDataStart; 
    } 
    else 
    {
	/* SP output over XBUS to DP: */
	tlistp->t.ucode = (u64 *) gspFast3DTextStart;
	tlistp->t.ucode_data = (u64 *) gspFast3DDataStart;
    }
    tlistp->t.ucode_size = SP_UCODE_SIZE;
    tlistp->t.ucode_data_size = SP_UCODE_DATA_SIZE;
    
    tlistp->t.dram_stack = (u64 *) OS_DCACHE_ROUNDUP_ADDR(dram_stack);
    tlistp->t.dram_stack_size = SP_DRAM_STACK_SIZE8;

    if (rdp_DRAM_io) 
    {
	tlistp->t.output_buff = (unsigned long long *)
	    OS_DCACHE_ROUNDUP_ADDR(&(rdp_output[0]));
	tlistp->t.output_buff_size =  (unsigned long long *)
	    OS_DCACHE_ROUNDUP_ADDR(&rdp_output_length[0]);
    } 
    else 
    {
	tlistp->t.output_buff = (unsigned long long *) 0x0;
	tlistp->t.output_buff_size = (unsigned long long *) 0x0;
    }

    /* initial display list: */
    tlistp->t.data_ptr = (u64 *) dynamicBuffer.glist;
    tlistp->t.data_size = ((u32)(glistp - dynamicBuffer.glist)
			   * sizeof (Gfx));
    /*assert(tlistp->t.data_size <= sizeof(dynamicBuffer.glist));*/
}

/*
 *  Dump display list
 */
void dump_dl( Gfx *uidl)
{
    unsigned int i, cmd;
    unsigned long long int j;

    /* dump UI display list */
    i = 0;
    do 
    {
        cmd = uidl[i].words.w0;
        cmd = (cmd & 0xff000000) >> 24; 
        switch (cmd)
        {
	    case G_SPNOOP: osSyncPrintf("%3d: G_SPNOOP\n", i); break;
	    case G_MTX: osSyncPrintf("%3d: G_G_MTX\n", i); break;
	    case G_MOVEMEM: osSyncPrintf("%3d: G_VIEWPORT or G_LIGHT (MOVEMEM)\n", i); break;
	    case G_VTX: osSyncPrintf("%3d: G_VTX\n", i); break;
	    case G_DL: osSyncPrintf("%3d: G_DL\n", i); break;
	    case 0xbf: osSyncPrintf("%3d: G_TRI1\n", i); break;
	    case 0xbd: osSyncPrintf("%3d: G_POPMTX\n", i); break;
	    case 0xbc: osSyncPrintf("%3d: G_SEGMENT\n", i); break;
	    case 0xb7: osSyncPrintf("%3d: G_SETGEOMETRYMODE\n", i); break;
	    case 0xb6: osSyncPrintf("%3d: G_CLEARGEOMETRYMODE\n", i); break;
	    case 0xb5: osSyncPrintf("%3d: G_LINE3D\n", i); break;
	    case 0xb4: osSyncPrintf("%3d: G_PERSPNORMALIZE\n", i); break;
	    case 0xb3: osSyncPrintf("%3d: G_RDPHALF_1\n", i); break;
	    case 0xb2: osSyncPrintf("%3d: G_RDPHALF_2\n", i); break;
	    case G_NOOP: osSyncPrintf("%3d: G_NOOP\n", i); break;
	    case G_SETCIMG: osSyncPrintf("%3d: G_SETCIMG\n", i); break;
	    case G_SETZIMG: osSyncPrintf("%3d: G_SETMIMG\n", i); break;
	    case G_SETTIMG: osSyncPrintf("%3d: G_SETTIMG\n", i); break;
	    case G_SETCOMBINE: osSyncPrintf("%3d: G_SETCOMBINE\n", i); break;
	    case G_SETENVCOLOR: osSyncPrintf("%3d: G_SETENVCOLOR\n", i); break;
	    case G_SETPRIMCOLOR: osSyncPrintf("%3d: G_SETPRIMCOLOR\n", i); break;
	    case G_SETBLENDCOLOR: osSyncPrintf("%3d: G_SETBLENDCOLOR\n", i); break;
	    case G_SETFOGCOLOR: osSyncPrintf("%3d: G_SETFOGCOLOR\n", i); break;
	    case G_SETFILLCOLOR: osSyncPrintf("%3d: G_SETFILLCOLOR\n", i); break;
	    case G_FILLRECT: osSyncPrintf("%3d: G_FILLRECT\n", i); break;
	    case G_SETTILE: osSyncPrintf("%3d: G_SETTILE\n", i); break;
	    case G_LOADTILE: osSyncPrintf("%3d: G_LOADTILE\n", i); break;
	    case G_LOADBLOCK: osSyncPrintf("%3d: G_LOADBLOCK\n", i); break;
	    case G_SETTILESIZE: osSyncPrintf("%3d: G_SETTILESIZE\n", i); break;
	    case G_LOADTLUT: osSyncPrintf("%3d: G_LOADTLUT\n", i); break;
	    case G_RDPSETOTHERMODE: osSyncPrintf("%3d: G_RDPSETOTHERMODE\n", i); break;
	    case G_SETPRIMDEPTH: osSyncPrintf("%3d: G_SETPRIMDEPTH\n", i); break;
	    case G_SETSCISSOR: osSyncPrintf("%3d: G_SETSCISSOR\n", i); break;
	    case G_SETCONVERT: osSyncPrintf("%3d: G_SETCONVERT\n", i); break;
	    case G_SETKEYR: osSyncPrintf("%3d: G_SETKEYR\n", i); break;
	    case G_SETKEYGB: osSyncPrintf("%3d: G_SETKEYGB\n", i); break;
	    case G_RDPFULLSYNC: osSyncPrintf("%3d: G_RDPFULLSYNC\n", i); break;
	    case G_RDPTILESYNC: osSyncPrintf("%3d: G_RDPTILESYNC\n", i); break;
	    case G_RDPPIPESYNC: osSyncPrintf("%3d: G_RDPPIPESYNC\n", i); break;
	    case G_RDPLOADSYNC: osSyncPrintf("%3d: G_RDPLOADSYNC\n", i); break;
	    case G_TEXRECTFLIP: osSyncPrintf("%3d: G_TEXRECTFLIP\n", i); break;
	    case G_TEXRECT: osSyncPrintf("%3d: G_TEXRECT\n", i); break;
	    case 0xb8: osSyncPrintf("%3d: G_ENDDL\n", i); break;
	    case 0xbb: osSyncPrintf("%3d: G_TEXTURE\n", i); break;
	    case 0xba: osSyncPrintf("%3d: G_SETOTHERMODE_H\n", i); break;
	    case 0xb9: osSyncPrintf("%3d: G_SETOTHERMODE_L\n", i); break;
	    default: osSyncPrintf("%3d: command %d not recognized\n", i, cmd); break;
        }
	for (j=0;j<=1000000;j++);
        osSyncPrintf("W0 %08x w1 %08x\n", uidl[i].words.w0, uidl[i].words.w1);
	for (j=0;j<=1000000;j++);
        i++;
    }  while (cmd != 0xb8 && i < 30);
}
 
/*
 *  Render object
 */
static void drawit( int model, Gfx *uidl, ProjInfo *p)
{
    OSMesg		dummyMesg;
    OSTask		*tlistp;
    Dynamic		*dynamicp;
    Gfx			*dlistHead;
    unsigned		i, cmd;

    /*
     * pointers to build the display list.
     */
    tlistp = &tlist;
    dynamicp = &dynamicBuffer;
    glistp = dynamicp->glist;

    if (viDitherFilter == 1){
	osViSetSpecialFeatures(OS_VI_DITHER_FILTER_ON);
    } else {
	osViSetSpecialFeatures(OS_VI_DITHER_FILTER_OFF);
    }

    /*
     * Tell RSP where dynamic segment is
     */
    gSPSegment(glistp++, DYNAMIC_SEGMENT, osVirtualToPhysical(dynamicp));
    gSPSegment(glistp++, PHYSICAL_SEGMENT, 0);
    gSPSegment(glistp++, STATIC_SEGMENT, osVirtualToPhysical(staticSegment));
    gSPSegment(glistp++, TEXTURE_SEGMENT, osVirtualToPhysical(textureSegment));
    /*
     * Image pointers are translated via RSP segment registers.
     * Preset segment register 0 with 0.
     */
    gDPPipeSync(glistp++);
    gDPSetDepthImage(glistp++,osVirtualToPhysical(zbuffer));

    /*
     * Graphics pipeline state initialization
     */
    gSPDisplayList(glistp++, setup_rspstate);
    if (initflag) {
	gSPDisplayList(glistp++, setup_rdpstate);
	initflag = 0;
    }
     
    dlistHead = glistp;
    /*
     * Clear framebuffer cvg = FULL or 1
     */
    gDPPipeSync(glistp++);
    gDPSetCycleType(glistp++,G_CYC_FILL);
    gDPSetScissor(glistp++,G_SC_NON_INTERLACE, 0, 0, SCREEN_WD, SCREEN_HT);
    /*
     * clear z, z = max z, dz = 0
     */
    gDPPipeSync(glistp++);
    gDPSetColorImage(glistp++,G_IM_FMT_RGBA, G_IM_SIZ_16b, SCREEN_WD, osVirtualToPhysical(zbuffer));
    gDPSetFillColor(glistp++,GPACK_ZDZ(G_MAXFBZ, 0) << 16 | GPACK_ZDZ(G_MAXFBZ, 0));
    gDPFillRectangle(glistp++,0, 0, SCREEN_WD-1, SCREEN_HT-1);

    gDPNoOp(glistp++);
    
    gDPPipeSync(glistp++);

    if (cfb_size == G_IM_SIZ_32b) 
    {
	gDPSetColorImage(glistp++, G_IM_FMT_RGBA,  G_IM_SIZ_32b, SCREEN_WD, osVirtualToPhysical(cfb_ptrs[draw_buffer]));
	gDPSetFillColor(glistp++, (0<<24) | (200<<16) | (200 << 8) | 0xff);
	gDPFillRectangle(glistp++, 0, 0, SCREEN_WD-1, SCREEN_HT-1);

	gDPNoOp(glistp++);
    } 
    else 
    {
	gDPSetColorImage(glistp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, SCREEN_WD, osVirtualToPhysical(cfb_ptrs[draw_buffer]));
	gDPSetFillColor(glistp++, GPACK_RGBA5551(0,200,200,1) << 16 | GPACK_RGBA5551(0,200,200,1));
	gDPFillRectangle(glistp++, 0, 0, SCREEN_WD-1, SCREEN_HT-1);

	gDPNoOp(glistp++);
/***** Inner rectangle fill for clipping bug testing *********
**********************************************************/
#ifdef SKINNY_VP
	gDPSetColorImage(glistp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, SCREEN_WD, osVirtualToPhysical(cfb_ptrs[draw_buffer]));
	gDPSetFillColor(glistp++, GPACK_RGBA5551(0,200,200,1) << 16 | GPACK_RGBA5551(0,200,200,1));
	gDPFillRectangle(glistp++, 80,60,240,180);
	gDPNoOp(glistp++);
#endif /* SKINNY_VP */
    }
    gDPPipeSync(glistp++);
    gDPSetCycleType(glistp++, G_CYC_1CYCLE);
    gDPSetRenderMode(glistp++,G_RM_AA_ZB_OPA_SURF, G_RM_AA_ZB_OPA_SURF2);

    
    /*
     *  Insert UI generated display list
     */
    if(uidl)
    {
	/* fix up texture pointer */
	i = 0;
	do 
	{
	    cmd = uidl[i].words.w0;
	    cmd = (cmd & 0xff000000) >> 24;
	    if (cmd == G_SETTIMG)
	    {
		if(uidl[i].setimg.dram == 0)
		    uidl[i].setimg.dram = (unsigned)RGBA16molecule;
		else if(uidl[i].setimg.dram == 1)
		    uidl[i].setimg.dram = (unsigned)RGBA16grid;
		else if(uidl[i].setimg.dram == 2)
		    uidl[i].setimg.dram = (unsigned)I8mand;
		else if(uidl[i].setimg.dram == 3)
		    uidl[i].setimg.dram = (unsigned)I8cloud;
		else if(uidl[i].setimg.dram == 4)
		    uidl[i].setimg.dram = (unsigned)I4granite3;
		else if(uidl[i].setimg.dram == 5)
		    uidl[i].setimg.dram = (unsigned)IA16tree;
		else if(uidl[i].setimg.dram == 6)
		    uidl[i].setimg.dram = (unsigned)IA8tree;
		else if(uidl[i].setimg.dram == 7)
		    uidl[i].setimg.dram = (unsigned)IA4tree;
		else if(uidl[i].setimg.dram == 8)
		    uidl[i].setimg.dram = (unsigned)I8grid;
		else if(uidl[i].setimg.dram == 9)
		    uidl[i].setimg.dram = (unsigned)CI8mario;
		else if(uidl[i].setimg.dram == 10)
		    uidl[i].setimg.dram = (unsigned)CI4mario;
		else if(uidl[i].setimg.dram == 11)
		    uidl[i].setimg.dram = (unsigned)RGBA16checkMM_buf;
		else if(uidl[i].setimg.dram == 12)
		    uidl[i].setimg.dram = (unsigned)RGBA16treeMM_buf;
		else if(uidl[i].setimg.dram == 13)
		    uidl[i].setimg.dram = (unsigned)RGBA16foliageMM_buf;
		else if(uidl[i].setimg.dram == 14)
		    uidl[i].setimg.dram = (unsigned)RGBA16mario;
		else if(uidl[i].setimg.dram == 15)
		    uidl[i].setimg.dram = (unsigned)RGBA32mario;
		else if(uidl[i].setimg.dram == 16)
		    uidl[i].setimg.dram = (unsigned)RGBA16check1MM_buf;
		else if(uidl[i].setimg.dram == 17)
		    uidl[i].setimg.dram = (unsigned)I8checkMM_buf;
		else if(uidl[i].setimg.dram == 108)
		    uidl[i].setimg.dram = (unsigned)CI8mariotlut;
		else if(uidl[i].setimg.dram == 109)
		    uidl[i].setimg.dram = (unsigned)CI4mariotlut;
	    } 
	    else if (cmd == G_SETOTHERMODE_H) 
		osSyncPrintf("OTHER\n");
	    i++;
	}  while (cmd != 0xb8 && i < 100);
	gSPDisplayList(glistp++, osVirtualToPhysical(uidl));
#ifdef DEBUG_UIDL
	osSyncPrintf("ui gen	erated\n");
	dump_dl(uidl);
#endif
    }

    gDPPipeSync(glistp++);

    /*
     *  Get modeling matrix for model rotation
     */

    gettracktransform(model_mat);
    guMtxF2L(model_mat, &(dynamicp->modeling));


    /*
     *  Get matrix for eye point position
     */
    getflytransform(eye_mat, initTrans);
    guMtxF2L(eye_mat, &(dynamicp->eye));

    initTrans = 0;
    /*
     *  Build rest of Graphics display list
     */    
    BuildDisplayList(dynamicp, model, p->fov, p->aspect, p->near, p->far);
    gSPEndDisplayList(glistp++); /* required */

#ifdef DEBUG_UIDL
    osSyncPrintf("app generated dl\n");
    dump_dl(dlistHead);
#endif

    /*
     *  Build Graphics Task
     */
    BuildGraphicsTask(tlistp, dynamicp);
    
    /*
     * XXX WASTEFUL, could just flush tlist & part of Dynamic
     * Can just flush 16KB and forget about each individual pieces
     * of data to flush.
     */
    osWritebackDCacheAll();
    osSpTaskStart(tlistp);

    /* Wait for SP completion */
    (void)osRecvMesg(&rspMessageQ, NULL, OS_MESG_BLOCK);
    
    if (rdp_DRAM_io) {
	osDpSetNextBuffer(OS_DCACHE_ROUNDUP_ADDR(&(rdp_output[0])), 
			  (u32)(*((u64 *)OS_DCACHE_ROUNDUP_ADDR(rdp_output_length))));
    }

    /* Wait for RDP completion */
    (void)osRecvMesg(&rdpMessageQ, &dummyMesg, OS_MESG_BLOCK);

    if (tp.trap) 
    {
	int k;
	switch (tp.type) 
	{
	    case 0: 
		guParseGbiDL((u64 *)(dynamicp->glist),
			     (glistp - dynamicp->glist), 0);
		break;
	    case 1: 
		guParseGbiDL(tlistp->t.data_ptr, tlistp->t.data_size,
		    GU_PARSEGBI_DUMPONLY);
		break;
	    case 2: 
		guParseRdpDL(OS_DCACHE_ROUNDUP_ADDR(&rdp_output[0]),
			     (u32)(*((u64 *)OS_DCACHE_ROUNDUP_ADDR(rdp_output_length))), 0);
		break;
	    case 3: 
		guParseRdpDL(OS_DCACHE_ROUNDUP_ADDR(&rdp_output[0]),
		    (u32)(*((u64 *)OS_DCACHE_ROUNDUP_ADDR(rdp_output_length))),
		    GU_PARSERDP_DUMPONLY);
		break;
	    default:
		break;
	}

	for (k=0; k < 100; k++) 
	    osSyncPrintf("=================\n");

	tp.trap--;
    }

    if (dumpImage)  
    {     
	osSyncPrintf("cfb_size == %d \n", cfb_size);
	dumpRGB(cfb_size, 320, 240, cfb_ptrs[draw_buffer]);
	for (i = 0; i < 1024; i++) 
	    osSyncPrintf("================\n");
	dumpImage = 0; /* Don't dump any more frame */
	osSyncPrintf("End frame dump \n");
     }


    /* setup to swap buffers */
    if (DoFrameBufferShift)
	fb_movebits(cfb_ptrs[draw_buffer], SCREEN_WD, SCREEN_HT, cfb_size, BitToUse);

    osViSwapBuffer(cfb_ptrs[draw_buffer]);
    /* Make sure there isn't an old retrace in queue (assumes queue has a depth of 1) */
    if (MQ_IS_FULL(&retraceMessageQ)) 
	(void)osRecvMesg(&retraceMessageQ, &dummyMesg, OS_MESG_BLOCK);
	
    /* Wait for Vertical retrace to finish swap buffers */    
    (void)osRecvMesg(&retraceMessageQ, &dummyMesg, OS_MESG_BLOCK);
    draw_buffer ^= 1;

    if (viAAFilter == 1)
    {
	if (cfb_size == G_IM_SIZ_32b)
	    osViSetMode(&osViModeTable[OS_VI_NTSC_LAN2]);
	else 
	    osViSetMode(&osViModeTable[OS_VI_NTSC_LAN1]);

	osViSetSpecialFeatures(OS_VI_DIVOT_ON);
    }
    else 
    { 
	if (cfb_size == G_IM_SIZ_32b)
	    osViSetMode(&osViModeTable[OS_VI_NTSC_LPN2]);
	else 
	    osViSetMode(&osViModeTable[OS_VI_NTSC_LPN1]);
	
	osViSetSpecialFeatures(OS_VI_DIVOT_OFF);
    }
} /* drawit */

boot(char *arg)
{
    int i;
    char *ap;
    u32 *argp;
    u32 argbuf[16];
      
    osInitialize();
    
    handler = osCartRomInit();

    argp = (u32 *)RAMROM_APP_WRITE_ADDR;
    for (i=0; i<sizeof(argbuf)/4; i++, argp++) {
	osEPiReadIo(handler, (u32)argp, &argbuf[i]);	/* Assume no DMA */
    }
    /* Parse the options */
    ap = (char *)argbuf;
    if ( *ap == '-' && *(ap+1) == 'd')
	debugflag = 1;
    else
	debugflag = 0;
	
    osCreateThread(&mainThread, 1, main, (void *)arg,
		   mainThreadStack+STACKSIZE/8, 10);
    osStartThread(&mainThread);
    
    /* Never Reached - feel free to use bootStack */
}

char rdbout_buf[0x1000];

void main(void *arg)
{
    char *ap = arg;

    /* Initialize video */
    osCreateViManager(OS_PRIORITY_VIMGR);
    if (cfb_size == G_IM_SIZ_32b) {
	osViSetMode(&osViModeTable[OS_VI_NTSC_LAN2]);
    }
    else {
	osViSetMode(&osViModeTable[OS_VI_NTSC_LAN1]);
    }

    /*
     * Start PI Mgr for access to cartridge
     */
    osCreatePiManager((OSPri)OS_PRIORITY_PIMGR, &PiMessageQ, PiMessages, NUM_PI_MSGS);

    osInitRdb(rdbout_buf,sizeof(rdbout_buf));  

    osCreateMesgQueue(&UiDataMQ,&UiDataMesg,1);
    osCreateMesgQueue(&UiDoneMQ,&UiDoneMesg,1);
    
    /*
     * Create spin thread
     */
    osCreateThread(&spinThread, 3, spinloop, (void *)0,
		   spinloopThreadStack+STACKSIZE/8, 10);

    if (!debugflag) 
        osStartThread(&spinThread); 
    
    osCreateThread(&hostioThread, 4, hostiohdl, (void*)0,
		   hostioThreadStack + STACKSIZE/8, 12);
    osStartThread(&hostioThread);
    /*
     * Become the idle thread 
     */
    osSetThreadPri( 0, 0 );
    for(;;);  
}

Gfx  dlbuffer[2048];

static void hostiohdl(void* arg)
{
    SpinControl   sp;

    while(1)
    {
	osReadHost(&sp,sizeof(SpinControl));
	if(sp.type == SPIN_DLIST_TYPE)
	{
	    osReadHost(dlbuffer,sp.u_msg.dlist.dlsize);
	}
	osSendMesg(&UiDataMQ,(OSMesg)&sp,OS_MESG_BLOCK);
	osRecvMesg(&UiDoneMQ,NULL,OS_MESG_BLOCK);
    }   
}

void getUiData(ProjInfo *p, MouseState *ms, int *model, Gfx **uidl, TrapInfo *tp)
{
    SpinControl	*sp;

    /* a returned value of zero means there is a message */
    if(osRecvMesg(&UiDataMQ,(OSMesg*)&sp, OS_MESG_NOBLOCK) == 0) 
    {
	switch (sp->type) 
	{
            case SPIN_PROJ_TYPE:
		p->fov = sp->u_msg.proj.fov;
		p->aspect = sp->u_msg.proj.aspect;
		p->near = sp->u_msg.proj.near;
		p->far = sp->u_msg.proj.far;
                break;

            case SPIN_MOUSE_TYPE:
                ms->x = sp->u_msg.mouse.x;
                ms->y = sp->u_msg.mouse.y;
                ms->buttons = sp->u_msg.mouse.buttons;
                break;

            case SPIN_MODEL_TYPE:
		if ( sp->u_msg.model.model == 105) {
		     viAAFilter = 1;
		} else if ( sp->u_msg.model.model == 104) {
		     viAAFilter = 0;
		} else if  ( sp->u_msg.model.model == 103) {
		     cfb_size = G_IM_SIZ_32b;
		} else if ( sp->u_msg.model.model == 102) {
		     cfb_size = G_IM_SIZ_16b;
		} else if ( sp->u_msg.model.model == 101) {
		    viDitherFilter = 1;
		} else if ( sp->u_msg.model.model == 100) {
		    viDitherFilter = 0;
		} else if ( sp->u_msg.model.model == 99) {
		    tinit();
		    initTrans = 1; /* used by getflytransform */
		} else if ( sp->u_msg.model.model < 99) {
                    *model = sp->u_msg.model.model;		    
		} else if ( (sp->u_msg.model.model >= 110) &&
			    (sp->u_msg.model.model <= 117)) {
		    BitToUse = sp->u_msg.model.model - 110;
		} else if ( (sp->u_msg.model.model == 118) ||
			    (sp->u_msg.model.model <= 119)) {
		    DoFrameBufferShift = sp->u_msg.model.model - 118;
		} else if ( sp->u_msg.model.model == 120) {
		    dumpImage = 1;
		} 
		break;

	    case SPIN_DLIST_TYPE:
	    	*uidl = &dlbuffer[0];
		break;

	    case SPIN_TRAP_TYPE:
		tp->trap = sp->u_msg.trap.trap;
		tp->type = sp->u_msg.trap.type;
		if ((tp->type == 0) || (tp->type == 1))
		    rdp_DRAM_io = 0;
		else
		    rdp_DRAM_io = 1;
		break;

	    default:
		osSyncPrintf("unknown sp->type 0x%x\n", sp->type);
		break;
	}

	osSendMesg(&UiDoneMQ,NULL,OS_MESG_BLOCK);
    }
}

void fb_movebits(unsigned long *lfbp, int x, int y, int size, int bit)
{
    unsigned short      *sfbp = (unsigned short *)lfbp;
    int                 i;
    int                 bitshift;

    if (size == G_IM_SIZ_16b) {
        bitshift = 4-bit;
        for (i=0; i<x*y; i++) {
            *sfbp++ = ((*sfbp << bitshift) & 0x8420) | 0x0001;
        }
    }

    if (size == G_IM_SIZ_32b) {
        bitshift = 7-bit;
        for (i=0; i<x*y; i++) {
            *lfbp++ = ((*lfbp << bitshift) & 0x808080ff) | 0x000000ff;
        }
    }
    osWritebackDCacheAll();
}

void spinloop(void *arg)
{
    MouseState  ms;
    int		model = 15;
    Gfx 	*uidl = NULL; /* user interface display list */
    int 	modelListCount;
    char	*nptr;
    int		i,signalVal;
    ProjInfo	p;
    OSMesg	dummyMesg;


    p.fov = 30;
    p.aspect = 320.0/240.0;
    p.near   = 50;
    p.far    = 10000;

    ms.x = 160;
    ms.y = 120;
    ms.buttons = 0;
    /*
     * Setup the message queues
     */
    osCreateMesgQueue(&dmaMessageQ, &dmaMessageBuf, 1);

    osCreateMesgQueue(&rspMessageQ, &rspMessageBuf, 1);
    osSetEventMesg(OS_EVENT_SP, &rspMessageQ, NULL);

    osCreateMesgQueue(&rdpMessageQ, &rdpMessageBuf, 1);
    osSetEventMesg(OS_EVENT_DP, &rdpMessageQ, dummyMessage);

    osCreateMesgQueue(&retraceMessageQ, &retraceMessageBuf, 1);
    osViSetEvent(&retraceMessageQ, dummyMessage, 1);

    /*
     * Stick the static segment right after the code/data segment
     */
    staticSegment = _cfbSegmentEnd + 8;
	    

    dmaIOMessageBuf.hdr.pri      = OS_MESG_PRI_NORMAL;
    dmaIOMessageBuf.hdr.retQueue = &dmaMessageQ;
    dmaIOMessageBuf.dramAddr     = staticSegment;
    dmaIOMessageBuf.devAddr      = (u32)_staticSegmentRomStart;
    dmaIOMessageBuf.size         = _staticSegmentRomEnd-_staticSegmentRomStart;

    osEPiStartDma(handler, &dmaIOMessageBuf, OS_READ);

    /*
     * Wait for DMA to finish
     */
    (void)osRecvMesg(&dmaMessageQ, &dummyMesg, OS_MESG_BLOCK);
    
    /*
     * Stick the texture segment right after the static segment
     */
    textureSegment = _cfbSegmentEnd + 8 +
		(_staticSegmentRomEnd - _staticSegmentRomStart);
	    

    dmaIOMessageBuf.hdr.pri      = OS_MESG_PRI_NORMAL;
    dmaIOMessageBuf.hdr.retQueue = &dmaMessageQ;
    dmaIOMessageBuf.dramAddr     = textureSegment;
    dmaIOMessageBuf.devAddr      = (u32)_textureSegmentRomStart;
    dmaIOMessageBuf.size         = _textureSegmentRomEnd-_textureSegmentRomStart;

    osEPiStartDma(handler, &dmaIOMessageBuf, OS_READ);

    /*
     * Wait for DMA to finish
     */
    (void)osRecvMesg(&dmaMessageQ, &dummyMesg, OS_MESG_BLOCK);

    /* 
     * count the models. Can't use sizeof(), do it here.
     */
    modelListCount = 0;
    while (modelList[modelListCount] != (Gfx *) NULL)
	modelListCount++;
    modelListCount--;
    
    /* signal Indy that we are ready to go */
    signalVal = SPIN_READY;
    osWriteHost(&signalVal,sizeof(int));


    /*
     * Main spin loop
     */

    while (1) {

	getUiData(&p,&ms,&model,&uidl,&tp);

	if (ms.buttons & BUTTON_RIGHT) 
	{
	    if(Spin_mode == FLY_MODEL)
	    {
		flystop();
	    }
	    Spin_mode =  SPIN_MODEL;
        } 
	else 
	{
	    if(Spin_mode == SPIN_MODEL)
		flyclick(ms.x, ms.y);
	    Spin_mode = FLY_MODEL;
        }


        if (ms.buttons & BUTTON_LEFT) 
	{
	    if(Spin_mode == SPIN_MODEL)
	    {
		trackclick(ms.x, ms.y);
		/* do trackball */
		do 
		{
		    trackpoll(ms);
		    drawit(model, uidl, &p);
		    getUiData(&p,&ms,&model,&uidl,&tp);
		} while (ms.buttons & BUTTON_LEFT);
	    }
	    else if(Spin_mode == FLY_MODEL)
	    {
		/* flying mode */
		flyrollclick(ms.x, ms.y);
		do 
		{
		    flypoll(ms);
		    drawit(model, uidl, &p);
		    getUiData(&p,&ms,&model,&uidl,&tp);
		} while (ms.buttons & BUTTON_LEFT);
	    }
        }
        else if (ms.buttons & BUTTON_MIDDLE) 
	{
	    if(Spin_mode == SPIN_MODEL)
	    {
		/* do trackball */
		trackclick(ms.x, ms.y);
		do 
		{
		    trackpoll(ms);
		    drawit(model, uidl, &p);
		    getUiData(&p,&ms,&model,&uidl,&tp);
		} while (ms.buttons & BUTTON_MIDDLE);
	    }
	    else if(Spin_mode == FLY_MODEL)
	    {
		/* flying mode, pitch up/down */
		flypitchclick(ms.x, ms.y);
		do 
		{
		    flypoll(ms);
		    drawit(model, uidl, &p);
		    getUiData(&p,&ms,&model,&uidl,&tp);
		} while (ms.buttons & BUTTON_MIDDLE);
	    }
        }
	else
	{
	    /* no buttons, track mouse movement */
	    if(Spin_mode == FLY_MODEL)
		flypoll(ms);
	    drawit(model, uidl, &p);
	}
    } /* while 1 */
}