예제 #1
0
파일: guifilelist.c 프로젝트: nop90/z26-3ds
int file_selector(char *result) {
//	SDL_Event ev;
    u32 keys; 
	int picked = 0;
//	int max_width = tiawidth/FONT_WIDTH;
	int max_height = MaxLines/FONT_HEIGHT; //-1;
	int k = 0;

	if (PaletteNumber != UserPaletteNumber)
	{
		PaletteNumber = UserPaletteNumber;
		gui_SetVideoMode();
	}
	clrscr();

	/* filesread is a global that gets updated by get_list */
	if (first_filelist) 
	{
		get_file_list();
		first_filelist = 0;
	}

	while(hidKeysHeld()) hidScanInput(); //wait for previous keys to be released

	while(!picked) {
		int action;

		window_line = draw_file_list(curfile, window_line, max_height-2);
//		SDL_WaitEvent(&ev);	
		hidScanInput();
		while(!hidKeysHeld()) hidScanInput();
		keys = hidKeysHeld();
		
		action = gui_navigation(keys); //&ev);

		if(action == GUI_NO_ACTION)
			continue;

		switch(action) 
		{
		char type;

		case GUI_EXIT_GUI:
			clrscr();
			return 0; /* abort */

		case GUI_ACTIVATE_SEC:
			match = 0;
			curfile++;
			if(curfile == filesread) curfile = 0;
			clrscr();
			type = file_list[curfile][strlen(file_list[curfile])-1];
			if(type == '/')	/* if it's a dir, cd to it and get new file list. */
			{
				if (chdir(file_list[curfile]) == 0)
				{
					curfile = 0;
					get_file_list();
				}
			} 
			else		/* if it's a file, return it */
			{
				strcpy(result, file_list[curfile]);
				picked = 1;
			}
			break;
		
		
		case GUI_ACTIVATE_PRI:
			match = 0;
			clrscr();
			type = file_list[curfile][strlen(file_list[curfile])-1];
			if(type == '/')	/* if it's a dir, cd to it and get new file list. */
			{
				if (chdir(file_list[curfile]) == 0)
				{
					curfile = 0;
					get_file_list();
				}
			} 
			else		/* if it's a file, return it */
			{
				strcpy(result, file_list[curfile]);
				picked = 1;
			}
			break;

		case GUI_UP:
			match = 0;
			curfile--;
			if(curfile < 0) curfile = filesread - 1;
			break;

		case GUI_DOWN:
			match = 0;
			curfile++;
			if(curfile == filesread) curfile = 0;
			break;

		case GUI_PAGEDOWN:
			match = 0;
			if(filesread > max_height-1) {
				curfile += max_height-1;
				if(curfile >= filesread)
					curfile = 0;
				window_line = curfile;
				clrscr();
			}
			break;

		case GUI_PAGEUP:
			match = 0;
			if(filesread > max_height-1) {
				curfile -= max_height-1;
				if(curfile < 0)
					curfile = filesread-1;
				window_line = curfile;
				clrscr();
				break;
			}

		case GUI_HOME:
			match = 0;
			curfile = 0;
			window_line = 0;
			clrscr();
			break;

		case GUI_END:
			match = 0;
			curfile = filesread-1;
			window_line = curfile;
			clrscr();
			break;
			
		case GUI_RANDOM:
			match = 0;
			curfile = rand() % filesread;
			window_line = curfile;
			type = file_list[curfile][strlen(file_list[curfile])-1];
			
			while (type == '/')	/* if it's a dir, find another file */
			{
				curfile = rand() % filesread;
				window_line = curfile;
				type = file_list[curfile][strlen(file_list[curfile])-1];
			} 
			
			
			
			clrscr();
			break;


		default:
//			if(ev.type == SDL_KEYDOWN)
//			if(keys)
//			{
//				k = ev.key.keysym.sym;
//				curfile = window_line = find_next_rom(curfile, keys); // !!!!!!
//			}
			break;
		}

		svcSleepThread (250000000);
//		SDL_WM_SetCaption(file_list[curfile], file_list[curfile]);

	}
	
	return picked;
}
예제 #2
0
// Main part of the coding, where everything works (or not)
int main(void) {
    init();

    // Main loop
    while (aptMainLoop()) {

        // Verify button presses
        hidScanInput();

        // Unsigned variables for different types of button presses
        u32 kDown = hidKeysDown();
        u32 kHeld = hidKeysHeld();
        // u32 kUp = hidKeysUp();

        // Exit homebrew
        if (kDown & KEY_START) {
            break;
        }

        // Activate first easter egg
        else if (kDown & KEY_SELECT) {
            easterEgg = !easterEgg;
        }

        // Change pages for the easterEgg/debug menu.
        else if (kDown & KEY_R) {
            if (++easterPage > MAX_PAGE) easterPage = 0;
        }
        else if (kDown & KEY_L) {
            if (--easterPage < 0) easterPage = MAX_PAGE;
        }


        timerStep();

        // If no movement, set the sprite timer to 0
        if (kDown & KEY_UP || kDown & KEY_DOWN || kDown & KEY_LEFT || kDown & KEY_RIGHT) {
            sprTimer = 0;
        }

        // Reset horizontal and vertical speeds
        vsp = 0;
        hsp = 0;

        // Player movement (pretty easy to understand)
        // TODO: Would it be possible to make this less... iffy?
        if (kHeld & KEY_UP) {
            if (!(kHeld & KEY_DOWN)) {
                vsp = -.5; // Vertical speed to negative .5
                playerDir = BACK; // Player direction = back
            }
        }

        if (kHeld & KEY_DOWN) {
            vsp = .5; // Vertical speed to .5
            playerDir = FORWARD; // Player direction = up
        }

        if (kHeld & KEY_LEFT) {
            if (!(kHeld & KEY_RIGHT)) {
                hsp = -.5; // Vertical speed to negative .5
                playerDir = LEFT; // Player direction = left
            }
        }

        if (kHeld & KEY_RIGHT) {
            hsp = .5; // Vertical speed to .5
            playerDir = RIGHT; // Player direction = right
        }

        // Diagonal movement speed fix
        if (vsp != 0) {
            if (hsp != 0) {
                vsp *= .8;
                hsp *= .8;
            }
        }

        // Movement calculation... AND proper room colision.
        // TODO: Consider a function for translating and/or clamping coordinates directly?
        player_pos.x = fclamp(player_pos.x + hsp * dt,
                              rooms[room].collision[0].x,
                              rooms[room].collision[1].x);

        player_pos.y = fclamp(player_pos.y + vsp * dt,
                              rooms[room].collision[0].y,
                              rooms[room].collision[1].y);

        // Scrolling calculation.
        // TODO: Make these constants better/customizable.
        if (player_pos.x - camera_pos.x >= 300) {
            camera_pos.x = player_pos.x - 300;
        }
        else if (player_pos.x - camera_pos.x <= 100) {
            camera_pos.x = player_pos.x - 100;
        }
        camera_pos.x = fclamp(camera_pos.x, 0, rooms[room].scroll_max.x);

        if (player_pos.y - camera_pos.y >= 200) {
            camera_pos.y = player_pos.y - 200;
        }
        else if (player_pos.y - camera_pos.y <= 50) {
            camera_pos.y = player_pos.y - 50;
        }
        camera_pos.y = fclamp(camera_pos.y, 0, rooms[room].scroll_max.y);

        // Player sprites
        if (hsp == 0 && vsp == 0) curr_tex = tex_arr_friskWalk[playerDir][0];

        else curr_tex = tex_arr_friskWalk[playerDir][(int)floor(sprTimer)];

        // Sprite animation timer
        // TODO: Why .15 * .03 * actual time?
        sprTimer += (.03 * dt);

        while (sprTimer >= 4) {
            sprTimer -= 4;
        }

        if (!next_exit){
            if (roomTimer < 255) {
                roomTimer = fmin(roomTimer + (4 * dt), 255);
            }
            next_exit = exit_room(room, &player_pos);
        }
        else {
            roomTimer -= 4 * dt;
            if (roomTimer <= 0) {
                room = next_exit->room_id;
                player_pos = next_exit->entrance;
                next_exit = NULL;
                roomTimer = 0;
            }
        }

        render();

        // Swap sf2d framebuffers and wait for VBlank
        sf2d_swapbuffers();
    }

    // Free images/textures/fonts from memory

    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            sf2d_free_texture(tex_arr_friskWalk[i][j]);
        }
    }

    for (int i = 0; i < 3; ++i) {
        sf2d_free_texture(rooms[i].bg.tex);
    }

    sftd_free_font(font);

    // Exit services
    sf2d_fini();
    sftd_fini();
    sound_stop(home);
    audio_stop();
    hidExit();
    aptExit();
    srvExit();

    return 0;
}
예제 #3
0
void vblank(void) {
	#ifdef WIN
		drawFramebuffer();
	#endif
	
	#ifdef PS4
		void readController(void);
		readController();
		
		extern unsigned int buttons;
		keys.c = (unsigned char)buttons;
		
		sceKernelUsleep(1000000 / 60);
	#endif
	
	#ifdef DS
		// The Game Boy and DS use the same key layout, how convenient :)
		keys.c = (unsigned char)REG_KEYINPUT;
		
		// Support scrolling
		copyMap();
	#endif
	
	#ifdef GC
		VIDEO_WaitVSync();
	#endif
	
	#ifdef DS3
		hidScanInput();
		u32 kHeld = hidKeysHeld();
		
		keys.keys1 = 0x0f;
		keys.keys2 = 0x0f;
		
		if(kHeld & KEY_B) keys.b = 0;
		if(kHeld & KEY_A) keys.a = 0;
		if(kHeld & KEY_START) keys.start = 0;
		if(kHeld & KEY_SELECT) keys.select = 0;
		if(kHeld & KEY_UP) keys.up = 0;
		if(kHeld & KEY_DOWN) keys.down = 0;
		if(kHeld & KEY_LEFT) keys.left = 0;
		if(kHeld & KEY_RIGHT) keys.right = 0;
		
		//gfxFlushBuffers();
		gspWaitForVBlank();
		gfxSwapBuffers();
		
		if(!aptMainLoop() || ((kHeld & KEY_START) && (kHeld & KEY_SELECT) && (kHeld & KEY_L) && (kHeld & KEY_R))) quit();
	#endif
	
	#ifdef LIN
		drawFramebuffer();
	#endif
	
	#ifdef PSP
		SceCtrlData pad;
		sceCtrlReadBufferPositive(&pad, 1);
		
		keys.keys1 = 0x0f;
		keys.keys2 = 0x0f;
		
		if(pad.Buttons & PSP_CTRL_SQUARE) keys.b = 0;
		if(pad.Buttons & PSP_CTRL_CROSS) keys.a = 0;
		if(pad.Buttons & PSP_CTRL_START) keys.start = 0;
		if(pad.Buttons & PSP_CTRL_SELECT) keys.select = 0;
		if(pad.Buttons & PSP_CTRL_UP) keys.up = 0;
		if(pad.Buttons & PSP_CTRL_DOWN) keys.down = 0;
		if(pad.Buttons & PSP_CTRL_LEFT) keys.left = 0;
		if(pad.Buttons & PSP_CTRL_RIGHT) keys.right = 0;
		
		sceDisplayWaitVblankStart();
	#endif
	
	interrupt.master = 0;
	writeShortToStack(registers.pc);
	registers.pc = 0x40;
	
	ticks += 12;
}
예제 #4
0
파일: main.c 프로젝트: nvella/luabox3ds
int main() {
	gfxInitDefault();
  consoleInit(GFX_TOP, &LuaBox_MainConsole); // Initialize console

	LuaBox_Running = 1;
	LuaBox_EventList = NULL; // Clear event list
	svcCreateMutex(&LuaBox_ConsoleMutex, 0); // Create the console mutex
	svcCreateMutex(&LuaBox_EventMutex, 0); // Create event list mutex
	svcCreateEvent(&LuaBox_EventSignal, 0); // Create event list mutex

	printf("%s version %s\ninitializing lua state...\n", LUABOX_NAME, LUABOX_VERSION);
	L = luaL_newstate();
	luaL_openlibs(L);

	// Install our apis
	lua_newtable(L);
	lua_pushstring(L, "exists");
	lua_pushcfunction(L, Api_fs_exists);
	lua_settable(L, -3);
	lua_setglobal(L, "fs");

	// Check if boot.lua exists
	FILE* fp = fopen("lua/bios.lua", "r");
	if(fp == NULL) {
		printf("lua/bios.lua does not exist\nplease create and place lua code in it for this to be useful.\npress start to exit.\n");
		while(1) {
			gspWaitForVBlank();
			hidScanInput();

			u32 kDown = hidKeysDown();

			if (kDown & KEY_START)
				break; // break in order to return to hbmenu

			// Flush and swap framebuffers
			gfxFlushBuffers();
			gfxSwapBuffers();
		}
		gfxExit();
		return 0;
	}
	fclose(fp);

	printf("initialized.\ninitializing keyboard...\n");
	SoftKb_Setup(GFX_BOTTOM, 4, 0);
	SoftKb_Draw();
	printf("initialized. use dpad and A button to type.\n");

	// Start lua thread.
	printf("starting lua thread...\n");
	Handle threadHandle;
	u32 *threadStack = memalign(32, LUABOX_THREAD_STACKSIZE);
	svcCreateThread(&threadHandle, LuaThread, 0, &threadStack[LUABOX_THREAD_STACKSIZE/4], 0x3f, 0);

	// Main loop
	while(LuaBox_Running) {
		gspWaitForVBlank();
		hidScanInput();

		u32 kDown = hidKeysDown();
		char out = SoftKb_Handle(kDown);
		if(out >= 32 || out == 10 || out == 7) {
			LuaBox_PushEvent(LUABOX_EVENT_CHAR, out);
		}

		if (kDown & KEY_START)
			break; // break in order to return to hbmenu

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();
	}

	gfxExit();
	return 0;
}
예제 #5
0
void pick_file(file_s *picked, const char *path) {

    picker = malloc(sizeof(picker_s));
    get_dir(path);

    // key repeat timer
    static time_t t_start = 0, t_end = 0, t_elapsed = 0;

    while (aptMainLoop()) {

        hidScanInput();
        u32 kHeld = hidKeysHeld();
        u32 kDown = hidKeysDown();

        if (hidKeysUp()) {
            time(&t_start); // reset held timer
        }

        if (kDown & KEY_DOWN) {
            picker->file_index++;
            if (picker->file_index >= picker->file_count)
                picker->file_index = 0;
            time(&t_start);
        } else if (kHeld & KEY_DOWN) {
            time(&t_end);
            t_elapsed = t_end - t_start;
            if (t_elapsed > 0) {
                picker->file_index++;
                if (picker->file_index >= picker->file_count)
                    picker->file_index = 0;
                svcSleep(100);
            }
        }

        if (kDown & KEY_UP) {
            picker->file_index--;
            if (picker->file_index < 0)
                picker->file_index = picker->file_count - 1;
            time(&t_start);
        } else if (kHeld & KEY_UP) {
            time(&t_end);
            t_elapsed = t_end - t_start;
            if (t_elapsed > 0) {
                picker->file_index--;
                if (picker->file_index < 0)
                    picker->file_index = picker->file_count - 1;
                svcSleep(100);
            }
        }

        if (kDown & KEY_A) {
            if (picker->file_count > 0) {
                int index = picker->file_index;
                if (!picker->files[index].isDir) {
                    if (confirm(0, "Launch \"%s\" ?", picker->files[index].name)) {
                        strncpy(picked->name, picker->files[index].name, 512);
                        strncpy(picked->path, picker->files[index].path, 512);
                        picked->isDir = picker->files[index].isDir;
                        picked->size = picker->files[index].size;
                        break;
                    }
                }
                else {
                    get_dir(picker->files[index].path);
                }
            }
        } else if (kDown & KEY_X) {
            int index = picker->file_index;
            if (!picker->files[index].isDir) {
                const char *ext = get_filename_ext(picker->files[index].name);
                if (strcasecmp(ext, "3dsx") == 0) {
                    if (confirm(3, "Add entry to boot menu: \"%s\" ?", picker->files[index].name)) {
                        if (config->count > CONFIG_MAX_ENTRIES - 1) {
                            debug("Maximum entries reached (%i)\n", CONFIG_MAX_ENTRIES);
                        } else if (configAddEntry(picker->files[index].name, picker->files[index].path, 0) == 0) {
                            debug("Added entry: %s\n", picker->files[index].name);
                        } else {
                            debug("Error adding entry: %s\n", picker->files[index].name);
                        }
                    }
                }
            }
        }
        else if (kDown & KEY_B) {
            // exit if we can't go back
            if (strlen(picker->now_path) <= 1)
                break;

            // remove slash if needed
            if (end_with(picker->now_path, '/'))
                picker->now_path[strlen(picker->now_path) - 1] = '\0';

            // build path
            char *slash = strrchr(picker->now_path, '/');
            if (slash == NULL)
                break;
            int len = (int) (slash - picker->now_path);
            picker->now_path[len] = '\0';

            // enter new dir
            get_dir(picker->now_path);
        }

        drawBg();
        drawTitle("*** Select a file ***");

        int i, y = 0;
        int page = picker->file_index / MAX_LINE;
        for (i = page * MAX_LINE; i < page * MAX_LINE + MAX_LINE; i++) {
            if (i >= picker->file_count)
                break;

            drawItemN(i == picker->file_index, 47, 16 * i, picker->files[i].name);
            if (i == picker->file_index && !picker->files[i].isDir) {
                drawInfo("Press (A) to launch\nPress (X) to add to boot menu");

            }
            y++;
        }
        gfxSwap();
    }
    free(picker);
}
예제 #6
0
파일: main.c 프로젝트: landm2000/sokoban
int main()
{
    char level_data_line[20*16];
    LEVELDATA this_level_data = {
        {&level_data_line[0],   &level_data_line[20], &level_data_line[40], &level_data_line[60],
         &level_data_line[80], &level_data_line[100],&level_data_line[120],&level_data_line[140],
         &level_data_line[160],&level_data_line[180],&level_data_line[200],&level_data_line[220],
         &level_data_line[240],&level_data_line[260],&level_data_line[280],&level_data_line[300]},
        19,11
    };
    // Initializations
    srvInit();  // services
    aptInit();  // applets
    hidInit();  // input
	gfxInitDefault();
//	gfxSet3D(true); // uncomment if using stereoscopic 3D
    gfxSetDoubleBuffering(GFX_TOP, true);
    gfxSetDoubleBuffering(GFX_BOTTOM, false);

    PrintConsole /*topScreen, */bottomScreen;
    consoleInit(GFX_BOTTOM, &bottomScreen);
//    consoleInit(GFX_TOP, &topScreen);
    clear_char_stack();
    int level = 0;
    int mode = MODE_INIT;
//    int mode_status  = 0;
    hcount = 0;

int timer = 0;
    // Main loop
    while (aptMainLoop())
    {
        hidScanInput();
        u32 kDown = hidKeysDown();
        u32 kUp   = hidKeysUp();
        u32 kHeld = hidKeysHeld();
        if (kDown & KEY_START){
            break; // break in order to return to hbmenu
        }

        if (mode == MODE_INIT){
//            consoleSelect(&topScreen);
//            printf("\033[2J");
            copyGame(level,&this_level_data);
            gspWaitForVBlank();
            printGame(&this_level_data);
            mode = MODE_GAME;
        }else if (mode == MODE_CLEAR){
            if ((kUp & KEY_A) || (kUp & KEY_B) || (kUp & KEY_X) || (kUp & KEY_Y)){
                level++;
                if (level >= sizeof(level_data)/sizeof(LEVELDATA)) {
                    mode = MODE_ALL_CLEAR;
                }else{
                    mode = MODE_INIT;
                }
            }
            if (level < sizeof(level_data)/sizeof(LEVELDATA)) {
                consoleSelect(&bottomScreen);
                printf("\033[2J");
                printf("\x1b[21;12HStage cleared!!");
                printf("\x1b[23;12HPush A to next Next Stage");
            }
        }else if (mode == MODE_ALL_CLEAR){
            level = 0;
            consoleSelect(&bottomScreen);
            printf("\033[2J");
            printf("\x1b[21;12HGame cleared!!!");
            printf("\x1b[23;12HPush Start to exit game");
            mode = MODE_NULL;
        }else if (mode == MODE_GAME){

        // Your code goes here


#ifdef DEBUG
consoleSelect(&bottomScreen);
if (timer%10==0){
//if (1    != 0){printf("\x1b[10;12HkUp  =%08x",(unsigned int)kUp);}
//if (1    != 0){printf("\x1b[11;12HkDown=%08x",(unsigned int)kDown);}
//if (1    != 0){printf("\x1b[12;12HkHeld=%08x",(unsigned int)kHeld);}
//printf("\x1b[22;12HKEY_CPAD_UP=%x",KEY_UP);
//printf("\x1b[23;12HKEY_CPAD_DN=%x",KEY_DOWN);
printf("\x1b[20;12HRest: [SELECT]");
printf("\x1b[22;12HExit: [START]");
printf("\x1b[24;12HTime: %08d",timer);
}
timer++;
#endif
            if (kDown != 0 || kHeld != 0){
                if (kDown & KEY_SELECT){
                    mode = MODE_INIT;
                }else{
                    moveMan(kDown, kHeld,level,&this_level_data);
                    if(checkCleared(&this_level_data,level)==0){ mode = MODE_CLEAR;}
                    gspWaitForVBlank();
                    draw_char_stack(this_level_data,spriteData, sizeof(spriteData)/sizeof(SPRITEDATA));
                }
            }else{
                gspWaitForVBlank();
            }
        }

        // Flush and swap framebuffers
        gfxFlushBuffers();
        gfxSwapBuffers();
    }

    gfxExit();
    hidExit();
    aptExit();
    srvExit();
	return 0;
}
예제 #7
0
int joystickInputScan(lua_State *L) { // love.joystick.scan()

	hidScanInput();
	
}
예제 #8
0
int main(int argc, char **argv)
{
	int abort=0;
	FILE *f = NULL;
	char *serverconfig_localpath = "server_config.xml";

	Result ret = 0;

	// Initialize services
	gfxInitDefault();

	consoleInit(GFX_TOP, NULL);

	printf("ctr-httpwn %s by yellows8.\n", VERSION);

	f = fopen(serverconfig_localpath, "rb");//Only run the below block when this file doesn't exist, which normally only happens when this app wasn't run before with the config file being downloaded successfully.
	if(f)
	{
		fclose(f);
	}
	else
	{
		printf("Please read the documentation before continuing:\nhttps://github.com/yellows8/ctr-httpwn\nPress A to continue, B to abort.\n");

		while(1)
		{
			gspWaitForVBlank();
			hidScanInput();
			if(hidKeysDown() & KEY_A)break;
			if(hidKeysDown() & KEY_B)
			{
				abort = 1;
				break;
			}
		}
	}

	if(!abort)
	{
		ret = httpwn_setup(serverconfig_localpath);

		if(ret==0)printf("Done.\n");
	}

	if(ret==0xC920181A)printf("This error means the HTTP sysmodule crashed.\n");
	if(ret!=0)printf("An error occured. If this is an actual issue not related to user failure, please report this to here if it persists(or comment on an already existing issue if needed), with a screenshot: https://github.com/yellows8/ctr-httpwn/issues\n");

	printf("Press the START button to exit.\n");
	// Main loop
	while (aptMainLoop())
	{
		gspWaitForVBlank();
		hidScanInput();

		u32 kDown = hidKeysDown();
		if (kDown & KEY_START)
			break; // break in order to return to hbmenu
	}

	// Exit services
	gfxExit();
	return 0;
}
예제 #9
0
int menu_more() {

    menu_index = 0;

    while (aptMainLoop()) {

        hidScanInput();
        u32 kDown = hidKeysDown();

        if (kDown & KEY_DOWN) {
            menu_index++;
            if (menu_index >= menu_count)
                menu_index = 0;
        }

        if (kDown & KEY_UP) {
            menu_index--;
            if (menu_index < 0)
                menu_index = menu_count - 1;
        }

        if (kDown & KEY_A) {
            if (menu_index == 0 && menu_choose() == 0) {
                return 0;
            } else if (menu_index == 1 && menu_netloader() == 0) {
                return 0;
            } else if (menu_index == 2) {
                menu_config();
            } else if (menu_index == 3) {
                reboot();
            } else if (menu_index == 4) {
                poweroff();
            }
        }

        if (kDown & KEY_B) {
            return -1;
        }

        gfxClear();
        gfxDrawText(GFX_TOP, GFX_LEFT, &fontDefault, "*** Select an option ***", 140, 20);

        int minX = 16;
        int maxX = 400 - 16;
        int minY = 32;
        int maxY = 240 - 16;
        drawRect(GFX_TOP, GFX_LEFT, minX, minY, maxX, maxY, 0xFF, 0xFF, 0xFF);
        minY += 20;

        int i;
        for (i = 0; i < menu_count; i++) {
            if (i >= menu_count) break;

            if (i == menu_index) {
                gfxDrawRectangle(GFX_TOP, GFX_LEFT, (u8[]) {
                    0xDC, 0xDC, 0xDC
                }, minX + 4, minY + (16 * i), maxX - 23,
                15);
                gfxDrawText(GFX_TOP, GFX_LEFT, &fontSelected, menu_item[i], minX + 6, minY + (16 * i));
            }
            else
                gfxDrawText(GFX_TOP, GFX_LEFT, &fontDefault, menu_item[i], minX + 6, minY + (16 * i));
        }
예제 #10
0
파일: main.cpp 프로젝트: Hikiruka/coffei
int main(int argc, char **argv)
{
	srvInit();	
	aptInit();
	gfxInit();
	acInit();
	initCfgu();
	ptmInit();
	hidInit(NULL);
	irrstInit(NULL);
	fsInit();
	hbInit();
	Handle fileHandle;
	u64 size;
	u32 bytesRead;
	int restore;
	
	// Set main script
	char path[256];
	if (argc > 0){	
		int latest_slash = 0;
		int i=5;
		while (argv[0][i]  != '\0'){
		if (argv[0][i] == '/'){
		latest_slash = i;
		}
		i++;
		}
		strcpy(path,&argv[0][5]);
		path[latest_slash-5] = 0;
		strcpy(start_dir,path);
		strcpy(cur_dir,path); // Set current dir
	}else{
		strcpy(start_dir,"/");
		strcpy(cur_dir,"/"); // Set current dir for GW Mode
	}
		
	while(aptMainLoop())
	{
		restore=0;		
		char error[256];
		
		errMsg = runScript((const char*)index_lua, true);
		
		if (errMsg != NULL);
                {
				// Fake error to force interpreter shutdown
				if (strstr(errMsg, "lpp_exit_04")){
					break;
				}
				
				strcpy(error,"Error: ");
				strcat(error,errMsg);
				strcat(error,"\n\nPress A to restart\nPress B to exit");
				}

						while (restore==0){
							gspWaitForVBlank();
							RefreshScreen();
							ClearScreen(0);
							ClearScreen(1);
							DebugOutput(error);
							hidScanInput();
							if(hidKeysDown() & KEY_A){
								strcpy(cur_dir,start_dir);
								restore=1;
							}else if(hidKeysDown() & KEY_B){
								restore=2;
							}
							gfxFlushBuffers();
							gfxSwapBuffers();
						}
						if (restore==2){
							break;
						}
	}
	
	fsExit();
	irrstExit();
	hidExit();
	ptmExit();
	hbExit();
	acExit();
	exitCfgu();
	gfxExit();
	aptExit();
	srvExit();

	return 0;
}
예제 #11
0
Result httpwn_setup(char *serverconfig_localpath)
{
	Result ret = 0;
	u64 http_sysmodule_titleid = 0x0004013000002902ULL;
	AM_TitleEntry title_entry;

	u8 *cert = (u8*)builtin_rootca_der;
	u32 certsize = builtin_rootca_der_size;

	u8 *filebuffer;
	u32 filebuffer_size = 0x100000;
	u32 statuscode = 0;

	configctx config;
	targeturlctx *first_targeturlctx = NULL;

	FILE *f;

	memset(&config, 0, sizeof(configctx));
	config.first_targeturlctx = &first_targeturlctx;

	ret = amInit();
	if(ret!=0)
	{
		printf("Failed to initialize AM: 0x%08x.\n", (unsigned int)ret);
		if(ret==0xd8e06406)
		{
			printf("The AM service is inaccessible. With the *hax payloads this should never happen. This is normal with plain ninjhax v1.x: this app isn't usable from ninjhax v1.x without any further hax.\n");
		}
		return ret;
	}

	ret = AM_ListTitles(0, 1, &http_sysmodule_titleid, &title_entry);
	amExit();
	if(ret!=0)
	{
		printf("Failed to get the HTTP sysmodule title-version: 0x%08x.\n", (unsigned int)ret);
		return ret;
	}

	http_codebin_buf = NULL;
	http_codebin_buf32 = NULL;
	http_codebin_size = 0;

	ret = loadcodebin(http_sysmodule_titleid, MEDIATYPE_NAND, &http_codebin_buf, &http_codebin_size);
	if(R_FAILED(ret))
	{
		printf("Failed to load the HTTP sysmodule codebin: 0x%08x.\n", (unsigned int)ret);
		return ret;
	}

	http_codebin_buf32 = (u32*)http_codebin_buf;

	ret = httpcInit(0x1000);
	if(ret!=0)
	{
		printf("Failed to initialize HTTPC: 0x%08x.\n", (unsigned int)ret);
		if(ret==0xd8e06406)
		{
			printf("The HTTPC service is inaccessible. With the *hax payload this may happen if the process this app is running under doesn't have access to that service. Please try rebooting the system, boot *hax payload, then directly launch the app.\n");
		}

		free(http_codebin_buf);

		return ret;
	}

	filebuffer = malloc(filebuffer_size);
	if(filebuffer==NULL)
	{
		printf("Failed to allocate the config filebuffer.\n");
		ret = -2;
		httpcExit();
		free(http_codebin_buf);
		return ret;
		
	}
	memset(filebuffer, 0, filebuffer_size);

	printf("Downloading config...\n");
	ret = download_config("https://yls8.mtheall.com/ctr-httpwn/config.php", cert, certsize, filebuffer, filebuffer_size-1, &statuscode);
	if(ret!=0)
	{
		printf("Config downloading failed: 0x%08x.\n", (unsigned int)ret);

		if(statuscode==500)
		{
			printf("HTTP status-code 500 was returned, server reply:\n%s\n", (char*)filebuffer);
		}

		f = fopen(serverconfig_localpath, "rb");
		if(f)
		{
			printf("Use the cached server_config from SD instead?\nPress the A button to continue, B to abort.\n");
			while(1)
			{
				gspWaitForVBlank();
				hidScanInput();
				if(hidKeysDown() & KEY_A)break;
				if(hidKeysDown() & KEY_B)
				{
					fclose(f);
					httpcExit();
					free(http_codebin_buf);
					return ret;
				}
			}

			memset(filebuffer, 0, filebuffer_size);
			fread(filebuffer, 1, filebuffer_size-1, f);
			fclose(f);
		}
		else
		{
			httpcExit();
			free(http_codebin_buf);
			return ret;
		}
	}
	else
	{
		unlink(serverconfig_localpath);
		f = fopen(serverconfig_localpath, "wb");
		if(f)
		{
			fwrite(filebuffer, 1, strlen((char*)filebuffer), f);
			fclose(f);
		}
	}

	ret = config_parse(&config, (char*)filebuffer);

	if(ret==0)
	{
		if(title_entry.version != 13318)
		{
			printf("The installed HTTP sysmodule version(v%u) is not supported.", title_entry.version);
			if(config.incompatsysver_message[0])printf(" %s", config.incompatsysver_message);
			printf("\n");

			httpcExit();
			free(http_codebin_buf);
			free(filebuffer);

			return -1;
		}

		if(display_config_message(&config, "Message from the server:"))
		{
			httpcExit();
			free(http_codebin_buf);
			free(filebuffer);
			return 0;
		}
	}

	if(ret==0)
	{
		f = fopen("user_config.xml", "rb");
		if(f)
		{
			printf("Loading+parsing user_config.xml since it exists on SD...\n");

			memset(filebuffer, 0, filebuffer_size);
			fread(filebuffer, 1, filebuffer_size-1, f);
			fclose(f);

			ret = config_parse(&config, (char*)filebuffer);

			if(ret==0)
			{
				if(display_config_message(&config, "Message from the user_config:"))
				{
					httpcExit();
					free(http_codebin_buf);
					free(filebuffer);
					return 0;
				}
			}
		}
	}

	if(ret!=0)
	{
		printf("Config parsing failed: 0x%08x.\n", (unsigned int)ret);
		httpcExit();
		free(http_codebin_buf);
		free(filebuffer);
		return ret;
	}

	f = fopen("user_nim_rootcertchain_rootca.der", "rb");
	if(f)
	{
		printf("Loading user_nim_rootcertchain_rootca.der since it exists on SD, which will be used instead of the built-in ctr-httpwn cert...\n");

		memset(filebuffer, 0, filebuffer_size);
		certsize = fread(filebuffer, 1, filebuffer_size, f);
		fclose(f);

		cert = filebuffer;
	}

	printf("Preparing the haxx...\n");
	ret = http_haxx("http://localhost/", cert, certsize, first_targeturlctx);//URL doesn't matter much since this won't actually be requested over the network.
	config_freemem(&config);
	httpcExit();
	free(http_codebin_buf);
	free(filebuffer);
	if(ret!=0)
	{
		printf("Haxx setup failed: 0x%08x.\n", (unsigned int)ret);
		return ret;
	}

	return ret;
}
예제 #12
0
파일: main.c 프로젝트: zoltx23/3Damnesic
int main(int argc, char *argv[])
{
//    char filename[]="/test400x240-mpeg4-witch.mp4";
//    char filename[]="/test400x240-witch.mp4";
//    char filename[]="/test800x400-witch-900kbps.mp4";
//    char filename[]="/test800x400-witch-1pass.mp4";
//    char filename[]="/test800x400-witch.mp4";
//    char filename[]="/test800x480-witch-mpeg4.mp4";
//    char filename[]="/test320x176-karanokyoukai.mp4";
    char filename[] = "/test.mp4";

    MovieState mvS;

    initServices();

    // Register all formats and codecs
    av_register_all();
    av_log_set_level(AV_LOG_INFO);


    printf("Press start to open the file\n");
    waitForStart();
    int ret = setup(&mvS, filename);
    if (ret)
    {
        waitForStartAndExit();
        return -1;
    }

    printf("Press start to decompress\n");
    waitForStart();
    // Read frames and save first five frames to disk
    int i = 0;
    int frameFinished;

    u64 timeBeginning, timeEnd;
    u64 timeBefore, timeAfter;
    u64 timeDecodeTotal = 0, timeScaleTotal = 0, timeDisplayTotal = 0;

    timeBefore = osGetTime();
    timeBeginning = timeBefore;
    bool stop = false;

    while (av_read_frame(mvS.pFormatCtx, &mvS.packet) >= 0 && !stop)
    {
        // Is this a packet from the video stream?
        if (mvS.packet.stream_index == mvS.videoStream)
        {

            /*********************
             * Decode video frame
             *********************/

            int err = avcodec_decode_video2(mvS.pCodecCtx, mvS.pFrame, &frameFinished, &mvS.packet);
            if (err <= 0)printf("decode error\n");
            // Did we get a video frame?
            if (frameFinished)
            {
                err = av_frame_get_decode_error_flags(mvS.pFrame);
                if (err)
                {
                    char buf[100];
                    av_strerror(err, buf, 100);
                }
                timeAfter = osGetTime();
                timeDecodeTotal += timeAfter - timeBefore;

                /*******************************
                 * Conversion of decoded frame
                 *******************************/
                timeBefore = osGetTime();
                colorConvert(&mvS);
                timeAfter = osGetTime();

                /***********************
                 * Display of the frame
                 ***********************/
                timeScaleTotal += timeAfter - timeBefore;
                timeBefore = osGetTime();

                if (mvS.renderGpu)
                {
                    gpuRenderFrame(&mvS);
                    gpuEndFrame();
                }
                else display(mvS.outFrame);

                timeAfter = osGetTime();
                timeDisplayTotal += timeAfter - timeBefore;

                ++i;//New frame

                hidScanInput();
                u32 kDown = hidKeysDown();
                if (kDown & KEY_START)
                    stop = true; // break in order to return to hbmenu
                if (i % 50 == 0)printf("frame %d\n", i);
                timeBefore = osGetTime();
            }

        }

        // Free the packet that was allocated by av_read_frame
        av_free_packet(&mvS.packet);
    }
    timeEnd = timeBefore;

    tearup(&mvS);

    printf("Played %d frames in %f s (%f fps)\n",
           i, (timeEnd - timeBeginning) / 1000.0,
           i / ((timeEnd - timeBeginning) / 1000.0));
    printf("\tdecode:\t%llu\t%f perframe"
           "\n\tscale:\t%llu\t%f perframe"
           "\n\tdisplay:\t%llu\t%f perframe\n",
           timeDecodeTotal, timeDecodeTotal / (double) i,
           timeScaleTotal, timeScaleTotal / (double) i,
           timeDisplayTotal, timeDisplayTotal / (double) i);

    waitForStartAndExit();
    return 0;
}
예제 #13
0
int main() 
{
	int i, x, y;
	
	touchPosition lastTouch;
	u32 repeatkeys = 0;
	int repeatstate = 0;
	int repeatcount = 0;
	
	running = 0;
	pause = 0;
	exitemu = 0;
	
	
		
	PPU_Init();
	
	
	srvInit();
		
	aptInit();
	aptOpenSession();
	APT_SetAppCpuTimeLimit(NULL, 30); // enables syscore usage
	aptCloseSession();

	gfxInit();
	hidInit(NULL);
	fsInit();
	
	GPU_Init(NULL);
	gpuCmdSize = 0x40000;
	gpuCmd = (u32*)linearAlloc(gpuCmdSize*4);
	GPU_Reset(gxCmdBuf, gpuCmd, gpuCmdSize);
	
	shader = SHDR_ParseSHBIN((u32*)blarg_shbin, blarg_shbin_size);
	
	GX_SetMemoryFill(gxCmdBuf, (u32*)gpuOut, 0x404040FF, (u32*)&gpuOut[0x2EE00], 0x201, (u32*)gpuDOut, 0x00000000, (u32*)&gpuDOut[0x2EE00], 0x201);
	gfxSwapBuffersGpu();
	
	UI_SetFramebuffer(gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL));
	
	BorderTex = (u32*)linearAlloc(512*256*4);
	MainScreenTex = (u32*)linearAlloc(512*256*4);
	SubScreenTex = (u32*)linearAlloc(512*256*4);
	BrightnessTex = (u8*)linearAlloc(8*256);
	
	borderVertices = (float*)linearAlloc(5*3 * 2 * sizeof(float));
	screenVertices = (float*)linearAlloc(7*3 * 2 * sizeof(float));
	
	float* fptr = &vertexList[0];
	for (i = 0; i < 5*3*2; i++) borderVertices[i] = *fptr++;
	for (i = 0; i < 7*3*2; i++) screenVertices[i] = *fptr++;
	

	sdmcArchive = (FS_archive){0x9, (FS_path){PATH_EMPTY, 1, (u8*)""}};
	FSUSER_OpenArchive(NULL, &sdmcArchive);
	
	if (!LoadBorder("/blargSnesBorder.bmp"))
		CopyBitmapToTexture(defaultborder, BorderTex, 400, 240, 0xFF, 0, 64, true);
		
	CopyBitmapToTexture(screenfill, PPU_MainBuffer, 256, 224, 0, 16, 64, false);
	memset(PPU_SubBuffer, 0, 256*256*4);
	memset(PPU_Brightness, 0xFF, 224);
	
	UI_Switch(&UI_ROMMenu);
	
	svcCreateEvent(&SPCSync, 0);
	
	aptSetupEventHandler();

	
	APP_STATUS status;
	while((status = aptGetStatus()) != APP_EXITING)
	{
		if(status == APP_RUNNING)
		{
			svcSignalEvent(SPCSync);
			
			hidScanInput();
			u32 press = hidKeysDown();
			u32 held = hidKeysHeld();
			u32 release = hidKeysUp();
			
			GPUCMD_SetBuffer(gpuCmd, gpuCmdSize, 0);
			RenderTopScreen();
			GPUCMD_Finalize();
			GPUCMD_Run(gxCmdBuf);
			
			if (running)
			{
				// emulate
				
				CPU_Run(); // runs the SNES for one frame. Handles PPU rendering.
				
				// SRAM autosave check
				// TODO: also save SRAM under certain circumstances (pausing, returning to home menu, etc)
				framecount++;
				if (!(framecount & 7))
					SNES_SaveSRAM();
			}
			else
			{
				// update UI
				
				if (held & KEY_TOUCH)
				{
					hidTouchRead(&lastTouch);
					UI_Touch(true, lastTouch.px, lastTouch.py);
					held &= ~KEY_TOUCH;
				}
				else if (release & KEY_TOUCH)
				{
					UI_Touch(false, lastTouch.px, lastTouch.py);
					release &= ~KEY_TOUCH;
				}
				
				if (press)
				{
					UI_ButtonPress(press);
					
					// key repeat
					repeatkeys = press & (KEY_UP|KEY_DOWN|KEY_LEFT|KEY_RIGHT);
					repeatstate = 1;
					repeatcount = 15;
				}
				else if (held == repeatkeys)
				{
					repeatcount--;
					if (!repeatcount)
					{
						repeatcount = 7;
						if (repeatstate == 2)
							UI_ButtonPress(repeatkeys);
						else
							repeatstate = 2;
					}
				}
			}
			
			UI_SetFramebuffer(gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL));
			UI_Render();
			
			/*GPUCMD_SetBuffer(gpuCmd, gpuCmdSize, 0);
			RenderTopScreen();
			GPUCMD_Finalize();
			GPUCMD_Run(gxCmdBuf);*/
			
			// flush the bottomscreen cache while the PICA200 is busy rendering
			GSPGPU_FlushDataCache(NULL, gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL), 0x38400);
			
			// wait for the PICA200 to finish drawing
			gspWaitForP3D();
			
			// copy new screen textures
			// SetDisplayTransfer with flags=2 converts linear graphics to the tiled format used for textures
			GX_SetDisplayTransfer(gxCmdBuf, PPU_MainBuffer, 0x01000200, MainScreenTex, 0x01000200, 0x2);
			gspWaitForPPF();
			GX_SetDisplayTransfer(gxCmdBuf, PPU_SubBuffer, 0x01000200, SubScreenTex, 0x01000200, 0x2);
			gspWaitForPPF();
			
			// copy brightness.
			// TODO do better
			u8* bptr = BrightnessTex;
			for (i = 0; i < 224;)
			{
				u32 pixels = *(u32*)&PPU_Brightness[i];
				i += 4;
				
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 2;
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 6;
				
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 2;
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 22;
			}
			
			// transfer the final color buffer to the LCD and clear it
			// we can mostly overlap those two operations
			GX_SetDisplayTransfer(gxCmdBuf, gpuOut, 0x019001E0, (u32*)gfxGetFramebuffer(GFX_TOP, GFX_LEFT, NULL, NULL), 0x019001E0, 0x01001000);
			svcSleepThread(20000);
			GX_SetMemoryFill(gxCmdBuf, gpuOut, 0x404040FF, &gpuOut[0x2EE00], 0x201, gpuDOut, 0x00000000, &gpuDOut[0x2EE00], 0x201);
			gspWaitForPPF();
			gspWaitForPSC0();

			gspWaitForEvent(GSPEVENT_VBlank0, false);
			gfxSwapBuffersGpu();
		}
		else if(status == APP_SUSPENDING)
예제 #14
0
//----------------------------------------------------------------------------
int main(int argc, char **argv) {
//----------------------------------------------------------------------------

	PrintConsole topScreen;
	ndspWaveBuf waveBuf[2];

	gfxInitDefault();

	consoleInit(GFX_TOP, &topScreen);

	consoleSelect(&topScreen);

	printf("libctru streaming audio\n");
	
	
	
	stb_vorbis_info info;
	int error;


      vorbisFile = stb_vorbis_open_filename("/mau5.ogg", &error, NULL);
      info = stb_vorbis_get_info(vorbisFile);
      Samples = info.sample_rate;
   
	

	u32 *audioBuffer = (u32*)linearAlloc(Samples*sizeof(s16)*2);

	bool fillBlock = false;

	ndspInit();

	ndspSetOutputMode(NDSP_OUTPUT_STEREO);

	ndspChnSetInterp(0, NDSP_INTERP_LINEAR);
	ndspChnSetRate(0, Samples);
	ndspChnSetFormat(0, NDSP_FORMAT_STEREO_PCM16);

	float mix[12];
	memset(mix, 0, sizeof(mix));
	mix[0] = 1.0;
	mix[1] = 1.0;
	ndspChnSetMix(0, mix);

	int note = 4;

	memset(waveBuf,0,sizeof(waveBuf));
	waveBuf[0].data_vaddr = &audioBuffer[0];
	waveBuf[0].nsamples = Samples;
	waveBuf[1].data_vaddr = &audioBuffer[Samples];
	waveBuf[1].nsamples = Samples;

	ndspChnWaveBufAdd(0, &waveBuf[0]);
	ndspChnWaveBufAdd(0, &waveBuf[1]);

	printf("Press up/down to change tone\n");

	
	
	
	
	
	
	while(aptMainLoop()) {

		gfxSwapBuffers();
		gfxFlushBuffers();
		gspWaitForVBlank();

		hidScanInput();
		u32 kDown = hidKeysDown();

		if (kDown & KEY_START)
			break; // break in order to return to hbmenu


		if (waveBuf[fillBlock].status == NDSP_WBUF_DONE) {

			fill_buffer(waveBuf[fillBlock].data_pcm16, waveBuf[fillBlock].nsamples);

			ndspChnWaveBufAdd(0, &waveBuf[fillBlock]);

			fillBlock = !fillBlock;
		}
	}

	ndspExit();

	linearFree(audioBuffer);

	gfxExit();
	return 0;
}
예제 #15
0
int main() {

	L = luaL_newstate();
	luaL_openlibs(L);
	luaL_requiref(L, "love", initLove, 1);

	sf2d_init(); // 2D Drawing lib.
	sftd_init(); // Text Drawing lib.
	cfguInit();
	ptmuInit();

	// consoleInit(GFX_BOTTOM, NULL);

	sf2d_set_clear_color(RGBA8(0x0, 0x0, 0x0, 0xFF)); // Reset background color.

	osSetSpeedupEnable(true); // Enables CPU speedup for a free performance boost.

	// Detect if we are running on a .cia, because if we are
	// we load from RomFS rather than the SD Card.
	// TODO: Load RomFS from .3dsx's aswell.

	Result rc = romfsInit();

	romfsExists = (rc) ? false : true;

	// Change working directory

	if (romfsExists) {

		chdir("romfs:/");

	} else {

		char cwd[256];
		getcwd(cwd, 256);
		char newCwd[261];

		strcat(newCwd, cwd);
		strcat(newCwd, "game");
		chdir(newCwd);

	}

	luaL_dobuffer(L, boot_lua, boot_lua_size, "boot"); // Do some setup Lua side.

	// If main.lua exists, execute it.
	// If not then just load the nogame screen.

	if (fileExists("main.lua")) {
		if (luaL_dofile(L, "main.lua")) displayError();
	} else {
		if (luaL_dobuffer(L, nogame_lua, nogame_lua_size, "nogame")) displayError();
	}
	
	if (luaL_dostring(L, "love.timer.step()")) displayError();

	if (luaL_dostring(L, "if love.load then love.load() end")) displayError();

	while (aptMainLoop()) {

		if (shouldQuit) {

			if (forceQuit) break;

			bool shouldAbort = false;

			// lua_getfield(L, LUA_GLOBALSINDEX, "love");
			// lua_getfield(L, -1, "quit");
			// lua_remove(L, -2);

			// if (!lua_isnil(L, -1)) {

			// 	lua_call(L, 0, 1);
			// 	shouldAbort = lua_toboolean(L, 1);
			// 	lua_pop(L, 1);

			// }; TODO: Do this properly.

			if (luaL_dostring(L, "if love.quit then love.quit() end")) displayError();

			if (!shouldAbort && !errorOccured) break;

		} // Quit event

		if (!errorOccured) {

			if (luaL_dostring(L,
				"love.keyboard.scan()\n"
				"love.timer.step()\n"
				"if love.update then love.update(love.timer.getDelta()) end")) {
					displayError();
			}

			// Top screen
			// Left side

			sf2d_start_frame(GFX_TOP, GFX_LEFT);

				if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError();

			sf2d_end_frame();

			// Right side

			if (is3D) {

				sf2d_start_frame(GFX_TOP, GFX_RIGHT);

					if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError();

				sf2d_end_frame();

			}

			// Bot screen

			sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);

				if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError();

			sf2d_end_frame();

			luaL_dostring(L, "love.graphics.present()");

		} else {

			hidScanInput();
			u32 kTempDown = hidKeysDown();
			if (kTempDown & KEY_START) {
				forceQuit = true;
				shouldQuit = true;
			}

			char *errMsg = lua_tostring(L, -1);

			sf2d_start_frame(GFX_TOP, GFX_LEFT);

				lua_getfield(L, LUA_GLOBALSINDEX, "love");
				lua_getfield(L, -1, "errhand");
				lua_remove(L, -2);

				if (!lua_isnil(L, -1)) {

					lua_pushstring(L, errMsg);
					lua_call(L, 1, 0);

				}

			sf2d_end_frame();

			sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);

				lua_getfield(L, LUA_GLOBALSINDEX, "love");
				lua_getfield(L, -1, "errhand");
				lua_remove(L, -2);

				if (!lua_isnil(L, -1)) {

					lua_pushstring(L, errMsg);
					lua_call(L, 1, 0);

				}

			sf2d_end_frame();

			luaL_dostring(L, "love.graphics.present()");

		}

	}

	luaL_dostring(L, "love.audio.stop()");

	lua_close(L);

	sftd_fini();
	sf2d_fini();
	cfguExit();
	ptmuExit();

	if (soundEnabled) ndspExit();
	if (romfsExists) romfsExit();

	return 0;

}
예제 #16
0
파일: main.c 프로젝트: wwylele/ctrhwtest
int main(int argc, char **argv){

    // Initialize services
    gfxInitDefault();

    //Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one
    consoleInit(GFX_TOP, NULL);


    int alevel=0, glevel = 0;

    //print GyroscopeRawToDpsCoefficient
    float gyroCoef;
    HIDUSER_GetGyroscopeRawToDpsCoefficient_(&gyroCoef);
    printf("\x1b[0;0HGyroCoef:%f", gyroCoef);

    //print GyroscopeLowCalibrateParam
    u8 Calibrate[20];
    HIDUSER_GetGyroscopeLowCalibrateParam(Calibrate);
    for(int i = 0; i<3; ++i){
        printf("\x1b[%d;0HGyroCalibrate(%d):", i+1, i+1);
        for(int j = 0; j<6; ++j){
            printf("%02X ", Calibrate[i*6+j]);
        }
    }


    printf("\x1b[13;0HPad:\n"); 
    printf("A:call EnableGyroscope\n");
    printf("B:call DisableGyroscope\n");
    printf("X:call EnableAccelerometer\n");
    printf("Y:call DisableAccelerometer\n");

    Result result=0;
    while(aptMainLoop()){
        hidScanInput();

        u32 kDown = hidKeysDown();

        if(kDown & KEY_START) break; // break in order to return to hbmenu
        if(kDown & KEY_A){
            ++glevel;
            result=HIDUSER_EnableGyroscope();
        }
        if(kDown & KEY_B){
            --glevel;
            result = HIDUSER_DisableGyroscope();
        }
        if(kDown & KEY_X){
            ++alevel;
            result = HIDUSER_EnableAccelerometer();
        }
        if(kDown & KEY_Y){
            --alevel;
            result = HIDUSER_DisableAccelerometer();
        }


        //Read gyro data
        myAngularRate gyro;
        hidGyroRead((angularRate*)&gyro);
        printf("\x1b[5;0Hgyro(level=%3d)%6d;%6d;%6d",glevel, gyro.x, gyro.y, gyro.z);

        //Read raw gyro data
        gyro = *(myAngularRate*)&hidSharedMem[86+6];
        printf("\x1b[6;0Hgyro(raw      )%6d;%6d;%6d", gyro.x, gyro.y, gyro.z);

        //Read accel data
        accelVector vector;
        hidAccelRead(&vector);
        printf("\x1b[7;0Hacce(level=%3d)%6d;%6d;%6d",alevel, vector.x, vector.y, vector.z);

        //Read raw accel
        vector = *(accelVector*)&hidSharedMem[66+6];
        printf("\x1b[8;0Hacce(raw      )%6d;%6d;%6d", vector.x, vector.y, vector.z);

        //test if gyro and accel events are activated
        printf("\x1b[9;0Hgyro event: %s", hidTryWaitForEvent(HIDEVENT_Gyro, 10000000) ? "true " : "false");
        printf("\x1b[10;0Hacce event: %s", hidTryWaitForEvent(HIDEVENT_Accel, 10000000)?"true ":"false");

        //print the last result of enable/disable gyroscope/accelerometer call
        printf("\x1b[11;0Henable/disable call result=%08lX", result);

        // Flush and swap framebuffers
        gfxFlushBuffers();
        gfxSwapBuffers();

        //Wait for VBlank
        gspWaitForVBlank();
    }


    // Exit services
    gfxExit();
    return 0;
}
예제 #17
0
파일: main.cpp 프로젝트: linoma/fb43ds
//---------------------------------------------------------------------------
int main(int argc, char** argv)
{
	touchPosition lastTouch;
	int frame=0,lp_frame=0;
	
	CWebRequest::InitializeClient();	
	gfxInitDefault();
	GPU_Init(NULL);
	gfxSet3D(false);
	srand(svcGetSystemTick());
	CFBClient::Initialize();
	while(aptMainLoop()){
		hidScanInput();		
		u32 press = hidKeysDown();
		u32 held = hidKeysHeld();
		u32 release = hidKeysUp();
		if((press & ~KEY_TOUCH)){
			CFBClient::onKeysPressEvent(press,1);
			hidCircleRead(&lcp);
		}
		if((release & ~KEY_TOUCH)){
			CFBClient::onKeysUpEvent(press,1);
			hidCircleRead(&lcp);
		}
		if (held & KEY_TOUCH){
			hidTouchRead(&lt);
			if(!lp_frame){
				lastTouch=lt;
				lp_frame++;
			}
			else{
				int i=0;
				
				if(abs(lt.px-lastTouch.px) <= 5){
					if(abs(lt.py-lastTouch.py) <= 5)
						i = 1;
				}
				if(i)
					lp_frame++;
				else{
					lp_frame = 0;
					CFBClient::onTouchEvent(&lt,2);
				}
			}
			if(!frame)
				CFBClient::onTouchEvent(&lt,1);
			frame++;
		}
		else{
			if(frame)
				CFBClient::onTouchEvent(&lt,lp_frame > 120 ? 8 : 4);
			frame = 0;
			lp_frame = 0;
		}
		CFBClient::main(0);
		gfxFlushBuffers();
		gfxSwapBuffers();
		gspWaitForVBlank();
	}
	CFBClient::Destroy();
	CWebRequest::DestroyClient();
	fsExit();
	hidExit();
	gfxExit();
	aptExit();
	srvExit();
	return 0;
}
예제 #18
0
파일: main.c 프로젝트: Cruel/DspDump
int main()
{
	Handle rsrc;
	bool failed = true;

	gfxInitDefault();
	consoleInit(GFX_TOP, NULL);

	printf("\x1b[10;10HFetching DSP component...\x1b[12;10H");

	rsrc = envGetHandle("hb:ndsp");
	if (!rsrc)
	{
		printf("\x1b[31;1mFailed\x1b[0m: Need to run using *hax 2.0+");
	}
	else do
	{
		Result rc;
		u32 len;
		void* bin;
		extern u32 fake_heap_end;
		char* filename = "sdmc:/3ds/dspfirm.cdc";

		u32 mapAddr = (fake_heap_end+0xFFF) &~ 0xFFF;
		rc = svcMapMemoryBlock(rsrc, mapAddr, 0x3, 0x3);
		if (R_FAILED(rc)) break;

		len = *(u32*)(mapAddr + 0x104);
		bin = malloc(len);
		if (bin)
			memcpy(bin, (void*)mapAddr, len);
		svcUnmapMemoryBlock(rsrc, mapAddr);
		if (!bin) break;

		FILE* file = fopen(filename, "wb");
		if (!file) break;
		fwrite(bin, 1, len, file);
		fclose(file);

		failed = false;
		printf("\x1b[32;1mDone\x1b[0m: No further steps needed!\n");
		free(bin);
	} while (0);

	if (rsrc && failed)
		printf("\x1b[31;1mFailed\x1b[0m: Unknown error. Try again.");

	printf("\x1b[28;15HPress START to exit.");

	while (aptMainLoop())
	{
		hidScanInput();
		u32 kDown = hidKeysDown();

		if (kDown & KEY_START)
			break;

		gfxFlushBuffers();
		gfxSwapBuffers();
		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}
예제 #19
0
int main(int argc, char **argv) {
#ifndef NO_3DS
	gfxInitDefault();

	//Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one
	consoleInit(GFX_TOP, NULL);
#else
#warning Compiling with NO_3DS!
#endif

printf("Hello!\n");

#if 0

	//Move the cursor to row 15 and column 19 and then prints "Hello World!"
	//To move the cursor you have to print "\x1b[r;cH", where r and c are respectively
	//the row and column where you want your cursor to move
	//The top screen has 30 rows and 50 columns
	//The bottom screen has 30 rows and 40 columns
	printf("\x1b[15;19HHello World!\n\n");

#endif

//test();
//while(1);

int mode = 0;
int ndigits = 2;
int decpt;
int sign;
char* buffer = (char*)malloc(128);

#ifndef NO_3DS
{

#if 0
static struct _reent re;

buffer = _dtoa_r(&re, 0.4, mode, ndigits, &decpt, &sign, &buffer);
printf("Got '%s'\n", buffer);

buffer = _dtoa_r(&re, 0.2, mode, ndigits, &decpt, &sign, &buffer);
printf("Got '%s'\n", buffer);
#endif

}
#endif

buffer = dtoa(0.2, mode, ndigits, &decpt, &sign, &buffer);
printf("Got '%s' (decpt: %d)\n", buffer, decpt);
while(1);

Bigint Sd;
Sd.wds = 1;
Sd.x[0] = 0xF00;
Bigint* S = &Sd;

int s5 = 0x7FFFFFFF;
S = pow5mult_nl (S, s5);

printf("Bye!");
while(1);

asm("nop\nnop\nnop\nnop\n");
while(1) {
  float sf = 1.0f;
  u32 f = *(u32*)&sf;
  for(unsigned int i = 0; i < 32; i++) {
    f = 1 << i;
    printf("%d: W %f\n", i, *(float*)&f);
  }
}

while(1);

#if 0

#if 0
  std::cout << "Works! " << 0.4f << std::endl;
  std::cout << "Crash! " << 0.3f << std::endl;
#else
//  printf("Works! %f", 0.4f);
//  printf("Crash! %f", 0.1375f);
#endif

	printf("\x1b[29;11HPress Start to exit.");

	// Main loop
	while (aptMainLoop())
	{
		//Scan all the inputs. This should be done once for each frame
		hidScanInput();

		//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
		u32 kDown = hidKeysDown();

		if (kDown & KEY_START) break; // break in order to return to hbmenu

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();

		//Wait for VBlank
		gspWaitForVBlank();
	}

	gfxExit();
#endif
	return 0;
}
예제 #20
0
파일: main.c 프로젝트: Parx-3DS/Parx-Pas
int main()
{
	gfxInitDefault();
        gfxSet3D(true); // uncomment if using stereoscopic 3D

        gfxFlushBuffers();

        transparent = BLACK;
	 gfxSetScreenFormat(GFX_TOP, GSP_BGR8_OES);
	 gfxSetScreenFormat(GFX_BOTTOM, GSP_BGR8_OES);
        InitParx(BLACK);
/*
	ParxLeft = gfxGetFramebuffer(GFX_TOP, GFX_LEFT, NULL, NULL); 
	ParxRight = gfxGetFramebuffer(GFX_TOP, GFX_RIGHT, NULL, NULL); 
	ParxBot = gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL); 

	ClrParx(ParxLeft, BLACK); 
	ClrParx(ParxRight, BLACK); 
	ClrParx(ParxBot, BLACK);
*/

	char* str[256];
        int l, k, j, i=20, posx = 100, posy = 100;
        TBGR rgbsam;
        TBGR rgb;
	u64 time; 
	u8* tempScr;
	bool Dbuf;	
	
	circlePosition pos;
	touchPosition touch;

	// Main loop
	while (aptMainLoop())
	{
//		gspWaitForVBlank();

//		  	ParxLeft = gfxGetFramebuffer(GFX_TOP, GFX_LEFT, NULL, NULL); 
//			ParxRight = gfxGetFramebuffer(GFX_TOP, GFX_RIGHT, NULL, NULL); 
//			ParxBot = gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL); 

		hidScanInput();              
		u32 kDown = hidKeysHeld();

         
		//Read the CirclePad position
		hidCircleRead(&pos);

		//Print the CirclePad position
//-		printf("\x1b[2;0H%04d; %04d", pos.dx, pos.dy);
		

		//Read the touch screen coordinates
		hidTouchRead(&touch);
		
		//Print the touch screen coordinates
//		printf("\x1b[2;0H%03d; %03d", touch.px, touch.py);
		

		if (kDown & KEY_START)
			break; // break in order to return to hbmenu
                if (kDown & KEY_A)
			{
                          CanvasString(ParxBot, CopyRight(), 10,10, LIGHT_GREEN);
			}
                if (kDown & KEY_B)
			{
                          time= osGetTime();
			
			rgb.r= 0xCC;
			rgb.g= 0x33;
			rgb.b= 0xCC;
			
                        for (k=0;k<400;k++)
                          for (l=0;l<240;l++)
{
  SetPixL(k,l,rgb); //TopLCD
  SetPixR(k,l,rgb);
  if (k<320) SetPixB(k,l,rgb); //BotLCD
}

time = osGetTime() - time; 
sprintf(str, "%i:ms ParxPro SetPix L/R/B,kdl", time);
CanvasString(ParxBot, str, 10,10, GREEN);  

			}
                if (kDown & KEY_X)
			{
                          TestPattern();
			}
                if (kDown & KEY_Y)
			{
			InitParx(BLACK);
		  	
//			  PasBotfill(ParxBot);
			rgb.r= 0xFF;
			rgb.g= 0x00;
			rgb.b= 0x8F;
			  PasClrSrc(ParxBot, rgb);
			  CanvasString(ParxBot, "InitParx", 10,10, GREEN);  
			}
                if(kDown & KEY_CPAD_DOWN)
                        {	     
			rgb.r= 0x00;
			rgb.g= 0x00;
			rgb.b= 0XFF;
			PasTopfill(ParxLeft, rgb);
			PasTopfill(ParxRight, rgb);
			}

                if(kDown & KEY_CPAD_UP) 
                        {	
                        
			rgb.r= 0xFF;
			rgb.g= 0x00;
			rgb.b= 0x00;		
			PasTopfill(ParxLeft, rgb);
			PasTopfill(ParxRight, rgb);
			}
                if(kDown & KEY_CPAD_RIGHT) 
                        {	
                        
			rgb.r= 0x00;
			rgb.g= 0xFF;
			rgb.b= 0x00;
time= osGetTime();
			PasTopfill(ParxLeft, rgb);
			PasTopfill(ParxRight, rgb);

time = osGetTime() - time; 
sprintf(str, "%i:ms L&R BGRTop,kdl", time);
CanvasString(ParxBot, str, 10,10, GREEN);  
			}

                if(kDown & KEY_CPAD_LEFT)
                        {
                        
			rgb.r= 0x00;
			rgb.g= 0x11;
			rgb.b= 0x00;
time= osGetTime();					
						
			HexTopfill(ParxLeft);
			HexTopfill(ParxRight);

time = osGetTime() - time; 
sprintf(str, "%i:ms L&R TopMapLED,kdl", time);
CanvasString(ParxBot, str, 10,10, GREEN);  
			}               
                if(kDown & KEY_R)
                        {	
                              	//InitBufSingle(BLACK);
                                ClrParx(ParxBot, BLACK);
                                //i of linearSpaceFree(); //no effect
                                //i of vramSpaceFree(); //reads as Zero 
                                //i of mappableSpaceFree(); //no change in alloc & free 
                                
                                sprintf(str, "v:%i  m:%i  l:%i", vramSpaceFree, mappableSpaceFree, linearSpaceFree);
				CanvasString(ParxBot, str, 0, 10, RED);
				
                                Topfill2;
                                sprintf(str, "v:%i  m:%i  l:%i", vramSpaceFree, mappableSpaceFree, linearSpaceFree);
				CanvasString(ParxBot, str, 0, 20, RED);
				
                               // Topfill3;
                               // sprintf(str, "Topfill3 Free :%i", vramSpaceFree);
				//CanvasString(ParxBot, str, 0, 40, RED);
				
                                //sprintf(str, "Topfill3 Free :%i", );
				//CanvasString(ParxBot, str, 0, 40, RED);
			}

                if(kDown & KEY_L) 
                        {	
                        	if (Dbuf) InitBufDub(BLACK); else InitBufSingle(BLACK);		
			        Topfill1;
                                ClrParx(ParxBot, BLACK);
                              //  sprintf(str, "Dergibal Rad:%i  X:%i  Y:%i", i, posx, posy);
                              
                        	if (Dbuf) CanvasString(ParxBot, "InitBufDub", 0, 40, RED); else
                        	CanvasString(ParxBot, "InitBufSingle", 0, 40, RED); (BLACK);	
                        	Dbuf = !Dbuf;
			}
                if(kDown & KEY_DUP)
                        {	
                        for (k=0;k<400;k++)
                          for (l=0;l<240;l++)
{
  if (k<320) PSetPixT(ParxRight,k,l, GetPixB(k,l));
} 

			}

                if(kDown & KEY_DDOWN)
                        {	
time= osGetTime();
			
			rgb.r= 0xCC;
			rgb.g= 0x11;
			rgb.b= 0xCC;
			
                        for (k=0;k<400;k++)
                          for (l=0;l<240;l++)
{
  PSetPixT(ParxRight,k,l, rgb); //TopLCD
  PSetPixT(ParxLeft,k,l, rgb);
  if (k<320) PSetPixB(ParxBot,k,l, rgb); //BotLCD
}

time = osGetTime() - time; 
sprintf(str, "%i:ms ParxPro,kdl", time);
CanvasString(ParxBot, str, 10,10, GREEN);  
		
			}                
		if(kDown & KEY_DRIGHT)
                        {

                         ClrParx(ParxBot, BLACK);    
                          
			rgb.r= 0xEE;
			rgb.g= 0x00;
			rgb.b= 0xCC;
		
time= osGetTime();			
                       for (k=0;k<400;k++)
                          for (l=0;l<240;l++) SetPixL(k,l,rgb); //TopLCD
time = osGetTime() - time; 
sprintf(str, "Left %i:ms ParxPro,kdl", time);
CanvasString(ParxBot, str, 10,10, LIGHT_GREEN); 

time= osGetTime();				
//ParxLeft = GetSrcL(-1); // good!!			
//tempScr = GetSrcL(0); // good!!	
//tempScr = GetSrcL(1); // good!!
//                       for (k=0;k<400;k++)
//                        { 
//                            ParxLeft = GetSrcL(-1); // good!!
//                          for (l=0;l<80;l++) PSetPixT(ParxRight,k,l, GetPixL(k,l)); // 
//       			    ParxLeft = GetSrcL(0); // good!!
//                          for (l=80;l<160;l++) PSetPixT(ParxRight,k,l, GetPixL(k,l));   		
//     			    ParxLeft = GetSrcL(1); // good!!
//                          for (l=160;l<240;l++) PSetPixT(ParxRight,k,l, GetPixL(k,l)); 
//                          //assignment to eg PSetPixT(GetSrcR(-1),k,l, GetPixL(k,l)) poops out                      
//                        }  
time = osGetTime() - time; 
sprintf(str, "ParxLeft = GetSrcL(-1&0&1); %i:ms ,kdl", time);
CanvasString(ParxBot, str, 10,20, LIGHT_GREEN); 

time= osGetTime();			
//SetSrcR(0,tempScr);	// No Good 

//SetSrcL(-1,ParxLeft);	// 
//sprintf(str, "SetSrcL(-1,ParxLeft); %i:ms ,kdl", time);
//CanvasString(ParxBot, str, 10,40, LIGHT_GREEN); 

//BufSub(-1);
//BufSub(-2);
//BufSub(-3);

//SetSrcL(-1,ParxLeft);	// 
sprintf(str, "SetSrcL(1,ParxLeft); %i:ms ,kdl", time);
CanvasString(ParxBot, str, 10,50, LIGHT_GREEN); 
//SetSrcR(0,ParxRight);	//
//sprintf(str, "SetSrcR(0,ParxRight) %i:ms ,kdl", time);
//CanvasString(ParxBot, str, 10,60, LIGHT_GREEN); 

                    //   for (k=0;k<400;k++)
                    //      for (l=0;l<240;l++) PSetPixT(GetSrcR(0),k,l,rgb); //GetSrcR(0) works                      
time = osGetTime() - time; 
sprintf(str, "SetSrc L&R(-1,(ParxLeft & ParxRight); %i:ms ,kdl", time);
CanvasString(ParxBot, str, 10,30, LIGHT_GREEN); 
			}

                if(kDown & KEY_DLEFT)
                        {				
                     //   SetTopFramebuffers(0);  
time= osGetTime();
			
                        for (k=0;k<400;k++)
                          for (l=0;l<240;l++)
{
  SetPix(ParxRight,k,l,BLACK);
  SetPix(ParxLeft,k,l,BLACK);
  if (k<320) SetPix(ParxBot,k,l,BLACK);
}

time = osGetTime() - time; 
sprintf(str, "%i:ms Parx-GDI,kdl", time);
CanvasString(ParxBot, str, 10,10, GREEN);  
		}
//gfxString(ParxRight, str, 30,30, 3, rgb); 
//gfxString(ParxLeft, str, 30,30, 3, rgb);   
//for (l=1;l<16;l++) print3d(rgb,10*l,10*l,l-1,3,str);



		//render rainbow
//		renderEffect();
		//copy buffer to lower screen (don't have to do it every frame)
//		memcpy(gfxGetFramebuffer(GFX_BOTTOM, GFX_BOTTOM, NULL, NULL), buffer, size);
		//wait & swap
//		gfxSwapBuffersGpu();
//		gspWaitForEvent(GSPGPU_EVENT_VBlank0, false);

		// Flush and swap framebuffers
	//	gfxFlushBuffers();
	//	gfxSwapBuffers();
        	RefreshBuffer();
		//Wait for VBlank
		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}
예제 #21
0
파일: main.c 프로젝트: iamn1ck/ctrrpc
/*----------------*/
int main(int argc, char *argv[])
{
    APP_STATUS status;

    srvInit();
    aptInit(APPID_APPLICATION);
    gfxInit();
    hidInit(NULL);
    fsInit();

    svcCreateEvent(&new_cmd_event, 0);
    svcCreateEvent(&cmd_done_event, 0);
    svcCreateThread(&thread, cmd_thread_func, 0x0,
                    (u32*)((char*)thread_stack + sizeof(thread_stack)),
                    0x31, 0xfffffffe);

    int where = 0;
    u32 ret = SOC_Initialize((u32*)0x08000000, 0x48000);

    if(ret == 0) {
        listen_socket = socket(AF_INET, SOCK_STREAM, 0);
        if(listen_socket == -1) {
            where = 1;
            ret = SOC_GetErrno();
        }
        else {
            u32 tmp = fcntl(listen_socket, F_GETFL);
            fcntl(listen_socket, F_SETFL, tmp | O_NONBLOCK);

            struct sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_port = __swap16(PORT);
            addr.sin_addr.s_addr = INADDR_ANY;

            ret = bind(listen_socket, (struct sockaddr *)&addr, sizeof(addr));
            if(ret != 0) {
                where = 2;
                ret = SOC_GetErrno();
            }
            else {
                ret = listen(listen_socket, 1);
                if(ret == -1) {
                    ret = SOC_GetErrno();
                    where = 3;
                }
            }
        }

    }

    u32 it = 0;
    int accept_errno = 0;
    int first = 1;


    while((status = aptGetStatus()) != APP_EXITING)
    {
        hidScanInput();
        consoleClear(&top);

        print(&top, "newver\n");
        print(&top, "ret: %08x, where: %d\n", ret, where);
        print(&top, "frame: %08x\n", it);
        u32 ip = gethostid();
        print(&top, "ip: %d.%d.%d.%d\n", ip & 0xFF, (ip>>8)&0xFF, (ip>>16)&0xFF, (ip>>24)&0xFF);
                
        if(accept_errno != 0) print(&top, "accept returned errno %d\n", accept_errno);

        if(!first) {
            int s = accept(listen_socket, NULL, NULL);
            if(s == -1) {
                int err = SOC_GetErrno();

                if(err != -EWOULDBLOCK)
                    accept_errno = err;
            }
            else {
                sock = s;
                conn_main();
                closesocket(sock);
            }
        }

        it++;
        first = 0;
        if(enable_draw)
            renderFrame(); 

        u32 keys = hidKeysUp();
        if(keys & KEY_A)
            break;
    }

    thread_exit = 1;
    svcSignalEvent(new_cmd_event);
    svcWaitSynchronization(thread, U64_MAX);
    svcCloseHandle(thread);

    svcCloseHandle(new_cmd_event);
    svcCloseHandle(cmd_done_event);

    SOC_Shutdown();
    fsExit();
    hidExit();
    gfxExit();
    aptExit();
    srvExit();
    return 0;
}
예제 #22
0
void I_StartTic (void)
{
  hidScanInput();
  I_GetInput();
  I_PollJoystick();
}
예제 #23
0
int main()
{
	httpcInit();

	gfxInitDefault();
	gfxSet3D(false);

	Result ret = filesystemInit();

	PrintConsole topConsole, bttmConsole;
	consoleInit(GFX_TOP, &topConsole);
	consoleInit(GFX_BOTTOM, &bttmConsole);

	consoleSelect(&topConsole);
	consoleClear();

	state_t current_state = STATE_NONE;
	state_t next_state = STATE_INITIAL;

	static char top_text[2048];
	top_text[0] = '\0';

	int selected_slot = 0;

	int firmware_version[firmware_length] = {0, 0, 9, 0, 0};
	int firmware_selected_value = 0;
	
	static char payload_name[256];
	u8* payload_buf = NULL;
	u32 payload_size = 0;

	while (aptMainLoop())
	{
		hidScanInput();
		if(hidKeysDown() & KEY_START)break;

		// transition function
		if(next_state != current_state)
		{
			switch(next_state)
			{
				case STATE_INITIAL:
					strcat(top_text, " Welcome to the oot3dhax installer! Please proceedwith caution, as you might lose data if you don't.You may press START at any time to return to menu.\n                            Press A to continue.\n\n");
					break;
				case STATE_SELECT_SLOT:
					strcat(top_text, " Please select the savegame slot oot3dhax will be\ninstalled to. D-Pad to select, A to continue.\n");
					break;
				case STATE_SELECT_FIRMWARE:
					strcat(top_text, "\n\n\n Please select your console's firmware version.\nOnly select NEW 3DS if you own a New 3DS (XL).\nD-Pad to select, A to continue.\n");
					break;
				case STATE_DOWNLOAD_PAYLOAD:
					getPayloadName(firmware_version, payload_name);
					sprintf(top_text, "%s\n\n\n Downloading payload... %s\n", top_text, payload_name);
					break;
				case STATE_INSTALL_PAYLOAD:
					strcat(top_text, " Installing payload...\n");
					break;
				case STATE_INSTALLED_PAYLOAD:
					strcat(top_text, " Done! oot3dhax was successfully installed.");
					break;
				case STATE_ERROR:
					strcat(top_text, " Looks like something went wrong. :(\n");
					break;
				default:
					break;
			}
			current_state = next_state;
		}

		consoleSelect(&topConsole);
		printf("\x1b[0;%dHoot3dhax installer", (50 - 17) / 2);
		printf("\x1b[1;%dHby smea, yellows8, phase, and meladroit\n\n\n", (50 - 38) / 2);
		printf(top_text);

		// state function
		switch(current_state)
		{
			case STATE_INITIAL:
				if(hidKeysDown() & KEY_A)next_state = STATE_SELECT_SLOT;
				break;
			case STATE_SELECT_SLOT:
				{
					if(hidKeysDown() & KEY_UP)selected_slot++;
					if(hidKeysDown() & KEY_DOWN)selected_slot--;
					if(hidKeysDown() & KEY_A)next_state = STATE_SELECT_FIRMWARE;

					if(selected_slot < 0) selected_slot = 0;
					if(selected_slot > 2) selected_slot = 2;

					printf((selected_slot >= 2) ? "                                             \n" : "                                            ^\n");
					printf("                            Selected slot: %d  \n", selected_slot + 1);
					printf((!selected_slot) ? "                                             \n" : "                                            v\n");
				}
				break;
			case STATE_SELECT_FIRMWARE:
				{
					if(hidKeysDown() & KEY_LEFT)firmware_selected_value--;
					if(hidKeysDown() & KEY_RIGHT)firmware_selected_value++;

					if(firmware_selected_value < 0) firmware_selected_value = 0;
					if(firmware_selected_value >= firmware_length) firmware_selected_value = firmware_length - 1;

					if(hidKeysDown() & KEY_UP)firmware_version[firmware_selected_value]++;
					if(hidKeysDown() & KEY_DOWN)firmware_version[firmware_selected_value]--;

					if(firmware_version[firmware_selected_value] < 0) firmware_version[firmware_selected_value] = 0;
					if(firmware_version[firmware_selected_value] >= firmware_num_values[firmware_selected_value]) firmware_version[firmware_selected_value] = firmware_num_values[firmware_selected_value] - 1;
					
					if(hidKeysDown() & KEY_A)next_state = STATE_DOWNLOAD_PAYLOAD;

					int offset = 28 + firmware_format_offsets[firmware_selected_value];
					printf((firmware_version[firmware_selected_value] < firmware_num_values[firmware_selected_value] - 1) ? "%*s^%*s" : "%*s-%*s", offset, " ", 50 - offset - 1, " ");
					printf("        Selected firmware: " "%s %s-%s-%s %s" "\n", firmware_labels[0][firmware_version[0]], firmware_labels[1][firmware_version[1]], firmware_labels[2][firmware_version[2]], firmware_labels[3][firmware_version[3]], firmware_labels[4][firmware_version[4]]);
					printf((firmware_version[firmware_selected_value] > 0) ? "%*sv%*s" : "%*s-%*s", offset, " ", 50 - offset - 1, " ");
				}
				break;
			case STATE_DOWNLOAD_PAYLOAD:
				{
					httpcContext context;
					static char url[512];
					sprintf(url, "http://smealum.github.io/ninjhax2/Pvl9iD2Im5/otherapp/%s.bin", payload_name);

					Result ret = httpcOpenContext(&context, url, 0);
					if(ret)
					{
						sprintf(status, "Failed to open http context\n    Error code: %08X", (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}

					ret = http_download(&context, &payload_buf, &payload_size);
					if(ret)
					{
						sprintf(status, "Failed to download payload\n    Error code: %08X", (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}

					next_state = STATE_INSTALL_PAYLOAD;
				}
				break;
			case STATE_INSTALL_PAYLOAD:
				{
					static char filename[128];
                    
                    sprintf(filename, "save0x.bin.%s", firmware_labels[4][firmware_version[4]]);
					read_payload(filename, save_buffer);
					sprintf(filename, "/save0%d.bin", selected_slot);
					Result ret = write_savedata(filename, save_buffer, save_size);
					if(ret)
					{
						sprintf(status, "Failed to install %s.\n    Error code: %08X", filename, (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}
				}

				{
					Result ret = write_savedata("/payload.bin", payload_buf, payload_size);
					if(ret)
					{
						sprintf(status, "Failed to install payload\n    Error code : %08X", (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}

					next_state = STATE_INSTALLED_PAYLOAD;
				}
				break;
			case STATE_INSTALLED_PAYLOAD:
				next_state = STATE_NONE;
				break;
			default:
				break;
		}

		consoleSelect(&bttmConsole);
		printf("\x1b[0;0H  \n Found a bug? Go to\n    https://github.com/meladroit/oot3dhax_installer/ \n\n  Current status:\n    %s\n", status);

		gspWaitForVBlank();
	}

	filesystemExit();

	gfxExit();
	httpcExit();
	return 0;
}
예제 #24
0
static void eventThreadFunc(void *arg) {
	OSystem_3DS *osys = (OSystem_3DS *)g_system;
	auto eventQueue = (Common::Queue<Common::Event> *)arg;
	
	uint32 touchStartTime = osys->getMillis();
	touchPosition lastTouch = {0, 0};
	bool isRightClick = false;
	float cursorX = 0;
	float cursorY = 0;
	float cursorDeltaX = 0;
	float cursorDeltaY = 0;
	int circleDeadzone = 20;
	int borderSnapZone = 6;
	Common::Event event;
	
	while (!osys->exiting) {
		do {
			osys->delayMillis(10);
		} while (osys->sleeping && !osys->exiting);
		
		hidScanInput();
		touchPosition touch;
		circlePosition circle;
		u32 held = hidKeysHeld();
		u32 keysPressed = hidKeysDown();
		u32 keysReleased = hidKeysUp();
		
		// C-Pad used to control the cursor
		hidCircleRead(&circle);
		if (circle.dx < circleDeadzone && circle.dx > -circleDeadzone)
			circle.dx = 0;
		if (circle.dy < circleDeadzone && circle.dy > -circleDeadzone)
			circle.dy = 0;
		cursorDeltaX = (0.0002f + config.sensitivity / 100000.f) * circle.dx * abs(circle.dx);
		cursorDeltaY = (0.0002f + config.sensitivity / 100000.f) * circle.dy * abs(circle.dy);
		
		// Touch screen events
		if (held & KEY_TOUCH) {
			hidTouchRead(&touch);
			if (config.snapToBorder) {
				if (touch.px < borderSnapZone)
					touch.px = 0;
				if (touch.px > 319 - borderSnapZone)
					touch.px = 319;
				if (touch.py < borderSnapZone)
					touch.py = 0;
				if (touch.py > 239 - borderSnapZone)
					touch.py = 239;
			}
			cursorX = touch.px;
			cursorY = touch.py;
			osys->transformPoint(touch);

			osys->warpMouse(touch.px, touch.py);
			event.mouse.x = touch.px;
			event.mouse.y = touch.py;
			
			if (keysPressed & KEY_TOUCH) {
				touchStartTime = osys->getMillis();
				isRightClick = (held & KEY_X || held & KEY_DUP);
				if (inputMode == MODE_DRAG) {
					event.type = isRightClick ? Common::EVENT_RBUTTONDOWN : Common::EVENT_LBUTTONDOWN;
					pushEventQueue(eventQueue, event);
				}
			} else if (touch.px != lastTouch.px || touch.py != lastTouch.py) {
				event.type = Common::EVENT_MOUSEMOVE;
				pushEventQueue(eventQueue, event);
			}
			
			lastTouch = touch;
		} else if (keysReleased & KEY_TOUCH) {
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			if (inputMode == MODE_DRAG) {
				event.type = isRightClick ? Common::EVENT_RBUTTONUP : Common::EVENT_LBUTTONUP;
				pushEventQueue(eventQueue, event);
			} else if (osys->getMillis() - touchStartTime < 200) {
				// Process click in MODE_HOVER
				event.type = Common::EVENT_MOUSEMOVE;
				pushEventQueue(eventQueue, event);
				event.type = isRightClick ? Common::EVENT_RBUTTONDOWN : Common::EVENT_LBUTTONDOWN;
				pushEventQueue(eventQueue, event);
				event.type = isRightClick ? Common::EVENT_RBUTTONUP : Common::EVENT_LBUTTONUP;
				pushEventQueue(eventQueue, event);
			}
		} else if (cursorDeltaX != 0 || cursorDeltaY != 0) {
			cursorX += cursorDeltaX;
			cursorY -= cursorDeltaY;
			if (cursorX < 0) cursorX = 0;
			if (cursorY < 0) cursorY = 0;
			if (cursorX > 320) cursorX = 320;
			if (cursorY > 240) cursorY = 240;
			lastTouch.px = cursorX;
			lastTouch.py = cursorY;
			osys->transformPoint(lastTouch);
			osys->warpMouse(lastTouch.px, lastTouch.py); 
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			event.type = Common::EVENT_MOUSEMOVE;
			pushEventQueue(eventQueue, event);
		}
		
		// Button events
		if (keysPressed & KEY_R) {
			if (inputMode == MODE_DRAG) {
				inputMode = MODE_HOVER;
				osys->displayMessageOnOSD("Hover Mode");
			} else {
				inputMode = MODE_DRAG;
				osys->displayMessageOnOSD("Drag Mode");
			}
		}
		if (keysPressed & KEY_A || keysPressed & KEY_DLEFT || keysReleased & KEY_A || keysReleased & KEY_DLEFT) {
			// SIMULATE LEFT CLICK
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			if (keysPressed & KEY_A || keysPressed & KEY_DLEFT)
				event.type = Common::EVENT_LBUTTONDOWN;
			else
				event.type = Common::EVENT_LBUTTONUP;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_X || keysPressed & KEY_DUP || keysReleased & KEY_X || keysReleased & KEY_DUP) {
			// SIMULATE RIGHT CLICK
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			if (keysPressed & KEY_X || keysPressed & KEY_DUP)
				event.type = Common::EVENT_RBUTTONDOWN;
			else
				event.type = Common::EVENT_RBUTTONUP;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_L) {
			event.type = Common::EVENT_VIRTUAL_KEYBOARD;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_START) {
			event.type = Common::EVENT_MAINMENU;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_SELECT) {
			if (!optionMenuOpened)
				optionMenuOpening = true;
		}
		if (keysPressed & KEY_B || keysReleased & KEY_B || keysPressed & KEY_DDOWN || keysReleased & KEY_DDOWN) {
			if (keysPressed & KEY_B || keysPressed & KEY_DDOWN)
				event.type = Common::EVENT_KEYDOWN;
			else
				event.type = Common::EVENT_KEYUP;
			event.kbd.keycode = Common::KEYCODE_ESCAPE;
			event.kbd.ascii = Common::ASCII_ESCAPE;
			event.kbd.flags = 0;
			pushEventQueue(eventQueue, event);
		}
		
		// TODO: EVENT_PREDICTIVE_DIALOG
		// EVENT_SCREEN_CHANGED
	}
}
예제 #25
0
int menu_more() {

    int i = 0;
    menu_index = 0;

    while (aptMainLoop()) {

        hidScanInput();
        u32 kDown = hidKeysDown();

        if (kDown & KEY_DOWN) {
            menu_index++;
            if (menu_index >= menu_count)
                menu_index = 0;
        }

        if (kDown & KEY_UP) {
            menu_index--;
            if (menu_index < 0)
                menu_index = menu_count - 1;
        }

        if (kDown & KEY_A) {
            if (menu_index == 0 && menu_choose() == 0) {
                return 0;
            } else if (menu_index == 1 && menu_netloader() == 0) {
                return 0;
            } else if (menu_index == 2) {
                menu_config();
            } else if (menu_index == 3) {
                reboot();
            } else if (menu_index == 4) {
                poweroff();
            }
        }

        if (kDown & KEY_B) {
            return -1;
        }

        drawBg();
        drawTitle("*** Select an option ***");

        for (i = 0; i < menu_count; i++) {
            drawItem(i == menu_index, 16 * i, menu_item[i]);
        }

        // draw "help"
        switch (menu_index) {
            case 0:
                drawInfo("Browse for a file to boot or add a boot entry");
                break;
            case 1:
                drawInfo("Netload a file (3dsx) from the computer with 3dslink");
                break;
            case 2:
                drawInfo("Edit boot settings");
                break;
            case 3:
                drawInfo("Reboot the 3ds...");
                break;
            case 4:
                drawInfo("Shutdown the 3ds...");
                break;
            default:
                break;
        }

        gfxSwap();
    }
    return -1;
}
예제 #26
0
파일: main.c 프로젝트: Cruel/3ds-examples
int main()
{
	Result ret=0;

	int draw=1;
	int ready=0;
	int type=0;

	gfxInit(GSP_RGB565_OES,GSP_BGR8_OES,false);
	consoleInit(GFX_BOTTOM, NULL);

	ret = romfsInit();
	if(R_FAILED(ret))
	{
		printf("romfsInit() failed: 0x%08x\n", (unsigned int)ret);
		ready = -1;
	}

	if(ready==0)
	{
		inaddr = linearMemAlign(0x1000000, 0x40);
		outaddr = linearMemAlign(0x100000, 0x40);

		if(!(inaddr && outaddr))
		{
			ready = -2;
			printf("Failed to allocate memory.\n");
		}
	}

	// Main loop
	while (aptMainLoop())
	{
		gspWaitForVBlank();
		hidScanInput();

		if(draw && type==0)
		{
			consoleClear();
			draw = 0;

			if(ready==0)printf("mvd example\n");

			printf("Press START to exit.\n");
			if(ready==0)
			{
				printf("Press A for color-format-conversion.\n");
				printf("Press B for video(no sound).\n");
			}
		}

		u32 kDown = hidKeysDown();

		if(type)
		{
			if(kDown & KEY_A)
			{
				type = 0;
				continue;
			}
		}

		if(type)continue;

		if (kDown & KEY_START)
			break; // break in order to return to hbmenu

		if(ready==0)
		{
			type = 0;
			if (kDown & KEY_A)type = 1;
			if (kDown & KEY_B)type = 2;

			if(type)
			{
				memset(inaddr, 0, 0x100000);
				memset(outaddr, 0, 0x100000);

				if(type==1)mvd_colorconvert();
				if(type==2)mvd_video();

				draw = 1;
				printf("Press A to continue.\n");
			}
		}
	}

	if(inaddr)linearFree(inaddr);
	if(outaddr)linearFree(outaddr);

	if(ready!=-1)romfsExit();

	gfxExit();
	return 0;
}
예제 #27
0
파일: brahma.c 프로젝트: 173210/CakeBrah
/* TODO: network code might be moved somewhere else */
s32 recv_arm9_payload (void) {
	s32 sockfd;
	struct sockaddr_in sa;
	u32 kDown, old_kDown;
	s32 clientfd;
	struct sockaddr_in client_addr;
	u32 addrlen = sizeof(client_addr);
	s32 sflags = 0;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printf("[!] Error: socket()\n");
		return 0;
	}

	bzero(&sa, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_port = htons(BRAHMA_NETWORK_PORT);
	sa.sin_addr.s_addr = gethostid();

	if (bind(sockfd, (struct sockaddr*)&sa, sizeof(sa)) != 0) {
		printf("[!] Error: bind()\n");
		close(sockfd);
		return 0;
	}

	if (listen(sockfd, 1) != 0) {
		printf("[!] Error: listen()\n");
		close(sockfd);
		return 0;
	}

	printf("[x] IP %s:%d\n", inet_ntoa(sa.sin_addr), BRAHMA_NETWORK_PORT);

	g_ext_arm9_size = 0;
	g_ext_arm9_loaded = 0;

	sflags = fcntl(sockfd, F_GETFL);
	if (sflags == -1) {
		printf("[!] Error: fcntl() (1)\n");
		close(sockfd);
	}
	fcntl(sockfd, F_SETFL, sflags | O_NONBLOCK);

	hidScanInput();
	old_kDown = hidKeysDown();
	while (1) {
		hidScanInput();
		kDown = hidKeysDown();
		if (kDown != old_kDown) {
			printf("[!] Aborted\n");
			close(sockfd);
			return 0;
		}

		clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
		svcSleepThread(100000000);
		if (clientfd > 0)
			break;
	}

	printf("[x] Connection from %s:%d\n\n", inet_ntoa(client_addr.sin_addr),
	ntohs(client_addr.sin_port));

	s32 recvd;
	u32 total = 0;
	s32 overflow = 0;
	while ((recvd = recv(clientfd, g_ext_arm9_buf + total,
	                     ARM9_PAYLOAD_MAX_SIZE - total, 0)) != 0) {
		if (recvd != -1) {
			total += recvd;
			printf(".");
		}
		if (total >= ARM9_PAYLOAD_MAX_SIZE) {
			overflow = 1;
			printf("[!] Error: invalid payload size\n");
			break;
		}
	}

	fcntl(sockfd, F_SETFL, sflags & ~O_NONBLOCK);

	printf("\n\n[x] Received %u bytes in total\n", (unsigned int)total);
	g_ext_arm9_size = overflow ? 0 : total;
	g_ext_arm9_loaded = (g_ext_arm9_size != 0);

	close(clientfd);
	close(sockfd);

	return g_ext_arm9_loaded;
}
예제 #28
0
파일: main.c 프로젝트: Cruel/3ds-examples
void mvd_video()
{
	Result ret;
	size_t video_size, nalunitsize;
	u32 video_pos=0;
	u32 cur_nalunit_pos=0, prev_nalunit_pos=0;
	u32 nalcount=0;
	u8 *video;

	u32 flagval=0;

	FILE *f = NULL;

	u8* gfxtopadr=NULL;

	MVDSTD_Config config;

	u32 prefix_offset;
	u8 prefix[4] = {0x00, 0x00, 0x00, 0x01};

	printf("Loading video...\n");

	//This loads the entire video into memory, normally you'd use a library to stream it.
	f = fopen("romfs:/video.h264", "r");
	if(f==NULL)
	{
		printf("Faile to open the video in romfs.\n");
		return;
	}

	video = &inaddr[0x100000];
	video_size = fread(video, 1, 0xF00000, f);
	fclose(f);

	if(video_size==0 || video_size>=0xF00000)
	{
		printf("Failed to read video / video is too large.\n");
		return;
	}

	ret = mvdstdInit(MVDMODE_VIDEOPROCESSING, MVD_INPUT_H264, MVD_OUTPUT_BGR565, MVD_DEFAULT_WORKBUF_SIZE, NULL);
	printf("mvdstdInit(): 0x%08x\n", (unsigned int)ret);
	if(ret!=0)return;

	printf("Processing 0x%08x-byte video...\n", (unsigned int)video_size);

	mvdstdGenerateDefaultConfig(&config, 240, 400, 240, 400, NULL, (u32*)outaddr, (u32*)outaddr);//Normally you'd set the input dimensions here to dimensions loaded from the actual video.

	//Normally you'd use a library to load each NAL-unit, this example just parses the data manually.
	while(video_pos < video_size+1)
	{
		cur_nalunit_pos = video_pos;
		video_pos++;

		prefix_offset = 1;

		if(cur_nalunit_pos<video_size)
		{
			/*
			{
				if(memcmp(&video[cur_nalunit_pos], &prefix[1], 3)==0 && cur_nalunit_pos==0x2dd)
				{
					prefix_offset = 0;
				}
			}
			if(prefix_offset)*/
			//else
			{
				if(memcmp(&video[cur_nalunit_pos], prefix, 4))
				{
					continue;
				}
				else
				{
					video_pos++;
				}
			}
		}

		if(nalcount && prev_nalunit_pos!=cur_nalunit_pos)
		{
			nalunitsize = cur_nalunit_pos - prev_nalunit_pos - prefix_offset;
			if(nalunitsize > 0x100000)
			{
				printf("The NAL-unit at offset 0x%08x is too large.\n", (unsigned int)nalunitsize);
				break;
			}

			memcpy(inaddr, &video[prev_nalunit_pos+prefix_offset], nalunitsize);
			GSPGPU_FlushDataCache(inaddr, nalunitsize);

			MVDSTD_ProcessNALUnitOut tmpout;//Normally you don't really need to use this.

			//printf("Processing NAL-unit at offset 0x%08x size 0x%08x...\n", (unsigned int)prev_nalunit_pos, (unsigned int)nalunitsize);
			ret = mvdstdProcessVideoFrame(inaddr, nalunitsize, flagval, &tmpout);
			if(!MVD_CHECKNALUPROC_SUCCESS(ret))
			{
				printf("mvdstdProcessVideoFrame() at NAL-unit offset 0x%08x size 0x%08x returned: 0x%08x. remaining_size=0x%08x.\n", (unsigned int)prev_nalunit_pos, (unsigned int)nalunitsize, (unsigned int)ret, (unsigned int)tmpout.remaining_size);
				break;
			}

			if(ret!=MVD_STATUS_PARAMSET && ret!=MVD_STATUS_INCOMPLETEPROCESSING)
			{
				gfxtopadr = gfxGetFramebuffer(GFX_TOP, GFX_LEFT, NULL, NULL);
				config.physaddr_outdata0 = osConvertVirtToPhys(gfxtopadr);

				//This sets the MVD output to the framebuffer directly. This is to avoid doing the video->framebuffer image rotation on the ARM11.
				//Normally you'd use a seperate MVD output buffer, then transfer that to the framebuffer(such as with GPU rendering).

				ret = mvdstdRenderVideoFrame(&config, true);
				if(ret!=MVD_STATUS_OK)
				{
					printf("mvdstdRenderVideoFrame() at NAL-unit offset 0x%08x returned: 0x%08x\n", (unsigned int)prev_nalunit_pos, (unsigned int)ret);
					break;
				}

				hidScanInput();
				if(hidKeysDown() & KEY_B)break;

				//Enable/disable the flag passed to mvdstdProcessVideoFrame().
				if(hidKeysDown() & KEY_DOWN)
				{
					flagval-= 0x1;
					printf("0x%08x\n", (unsigned int)flagval);
				}
				if(hidKeysDown() & KEY_UP)
				{
					flagval+= 0x1;
					printf("0x%08x\n", (unsigned int)flagval);
				}

				//gspWaitForVBlank();//Can't use this under this example without a major slowdown. This is due to this example not doing any buffering for the frames.
				gfxSwapBuffersGpu();
			}
		}

		nalcount++;

		prev_nalunit_pos = cur_nalunit_pos;
	}

	mvdstdExit();
}
예제 #29
0
파일: main.c 프로젝트: thejsa/tinytot
int main() {
	gfxInitDefault();
	consoleInit(GFX_BOTTOM, NULL);
	
	printf("%s %s by %s\n", APP_TITLE, APP_VERSION, APP_AUTHOR);
	printf("Build date: %s %s\n\n", __DATE__, __TIME__);
	//printf("Current time: %d\n\n", (int)time(NULL));

	printf("Calculating time difference from UTC... make sure you are connected to the Internet. ");
	
	Result InitClockOffsetResult = InitializeClockOffset();
	if (!InitClockOffsetResult) {
		printf("Error initializing time offset: %08x", InitClockOffsetResult);
		return 1;
	}
	printf("OK\n");
	
	int ret = oath_init();
	if(ret != OATH_OK) {
		printf("Error initializing liboath: %s\n", oath_strerror(ret));
		return 1;
	}

	char encoded_secret[1024];
	FILE *secretFile;
	signed short secretTxtDecLength;
	if((secretFile = fopen("secret.txt", "r")) == NULL) {
		printf("warning: Secret.txt not found in application directory (SD root if installed as CIA)");
		/*while(aptMainLoop()) {
			gspWaitForVBlank();
			hidScanInput();
			
			unsigned long kDown = hidKeysDown();
			if(kDown & KEY_A) break;
			gfxFlushBuffers();
			gfxSwapBuffers();
		}
		return 1;*/
	}else{
		printf("Opened secret.txt\n");
		fscanf(secretFile, "%[^\n]", encoded_secret);
		fclose(secretFile);
		if(strlen(encoded_secret) < 1){
			printf("warning: secret.txt exists but is empty.\n");
		}else{
			printf("Read secret.txt: %s\n", encoded_secret);
	
			ret = oath_base32_decode(&encoded_secret, strlen(&encoded_secret), NULL, &secretTxtDecLength);
			if(ret != OATH_OK) {
				printf("Error decoding secret.txt: %s\n", oath_strerror(ret));
				memset(&encoded_secret[0], 0, sizeof(encoded_secret)); // wipe the copy we have in memory, to avoid prefilling the swkbd with undecodable stuff
			}else{
				printf("Read secret.txt successfully.");
			}
		}
	}

	char inputSecret[1024];

	bool quit = false;
	bool ask = false;
	
	printf("Press A to begin, or start to exit.\n\n");
	
	// Main loop
	while (aptMainLoop())
	{
		gspWaitForVBlank();
		hidScanInput();

		unsigned long kDown = hidKeysDown();
		if (kDown & KEY_A) ask = true;

		if(ask && !quit) {
			static SwkbdState swkbd;
			static SwkbdStatusData swkbdStatus;
			SwkbdButton button = SWKBD_BUTTON_NONE;

			swkbdInit(&swkbd, SWKBD_TYPE_WESTERN, 2, 512);
			swkbdSetHintText(&swkbd, "Enter your TOTP secret.");
			swkbdSetButton(&swkbd, SWKBD_BUTTON_LEFT, "Quit", false);
			swkbdSetButton(&swkbd, SWKBD_BUTTON_MIDDLE, "Load txt", true);
			swkbdSetButton(&swkbd, SWKBD_BUTTON_RIGHT, "Go", true);
			swkbdSetInitialText(&swkbd, inputSecret);
			swkbdSetFeatures(&swkbd, SWKBD_DEFAULT_QWERTY);
			swkbdSetFilterCallback(&swkbd, swkbdCallbackThing, NULL);

			swkbdInputText(&swkbd, inputSecret, sizeof(inputSecret));

			switch(button) {
				case SWKBD_BUTTON_LEFT: // quit
					quit = true;
					break;
				case SWKBD_BUTTON_MIDDLE: // read secret.txt
					strcpy(inputSecret, encoded_secret);
					break;
				case SWKBD_BUTTON_RIGHT: // go (this is handled in filter callback)
					break;
				default:
					break;
			}

			if(quit) break; // quit to HBL
		}
		
		if (kDown & KEY_START) {
			break; // break in order to return to hbmenu
		}

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();
	}

	gfxExit();
	return 0;
}
예제 #30
0
int main() {
    srvInit();
    aptInit();
    hidInit(NULL);
    gfxInitDefault();
    resetGame();
    int x;
    while (aptMainLoop()) {
        hidScanInput();
        hidTouchRead(&touch);
        u32 kDown = hidKeysDown();
        //u32 kHeld = hidKeysHeld(); Not used an otherwise you'll get warning during compile, this makes compile more pleasant to look at yea!
        if (state != 0 && cur_row != 7) {
            if (secretCode() && state != 3)
                cheat=1;
            if (kDown & KEY_TOUCH) {
                cur_visable=false;
            }

            if (kDown & KEY_RIGHT) {
                cur_field+=1;
                if (cur_field > 3)
                    cur_field=0;
                cur_visable=true;
            }
            if (kDown & KEY_LEFT) {
                cur_field-=1;
                if (cur_field < 0)
                    cur_field=3;
                cur_visable=true;
            }
            if (kDown & KEY_UP) {
                local_field[cur_field]+=1;
                if (local_field[cur_field] > col_amount)
                    local_field[cur_field]=1;
                cur_visable=true;
            }
            if (kDown & KEY_DOWN) {
                local_field[cur_field]-=1;
                if (local_field[cur_field] < 1)
                    local_field[cur_field]=col_amount;
                cur_visable=true;
            }
            if (kDown & KEY_A)
                submitTry();
            if (touchInBox(touch,231,163,84,44))
                submitTry();

            if (touchInBox(touch,7,28,71,16)) {
                local_field[0]+=1;
                if (local_field[0] > col_amount)
                    local_field[0]=1;
            }
            if (touchInBox(touch,85,28,71,16)) {
                local_field[1]+=1;
                if (local_field[1] > col_amount)
                    local_field[1]=1;
            }
            if (touchInBox(touch,163,28,71,16)) {
                local_field[2]+=1;
                if (local_field[2] > col_amount)
                    local_field[2]=1;
            }
            if (touchInBox(touch,241,28,71,16)) {
                local_field[3]+=1;
                if (local_field[3] > col_amount)
                    local_field[3]=1;
            }
            if (touchInBox(touch,7,119,71,16)) {
                local_field[0]-=1;
                if (local_field[0] <= 0)
                    local_field[0]=col_amount;
            }
            if (touchInBox(touch,85,119,71,16)) {
                local_field[1]-=1;
                if (local_field[1] <= 0)
                    local_field[1]=col_amount;
            }
            if (touchInBox(touch,163,119,71,16)) {
                local_field[2]-=1;
                if (local_field[2] <= 0)
                    local_field[2]=col_amount;
            }
            if (touchInBox(touch,241,119,71,16)) {
                local_field[3]-=1;
                if (local_field[3] <= 0)
                    local_field[3]=col_amount;
            }
            if (state != 2) {
                for (x=0; x < 4; x++) {
                    full_field[cur_row*4+x]=local_field[x];
                }
            }
        } else if (state == 0) {
            if (touchInBox(touch,65,66,98,34))
                modeselector=1;
            if (touchInBox(touch,65,102,98,34))
                modeselector=2;
            if (modeselector != 0) {
                if (touchInBox(touch,168,65,88,22)) {
                    difficulty=0;
                    startGame(modeselector);
                }
                if (touchInBox(touch,168,90,88,22)) {
                    difficulty=1;
                    startGame(modeselector);
                }
                if (touchInBox(touch,168,125,88,22)) {
                    difficulty=2;
                    startGame(modeselector);
                }
            }
        }

        if (touchInBox(touch,0,211,320,30)) {
            resetGame();
            state=0;
            modeselector=0;
        }
        if (touchInBox(touch,0,0,74,21))
            break;

        render(full_field, full_judgement, local_field, cur_field, cur_row, cur_visable, ans, win, cheat, state, modeselector);
        gfxFlushBuffers();
        gfxSwapBuffers();
        gspWaitForEvent(GSPEVENT_VBlank0, false);
    }
    gfxExit();
    hidExit();
    aptExit();
    srvExit();
    return 0;
}