diff --git a/examples/collisions/barrels/source/main.c b/examples/collisions/barrels/source/main.c index 4886de3..79d3046 100644 --- a/examples/collisions/barrels/source/main.c +++ b/examples/collisions/barrels/source/main.c @@ -1,202 +1,156 @@ // SPDX-License-Identifier: CC0-1.0 // // SPDX-FileContributor: NightFox & Co., 2009-2011 +// +// Example of per-pixel collisions. +// http://www.nightfoxandco.com -/* -------------------------------------------------- - - NightFox's Lib Template - Ejemplo de mapas de colisiones por pixels - en superficies inclinadas - - Requiere DevkitARM - Requiere NightFox's Lib - - Codigo por NightFox - http://www.nightfoxandco.com - Inicio 10 de Octubre del 2009 - -------------------------------------------------- -*/ - - - - - -/* -------------------------------------------------- - Includes -------------------------------------------------- -*/ - -// Includes C #include -// Includes propietarios NDS #include #include -// Includes librerias propias #include +int main(int argc, char **argv) +{ + // Prepare a NitroFS initialization screen + NF_Set2D(0, 0); + NF_Set2D(1, 0); + consoleDemoInit(); + printf("\n NitroFS init. Please wait.\n\n"); + printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); + swiWaitForVBlank(); + // Initialize NitroFS and set it as the root folder of the filesystem + nitroFSInit(NULL); + NF_SetRootFolder("NITROFS"); + // Initialize 2D engine in the top screen and use mode 0 + NF_Set2D(0, 0); + // Initialize tiled backgrounds system + NF_InitTiledBgBuffers(); // Initialize storage buffers + NF_InitTiledBgSys(0); // Top screen -/* -------------------------------------------------- - Main() - Bloque general del programa -------------------------------------------------- -*/ + // Initialize sprite system + NF_InitSpriteBuffers(); + NF_InitSpriteSys(0); // Top screen -int main(int argc, char **argv) { + // Initialize collision map buffers + NF_InitCmapBuffers(); - // Pantalla de espera inicializando NitroFS - NF_Set2D(0, 0); - NF_Set2D(1, 0); - consoleDemoInit(); - printf("\n NitroFS init. Please wait.\n\n"); - printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); - swiWaitForVBlank(); + // Load background files from NitroFS + NF_LoadTiledBg("bg/pdemo_bg", "bg3", 256, 256); - // Define el ROOT e inicializa el sistema de archivos - nitroFSInit(NULL); - NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS + // Load sprite files from NitroFS + NF_LoadSpriteGfx("sprite/whiteball", 0, 16, 16); + NF_LoadSpritePal("sprite/whiteball", 0); - // Inicializa el motor 2D - NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior + // Load collision map files from NitroFS + NF_LoadCollisionBg("maps/pdemo_colmap", 0, 256, 256); - // Inicializa los fondos tileados - NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos - NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior + // Create top screen background + NF_CreateTiledBg(0, 3, "bg3"); - // Inicializa los Sprites - NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas - NF_InitSpriteSys(0); // Inicializa los sprites para la pantalla superior + // Transfer the required sprites to VRAM + NF_VramSpriteGfx(0, 0, 0, true); + NF_VramSpritePal(0, 0, 0); - // Inicializa los buffers de mapas de colisiones - NF_InitCmapBuffers(); + // Create sprites and set their priority layer + for (int b = 0; b < 3; b ++) + { + NF_CreateSprite(0, b, 0, 0, -16, -16); + NF_SpriteLayer(0, b, 3); + } - // Carga los archivos de fondo - NF_LoadTiledBg("bg/pdemo_bg", "bg3", 256, 256); // Carga el fondo para la capa 3, pantalla superior + // Location of the sprites + s16 x[3] = { 32, 228, 10 }; + s16 y[3] = { -16, 32, 100 }; - // Carga los archivos de sprites - NF_LoadSpriteGfx("sprite/whiteball", 0, 16, 16); // Pelota - NF_LoadSpritePal("sprite/whiteball", 0); + // Coordinates of the sprite that have to be used as collision points + s16 py[16] = { + 11, 13, 14, 15, 15, 16, 16, 16, 16, 16, 16, 15, 15, 14, 13, 11 + }; - // Carga el fondo de colisiones - NF_LoadCollisionBg("maps/pdemo_colmap", 0, 256, 256); + while (1) + { + // Clear text console + consoleClear(); - // Crea los fondos de la pantalla superior - NF_CreateTiledBg(0, 3, "bg3"); + bool down = false; + bool left = false; + bool right = false; - // Transfiere a la VRAM los sprites necesarios - NF_VramSpriteGfx(0, 0, 0, true); // Puntero - NF_VramSpritePal(0, 0, 0); + // Handle collisions and fall of all balls + for (int b = 0; b < 3; b ++) + { + down = true; // If this remains true, there is no collision - // Variables de uso genereal - u8 b = 0; - u8 n = 0; + // Check all pixels of the lower half of the ball to see if there is + // a collision. + for (int n = 0; n < 16; n ++) + { + // Blue pixels are index 4 + if (NF_GetPoint(0, (x[b] + n), (y[b] + py[n])) == 4) + down = false; + } - // Crea el Sprite del puntero en la pantalla inferior - for (b = 0; b < 3; b ++) { - NF_CreateSprite(0, b, 0, 0, -16, -16); // Crea el puntero en la pantalla inferior - NF_SpriteLayer(0, b, 3); // Y la capa sobre la que se dibujara - } + // Check for collisions left and right of the ball + right = true; + left = true; - // Variables para el control de movimiento - s16 x[3]; - s16 y[3]; - x[0] = 32; - y[0] = -16; - x[1] = 228; - y[1] = 32; - x[2] = 10; - y[2] = 100; + // Falling to the left + if (NF_GetPoint(0, (x[b] - 1), (y[b] + 16)) == 4) + left = false; + // Falling to the right + if (NF_GetPoint(0, (x[b] + 16), (y[b] + 16)) == 4) + right = false; - // Variables de control de colisiones, define todos los puntos de colision del sprite - s16 py[16]; - py[0] = 11; - py[1] = 13; - py[2] = 14; - py[3] = 15; - py[4] = 15; - py[5] = 16; - py[6] = 16; - py[7] = 16; - py[8] = 16; - py[9] = 16; - py[10] = 16; - py[11] = 15; - py[12] = 15; - py[13] = 14; - py[14] = 13; - py[15] = 11; + // On free fall, don't move on the X axis + if (left && right) + { + right = false; + left = false; + } - // Control de movimiento - bool down = false; - bool left = false; - bool right = false; + // Free fall + if (down) + y[b] ++; - // Bucle (repite para siempre) - while(1) { + // Move right + if (right) + x[b] ++; - // Borra la pantalal de texto - consoleClear(); + // Move left + if (left) + x[b] --; - // Bola a bola - for (b = 0; b < 3; b ++) { + // If the ball exits the screen from the bottom move it to the top + if (y[b] > 192) + { + x[b] = 32; + y[b] = -16; + } - // Control de colisiones, caida - down = true; // Flag de descenso arriba - // Busca pixel por pixel, si hay colisiones (pixel azul, nº4) - for (n = 0; n < 16; n ++) { - if (NF_GetPoint(0, (x[b] + n), (y[b] + py[n])) == 4) down = false; - } + // Set the sprite position + NF_MoveSprite(0, b, x[b], y[b]); - // Control de colisiones, decide derecha o izquierda - right = true; // Flag de movimiento lateral arriba - left = true; - // Caida a izquierda - if (NF_GetPoint(0, (x[b] - 1), (y[b] + 16)) == 4) left = false; - // Caida a derecha - if (NF_GetPoint(0, (x[b] + 16), (y[b] + 16)) == 4) right = false; - // Si hay caida libre, no te muevas en horizontal - if (left && right) { - right = false; - left = false; - } + // Print sprite coordinates + printf("x:%03d y:%03d\n", x[b], y[b]); - // Si es necesario, caida libre - if (down) y[b] ++; - // Muevete a la derecha - if (right) x[b] ++; - // Muevete a la izquierda - if (left) x[b] --; + } - // Recoloca la pelota si sale de los limites de pantalla - if (y[b] > 192) { - x[b] = 32; - y[b] = -16; - } + // Update OAM array + NF_SpriteOamSet(0); - // Posicion del Sprite - NF_MoveSprite(0, b, x[b], y[b]); + // Wait for the screen refresh + swiWaitForVBlank(); - // Imprime la posicion de la pelota - printf("x:%03d y:%03d\n", x[b], y[b]); - - } - - NF_SpriteOamSet(0); // Actualiza el Array del OAM - - swiWaitForVBlank(); // Espera al sincronismo vertical - - oamUpdate(&oamMain); // Actualiza a VRAM el OAM Secundario - - } - - return 0; + // Update OAM + oamUpdate(&oamMain); + } + return 0; } diff --git a/examples/collisions/pixels/source/main.c b/examples/collisions/pixels/source/main.c index 031bbbc..f79ceb8 100644 --- a/examples/collisions/pixels/source/main.c +++ b/examples/collisions/pixels/source/main.c @@ -1,178 +1,154 @@ // SPDX-License-Identifier: CC0-1.0 // // SPDX-FileContributor: NightFox & Co., 2009-2011 +// +// Collision background example +// http://www.nightfoxandco.com -/* -------------------------------------------------- - - NightFox's Lib Template - Ejemplo de fondos de colisiones - - Requiere DevkitARM - Requiere NightFox's Lib - - Codigo por NightFox - http://www.nightfoxandco.com - Inicio 10 de Octubre del 2009 - -------------------------------------------------- -*/ - - - - - -/* -------------------------------------------------- - Includes -------------------------------------------------- -*/ - -// Includes C #include -// Includes propietarios NDS #include #include -// Includes librerias propias #include +int main(int argc, char **argv) +{ + // Prepare a NitroFS initialization screen + NF_Set2D(0, 0); + NF_Set2D(1, 0); + consoleDemoInit(); + printf("\n NitroFS init. Please wait.\n\n"); + printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); + swiWaitForVBlank(); + // Initialize NitroFS and set it as the root folder of the filesystem + nitroFSInit(NULL); + NF_SetRootFolder("NITROFS"); + // Initialize 2D engine in the top screen and use mode 0 + NF_Set2D(0, 0); + // Initialize tiled backgrounds system + NF_InitTiledBgBuffers(); // Initialize storage buffers + NF_InitTiledBgSys(0); // Top screen -/* -------------------------------------------------- - Main() - Bloque general del programa -------------------------------------------------- -*/ + // Initialize sprite system + NF_InitSpriteBuffers(); + NF_InitSpriteSys(0); // Top screen -int main(int argc, char **argv) { + // Initialize collision map buffers + NF_InitCmapBuffers(); - // Pantalla de espera inicializando NitroFS - NF_Set2D(0, 0); - NF_Set2D(1, 0); - consoleDemoInit(); - printf("\n NitroFS init. Please wait.\n\n"); - printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); - swiWaitForVBlank(); + // Load background files from NitroFS + NF_LoadTiledBg("bg/ppc_bg", "bg3", 512, 512); - // Define el ROOT e inicializa el sistema de archivos - nitroFSInit(NULL); - NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS + // Load sprite files from NitroFS + NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8); + NF_LoadSpritePal("sprite/puntero", 0); - // Inicializa el motor 2D - NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior + // Load collision map files from NitroFS + NF_LoadCollisionBg("maps/ppc_cmap", 0, 512, 512); - // Inicializa los fondos tileados - NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos - NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior + // Create top screen background + NF_CreateTiledBg(0, 3, "bg3"); - // Inicializa los Sprites - NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas - NF_InitSpriteSys(0); // Inicializa los sprites para la pantalla superior + // Transfer the required sprites to VRAM + NF_VramSpriteGfx(0, 0, 0, true); + NF_VramSpritePal(0, 0, 0); - // Inicializa los buffers de mapas de colisiones - NF_InitCmapBuffers(); + // Create pointer sprite in the bottom screen and set its priority layer + NF_CreateSprite(0, 0, 0, 0, 124, 92); + NF_SpriteLayer(0, 0, 3); - // Carga los archivos de fondo - NF_LoadTiledBg("bg/ppc_bg", "bg3", 512, 512); // Carga el fondo para la capa 3, pantalla superior + // Movement variables + s16 x = 128; + s16 y = 96; + s16 spr_x = 0; + s16 spr_y = 0; + s16 bg_x = 0; + s16 bg_y = 0; - // Carga los archivos de sprites - NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8); // Puntero - NF_LoadSpritePal("sprite/puntero", 0); + while (1) + { + scanKeys(); // Read keypad + u16 keys = keysHeld(); // Keys currently pressed - // Carga el fondo de colisiones - NF_LoadCollisionBg("maps/ppc_cmap", 0, 512, 512); + if (keys & KEY_UP) + y --; + if (keys & KEY_DOWN) + y ++; + if (keys & KEY_LEFT) + x --; + if (keys & KEY_RIGHT) + x ++; - // Crea los fondos de la pantalla superior - NF_CreateTiledBg(0, 3, "bg3"); + // Movement limits + if (x < 0) + x = 0; + if (x > 511) + x = 511; - // Transfiere a la VRAM los sprites necesarios - NF_VramSpriteGfx(0, 0, 0, true); // Puntero - NF_VramSpritePal(0, 0, 0); + if (y < 0) + y = 0; + if (y > 511) + y = 511; - // Crea el Sprite del puntero en la pantalla inferior - NF_CreateSprite(0, 0, 0, 0, 124, 92); // Crea el puntero en la pantalla inferior - NF_SpriteLayer(0, 0, 3); // Y la capa sobre la que se dibujara + // Background position + bg_x = x - 128; + if (bg_x < 0) + bg_x = 0; + if (bg_x > 256) + bg_x = 256; - // Variable para la lectura del keypad - u16 keys = 0; + bg_y = y - 96; + if (bg_y < 0) + bg_y = 0; + if (bg_y > 320) + bg_y = 320; - // Variables para el control de movimiento - s16 x = 128; - s16 y = 96; - s16 spr_x = 0; - s16 spr_y = 0; - s16 bg_x = 0; - s16 bg_y = 0; - u8 pixel = 0; + // Sprite position + spr_x = (x - bg_x) - 4; + spr_y = (y - bg_y) - 4; + NF_MoveSprite(0, 0, spr_x, spr_y); - // Bucle (repite para siempre) - while(1) { + // Print pointer position + consoleClear(); + printf("x:%03d y:%03d \n\n", x, y); - // Lee el teclado - scanKeys(); - keys = keysHeld(); - if (keys & KEY_UP) y --; - if (keys & KEY_DOWN) y ++; - if (keys & KEY_LEFT) x --; - if (keys & KEY_RIGHT) x ++; + // Print pixel color + u8 pixel = NF_GetPoint(0, x, y); + switch (pixel) + { + case 1: + printf("Tile: Negro / Black"); + break; + case 2: + printf("Tile: Rojo / Red"); + break; + case 3: + printf("Tile: Verde / Green"); + break; + case 4: + printf("Tile: Azul / Blue"); + break; + default: + printf("Value: %03d", pixel); + break; + } - // Limites del movimiento - if (x < 0) x = 0; - if (x > 511) x = 511; - if (y < 0) y = 0; - if (y > 511) y = 511; + // Update OAM array + NF_SpriteOamSet(0); - // Posicion del fondo - bg_x = (x - 128); - if (bg_x < 0) bg_x = 0; - if (bg_x > 256) bg_x = 256; - bg_y = (y - 96); - if (bg_y < 0) bg_y = 0; - if (bg_y > 320) bg_y = 320; + // Wait for the screen refresh + swiWaitForVBlank(); - // Posicion del Sprite - spr_x = (x - bg_x) - 4; - spr_y = (y - bg_y) - 4; - NF_MoveSprite(0, 0, spr_x, spr_y); + // Update OAM + oamUpdate(&oamMain); - // Imprime la posicion del cursor - consoleClear(); - printf("x:%03d y:%03d \n\n", x, y); - - // Imprime el color del pixel - pixel = NF_GetPoint(0, x, y); - switch (pixel) { - case 1: - printf("Tile: Negro / Black"); - break; - case 2: - printf("Tile: Rojo / Red"); - break; - case 3: - printf("Tile: Verde / Green"); - break; - case 4: - printf("Tile: Azul / Blue"); - break; - default: - printf("Value: %03d", pixel); - break; - } - - NF_SpriteOamSet(0); // Actualiza el Array del OAM - - swiWaitForVBlank(); // Espera al sincronismo vertical - - oamUpdate(&oamMain); // Actualiza a VRAM el OAM Secundario - - NF_ScrollBg(0, 3, bg_x, bg_y); // Actualiza el scroll - - } - - return 0; + // Update scroll + NF_ScrollBg(0, 3, bg_x, bg_y); + } + return 0; } diff --git a/examples/collisions/tiles/source/main.c b/examples/collisions/tiles/source/main.c index e7064df..8b1e387 100644 --- a/examples/collisions/tiles/source/main.c +++ b/examples/collisions/tiles/source/main.c @@ -1,196 +1,174 @@ // SPDX-License-Identifier: CC0-1.0 // // SPDX-FileContributor: NightFox & Co., 2009-2011 +// +// Collision map example. +// http://www.nightfoxandco.com -/* -------------------------------------------------- - - NightFox's Lib Template - Ejemplo de mapas de colisiones - - Requiere DevkitARM - Requiere NightFox's Lib - - Codigo por NightFox - http://www.nightfoxandco.com - Inicio 10 de Octubre del 2009 - -------------------------------------------------- -*/ - - - - - -/* -------------------------------------------------- - Includes -------------------------------------------------- -*/ - -// Includes C #include -// Includes propietarios NDS #include #include -// Includes librerias propias #include +int main(int argc, char **argv) +{ + // Prepare a NitroFS initialization screen + NF_Set2D(0, 0); + NF_Set2D(1, 0); + consoleDemoInit(); + printf("\n NitroFS init. Please wait.\n\n"); + printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); + swiWaitForVBlank(); + // Initialize NitroFS and set it as the root folder of the filesystem + nitroFSInit(NULL); + NF_SetRootFolder("NITROFS"); + // Initialize 2D engine in both screens and use mode 0 + NF_Set2D(0, 0); + NF_Set2D(1, 0); + // Initialize tiled backgrounds system + NF_InitTiledBgBuffers(); // Initialize storage buffers + NF_InitTiledBgSys(0); // Top screen + NF_InitTiledBgSys(1); // Bottom screen -/* -------------------------------------------------- - Main() - Bloque general del programa -------------------------------------------------- -*/ + // Initialize sprite system + NF_InitSpriteBuffers(); + NF_InitSpriteSys(0); // Top screen + NF_InitSpriteSys(1); // Bottom screen -int main(int argc, char **argv) { + // Initialize text system + NF_InitTextSys(0); // Top screen - // Pantalla de espera inicializando NitroFS - NF_Set2D(0, 0); - NF_Set2D(1, 0); - consoleDemoInit(); - printf("\n NitroFS init. Please wait.\n\n"); - printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); - swiWaitForVBlank(); + // Initialize collision map buffers + NF_InitCmapBuffers(); - // Define el ROOT e inicializa el sistema de archivos - nitroFSInit(NULL); - NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS + // Load background files from NitroFS + NF_LoadTiledBg("bg/layer3", "moon", 256, 256); + NF_LoadTiledBg("bg/colmap", "boxes", 768, 512); - // Inicializa el motor 2D - NF_Set2D(0, 0); // Modo 2D_0 en ambas pantallas - NF_Set2D(1, 0); + // Load sprite files from NitroFS + NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8); + NF_LoadSpritePal("sprite/puntero", 0); - // Inicializa los fondos tileados - NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos - NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior - NF_InitTiledBgSys(1); // Iniciliaza los fondos Tileados para la pantalla inferior + // Load text font files from NitroFS + NF_LoadTextFont("fnt/default", "normal", 256, 256, 0); - // Inicializa los Sprites - NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas - NF_InitSpriteSys(0); // Inicializa los sprites para la pantalla superior - NF_InitSpriteSys(1); // Inicializa los sprites para la pantalla inferior + // Load collision map files from NitroFS + NF_LoadCollisionMap("maps/cmap", 0, 768, 512); - // Inicializa el motor de texto - NF_InitTextSys(0); // Inicializa el texto para la pantalla superior + // Create top screen background + NF_CreateTiledBg(0, 3, "moon"); - // Inicializa los buffers de mapas de colisiones - NF_InitCmapBuffers(); + // Create bottom screen backgrounds + NF_CreateTiledBg(1, 3, "moon"); + NF_CreateTiledBg(1, 2, "boxes"); - // Carga los archivos de fondo desde la FAT / NitroFS a la RAM - NF_LoadTiledBg("bg/layer3", "moon", 256, 256); // Carga el fondo para la capa 3, pantalla inferior - NF_LoadTiledBg("bg/colmap", "boxes", 768, 512); // Carga el fondo para la capa 2, pantalla inferior + // Create a text layer + NF_CreateTextLayer(0, 2, 0, "normal"); - // Carga los archivos de sprites desde la FAT / NitroFS a la RAM - NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8); // Puntero - NF_LoadSpritePal("sprite/puntero", 0); + // Transfer the required sprites to VRAM + NF_VramSpriteGfx(1, 0, 0, true); + NF_VramSpritePal(1, 0, 0); - // Carga la fuente por defecto para el texto - NF_LoadTextFont("fnt/default", "normal", 256, 256, 0); + // Create pointer sprite in the bottom screen and set its priority layer + NF_CreateSprite(1, 0, 0, 0, 124, 92); + NF_SpriteLayer(1, 0, 2); - // Carga el mapa de colisiones - NF_LoadCollisionMap("maps/cmap", 0, 768, 512); + // Movement variables + s16 x = 128; + s16 y = 96; + s16 spr_x = 0; + s16 spr_y = 0; + s16 bg_x = 0; + s16 bg_y = 0; - // Crea los fondos de la pantalla superior - NF_CreateTiledBg(0, 3, "moon"); - // Crea los fondos de la pantalla inferior - NF_CreateTiledBg(1, 3, "moon"); - NF_CreateTiledBg(1, 2, "boxes"); + // Buffer de texto + char mytext[32]; - // Crea una capa de texto - NF_CreateTextLayer(0, 2, 0, "normal"); + while (1) + { + scanKeys(); // Read keypad + u16 keys = keysHeld(); // Keys currently pressed - // Transfiere a la VRAM los sprites necesarios - NF_VramSpriteGfx(1, 0, 0, true); // Puntero - NF_VramSpritePal(1, 0, 0); + if (keys & KEY_UP) + y --; + if (keys & KEY_DOWN) + y ++; + if (keys & KEY_LEFT) + x --; + if (keys & KEY_RIGHT) + x ++; - // Crea el Sprite del puntero en la pantalla inferior - NF_CreateSprite(1, 0, 0, 0, 124, 92); // Crea el puntero en la pantalla inferior - NF_SpriteLayer(1, 0, 2); // Y la capa sobre la que se dibujara + // Limites del movimiento + if (x < 0) + x = 0; + if (x > 767) + x = 767; - // Variable para la lectura del keypad - u16 keys = 0; + if (y < 0) + y = 0; + if (y > 511) + y = 511; - // Variables para el control de movimiento - s16 x = 128; - s16 y = 96; - s16 spr_x = 0; - s16 spr_y = 0; - s16 bg_x = 0; - s16 bg_y = 0; + // Background position + bg_x = x - 128; + if (bg_x < 0) + bg_x = 0; + if (bg_x > 512) + bg_x = 512; - // Buffer de texto - char mytext[32]; + bg_y = y - 96; + if (bg_y < 0) + bg_y = 0; + if (bg_y > 320) + bg_y = 320; + // Sprite position + spr_x = (x - bg_x) - 4; + spr_y = (y - bg_y) - 4; + NF_MoveSprite(1, 0, spr_x, spr_y); + // Print pointer position + sprintf(mytext,"x:%d y:%d ", x, y); + NF_WriteText(0, 2, 1, 1, mytext); - // Bucle (repite para siempre) - while(1) { + // Print tile number + switch (NF_GetTile(0, x, y)) + { + case 0: + sprintf(mytext,"Tile: Vacio / Void "); + break; + case 1: + sprintf(mytext,"Tile: Rojo / Red "); + break; + case 2: + sprintf(mytext,"Tile: Verde / Green "); + break; + case 3: + sprintf(mytext,"Tile: Azul / Blue "); + break; + } + NF_WriteText(0, 2, 1, 3, mytext); - // Lee el teclado - scanKeys(); - keys = keysHeld(); - if (keys & KEY_UP) y --; - if (keys & KEY_DOWN) y ++; - if (keys & KEY_LEFT) x --; - if (keys & KEY_RIGHT) x ++; + // Update text layers + NF_UpdateTextLayers(); - // Limites del movimiento - if (x < 0) x = 0; - if (x > 767) x = 767; - if (y < 0) y = 0; - if (y > 511) y = 511; + // Update OAM array + NF_SpriteOamSet(1); - // Posicion del fondo - bg_x = (x - 128); - if (bg_x < 0) bg_x = 0; - if (bg_x > 512) bg_x = 512; - bg_y = (y - 96); - if (bg_y < 0) bg_y = 0; - if (bg_y > 320) bg_y = 320; + // Wait for the screen refresh + swiWaitForVBlank(); - // Posicion del Sprite - spr_x = (x - bg_x) - 4; - spr_y = (y - bg_y) - 4; - NF_MoveSprite(1, 0, spr_x, spr_y); + // Update OAM + oamUpdate(&oamSub); - // Imprime la posicion del cursor - sprintf(mytext,"x:%d y:%d ", x, y); - NF_WriteText(0, 2, 1, 1, mytext); - - // Imprime el nº de tile - switch (NF_GetTile(0, x, y)) { - case 0: - sprintf(mytext,"Tile: Vacio / Void "); - break; - case 1: - sprintf(mytext,"Tile: Rojo / Red "); - break; - case 2: - sprintf(mytext,"Tile: Verde / Green "); - break; - case 3: - sprintf(mytext,"Tile: Azul / Blue "); - break; - } - NF_WriteText(0, 2, 1, 3, mytext); - - NF_UpdateTextLayers(); // Actualiza las capas de texto - NF_SpriteOamSet(1); // Actualiza el Array del OAM - - swiWaitForVBlank(); // Espera al sincronismo vertical - - oamUpdate(&oamSub); // Actualiza a VRAM el OAM Secundario - - NF_ScrollBg(1, 2, bg_x, bg_y); // Actualiza el scroll - - } - - return 0; + // Update background scroll + NF_ScrollBg(1, 2, bg_x, bg_y); + } + return 0; } diff --git a/examples/demo/reveal/source/main.c b/examples/demo/reveal/source/main.c index d891132..5de90ed 100644 --- a/examples/demo/reveal/source/main.c +++ b/examples/demo/reveal/source/main.c @@ -1,200 +1,163 @@ // SPDX-License-Identifier: CC0-1.0 // // SPDX-FileContributor: NightFox & Co., 2009-2011 +// +// "Reveal" effect +// http://www.nightfoxandco.com -/* -------------------------------------------------- - - NightFox's Lib Template - Efecto de "revelado" - - Requiere DevkitARM - Requiere NightFox's Lib - - Codigo por NightFox - http://www.nightfoxandco.com - Inicio 10 de Octubre del 2009 - -------------------------------------------------- -*/ - - - - - -/* -------------------------------------------------- - Includes -------------------------------------------------- -*/ - -// Includes C #include #include #include #include -// Includes propietarios NDS #include #include -// Includes librerias propias #include +int main(int argc, char **argv) +{ + // Prepare a NitroFS initialization screen + NF_Set2D(0, 0); + NF_Set2D(1, 0); + consoleDemoInit(); + printf("\n NitroFS init. Please wait.\n\n"); + printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); + swiWaitForVBlank(); + // Initialize NitroFS and set it as the root folder of the filesystem + nitroFSInit(NULL); + NF_SetRootFolder("NITROFS"); + // Initialize 2D engine in both screens. Use mode 0 in the top screen, and + // mode 5 in the bottom screen. + NF_Set2D(0, 0); + NF_Set2D(1, 5); + // Initialize tiled backgrounds system in the top screen + NF_InitTiledBgBuffers(); // Initialize storage buffers + NF_InitTiledBgSys(0); -/* -------------------------------------------------- - Main() - Bloque general del programa -------------------------------------------------- -*/ + // Initialize bitmap backgrounds system in the bottom screen + NF_Init8bitsBgBuffers(); // Initialize storage buffers + NF_InitBitmapBgSys(1, 0); // Initialize 8-bit bitmap backgrounds + NF_Init8bitsBackBuffer(1); // Initialize backbuffer + NF_Enable8bitsBackBuffer(1); // Enable backbuffer -int main(int argc, char **argv) { + // Initialize sprite system in the bottom screen + NF_InitSpriteBuffers(); // Initialize storage buffers + NF_InitSpriteSys(1); - // Pantalla de espera inicializando NitroFS - NF_Set2D(0, 0); - NF_Set2D(1, 0); - consoleDemoInit(); - printf("\n NitroFS init. Please wait.\n\n"); - printf(" Iniciando NitroFS,\n por favor, espere.\n\n"); - swiWaitForVBlank(); + // Load tiled background files from NitroFS + NF_LoadTiledBg("bg/nfl", "nfl", 256, 256); - // Define el ROOT e inicializa el sistema de archivos - nitroFSInit(NULL); - NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS + // Load bitmap background files from NitroFS + NF_Load8bitsBg("bg/img8b_1", 0); + NF_Load8bitsBg("bg/img8b_2", 1); - // Inicializa el motor 2D - NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior - NF_Set2D(1, 5); // Modo 2D_5 en la pantalla superior + // Load sprite files from NitroFS + NF_LoadSpriteGfx("spr/bola", 0, 32, 32); + NF_LoadSpritePal("spr/bola", 0); - // Inicializa los fondos tileados (Pantalla superior) - NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos - NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior + // Create bottom screen background + NF_CreateTiledBg(0, 3, "nfl"); - // Inicializa los fondos en modo "BITMAP" (Pantalla inferior) - NF_Init8bitsBgBuffers(); // Inicializa los buffers para almacenar fondos - NF_InitBitmapBgSys(1, 0); // Inicializa los fondos bitmap de 8 bits - NF_Init8bitsBackBuffer(1); // Inicializa el BackBuffer - NF_Enable8bitsBackBuffer(1); // Habilita el BackBuffer en la pantalla inferior + // Transfer image to the backbuffer of the top screen + NF_Copy8bitsBuffer(1, 2, 1); + // Transfer image to layer 3 of the top screen + NF_Copy8bitsBuffer(1, 1, 0); + // Copy backbuffer of the top screen to layer 2 + NF_Flip8bitsBackBuffer(1, 0); - // Inicializa los Sprites - NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas - NF_InitSpriteSys(1); // Inicializa los sprites para la pantalla inferior + // Transfer the required sprites to VRAM + NF_VramSpriteGfx(1, 0, 0, true); + NF_VramSpritePal(1, 0, 0); - // Carga los archivos de tiles desde la FAT / NitroFS a la RAM - NF_LoadTiledBg("bg/nfl", "nfl", 256, 256); + // Set random seed based on the current time + srand(time(NULL)); - // Carga el archivo BITMAP de imagen en formato RAW a la RAM - NF_Load8bitsBg("bg/img8b_1", 0); - NF_Load8bitsBg("bg/img8b_2", 1); + // State of the balls + s16 bola_x[32]; + s16 bola_y[32]; + s8 bola_spx[32]; + s8 bola_spy[32]; - // Carga los archivos de sprites desde la FAT / NitroFS a la RAM - NF_LoadSpriteGfx("spr/bola", 0, 32, 32); // Bola azul - NF_LoadSpritePal("spr/bola", 0); + for (int n = 0; n < 32; n ++) + { + bola_x[n] = rand() % 223; + bola_y[n] = rand() % 159; + bola_spx[n] = (rand() % 3) + 1; + bola_spy[n] = (rand() % 3) + 1; + NF_CreateSprite(1, n, 0, 0, bola_x[n], bola_y[n]); + NF_SpriteLayer(1, n, 3); + } - // Crea los fondos de la pantalla superior - NF_CreateTiledBg(0, 3, "nfl"); + while (1) + { + // Read keys and touchscreen + scanKeys(); + touchPosition touchscreen; + touchRead(&touchscreen); + u16 keys_held = keysHeld(); + u16 keys_down = keysDown(); - // Tranfiere las imagenes a la pantalla superior, backbuffer - NF_Copy8bitsBuffer(1, 2, 1); - // Tranfiere las imagenes a la pantalla superior, capa 3 - NF_Copy8bitsBuffer(1, 1, 0); - // Copia el BackBuffer de la pantalla superior a la capa 2 - NF_Flip8bitsBackBuffer(1, 0); + // Check if the touch screen is pressed + if (keys_held & KEY_TOUCH) + { + int x = touchscreen.px - 8; + if (x < 0) + x = 0; + if (x > 239) + x = 239; - // Transfiere a la VRAM los sprites necesarios - NF_VramSpriteGfx(1, 0, 0, true); // Bola (todos los frames en VRAM) Pantalla superior - NF_VramSpritePal(1, 0, 0); + int y = touchscreen.py - 8; + if (y < 0) + y = 0; + if (y > 175) + y = 175; - // Variables generales y inicializacion del random - u8 n = 0; - srand(time(NULL)); + // Draw a 16x16 block around the touchscreen coordinates in the + // bottom screen. + for (int dy = 0; dy < 16; dy ++) + { + for (int dx = 0; dx < 16; dx ++) + { + u16 idx = ((y + dy) << 8) + (x + dx); + NF_8BITS_BACKBUFFER[1].data[idx] = 0; + } + } + } - // Crea las bolas en la pantalla superior - s16 bola_x[32]; - s16 bola_y[32]; - s8 bola_spx[32]; - s8 bola_spy[32]; - for (n = 0; n < 32; n ++) { - bola_x[n] = (rand() % 223); - bola_y[n] = (rand() % 159); - bola_spx[n] = (rand() % 3) + 1; - bola_spy[n] = (rand() % 3) + 1; - NF_CreateSprite(1, n, 0, 0, bola_x[n], bola_y[n]); - NF_SpriteLayer(1, n, 3); - } + // Press X to reload the top screen image + if (keys_down & KEY_B) + NF_Copy8bitsBuffer(1, 2, 1); - // Variables del control del touchpad - u16 keys = 0; - touchPosition touchscreen; - s16 x = 0; - s16 y = 0; + // Copy bottom screen backbuffer to layer 2 + NF_Flip8bitsBackBuffer(1, 0); - // Control del dibujado - u16 idx = 0; - u16 dx = 0; - u16 dy = 0; + // Move the sprites + for (int n = 0; n < 32; n ++) + { + bola_x[n] += bola_spx[n]; + if ((bola_x[n] < 0) || (bola_x[n] > 223)) + bola_spx[n] *= -1; - // Repite para siempre - while (1) { + bola_y[n] += bola_spy[n]; + if ((bola_y[n] < 0) || (bola_y[n] > 159)) + bola_spy[n] *= -1; - // Lectura de posicion del stylus - scanKeys(); // Lee el touchpad via Libnds - touchRead(&touchscreen); - keys = keysHeld(); // Verifica el estado del touchscreen + NF_MoveSprite(1, n, bola_x[n], bola_y[n]); + } - // Si presionas sobre el keypad... - if (keys & KEY_TOUCH) { + // Update OAM array + NF_SpriteOamSet(1); - // Lee el touchpad - x = (touchscreen.px - 8); - if (x < 0) x = 0; - if (x > 239) x = 239; - y = ((touchscreen.py - 8)); - if (y < 0) y = 0; - if (y > 175) y = 175; + // Wait for the screen refresh + swiWaitForVBlank(); - // Borra un bloque de 16x16 - for (dy = 0; dy < 16; dy ++) { - for (dx = 0; dx < 16; dx ++) { - idx = ((y + dy) << 8) + (x + dx); - // Pantalla inferior - NF_8BITS_BACKBUFFER[1].data[idx] = 0; - } - } - - } - - // Lee las teclas pulsadas - keys = keysDown(); - - // Presiona X restaura imagen superior - if (keys & KEY_B) NF_Copy8bitsBuffer(1, 2, 1); - - // Copia el BackBuffer de la pantalla inferior a la capa 2 - NF_Flip8bitsBackBuffer(1, 0); - - // Mueve las bolas - for (n = 0; n < 32; n ++) { - bola_x[n] += bola_spx[n]; - if ((bola_x[n] < 0) || (bola_x[n] > 223)) bola_spx[n] *= -1; - bola_y[n] += bola_spy[n]; - if ((bola_y[n] < 0) || (bola_y[n] > 159)) bola_spy[n] *= -1; - NF_MoveSprite(1, n, bola_x[n], bola_y[n]); - } - - // Actualiza el array de OAM - NF_SpriteOamSet(1); - - swiWaitForVBlank(); // Espera al sincronismo vertical - - // Actualiza el OAM - oamUpdate(&oamSub); - - } - - return 0; + // Update OAM + oamUpdate(&oamSub); + } + return 0; } diff --git a/examples/graphics/affine/source/main.c b/examples/graphics/affine/source/main.c index 224306a..055bef8 100644 --- a/examples/graphics/affine/source/main.c +++ b/examples/graphics/affine/source/main.c @@ -137,7 +137,8 @@ int main(int argc, char **argv) angle -= 2048; } - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); // Update parameters of the affine backgrounds for (int n = 0; n < 2; n ++) diff --git a/examples/graphics/bg/source/main.c b/examples/graphics/bg/source/main.c index 52e7e9b..e1dc20c 100644 --- a/examples/graphics/bg/source/main.c +++ b/examples/graphics/bg/source/main.c @@ -60,7 +60,7 @@ int main(int argc, char **argv) while (1) { scanKeys(); // Read keypad - uint16_t keys = keysHeld(); // Keys currently pressed + u16 keys = keysHeld(); // Keys currently pressed // If pressing left if (keys & KEY_LEFT) @@ -82,7 +82,8 @@ int main(int argc, char **argv) bg_x[1] = (int)(bg_x[0] / 1.5); bg_x[2] = (int)(bg_x[1] / 1.5); - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); // Update background scroll during vertical blanking to avoid tearing for (int n = 0; n < 4; n ++) diff --git a/examples/graphics/imgdraw/source/main.c b/examples/graphics/imgdraw/source/main.c index 8b3c6ae..025269f 100644 --- a/examples/graphics/imgdraw/source/main.c +++ b/examples/graphics/imgdraw/source/main.c @@ -78,7 +78,8 @@ int main(int argc, char **argv) NF_Copy16bitsBuffer(1, 1, 0); // Background NF_Draw16bitsImage(1, 1, x, y, true); // Ball (magenta is transparent) - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); // Send backbuffers to the screen NF_Flip16bitsBackBuffer(0); diff --git a/examples/graphics/sprite/source/main.c b/examples/graphics/sprite/source/main.c index 2aa439b..af12f58 100644 --- a/examples/graphics/sprite/source/main.c +++ b/examples/graphics/sprite/source/main.c @@ -36,7 +36,7 @@ int main(int argc, char **argv) NF_InitTiledBgSys(0); // Top screen NF_InitTiledBgSys(1); // Bottom screen - // Initialize sprite backgrounds system + // Initialize sprite system NF_InitSpriteBuffers(); // Initialize storage buffers NF_InitSpriteSys(0); // Top screen NF_InitSpriteSys(1); // Bottom screen @@ -134,7 +134,8 @@ int main(int argc, char **argv) NF_SpriteOamSet(0); NF_SpriteOamSet(1); - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); // Update OAM oamUpdate(&oamMain); diff --git a/examples/media/bmpload/source/main.c b/examples/media/bmpload/source/main.c index 1bfdb95..0c53efb 100644 --- a/examples/media/bmpload/source/main.c +++ b/examples/media/bmpload/source/main.c @@ -93,7 +93,8 @@ int main(int argc, char **argv) NF_Draw16bitsImage(1, img2, 0, 0, false); } - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); // Send backbuffers to the screen NF_Flip16bitsBackBuffer(0); diff --git a/examples/media/bmpscroll/source/main.c b/examples/media/bmpscroll/source/main.c index 699d641..afb3fff 100644 --- a/examples/media/bmpscroll/source/main.c +++ b/examples/media/bmpscroll/source/main.c @@ -155,7 +155,8 @@ int main(int argc, char **argv) } } - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); // Send backbuffer to the screen NF_Flip16bitsBackBuffer(0); diff --git a/examples/sound/rawsfx/source/main.c b/examples/sound/rawsfx/source/main.c index 4e178e2..1ac7da4 100644 --- a/examples/sound/rawsfx/source/main.c +++ b/examples/sound/rawsfx/source/main.c @@ -92,7 +92,8 @@ int main(int argc, char **argv) if (newpress & KEY_L) NF_PlayRawSound(0, 127, 0, false, 0); - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); } return 0; diff --git a/examples/wifi/udptalk/source/main.c b/examples/wifi/udptalk/source/main.c index 89990da..19dc4bd 100644 --- a/examples/wifi/udptalk/source/main.c +++ b/examples/wifi/udptalk/source/main.c @@ -1,404 +1,350 @@ // SPDX-License-Identifier: CC0-1.0 // // SPDX-FileContributor: NightFox & Co., 2010 +// +// Basic UDP communications example. +// http://www.nightfoxandco.com -/* -------------------------------------------------- - - NightFox's Lib Template - Ejemplo basico comunicacion con el protocolo UDP - - Requiere DevkitARM - Requiere NightFox's Lib - - Codigo por NightFox - http://www.nightfoxandco.com - Inicio 10 de Octubre del 2009 - -------------------------------------------------- -*/ - - - - - -/* -------------------------------------------------- - Includes -------------------------------------------------- -*/ - - -// Includes propietarios NDS #include -// Includes C++ #include #include #include -// Includes propios #include -#include "nf_wifi.h" - - -/* -------------------------------------------------- - Defines -------------------------------------------------- -*/ +#include #define myport 22334 -char server_ip[18]; // Guarda la IP del servidor +char server_ip[18]; // Stores the IP of the server -bool _ConnectWIFI(void); // Conectate al punto de acceso por defecto -u8 _SelectMode(void); // Servidor o cliente -s16 _SendData(const char* mydata); // Envia datos por el canal abierto -s16 _GetData(void); // Recibe datos por el canal abierto -s16 _LookForServer(void); // Busca un servidor al que conectarse +// Tries to connect to the default access point +bool ConnectWIFI(void) +{ + bool status = false; + printf("Conectando via WFC...\n\n"); + swiWaitForVBlank(); + if (NF_WiFiConnectDefaultAp()) + { + // Return connection parameters + printf("Conexion realizada.\n\n"); + printf("IP : %s\n", inet_ntoa(NF_IP)); + printf("Gateway: %s\n", inet_ntoa(NF_GATEWAY)); + printf("Mask : %s\n", inet_ntoa(NF_MASK)); + printf("DNS1 : %s\n", inet_ntoa(NF_DNS1)); + printf("DNS2 : %s\n\n", inet_ntoa(NF_DNS2)); + // Success + status = true; + } + else + { + // Error + printf("Conexion no establecida\n"); + } -/* -------------------------------------------------- - Main() - Bloque general del programa -------------------------------------------------- -*/ - -int main(int argc, char **argv) { - - u8 modo = 0; // Cliente (1) - Servidor (2) - u16 keys = 0; // Lectura del teclado - - u32 contador = 0; - char temp[256]; - bool loop = true; - bool senddata = true; - - // Inicializa las 2D - NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior - NF_Set2D(1, 0); // Modo 2D_0 en la pantalla inferior - - // Inicializa la consola de texto - consoleDemoInit(); - consoleClear(); - - // Intenta conectarte al WFC... - if (_ConnectWIFI()) { - - // Selecciona si seras servidor o cliente - modo = _SelectMode(); - - // Inicia como servidor o cliente - if (modo == 1) { - // Cliente - if (_LookForServer() > 0) { - //if (1) { - NF_WIFI_CreateUdpSender(server_ip, myport); - } else { - loop = false; - } - } else { - // Servidor - NF_WIFI_CreateUdpListener(myport); - } - - - - // Envia o recive datos hasta cancelar la transmision - while (loop) { - - // Lee el teclado - scanKeys(); - keys = keysDown(); - - if (modo == 1) { // Envio de datos al servidor - - // Si pulsas A, envia datos - if (keys & KEY_A) senddata = true; - // Si pulsas B, pausa el envio - if (keys & KEY_B) senddata = false; - // Si pulsas X, resetea el contador - if (keys & KEY_X) contador = 0; - // Si se pulsa R, sal - if (keys & KEY_R) loop = false; - - - - if (senddata) { - - if (loop) { - // Debes enviar datos... - sprintf(temp, "%05lu", contador); - } else { - // o la señal de salida? - sprintf(temp, "Exit"); - } - - // Envia y verifica si se han recibido - printf("Envio: %s\n", temp); - if (_SendData(temp) > 0) { - // Imprime los datos recibidos - printf("Verificado: %s\n\n", NF_RECV_BUFFER); - // Incrementa el valor - contador ++; - if (contador > 9999) contador = 0; - } else { - printf("Error de envio.\n"); - } - - } - - - } else { // Recepcion de datos desde el cliente - - // Si se pulsa R, sal - if (keys & KEY_R) loop = false; - - // Recibe los datos - if (_GetData() > 0) { - // Imprime los datos recibidos - printf("Recivido: %s\n", NF_RECV_BUFFER); - // Si has recibido la señal de salida... - if (strcmp(NF_RECV_BUFFER, "Exit") == 0) loop = false; - } else { - // Si no hay datos, esperalos - printf("Esperando datos...\n"); - } - - } - - // Espera al sincronismo vertical - swiWaitForVBlank(); - - } - - } - - // Cierra el socket - close(NF_SOCKET); - - // Deten el WIFI - NF_WiFiDisconnectAp(); - - // Informa - printf("\nSesion finalizada\n"); - - while (1) { - swiWaitForVBlank(); - } - - - return 0; - + swiWaitForVBlank(); + return status; } +// Wait for the user to select client (1) or server (2) mode. +u8 SelectMode(void) +{ + u8 modo = 0; + printf("A - Cliente\nB - Servidor\n"); + swiWaitForVBlank(); + while (modo == 0) + { + scanKeys(); + u16 keys = keysDown(); + if (keys & KEY_A) + modo = 1; + if (keys & KEY_B) + modo = 2; -/* -------------------------------------------------- - Funciones -------------------------------------------------- -*/ - -// Intenta conectarte al punto de acceso por defecto -bool _ConnectWIFI(void) { - - bool status = false; - - // Intenta conectarte al AP... - printf("Conectando via WFC...\n\n"); - swiWaitForVBlank(); - - if (NF_WiFiConnectDefaultAp()) { - - // Devuelve los parametros de la conexion TCP/IP con el AP - printf("Conexion realizada.\n\n"); - printf("Ip : %s\n", inet_ntoa(NF_IP)); - printf("Gateway: %s\n", inet_ntoa(NF_GATEWAY)); - printf("Mask : %s\n", inet_ntoa(NF_MASK)); - printf("Dns1 : %s\n", inet_ntoa(NF_DNS1)); - printf("Dns2 : %s\n\n", inet_ntoa(NF_DNS2)); - - // Marca como conectado - status = true; - - } else { - - // No se ha podido conectar - printf("Conexion no establecida\n"); - - } - - swiWaitForVBlank(); - return status; + swiWaitForVBlank(); + } + return modo; } +// Send data through the open channel +s16 SendData(const char *mydata) +{ + bool checksum = false; + bool timeout = false; + s32 status = 0; + char buffer[NF_WIFI_BUFFER_SIZE]; + // Copy data to a temporary buffer + sprintf(buffer, "%s", mydata); -// Selecciona si seras Cliente (1) o Servidor (2) -u8 _SelectMode(void) { + while (!checksum && !timeout) + { + // Send data using UDP + NF_WIFI_UdpSend(buffer); - u8 modo = 0; - u16 keys = 0; + // Wait for the confirmation from the other end with a 600 ms timeout + status = NF_WIFI_UdpListen(600000); - printf("A - Cliente\nB - Servidor\n"); - swiWaitForVBlank(); - - while (modo == 0) { - scanKeys(); - keys = keysDown(); - if (keys & KEY_A) modo = 1; - if (keys & KEY_B) modo = 2; - swiWaitForVBlank(); - } - - return modo; + // Do a data checksum + if (status > 0) + { + if ((strcmp(NF_SEND_BUFFER, NF_RECV_BUFFER) == 0)) + { + checksum = true; + } + else + { + checksum = true; + status = -1; // Checksum error + } + } + else + { + timeout = true; + status = -2; // Timed out + } + } + return status; } +// Receive data from the open channel +s16 GetData(void) +{ + // Listen to data with a 300 millisecond timeout + s32 status = NF_WIFI_UdpListen(300000); + // If any data has been received, return them to the sender to check them + if (status > 0) + NF_WIFI_UdpSend(NF_RECV_BUFFER); -// Envia datos por el canal abierto -s16 _SendData(const char* mydata) { - - // Variables - bool checksum = false; - bool timeout = false; - s32 status = 0; - char buffer[NF_WIFI_BUFFER_SIZE]; - - // Copia los datos al buffer - sprintf(buffer, "%s", mydata); - - while (!checksum && !timeout) { - // Envia los datos por UDP - NF_WIFI_UdpSend(buffer); - // Espera la confirmacion de los datos - status = NF_WIFI_UdpListen(600000); // Time out 600 milisegundos - // Realiza un checksum de los datos - if (status > 0) { - if ((strcmp(NF_SEND_BUFFER, NF_RECV_BUFFER) == 0)) { - // Si el envio es correcto, continua - checksum = true; - } else { - checksum = true; - status = -1; // Error de checksum - } - } else { - timeout = true; - status = -2; // Time out - } - } - - // Devuelve el estado - return status; - + return status; } +// Scans all IPs in the specified range to look for a server to connect to. +s16 LookForServer(void) +{ + // Variables locales + char myip[18]; + char temp[64]; + u16 p = 0; -// Recibe datos por el canal abierto -s16 _GetData(void) { + bool loop = true; + s8 status = 0; - // Variables - s32 status = 0; + // Get the local IP and extract its range (for example, "192.168.0.") + sprintf(temp, "%s", inet_ntoa(NF_IP)); + for (int n = 0; n < strlen(temp); n ++) + { + myip[n] = temp[n]; + char c = temp[n]; - // Espera los datos - status = NF_WIFI_UdpListen(300000); // Time out 300 milisegundos + if (c == '.') + { + p++; - // Si se han recibido datos, devuelvelos para su verificacion - if (status > 0) NF_WIFI_UdpSend(NF_RECV_BUFFER); + // If this is the third dot, end the string + if (p == 3) + { + myip[n + 1] = '\0'; + break; + } + } + } - // Devuelve el estado - return status; + // Scan all possible IPs + p = 0; + for (int n = 1; n < 255; n ++) + { + scanKeys(); + u16 keys = keysDown(); + + // Generate IP + sprintf(temp, "%s%d", myip, n); + printf("%s ", temp); + swiWaitForVBlank(); + + // Create sender socket + NF_WIFI_CreateUdpSender(temp, myport); + + // Send data and verify that it has been received + loop = true; + while (loop) + { + status = SendData("HANDSHAKE"); + if (status > 0) + { + // Print received data + printf("Encontrado.\n"); + + // Save its value + sprintf(server_ip, temp); + p = n; + n = 255; + loop = false; + } + else + { + printf("Timed out.\n"); + if (status == -2) + loop = false; + } + } + + // Close the socket + close(NF_SOCKET); + + // If the user wants to cancel, exit + if (keys & KEY_R) + break; + } + + return p; } +int main(int argc, char **argv) +{ + u8 modo = 0; // Client (1) - Server (2) + u32 contador = 0; + char temp[256]; + bool loop = true; + bool senddata = true; -// Escanea el rango de IP's para encontrar el servidor -s16 _LookForServer(void) { + // Initialize 2D engine in both screens and use mode 0 + NF_Set2D(0, 0); + NF_Set2D(1, 0); - // Variables locales - char myip[18]; - char temp[64]; - char character[2]; + // Initialize demo text console + consoleDemoInit(); - u16 n = 0; - u16 p = 0; + // Try to connect to the WiFi access point + if (ConnectWIFI()) + { + // Ask the user if this console is a server or a client + modo = SelectMode(); - bool loop = true; - s8 status = 0; + if (modo == 1) + { + // Run as client + if (LookForServer() > 0) + NF_WIFI_CreateUdpSender(server_ip, myport); + else + loop = false; + } + else + { + // Run as server + NF_WIFI_CreateUdpListener(myport); + } - u16 keys = 0; + // Send or receive data until the transmission is cancelled + while (loop) + { + scanKeys(); + u16 keys = keysDown(); - // Guarda la direccion IP local (su rango, por ejemplo "192.168.0." - sprintf(temp, "%s", inet_ntoa(NF_IP)); - for (n = 0; n < (strlen(temp)); n ++) { - // Copia el caracter - memcpy((myip + n), (temp + n), 1); - memcpy(character, (temp + n), 1); - character[1] = '\0'; - // Si es un punto... - if (strcmp(character, ".") == 0) { - p ++; - // Si es el 3er punto... - if (p == 3) { - myip[(n + 1)] = '\0'; // Pon el caracter terminador - n = strlen(temp); // Y termina - } - } - } + if (modo == 1) + { + // Send data to server - // Escanea todo el rango de IP's - p = 0; + // Send data when the user presses A + if (keys & KEY_A) + senddata = true; - for (n = 1; n < 255; n ++) { + // Stop sending data when the user presses B + if (keys & KEY_B) + senddata = false; - // Lee el teclado - scanKeys(); - keys = keysDown(); + // Reset counter when the user presses X + if (keys & KEY_X) + contador = 0; - // Calcula la IP - sprintf(temp, "%s%d", myip, n); - printf("%s ", temp); - swiWaitForVBlank(); + // Exit if R is pressed + if (keys & KEY_R) + loop = false; - // Crea el socket de envio - NF_WIFI_CreateUdpSender(temp, myport); + if (senddata) + { + if (loop) + { + // Send data if the loop is active + sprintf(temp, "%05lu", contador); + } + else + { + // If not, send an exit string + sprintf(temp, "Exit"); + } - // Envia y verifica si se han recibido - loop = true; - while (loop) { - status = _SendData("HANDSHAKE"); - if (status > 0) { - // Imprime los datos recibidos - printf("Encontrado.\n"); - // Guarda el valor - sprintf(server_ip, temp); - p = n; - n = 255; - loop = false; - } else { - printf("Time Out.\n"); - if (status == -2) loop = false; - } - } + // Send it and verify that it has been received + printf("Envio: %s\n", temp); + if (SendData(temp) > 0) + { + // Print the received data + printf("Verificado: %s\n\n", NF_RECV_BUFFER); + // Increment counter + contador++; + if (contador > 9999) + contador = 0; + } + else + { + printf("Error de envio.\n"); + } + } + } + else + { + // Data reception in the client - // Cierra el socket creado - close(NF_SOCKET); + // Exit loop if R is pressed + if (keys & KEY_R) + loop = false; - // Si pulsas cancelar - if (keys & KEY_R) n = 255; + // Receive data + if (GetData() > 0) + { + // Print received data + printf("Recivido: %s\n", NF_RECV_BUFFER); - } + // If the exit signal has been received + if (strcmp(NF_RECV_BUFFER, "Exit") == 0) + loop = false; + } + else + { + // If there is nothing available, wait for data + printf("Esperando datos...\n"); + } + } - return p; + // Wait for the screen refresh + swiWaitForVBlank(); + } + } + // Close the socket + close(NF_SOCKET); + + // Stop WiFi + NF_WiFiDisconnectAp(); + + printf("\nSesion finalizada\n"); + + while (1) + { + swiWaitForVBlank(); + } + + return 0; } diff --git a/template/source/main.c b/template/source/main.c index 77d72cd..1263ef9 100644 --- a/template/source/main.c +++ b/template/source/main.c @@ -19,7 +19,8 @@ int main(int argc, char **argv) while (1) { - swiWaitForVBlank(); // Wait for the screen refresh + // Wait for the screen refresh + swiWaitForVBlank(); } // If this is reached, the program will return to the loader if the loader