Forráskód Böngészése

* Nintendo DS port updated to libnds ver.1.7.3

git-svn-id: trunk@42202 -
Legolas 6 éve
szülő
commit
7c02f2b531
98 módosított fájl, 5009 hozzáadás és 1970 törlés
  1. 13 0
      .gitattributes
  2. 199 103
      compiler/systems/t_nds.pas
  3. 7 0
      packages/libndsfpc/examples/audio/maxmod/audio_modes/audio_modes.pp
  4. 7 0
      packages/libndsfpc/examples/audio/maxmod/reverb/reverb.pp
  5. 12 1
      packages/libndsfpc/examples/audio/maxmod/song_events_example/song_events_example.pp
  6. 12 0
      packages/libndsfpc/examples/audio/maxmod/song_events_example2/song_events_example2.pp
  7. 13 0
      packages/libndsfpc/examples/audio/maxmod/streaming/streaming.pp
  8. 6 2
      packages/libndsfpc/examples/audio/micrecord/micrecord.pp
  9. 12 7
      packages/libndsfpc/examples/card/eeprom/eeprom.pp
  10. 6 3
      packages/libndsfpc/examples/ds_motion/dsMotion.pp
  11. 126 55
      packages/libndsfpc/examples/dswifi/ap_search/apSearch.pp
  12. 5 1
      packages/libndsfpc/examples/dswifi/autoconnect/autoconnect.pp
  13. 8 1
      packages/libndsfpc/examples/dswifi/httpget/httpget.pp
  14. 5 2
      packages/libndsfpc/examples/filesystem/libfat/libfatdir/libfatdir.pp
  15. 5 0
      packages/libndsfpc/examples/graphics/3D/3D_Both_Screens/3DBothScreens.pp
  16. 96 96
      packages/libndsfpc/examples/graphics/3D/BoxTest/BoxTest.pp
  17. 2 1
      packages/libndsfpc/examples/graphics/3D/Display_List/DisplayList.pp
  18. 1 0
      packages/libndsfpc/examples/graphics/3D/Display_List_2/DisplayList2.pp
  19. 1 0
      packages/libndsfpc/examples/graphics/3D/Env_Mapping/EnvMapping.pp
  20. 7 0
      packages/libndsfpc/examples/graphics/3D/Mixed_Text_3D/MixedText3D.pp
  21. 8 2
      packages/libndsfpc/examples/graphics/3D/Ortho/Ortho.pp
  22. 4 2
      packages/libndsfpc/examples/graphics/3D/Paletted_Cube/PalettedCube.pp
  23. 134 132
      packages/libndsfpc/examples/graphics/3D/Picking/Picking.pp
  24. 2 0
      packages/libndsfpc/examples/graphics/3D/Simple_Quad/SimpleQuad.pp
  25. 2 0
      packages/libndsfpc/examples/graphics/3D/Simple_Tri/SimpleTri.pp
  26. 16 14
      packages/libndsfpc/examples/graphics/3D/Textured_Cube/TexturedCube.pp
  27. 7 5
      packages/libndsfpc/examples/graphics/3D/Textured_Quad/TexturedQuad.pp
  28. 101 99
      packages/libndsfpc/examples/graphics/3D/Toon_Shading/ToonShading.pp
  29. 7 1
      packages/libndsfpc/examples/graphics/3D/nehe/lesson01/lesson01.pp
  30. 65 59
      packages/libndsfpc/examples/graphics/3D/nehe/lesson02/lesson02.pp
  31. 51 48
      packages/libndsfpc/examples/graphics/3D/nehe/lesson03/lesson03.pp
  32. 62 58
      packages/libndsfpc/examples/graphics/3D/nehe/lesson04/lesson04.pp
  33. 112 107
      packages/libndsfpc/examples/graphics/3D/nehe/lesson05/lesson05.pp
  34. 130 124
      packages/libndsfpc/examples/graphics/3D/nehe/lesson06/lesson06.pp
  35. 161 161
      packages/libndsfpc/examples/graphics/3D/nehe/lesson07/lesson07.pp
  36. 162 162
      packages/libndsfpc/examples/graphics/3D/nehe/lesson08/lesson08.pp
  37. 134 130
      packages/libndsfpc/examples/graphics/3D/nehe/lesson09/lesson09.pp
  38. 11 7
      packages/libndsfpc/examples/graphics/3D/nehe/lesson10/lesson10.pp
  39. 2 0
      packages/libndsfpc/examples/graphics/3D/nehe/lesson10b/lesson10b.pp
  40. 145 139
      packages/libndsfpc/examples/graphics/3D/nehe/lesson11/lesson11.pp
  41. 55 53
      packages/libndsfpc/examples/graphics/Backgrounds/all_in_one/BackgroundAllInOne.pp
  42. 1 1
      packages/libndsfpc/examples/graphics/Makefile.fpc
  43. 8 2
      packages/libndsfpc/examples/graphics/Printing/ansi_console/AnsiConsole.pp
  44. 1 1
      packages/libndsfpc/examples/graphics/Printing/console_windows/ConsoleWindows.pp
  45. 29 24
      packages/libndsfpc/examples/graphics/Printing/custom_font/CustomFont.pp
  46. 25 21
      packages/libndsfpc/examples/graphics/Printing/print_both_screens/printBothScreens.pp
  47. 43 42
      packages/libndsfpc/examples/graphics/Printing/rotscale_text/RotscaleText.pp
  48. 7 4
      packages/libndsfpc/examples/graphics/Sprites/allocation_test/AllocationTest.pp
  49. 5 0
      packages/libndsfpc/examples/graphics/Sprites/bitmap_sprites/BitmapSprites.pp
  50. 149 117
      packages/libndsfpc/examples/graphics/Sprites/fire_and_sprites/FireAndSprites.pp
  51. BIN
      packages/libndsfpc/examples/graphics/Sprites/fire_and_sprites/data/ball.pcx
  52. 1679 0
      packages/libndsfpc/examples/graphics/grit/256colorTilemap/Makefile
  53. 124 0
      packages/libndsfpc/examples/graphics/grit/256colorTilemap/Makefile.fpc
  54. 21 0
      packages/libndsfpc/examples/graphics/grit/256colorTilemap/gfx/tilemap.grit
  55. BIN
      packages/libndsfpc/examples/graphics/grit/256colorTilemap/gfx/tilemap.png
  56. 39 0
      packages/libndsfpc/examples/graphics/grit/256colorTilemap/tilemap_256_color.pp
  57. 18 0
      packages/libndsfpc/examples/graphics/grit/Makefile.fpc
  58. 15 1
      packages/libndsfpc/examples/hello_world/helloWorld.pp
  59. 1 1
      packages/libndsfpc/examples/time/RealTimeClock/Makefile.fpc
  60. 2 2
      packages/libndsfpc/src/dswifi/inc/dswifi9.inc
  61. 2 1
      packages/libndsfpc/src/fat/fat.inc
  62. 3 0
      packages/libndsfpc/src/fat/gbfs.pp
  63. 76 0
      packages/libndsfpc/src/nds/arm7/aes.inc
  64. 46 0
      packages/libndsfpc/src/nds/arm7/audio.inc
  65. 2 2
      packages/libndsfpc/src/nds/arm7/clock.inc
  66. 38 0
      packages/libndsfpc/src/nds/arm7/codec.inc
  67. 25 3
      packages/libndsfpc/src/nds/arm7/sdmmc.inc
  68. 1 1
      packages/libndsfpc/src/nds/arm7/touch.inc
  69. 37 0
      packages/libndsfpc/src/nds/arm9/cache_asm.inc
  70. 4 4
      packages/libndsfpc/src/nds/arm9/dldi.inc
  71. 20 0
      packages/libndsfpc/src/nds/arm9/dldi_asm.inc
  72. 2 2
      packages/libndsfpc/src/nds/arm9/guitarGrip.inc
  73. 2 2
      packages/libndsfpc/src/nds/arm9/math.inc
  74. 6 0
      packages/libndsfpc/src/nds/arm9/nand.inc
  75. 1 1
      packages/libndsfpc/src/nds/arm9/sassert.inc
  76. 1 1
      packages/libndsfpc/src/nds/arm9/sprite.inc
  77. 5 5
      packages/libndsfpc/src/nds/arm9/video.inc
  78. 9 8
      packages/libndsfpc/src/nds/card.inc
  79. 9 9
      packages/libndsfpc/src/nds/disc_io.inc
  80. 2 2
      packages/libndsfpc/src/nds/dma.inc
  81. 8 7
      packages/libndsfpc/src/nds/fifocommon.inc
  82. 1 1
      packages/libndsfpc/src/nds/fifomessages.inc
  83. 1 1
      packages/libndsfpc/src/nds/interrupts.inc
  84. 3 3
      packages/libndsfpc/src/nds/libversion.inc
  85. 88 10
      packages/libndsfpc/src/nds/memory.inc
  86. 7 0
      packages/libndsfpc/src/nds/ndsinclude.inc
  87. 8 1
      packages/libndsfpc/src/nds/ndstypes.inc
  88. 8 8
      packages/libndsfpc/src/nds/registers_alt.inc
  89. 31 0
      packages/libndsfpc/src/nds/rsa.inc
  90. 30 0
      packages/libndsfpc/src/nds/sha1.inc
  91. 33 10
      packages/libndsfpc/src/nds/system.inc
  92. 1 1
      packages/libndsfpc/src/nds7.pp
  93. 1 0
      packages/libndsfpc/src/nds9.pp
  94. 93 4
      rtl/nds/cprt07.as
  95. 110 44
      rtl/nds/cprt09.as
  96. 99 2
      rtl/nds/prt07.as
  97. 112 46
      rtl/nds/prt09.as
  98. 3 0
      rtl/nds/system.pp

+ 13 - 0
.gitattributes

@@ -5898,6 +5898,12 @@ packages/libndsfpc/examples/graphics/Sprites/sprite_extended_palettes/SpriteExte
 packages/libndsfpc/examples/graphics/Sprites/sprite_rotate/Makefile svneol=native#text/plain
 packages/libndsfpc/examples/graphics/Sprites/sprite_rotate/Makefile.fpc svneol=native#text/plain
 packages/libndsfpc/examples/graphics/Sprites/sprite_rotate/SpriteRotate.pp svneol=native#text/plain
+packages/libndsfpc/examples/graphics/grit/256colorTilemap/Makefile svneol=native#text/plain
+packages/libndsfpc/examples/graphics/grit/256colorTilemap/Makefile.fpc svneol=native#text/plain
+packages/libndsfpc/examples/graphics/grit/256colorTilemap/gfx/tilemap.grit svneol=native#text/plain
+packages/libndsfpc/examples/graphics/grit/256colorTilemap/gfx/tilemap.png -text
+packages/libndsfpc/examples/graphics/grit/256colorTilemap/tilemap_256_color.pp svneol=native#text/plain
+packages/libndsfpc/examples/graphics/grit/Makefile.fpc svneol=native#text/plain
 packages/libndsfpc/examples/hello_world/Makefile svneol=native#text/plain
 packages/libndsfpc/examples/hello_world/Makefile.fpc svneol=native#text/plain
 packages/libndsfpc/examples/hello_world/helloWorld.pp svneol=native#text/plain
@@ -5963,8 +5969,10 @@ packages/libndsfpc/src/maxmod/inc/mm_msl.inc svneol=native#text/plain
 packages/libndsfpc/src/maxmod/inc/mm_types.inc svneol=native#text/plain
 packages/libndsfpc/src/maxmod/maxmod7.pp svneol=native#text/plain
 packages/libndsfpc/src/maxmod/maxmod9.pp svneol=native#text/plain
+packages/libndsfpc/src/nds/arm7/aes.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm7/audio.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm7/clock.inc svneol=native#text/plain
+packages/libndsfpc/src/nds/arm7/codec.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm7/i2c.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm7/input.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm7/sdmmc.inc svneol=native#text/plain
@@ -5973,9 +5981,11 @@ packages/libndsfpc/src/nds/arm7/touch.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/background.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/boxtest.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/cache.inc svneol=native#text/plain
+packages/libndsfpc/src/nds/arm9/cache_asm.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/console.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/decompress.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/dldi.inc svneol=native#text/plain
+packages/libndsfpc/src/nds/arm9/dldi_asm.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/dynamicArray.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/exceptions.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/guitarGrip.inc svneol=native#text/plain
@@ -5984,6 +5994,7 @@ packages/libndsfpc/src/nds/arm9/input.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/keyboard.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/linkedlist.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/math.inc svneol=native#text/plain
+packages/libndsfpc/src/nds/arm9/nand.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/ndsmotion.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/paddle.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/arm9/pcx.inc svneol=native#text/plain
@@ -6015,6 +6026,8 @@ packages/libndsfpc/src/nds/nds.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/ndsinclude.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/ndstypes.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/registers_alt.inc svneol=native#text/plain
+packages/libndsfpc/src/nds/rsa.inc svneol=native#text/plain
+packages/libndsfpc/src/nds/sha1.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/system.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/timers.inc svneol=native#text/plain
 packages/libndsfpc/src/nds/touch.inc svneol=native#text/plain

+ 199 - 103
compiler/systems/t_nds.pas

@@ -248,22 +248,24 @@ begin
       if apptype=app_arm9 then //ARM9
       begin
         add('MEMORY {');
-        add('	rom	: ORIGIN = 0x08000000, LENGTH = 32M');
-        add('	ewram	: ORIGIN = 0x02000000, LENGTH = 4M - 4k');
+        add('	ewram	: ORIGIN = 0x02000000, LENGTH = 4M - 512k');
         add('	dtcm	: ORIGIN = 0x0b000000, LENGTH = 16K');
         add('	vectors	: ORIGIN = 0x01000000, LENGTH = 256');
         add('	itcm	: ORIGIN = 0x01000100, LENGTH = 32K - 256');
         add('}');
-        add('');
-        add('OUTPUT_ARCH(arm)');
+
+        add('/*--------------------------------------------------------------------------------');
+        add('	This Source Code Form is subject to the terms of the Mozilla Public License,');
+        add('	v. 2.0. If a copy of the MPL was not distributed with this file, You can');
+        add('	obtain one at https://mozilla.org/MPL/2.0/.');
+        add('--------------------------------------------------------------------------------*/');
         add('OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")');
+        add('OUTPUT_ARCH(arm)');
         add('ENTRY(_start)');
         add('');
-        add('__vectors_start	=	ORIGIN(vectors);');
-        add('__itcm_start	=	ORIGIN(itcm);');
         add('__ewram_end	=	ORIGIN(ewram) + LENGTH(ewram);');
         add('__eheap_end	=	ORIGIN(ewram) + LENGTH(ewram);');
-        add('__dtcm_start	=	ORIGIN(dtcm);');
+        add('');
         add('__dtcm_top	=	ORIGIN(dtcm) + LENGTH(dtcm);');
         add('__irq_flags	=	__dtcm_top - 0x08;');
         add('__irq_vector	=	__dtcm_top - 0x04;');
@@ -272,52 +274,67 @@ begin
         add('__sp_irq	=	__sp_svc - 0x100;');
         add('__sp_usr	=	__sp_irq - 0x100;');
         add('');
+        add('PHDRS {');
+        add('	main    PT_LOAD FLAGS(7);');
+        add('	dtcm    PT_LOAD FLAGS(7);');
+        add('	itcm    PT_LOAD FLAGS(7);');
+        add('	vectors PT_LOAD FLAGS(7);');
+        add('	twl     PT_LOAD FLAGS(0x100007);');
+        add('}');
+        add('');
         add('SECTIONS');
         add('{');
-        add('	.init	:');
+        add('	/* Secure area crap */');
+        add('	.secure : { *(.secure) } >ewram :main = 0');
+        add('');
+        add('	.crt0	:');
         add('	{');
         add('		__text_start = . ;');
-        add('		KEEP (*(.init))');
+        add('		KEEP (*(.crt0))');
         add('		. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0x00');
         add('');
-        add('	.plt : { *(.plt) } >ewram = 0xff');
+        add('	.plt : { *(.plt) } >ewram :main = 0xff');
         add('');
-        add('	.text :   /* ALIGN (4): */');
+        add('	.init :');
         add('	{');
-        add('		*(EXCLUDE_FILE (*.itcm*) .text)');
+        add('		KEEP (*(SORT_NONE(.init)))');
+        add('	} >ewram :main');
         add('');
-        add('		*(.text.*)');
-        add('		*(.stub)');
+        add('	.text :   /* ALIGN (4): */');
+        add('	{');
+        add('		*(EXCLUDE_FILE(*.itcm* *.vectors* *.twl*) .text)');
+        add('		*(EXCLUDE_FILE(*.itcm* *.vectors* *.twl*) .stub)');
+        add('		*(EXCLUDE_FILE(*.itcm* *.vectors* *.twl*) .text.*)');
         add('		/* .gnu.warning sections are handled specially by elf32.em.  */');
-        add('		*(.gnu.warning)');
-        add('		*(.gnu.linkonce.t*)');
+        add('		*(EXCLUDE_FILE(*.twl*) .gnu.warning)');
+        add('		*(EXCLUDE_FILE(*.twl*) .gnu.linkonce.t*)');
         add('		*(.glue_7)');
         add('		*(.glue_7t)');
         add('		. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
         add('	.fini           :');
         add('	{');
         add('		KEEP (*(.fini))');
-        add('	} >ewram =0xff');
+        add('	} >ewram :main =0xff');
         add('');
         add('	__text_end = . ;');
         add('');
         add('	.rodata :');
         add('	{');
-        add('		*(.rodata)');
+        add('		*(EXCLUDE_FILE(*.twl*) .rodata)');
         add('		*all.rodata*(*)');
-        add('		*(.roda)');
-        add('		*(.rodata.*)');
-        add('		*(.gnu.linkonce.r*)');
+        add('		*(EXCLUDE_FILE(*.twl*) .roda)');
+        add('		*(EXCLUDE_FILE(*.twl*) .rodata.*)');
+        add('		*(EXCLUDE_FILE(*.twl*) .gnu.linkonce.r*)');
         add('		SORT(CONSTRUCTORS)');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
-        add('	.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >ewram');
+        add('	.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >ewram :main');
         add(' 	__exidx_start = .;');
-        add('	ARM.exidx   : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } >ewram');
+        add('	ARM.exidx   : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } >ewram :main');
         add(' 	__exidx_end = .;');
         add('');
         add('	/*	Ensure the __preinit_array_start label is properly aligned.  We');
@@ -328,21 +345,21 @@ begin
         add('	. = ALIGN(32 / 8);');
         add('');
         add('	PROVIDE (__preinit_array_start = .);');
-        add('	.preinit_array     : { KEEP (*(.preinit_array)) } >ewram = 0xff');
+        add('	.preinit_array     : { KEEP (*(.preinit_array)) } >ewram :main = 0xff');
         add('	PROVIDE (__preinit_array_end = .);');
         add('	PROVIDE (__init_array_start = .);');
         add('	.init_array     :');
         add('	{');
         add('		KEEP (*(SORT(.init_array.*)))');
         add('		KEEP (*(.init_array))');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('	PROVIDE (__init_array_end = .);');
         add('	PROVIDE (__fini_array_start = .);');
         add('	.fini_array     :');
         add('	{');
         add('		KEEP (*(.fini_array))');
         add('		KEEP (*(SORT(.fini_array.*)))');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
         add('	PROVIDE (__fini_array_end = .);');
         add('');
@@ -359,7 +376,7 @@ begin
         add('		KEEP (*(SORT(.ctors.*)))');
         add('		KEEP (*(.ctors))');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
         add('	.dtors :');
         add('	{');
@@ -368,98 +385,122 @@ begin
         add('		KEEP (*(SORT(.dtors.*)))');
         add('		KEEP (*(.dtors))');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
         add('	.eh_frame :');
         add('	{');
         add('		KEEP (*(.eh_frame))');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
         add('	.gcc_except_table :');
         add('	{');
         add('		*(.gcc_except_table)');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
-        add('	.jcr            : { KEEP (*(.jcr)) } >ewram = 0');
-        add('	.got            : { *(.got.plt) *(.got) *(.rel.got) } >ewram = 0');
+        add('	} >ewram :main = 0xff');
+        add('	.jcr            : { KEEP (*(.jcr)) } >ewram :main = 0');
+        add('	.got            : { *(.got.plt) *(.got) *(.rel.got) } >ewram :main = 0');
         add('');
-        add('	.ewram ALIGN(4) : ');
+        add('	.ewram ALIGN(4) :'); 
         add('	{');
         add('		__ewram_start = ABSOLUTE(.) ;');
         add('		*(.ewram)');
         add('		*ewram.*(.text)');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
         add('');
         add('	.data ALIGN(4) :');
         add('	{');
         add('		__data_start = ABSOLUTE(.);');
-        add('		*(.data)');
-        add('		*(.data.*)');
-        add('		*(.gnu.linkonce.d*)');
+        add('		*(EXCLUDE_FILE(*.twl*) .data)');
+        add('		*(EXCLUDE_FILE(*.twl*) .data.*)');
+        add('		*(EXCLUDE_FILE(*.twl*) .gnu.linkonce.d*)');
         add('		CONSTRUCTORS');
         add('		. = ALIGN(4);');
         add('		__data_end = ABSOLUTE(.) ;');
-        add('	} >ewram = 0xff');
+        add('	} >ewram :main = 0xff');
         add('');
-        add('');
-        add('	__dtcm_lma = . ;');
         add('	__bss_vma = . ;');
         add('');
-        add('	.dtcm __dtcm_start : AT (__dtcm_lma)');
+        add('	.dtcm :');
         add('	{');
+        add('		__dtcm_lma = LOADADDR(.dtcm);');
+        add('		__dtcm_start = ABSOLUTE(.);');
         add('		*(.dtcm)');
         add('		*(.dtcm.*)');
         add('		. = ALIGN(4);');
         add('		__dtcm_end = ABSOLUTE(.);');
-        add('	} >dtcm  = 0xff');
-        add('');
+        add('	} >dtcm AT>ewram :dtcm = 0xff');
         add('');
-        add('	__itcm_lma = __dtcm_lma + SIZEOF(.dtcm);');
-        add('');
-        add('	.itcm __itcm_start : AT (__itcm_lma)');
+        add('	.itcm :');
         add('	{');
+        add('		__itcm_lma = LOADADDR(.itcm);');
+        add('		__itcm_start = ABSOLUTE(.);');
         add('		*(.itcm)');
-        add('		*itcm.*(.text)');
+        add('		*.itcm*(.text .stub .text.*)');
         add('		. = ALIGN(4);');
         add('		__itcm_end = ABSOLUTE(.);');
-        add('	} >itcm = 0xff');
-        add('	');
-        add('	__vectors_lma = __itcm_lma + SIZEOF(.itcm);');
+        add('	} >itcm AT>ewram :itcm = 0xff');
         add('');
-        add('	.vectors __vectors_start : AT (__vectors_lma)');
+        add('	.vectors :');
         add('	{');
-        add('		*(.vectors)');
-        add('		*vectors.*(.text)');
+        add('		__vectors_lma = LOADADDR(.vectors);');
+        add('		__vectors_start = ABSOLUTE(.);');
+        add('		KEEP(*(.vectors .vectors.*))');
         add('		. = ALIGN(4);');
         add('		__vectors_end = ABSOLUTE(.);');
-        add('	} >vectors = 0xff');
+        add('	} >vectors AT>ewram :vectors = 0xff');
         add('	');
-        add('	.sbss __dtcm_end (NOLOAD): ');
+        add('	.sbss __dtcm_end (NOLOAD):'); 
         add('	{');
         add('		__sbss_start = ABSOLUTE(.);');
         add('		__sbss_start__ = ABSOLUTE(.);');
         add('		*(.sbss)');
         add('		. = ALIGN(4);    /* REQUIRED. LD is flaky without it. */');
         add('		__sbss_end = ABSOLUTE(.);');
-        add('	} >dtcm ');
+        add('	} >dtcm :NONE');
         add('');
-        add('	.bss __bss_vma (NOLOAD): ');
+        add('	.bss __bss_vma (NOLOAD):'); 
         add('	{');
         add('		__bss_start = ABSOLUTE(.);');
         add('		__bss_start__ = ABSOLUTE(.);');
-        add('		*(.dynbss)');
-        add('		*(.gnu.linkonce.b*)');
-        add('		*(.bss*)');
-        add('		*(COMMON)');
+        add('		*(EXCLUDE_FILE(*.twl*) .dynbss)');
+        add('		*(EXCLUDE_FILE(*.twl*) .gnu.linkonce.b*)');
+        add('		*(EXCLUDE_FILE(*.twl*) .bss*)');
+        add('		*(EXCLUDE_FILE(*.twl*) COMMON)');
         add('		. = ALIGN(4);    /* REQUIRED. LD is flaky without it. */');
         add('		__bss_end__ = ABSOLUTE(.) ;');
         add('		__end__ = ABSOLUTE(.) ;');
-        add('	} AT>ewram ');
-        add('');
+        add('	} >ewram :NONE');
         add('');
+        add('	.twl __end__ : AT(MAX(0x2400000,MAX(__end__,LOADADDR(.vectors)+SIZEOF(.vectors))))');
+        add('	{');
+        add('		__arm9i_lma__ = LOADADDR(.twl);');
+        add('		__arm9i_start__ = ABSOLUTE(.);');
+        add('		*(.twl)');
+        add('		*.twl*(.text .stub .text.* .gnu.linkonce.t.*)');
+        add('		*.twl*(.rodata)');
+        add('		*.twl*(.roda)');
+        add('		*.twl*(.rodata.*)');
+        add('		*.twl*(.data)');
+        add('		*.twl*(.data.*)');
+        add('		*.twl*(.gnu.linkonce.d*)');
+        add('		__arm9i_end__ = ABSOLUTE(.);');
+        add('	} :twl');
+        add('');
+        add('	.twl_bss __arm9i_end__ (NOLOAD):');
+        add('	{');
+        add('		__twl_bss_start__ = ABSOLUTE(.);');
+        add('		*(.twl_bss)');
+        add('		*.twl*(.dynbss)');
+        add('		*.twl*(.gnu.linkonce.b*)');
+        add('		*.twl*(.bss*)');
+        add('		*.twl*(COMMON)');
+        add('		. = ALIGN(4);    /* REQUIRED. LD is flaky without it. */');
+        add('		__twl_bss_end__ = ABSOLUTE(.);');
+        add('		__twl_end__ = ABSOLUTE(.);');
+        add('	} :NONE');
         add('');
         add('	/* Stabs debugging sections.  */');
         add('	.stab 0 : { *(.stab) }');
@@ -497,18 +538,33 @@ begin
         add('	.stack 0x80000 : { _stack = .; *(.stack) }');
         add('	/* These must appear regardless of  .  */');
         add('}');
-        add('');
       end;
       if apptype=app_arm7 then
       begin
+        add('/*--------------------------------------------------------------------------------');
+        add('	This Source Code Form is subject to the terms of the Mozilla Public License,');
+        add('	v. 2.0. If a copy of the MPL was not distributed with this file, You can');
+        add('	obtain one at https://mozilla.org/MPL/2.0/.');
+        add('--------------------------------------------------------------------------------*/');
         add('OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")');
         add('OUTPUT_ARCH(arm)');
         add('ENTRY(_start)');
         add('');
+        add('');
+        add('PHDRS {');
+        add('	crt0  PT_LOAD FLAGS(7);');
+        add('	arm7  PT_LOAD FLAGS(7);');
+        add('	arm7i PT_LOAD FLAGS(0x100007);');
+        add('}');
+        add('');
+        add('');
         add('MEMORY {');
+        add('	ewram  : ORIGIN = 0x02380000, LENGTH = 12M - 512K');
+        add('	rom    : ORIGIN = 0x08000000, LENGTH = 32M');
+        add('	iwram  : ORIGIN = 0x037f8000, LENGTH = 96K');
         add('');
-        add('	rom	: ORIGIN = 0x08000000, LENGTH = 32M');
-        add('	iwram	: ORIGIN = 0x037f8000, LENGTH = 96K	');
+        add('	twl_ewram : ORIGIN = 0x02e80000, LENGTH = 512K - 64K');
+        add('	twl_iwram : ORIGIN = 0x03000000, LENGTH = 256K');
         add('}');
         add('');
         add('__iwram_start	=	ORIGIN(iwram);');
@@ -524,30 +580,59 @@ begin
         add('');
         add('SECTIONS');
         add('{');
-        add('	.init	:');
+        add('');
+        add('	.twl :');
         add('	{');
-        add('		__text_start = . ;');
-        add('		KEEP (*(.init))');
+        add('		__arm7i_lma__ = LOADADDR(.twl);');
+        add('		__arm7i_start__ = .;');
+        add('		*(.twl)');
+        add('		*.twl*(.text .stub .text.* .gnu.linkonce.t.*)');
+        add('		*.twl*(.rodata)');
+        add('		*.twl*(.roda)');
+        add('		*.twl*(.rodata.*)');
+        add('		*.twl*(.data)');
+        add('		*.twl*(.data.*)');
+        add('		*.twl*(.gnu.linkonce.d*)');
+        add('		. = ALIGN(4);');
+        add('		__arm7i_end__ = .;');
+        add('	} >twl_iwram AT>twl_ewram :arm7i');
+        add('');
+        add('	.twl_bss ALIGN(4) (NOLOAD) :');
+        add('	{');
+        add('		__twl_bss_start__ = .;');
+        add('		*(.twl_bss)');
+        add('		*.twl.*(.dynbss)');
+        add('		*.twl.*(.gnu.linkonce.b*)');
+        add('		*.twl.*(.bss*)');
+        add('		*.twl.*(COMMON)');
+        add('		. = ALIGN(4);');
+        add('		__twl_bss_end__ = .;');
+        add('	} >twl_iwram :NONE');
+        add('');
+        add('	.crt0	:');
+        add('	{');
+        add('		KEEP (*(.crt0))');
         add('		. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */');
-        add('		} >iwram = 0xff');
-        add('	.plt : { *(.plt) } >iwram = 0xff');
+        add('	} >ewram :crt0');
         add('');
-        add('	.text :   /* ALIGN (4): */');
+        add('	.text :');
         add('	{');
+        add('		__arm7_lma__ = LOADADDR(.text);');
+        add('		__arm7_start__ = .;');
+        add('		KEEP (*(SORT_NONE(.init)))');
+        add('		*(.plt)');
         add('		*(.text .stub .text.* .gnu.linkonce.t.*)');
         add('		KEEP (*(.text.*personality*))');
         add('		/* .gnu.warning sections are handled specially by elf32.em.  */');
         add('		*(.gnu.warning)');
         add('		*(.glue_7t) *(.glue_7) *(.vfp11_veneer)');
         add('		. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */');
-        add('	} >iwram = 0xff');
+        add('	} >iwram AT>ewram :arm7');
         add('');
         add('	.fini           :');
         add('	{');
         add('		KEEP (*(.fini))');
-        add('	} >iwram =0xff');
-        add('');
-        add('	__text_end = . ;');
+        add('	} >iwram AT>ewram');
         add('');
         add('	.rodata :');
         add('	{');
@@ -558,27 +643,38 @@ begin
         add('		*(.gnu.linkonce.r*)');
         add('		SORT(CONSTRUCTORS)');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >iwram = 0xff');
+        add('	} >iwram AT>ewram');
         add('');
-        add('	.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >iwram');
-        add('	__exidx_start = .;');
-        add('	.ARM.exidx   : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } >iwram');
-        add('	__exidx_end = .;');
+        add('	.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >iwram AT>ewram');
+        add('');
+        add('	.ARM.exidx   : {');
+        add('		__exidx_start = .;');
+        add('		*(.ARM.exidx* .gnu.linkonce.armexidx.*)');
+        add('		__exidx_end = .;');
+        add('	 } >iwram AT>ewram');
         add('');
         add('/* Ensure the __preinit_array_start label is properly aligned.  We');
         add('   could instead move the label definition inside the section, but');
         add('   the linker would then create the section even if it turns out to');
         add('   be empty, which isn''t pretty.  */');
-        add('	. = ALIGN(32 / 8);');
-        add('	PROVIDE (__preinit_array_start = .);');
-        add('	.preinit_array     : { KEEP (*(.preinit_array)) } >iwram = 0xff');
-        add('	PROVIDE (__preinit_array_end = .);');
-        add('	PROVIDE (__init_array_start = .);');
-        add('	.init_array     : { KEEP (*(.init_array)) } >iwram = 0xff');
-        add('	PROVIDE (__init_array_end = .);');
-        add('	PROVIDE (__fini_array_start = .);');
-        add('	.fini_array     : { KEEP (*(.fini_array)) } >iwram = 0xff');
-        add('	PROVIDE (__fini_array_end = .);');
+        add('	.preinit_array     : {');
+        add('		. = ALIGN(32 / 8);');
+        add('		PROVIDE (__preinit_array_start = .);');
+        add('		KEEP (*(.preinit_array))');
+        add('		PROVIDE (__preinit_array_end = .);');
+        add('	} >iwram AT>ewram');
+        add('');
+        add('	.init_array     : {');
+        add('		PROVIDE (__init_array_start = .);');
+        add('		KEEP (*(.init_array))');
+        add('		PROVIDE (__init_array_end = .);');
+        add('	} >iwram AT>ewram');
+        add('');
+        add('	.fini_array     : {');
+        add('		PROVIDE (__fini_array_start = .);');
+        add('		KEEP (*(.fini_array))');
+        add('		PROVIDE (__fini_array_end = .);');
+        add('	} >iwram AT>ewram');
         add('');
         add('	.ctors :');
         add('	{');
@@ -593,7 +689,7 @@ begin
         add('		KEEP (*(SORT(.ctors.*)))');
         add('		KEEP (*(.ctors))');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >iwram = 0xff');
+        add('	} >iwram AT>ewram');
         add('');
         add('	.dtors :');
         add('	{');
@@ -602,21 +698,21 @@ begin
         add('		KEEP (*(SORT(.dtors.*)))');
         add('		KEEP (*(.dtors))');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >iwram = 0xff');
+        add('	} >iwram AT>ewram');
         add('');
         add('	.eh_frame :');
         add('	{');
         add('		KEEP (*(.eh_frame))');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >iwram = 0xff');
+        add('	} >iwram AT>ewram');
         add('');
         add('	.gcc_except_table :');
         add('	{');
         add('		*(.gcc_except_table)');
         add('		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */');
-        add('	} >iwram = 0xff');
-        add('	.jcr            : { KEEP (*(.jcr)) } >iwram = 0');
-        add('	.got            : { *(.got.plt) *(.got) } >iwram = 0');
+        add('	} >iwram AT>ewram');
+        add('	.jcr            : { KEEP (*(.jcr)) } >iwram AT>ewram');
+        add('	.got            : { *(.got.plt) *(.got) } >iwram AT>ewram');
         add('');
         add('	.data ALIGN(4) : 	{');
         add('		__data_start = ABSOLUTE(.);');
@@ -626,10 +722,11 @@ begin
         add('		CONSTRUCTORS');
         add('		. = ALIGN(4);');
         add('		__data_end = ABSOLUTE(.) ;');
-        add('	} >iwram = 0xff');
+        add('	} >iwram AT>ewram');
         add('');
-        add('	.bss ALIGN(4) :');
+        add('	.bss ALIGN(4) (NOLOAD) :');
         add('	{');
+        add('		__arm7_end__ = .;');
         add('		__bss_start = ABSOLUTE(.);');
         add('		__bss_start__ = ABSOLUTE(.);');
         add('		*(.dynbss)');
@@ -674,7 +771,6 @@ begin
         add('	.debug_funcnames 0 : { *(.debug_funcnames) }');
         add('	.debug_typenames 0 : { *(.debug_typenames) }');
         add('	.debug_varnames  0 : { *(.debug_varnames) }');
-        add('	.stack 0x80000 : { _stack = .; *(.stack) }');
         add('	/* These must appear regardless of  .  */');
         add('}');
       end;

+ 7 - 0
packages/libndsfpc/examples/audio/maxmod/audio_modes/audio_modes.pp

@@ -201,6 +201,13 @@ begin
 			// switch audio mode
 			mmSelectMode( mode );
 		end;
+
+		//-----------------------------------------------------
+		// START: exit
+		//-----------------------------------------------------
+		if( keys and KEY_START ) <> 0 then 
+      break;
+		//-----------------------------------------------------
 		
 		//-----------------------------------------------------
 		// wait until next frame

+ 7 - 0
packages/libndsfpc/examples/audio/maxmod/reverb/reverb.pp

@@ -151,6 +151,13 @@ begin
 				reverb_is_started := 0;
 			end;
 		end;
+
+		//-----------------------------------------------------
+		// START: exit
+		//-----------------------------------------------------
+		if( keys and KEY_START ) <> 0 then 
+      break;
+		//-----------------------------------------------------
 		
 		//-----------------------------------------------------
 		// wait until next frame

+ 12 - 1
packages/libndsfpc/examples/audio/maxmod/song_events_example/song_events_example.pp

@@ -48,7 +48,7 @@ end;
 
 var
   gfx: pcuint16;
-
+  keys: cint;
 begin	
 	videoSetMode(MODE_0_2D);
 	
@@ -114,6 +114,17 @@ begin
 		
 		//send the updates to the hardware
 		oamUpdate(oamMain);
+   
+ 		//-----------------------------------------------------
+		// get new keypad input
+		//-----------------------------------------------------
+		scanKeys();
+		keys := keysDown();
+
+		//-----------------------------------------------------
+		// START: exit
+		//-----------------------------------------------------
+		if (keys and KEY_START) <> 0 then break;
 	end;
 
 end.

+ 12 - 0
packages/libndsfpc/examples/audio/maxmod/song_events_example2/song_events_example2.pp

@@ -58,6 +58,7 @@ end;
 var
   j: integer;
 	i: integer;
+  keys: cint;
 
 begin
   for j := 0 to 4 do
@@ -148,6 +149,17 @@ begin
 		
 		//send the updates to the hardware
 		oamUpdate(oamMain);
+   
+ 		//-----------------------------------------------------
+		// get new keypad input
+		//-----------------------------------------------------
+		scanKeys();
+		keys := keysDown();
+
+		//-----------------------------------------------------
+		// START: exit
+		//-----------------------------------------------------
+		if (keys and KEY_START) <> 0 then break;   
 	end;
 
 end.

+ 13 - 0
packages/libndsfpc/examples/audio/maxmod/streaming/streaming.pp

@@ -64,6 +64,7 @@ end;
 var
   sys: mm_ds_system;
   mystream: mm_stream;
+  keys: cint;
 begin	
 
 	//----------------------------------------------------------------
@@ -122,6 +123,18 @@ begin
 		
 		// wait until next frame
 		swiWaitForVBlank();
+
+   
+ 		//-----------------------------------------------------
+		// get new keypad input
+		//-----------------------------------------------------
+		scanKeys();
+		keys := keysDown();
+
+		//-----------------------------------------------------
+		// START: exit
+		//-----------------------------------------------------
+		if (keys and KEY_START) <> 0 then break;  
 		
 		// set backdrop to show cpu usage
 		BG_PALETTE_SUB[0] := cpu_colour;

+ 6 - 2
packages/libndsfpc/examples/audio/micrecord/micrecord.pp

@@ -55,7 +55,7 @@ procedure play();
 begin
 	soundMicOff();
 	soundEnable();
-	iprintf('data length: %i'#10, data_length);
+	iprintf('data length: %li'#10, data_length);
 	soundPlaySample(sound_buffer, SoundFormat_16Bit, data_length, sample_rate, 127, 64, false, 0);
 end;
 
@@ -89,7 +89,11 @@ begin
 			end;
       recording := not recording;
 		end;
-
+		//-----------------------------------------------------
+		// START: exit
+		//-----------------------------------------------------
+		if (keys and KEY_START) <> 0 then break;
+      
 		swiWaitForVBlank();
 
 	end;

+ 12 - 7
packages/libndsfpc/examples/card/eeprom/eeprom.pp

@@ -11,14 +11,19 @@ var
   vtype, vsize: integer;
   data: array [0..511] of cchar;
 
-procedure pause();
+procedure ButtonWait();
+var
+  buttons: cint;
 begin
-	iprintf('Press start...'#10);
+	iprintf('Press a key, start to exit...'#10);
 	while true do
 	begin
 		scanKeys();
-		if (keysDown() and KEY_START)<>0 then
-			exit;
+   buttons := keysDown();
+		if (buttons and KEY_START)<>0 then
+			exit;  
+    if buttons <> 0 then
+      break;
 		swiWaitForVBlank();
 	end;
 	scanKeys();
@@ -47,7 +52,7 @@ begin
     begin
       // If not, the card needs ejected and reinserted into the DS
       iprintf('Please eject & reinsert DS card.'#10);
-      pause();
+      ButtonWait();
       cardReadHeader(@header1);
       cardReadHeader(@header2);
     end;
@@ -63,7 +68,7 @@ begin
     iprintf('EEPROM:'#10);
     iprintf(' Type: %d'#10, vtype);
     iprintf(' Size: %d'#10, vsize);
-    pause();
+    ButtonWait();
 
     // Read the first 512 bytes of EEPROM
     cardReadEeprom(0, @data, 512, vtype);
@@ -91,6 +96,6 @@ begin
     end;
   
     iprintf('Insert a new card to read again'#10);
-    pause();
+    ButtonWait();
   end;
 end.

+ 6 - 3
packages/libndsfpc/examples/ds_motion/dsMotion.pp

@@ -29,6 +29,8 @@ begin
   
 end;
 
+var
+  keys: cint;
 
 begin	
   consoleDemoInit();
@@ -38,10 +40,11 @@ begin
   while true do
   begin	
     scanKeys();
-    
-    if (keysDown() and KEY_A) <> 0 then 
+    keys := keysDown();
+    if (keys and KEY_A) <> 0 then 
       Calibrate();
-  
+    if (keys and KEY_START) <> 0 then 
+      break;
     consoleClear();
     if motion_init() <> 0 then
       iprintf('Nds is inserted'#10)

+ 126 - 55
packages/libndsfpc/examples/dswifi/ap_search/apSearch.pp

@@ -5,43 +5,67 @@ program apSearch;
 uses
   ctypes, nds9, dswifi9;
 
-procedure findAP(ap: pWifi_AccessPoint); 
 var
-	selected, i, count: integer;
+  ap: pWifi_AccessPoint;
+
+function findAP(): pWifi_AccessPoint; 
+var
+	selected, i, count, displaytop: integer;
 	ap2: Wifi_AccessPoint;
+  pressed: cint;
+  displayend: integer;
+  s1, s2: string;
 begin
   selected := 0;  
   count := 0;
-
+  displaytop := 0;
+  
   Wifi_ScanMode(); //this allows us to search for APs
   
-  while ((keysDown() and KEY_A) = 0) do
+  pressed := 0;
+  
+  while ((pressed and KEY_A) = 0) do
   begin
     scanKeys();
     
+    pressed := keysDown();
+    
+    if (pressed and KEY_START) <> 0 then exit;
+    
     //find out how many APs there are in the area
     count := Wifi_GetNumAP();
+    
     consoleClear();
     
-    iprintf('Number of APs found: %d'#10, count);
+    iprintf('%d APs detected'#10, count);
+
+		displayend := displaytop + 10;
+		if (displayend > count) then displayend := count;
     
     //display the APs to the user
-    for i := 0 to count - 1 do
+    for i := displaytop to displayend - 1 do
     begin
-      Wifi_GetAPData(i, @ap2);
+      Wifi_GetAPData(i, ap);
       // display the name of the AP
       if i = selected then
-        iprintf('%s %s'#10, '*', pcchar(ap2.ssid))
+        s1 := '*' 
       else
-        iprintf('%s %s'#10, ' ', pcchar(ap2.ssid));
+        s1 := ' ';
+      
+      if (ap.flags and WFLAG_APDATA_WEP) <> 0 then
+        s2 := 'Yes ' 
+      else
+        s2 :=  'No ';
+      
+      iprintf('%s %.29s'#10'  Wep:%s Sig:%i'#10, s1, pcchar(ap^.ssid), s2, ap.rssi * 100 div $D0);
       
     end;
-
+    
 		//move the selection asterick
-		if ((keysDown() and KEY_UP) <> 0) and (selected > 0) then 
+		if ((pressed and KEY_UP) <> 0) and (selected > 0) then 
       dec(selected);
 
-		if ((keysDown() and KEY_DOWN) <> 0) and (selected < (count-1)) then 
+		if ((pressed and KEY_DOWN) <> 0) and (selected < (count-1)) then 
       inc(selected);
 
 		swiWaitForVBlank();
@@ -49,7 +73,7 @@ begin
 
 	//user has made a choice so grab the ap and return it
 	Wifi_GetAPData(selected, ap);
-
+  result := ap;
 end;
 
 //---------------------------------------------------------------------------------
@@ -66,58 +90,105 @@ var
   oldStatus: integer;
 	url: array [0..255] of char;
   host: phostent;
-
+  wepkey = array [0..63] of char;
+  wepmode: cint;
+  len: integer;
+  ip: cuint32;
+  quit: integer;
+  pressed: cint;
 begin
-  status := integer(ASSOCSTATUS_DISCONNECTED);
-  
+  Wifi_InitDefault(false);
   consoleDemoInit(); 
-
   new(kb);
   kb := keyboardDemoInit();
   kb^.OnKeyPressed := @keyPressed;
-  
-  Wifi_InitDefault(false);
-  
-  findAP(ap3);
-  	
-  iprintf('Connecting to %s'#10, pcchar(ap3^.ssid));
-  
-  //this tells the wifi lib to use dhcp for everything
-  Wifi_SetIP(0,0,0,0,0);	
-  
-  Wifi_ConnectAP(ap3, integer(WEPMODE_NONE), 0, nil);
 
-  while (status <> integer(ASSOCSTATUS_ASSOCIATED)) and (status <> integer(ASSOCSTATUS_CANNOTCONNECT)) do
+  while true do
   begin
-    oldStatus := status;
-    
-    status := Wifi_AssocStatus();
-    if oldStatus <> status then
-      iprintf('%s', pchar(@ASSOCSTATUS_STRINGS[status]))
-    else 
-      iprintf('%s', '.');
-    
-    swiWaitForVBlank();
-  end;
+    status := integer(ASSOCSTATUS_DISCONNECTED);
+    consoleClear();
+    consoleSetWindow(nil, 0,0,32,24);   
 
-	consoleClear();
-	consoleSetWindow(nil, 0,0,32,10);
+    ap3 := findAp();
 
+    consoleClear();
+    consoleSetWindow(nil, 0,0,32,10);
 
-  while true do
-  begin
-    iprintf('Url? ');
-    
-    scanf('%s', url);
-    
-    host := gethostbyname(url);
-    
-    if (host) <> nil then
-    	iprintf('IP (%s) : %s'#10,  url, inet_ntoa(in_addr(host^.h_addr_list^)))
-    else
-    	iprintf('Could not resolve'#10);
-    
-    swiWaitForVBlank();
+    iprintf('Connecting to %s'#10, pcchar(ap3^.ssid));
+
+    //this tells the wifi lib to use dhcp for everything
+    Wifi_SetIP(0,0,0,0,0);
+    wepmode := WEPMODE_NONE;
+
+    if (ap3^.flags and WFLAG_APDATA_WEP) <> 0 then
+    begin
+      iprintf('Enter Wep Key'#10);
+      while (wepmode = WEPMODE_NONE) do
+      begin
+        scanf('%s', wepkey);
+        if (strlen(wepkey) = 13) then
+          wepmode := WEPMODE_128BIT;
+        else if (strlen(wepkey) = 5) then
+          wepmode := WEPMODE_40BIT;
+        else 
+          iprintf('Invalid key!'#10);
+      end;
+      Wifi_ConnectAP(ap3, wepmode, 0, pcuint8(wepkey));
+    end else 
+      Wifi_ConnectAP(ap3, integer(WEPMODE_NONE), 0, nil);
+
+    consoleClear();
+    while (status <> ASSOCSTATUS_ASSOCIATED) and (status <> ASSOCSTATUS_CANNOTCONNECT) do
+    begin
+      status := Wifi_AssocStatus();
+      len := strlen(ASSOCSTATUS_STRINGS[status]);
+      iprintf(#27'[0;0H\x1b[K');
+      iprintf(#27'[0;%dH%s', (32-len) div 2, ASSOCSTATUS_STRINGS[status]);
+      
+      scanKeys();
+      
+      if (keysDown() and KEY_B) <> 0 then break;
+      
+      swiWaitForVBlank();
+    end;
+   
+
+    if (status = ASSOCSTATUS_ASSOCIATED) then
+    begin
+      ip := Wifi_GetIP();
+
+      iprintf(#10'ip: [%li.%li.%li.%li]'#10, (ip ) and $FF, (ip shr 8) and $FF, (ip shr 16) and $FF, (ip shr 24) and $FF);
+			while true do 
+      begin
+
+				scanf('%s', url);
+
+				if (strcmp(url, 'quit') = 0) then break;
+
+				host := gethostbyname(url);
+
+				if(host <> nil) then
+					iprintf('IP (%s) : %s'#10,  url, inet_ntoa(pin_addr(host)^.h_addr_list[0]))
+				else
+					iprintf('Could not resolve'#10);
+
+				swiWaitForVBlank();
+			end;
+		end else 
+			iprintf(#10'Connection failed!'#10);
+
+		quit := 0;
+		iprintf('Press A to try again, B to quit.');
+		while true do
+   begin
+			swiWaitForVBlank();
+			scanKeys();
+			pressed := keysDown();
+			if(pressed and KEY_B) <> 0 then quit := 1;
+			if(pressed and (KEY_A or KEY_B)) <> 0 then break;
+		end;
+		if (quit) <> 0 then break;
+   
   end;
 
 end.

+ 5 - 1
packages/libndsfpc/examples/dswifi/autoconnect/autoconnect.pp

@@ -7,7 +7,7 @@ uses
 
 var
 	ip, gateway, mask, dns1, dns2: in_addr;
-
+    keys: integer;
 begin
 
 	consoleDemoInit();  //setup the sub screen for printing
@@ -31,6 +31,10 @@ begin
 	end;
 
 	while true do
+  begin
 		swiWaitForVBlank();
+		if( keys and KEY_START ) <> 0 then 
+      break;
+  end;
 end.
 

+ 8 - 1
packages/libndsfpc/examples/dswifi/httpget/httpget.pp

@@ -54,6 +54,9 @@ begin
   closesocket(my_socket); // remove the socket.
 end;
 
+var
+    keys: integer;
+
 begin
 	consoleDemoInit();  //setup the sub screen for printing
 
@@ -68,6 +71,10 @@ begin
 		getHttp('www.akkit.org');
 	end;
 
-	while true do
+  while true do
+  begin
 		swiWaitForVBlank();
+		if( keys and KEY_START ) <> 0 then 
+      break;
+  end;
 end.

+ 5 - 2
packages/libndsfpc/examples/filesystem/libfat/libfatdir/libfatdir.pp

@@ -42,7 +42,10 @@ begin
 		iprintf('fatInitDefault failure: terminating'#10);
 	end;
 
-	while true do
+  while true do
+  begin
 		swiWaitForVBlank();
-
+    scanKeys();
+    if (keysDown() and KEY_START) <> 0 then break;
+  end;
 end.

+ 5 - 0
packages/libndsfpc/examples/graphics/3D/3D_Both_Screens/3DBothScreens.pp

@@ -132,6 +132,7 @@ end;
 
 var
 	top: boolean = true;
+  keys: integer;
 
 begin 
   videoSetMode(MODE_0_3D);
@@ -171,6 +172,10 @@ begin
     // wait for capture unit to be ready
     while (REG_DISPCAPCNT^ and DCAP_ENABLE) <> 0 do;
     
+    scanKeys();
+		keys := keysDown();
+		if (keys and KEY_START) <> 0 then break;
+    
     //-------------------------------------------------------
     //	 Switch render targets
     //-------------------------------------------------------

+ 96 - 96
packages/libndsfpc/examples/graphics/3D/BoxTest/BoxTest.pp

@@ -9,9 +9,9 @@ uses
 function startTimer(timer: integer): cuint16;
 begin
   TIMER_CR(timer)^ := 0;
-	TIMER_DATA(0)^ := 0;
-	TIMER_CR(timer)^ := TIMER_DIV_1 or TIMER_ENABLE;
-	startTimer := TIMER_DATA(0)^;
+  TIMER_DATA(0)^ := 0;
+  TIMER_CR(timer)^ := TIMER_DIV_1 or TIMER_ENABLE;
+  startTimer := TIMER_DATA(0)^;
 end;
 
 
@@ -74,7 +74,7 @@ begin
 end;
 
 var
-	touchXY: touchPosition;
+  touchXY: touchPosition;
 
   rotX: cfloat = 0;
   rotY: cfloat = 0;
@@ -92,7 +92,7 @@ var
   oldx: integer = 0;
   oldy: integer = 0;
 
-	held, pressed: integer;
+  held, pressed: integer;
   hit: integer;
   
   i: integer;
@@ -121,114 +121,114 @@ begin
   // Set our view port to be the same size as the screen
   glViewport(0,0,255,191);
   
-	printf(#$1b'[10;0HPress A to change culling');
-	printf(#10#10'Press B to change Ortho vs Persp');
-	printf(#10'Left/Right/Up/Down to rotate');
-	printf(#10'Press L and R to zoom');
-	printf(#10'Touch screen to rotate cube');
+  printf(#$1b'[10;0HPress A to change culling');
+  printf(#10#10'Press B to change Ortho vs Persp');
+  printf(#10'Left/Right/Up/Down to rotate');
+  printf(#10'Press L and R to zoom');
+  printf(#10'Touch screen to rotate cube');
 
-	//main loop
-	while true do
-	begin
+  //main loop
+  while true do
+  begin
     
     //process input
     scanKeys();
     
     touchRead(touchXY);
 
-		
+    
     held := keysHeld();
     pressed := keysDown();
-		
-		if( held and KEY_LEFT) <> 0 then rotY := rotY + 1;
-		if( held and KEY_RIGHT) <> 0 then rotY := rotY - 1;
-		if( held and KEY_UP) <> 0 then rotX := rotX + 1;
-		if( held and KEY_DOWN) <> 0 then rotX := rotX - 1;
-		if( held and KEY_L) <> 0 then translate := translate + 0.1;
-		if( held and KEY_R) <> 0 then translate := translate - 0.1;
-
-		//reset x and y when user touches screen
-		if (pressed and KEY_TOUCH) <> 0 then
-		begin
-			oldx := touchXY.px;
-			oldy := touchXY.py;
-		end;
-
-		//if user drags then grab the delta
-		if (held and KEY_TOUCH) <> 0 then
-		begin
-			rx := rx + (touchXY.px - oldx); 
-			ry := ry + (touchXY.py - oldy);
-			oldx := touchXY.px;
-			oldy := touchXY.py;
-		end;
-
-		
-		//change ortho vs perspective
-		glMatrixMode(GL_PROJECTION);
-		glLoadIdentity();
-		if (keysHeld() and KEY_B) <> 0 then
-			glOrtho(-4,4,-3,3,0.1,10)	
-		else 
-			gluPerspective(70, 256.0 / 192.0, 0.1, 10);
-	
-		//change cull mode
-		if (held and KEY_A) <> 0 then
-			glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE )
-		else
-			glPolyFmt(POLY_ALPHA(31) or POLY_CULL_FRONT );
-
-		// Set the current matrix to be the model matrix
-		glMatrixMode(GL_MODELVIEW);
-		glLoadIdentity();
-
-		//handle camera
-		glRotateY(rotY);
-		glRotateX(rotX);
-		glTranslatef(0,0,translate);
-
-		//move the cube
-		glRotateX(ry);
-		glRotateY(rx);
-
-		DrawBox(-1,-1,-1,2,2,2);
-
-		swiWaitForVBlank();
-		printf(#$1b'[0;0HBox test cycle count');
-
-		time := startTimer(0);
-		hit := BoxTestf(-1,-1,-1,2,2,2);
-		printf(#10'Single test (float): %i', 2*(getTimer(0) - time));
-
-		time := startTimer(0);
-		BoxTest(inttov16(-1),inttov16(-1),inttov16(-1),inttov16(2),inttov16(2),inttov16(2));
-		printf(#10'Single test (fixed): %i', 2*(getTimer(0) - time));
-
-		time := startTimer(0);
-		for i := 0 to 63 do
-			BoxTest(inttov16(-1),inttov16(-1),inttov16(-1),inttov16(2),inttov16(2),inttov16(2));
-
-		printf(#10'64 tests avg. (fixed): %i', (getTimer(0) - time) / 32);
-		if hit <> 0 then
-		  printf(#10'Box Test result: hit') 
+    
+    if( held and KEY_LEFT) <> 0 then rotY := rotY + 1;
+    if( held and KEY_RIGHT) <> 0 then rotY := rotY - 1;
+    if( held and KEY_UP) <> 0 then rotX := rotX + 1;
+    if( held and KEY_DOWN) <> 0 then rotX := rotX - 1;
+    if( held and KEY_L) <> 0 then translate := translate + 0.1;
+    if( held and KEY_R) <> 0 then translate := translate - 0.1;
+
+    //reset x and y when user touches screen
+    if (pressed and KEY_TOUCH) <> 0 then
+    begin
+      oldx := touchXY.px;
+      oldy := touchXY.py;
+    end;
+
+    //if user drags then grab the delta
+    if (held and KEY_TOUCH) <> 0 then
+    begin
+      rx := rx + (touchXY.px - oldx); 
+      ry := ry + (touchXY.py - oldy);
+      oldx := touchXY.px;
+      oldy := touchXY.py;
+    end;
+
+    
+    //change ortho vs perspective
+    glMatrixMode(GL_PROJECTION);
+    glLoadIdentity();
+    if (keysHeld() and KEY_B) <> 0 then
+      glOrtho(-4,4,-3,3,0.1,10) 
+    else 
+      gluPerspective(70, 256.0 / 192.0, 0.1, 10);
+  
+    //change cull mode
+    if (held and KEY_A) <> 0 then
+      glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE )
+    else
+      glPolyFmt(POLY_ALPHA(31) or POLY_CULL_FRONT );
+
+    // Set the current matrix to be the model matrix
+    glMatrixMode(GL_MODELVIEW);
+    glLoadIdentity();
+
+    //handle camera
+    glRotateY(rotY);
+    glRotateX(rotX);
+    glTranslatef(0,0,translate);
+
+    //move the cube
+    glRotateX(ry);
+    glRotateY(rx);
+
+    DrawBox(-1,-1,-1,2,2,2);
+
+    swiWaitForVBlank();
+    printf(#$1b'[0;0HBox test cycle count');
+
+    time := startTimer(0);
+    hit := BoxTestf(-1,-1,-1,2,2,2);
+    printf(#10'Single test (float): %i', 2*(getTimer(0) - time));
+
+    time := startTimer(0);
+    BoxTest(inttov16(-1),inttov16(-1),inttov16(-1),inttov16(2),inttov16(2),inttov16(2));
+    printf(#10'Single test (fixed): %i', 2*(getTimer(0) - time));
+
+    time := startTimer(0);
+    for i := 0 to 63 do
+      BoxTest(inttov16(-1),inttov16(-1),inttov16(-1),inttov16(2),inttov16(2),inttov16(2));
+
+    printf(#10'64 tests avg. (fixed): %i', (getTimer(0) - time) / 32);
+    if hit <> 0 then
+      printf(#10'Box Test result: hit') 
     else
       printf(#10'Box Test result: miss');
 
-		while (GFX_STATUS^ and (1 shl 27)) <> 0 do; // wait until the geometry engine is not busy
+    while (GFX_STATUS^ and (1 shl 27)) <> 0 do; // wait until the geometry engine is not busy
 
-		glGetInt(GL_GET_VERTEX_RAM_COUNT, vertex_count);
-		glGetInt(GL_GET_POLYGON_RAM_COUNT, polygon_count);
+    glGetInt(GL_GET_VERTEX_RAM_COUNT, vertex_count);
+    glGetInt(GL_GET_POLYGON_RAM_COUNT, polygon_count);
 
     if (held and KEY_A)<> 0 then 
-		  printf(#10#10'Ram usage: Culling none')
+      printf(#10#10'Ram usage: Culling none')
     else 
     printf(#10#10'Ram usage: Culling back faces');
     
-		printf(#10'Vertex ram: %i', vertex_count);
-		printf(#10'Polygon ram: %i', polygon_count);
-
-		// flush to the screen
-		glFlush(0);
+    printf(#10'Vertex ram: %i', vertex_count);
+    printf(#10'Polygon ram: %i', polygon_count);
 
-	end;
+    // flush to the screen
+    glFlush(0);
+    if (pressed and KEY_START) <> 0 then break;
+  end;
 end.

+ 2 - 1
packages/libndsfpc/examples/graphics/3D/Display_List/DisplayList.pp

@@ -78,7 +78,8 @@ begin
     scanKeys();
     
     keys := keysHeld();
-
+    if (keys and KEY_START) <> 0 then break;
+    
     if ((keys and KEY_UP)) <> 0 then rotateX := rotateX + 3;
     if ((keys and KEY_DOWN)) <> 0 then rotateX := rotateX - 3;
     if ((keys and KEY_LEFT)) <> 0 then rotateY := rotateY + 3;

+ 1 - 0
packages/libndsfpc/examples/graphics/3D/Display_List_2/DisplayList2.pp

@@ -70,6 +70,7 @@ begin
 		glPopMatrix(1);
 			
 		glFlush(0);
+   if (keys and KEY_START) <> 0 then break;
 	end;
 
 end.

+ 1 - 0
packages/libndsfpc/examples/graphics/3D/Env_Mapping/EnvMapping.pp

@@ -124,5 +124,6 @@ begin
 		glCallList(@teapot_bin);
 
 		glFlush(0);
+    if (keys and KEY_START) <> 0 then break;
   end;
 end.

+ 7 - 0
packages/libndsfpc/examples/graphics/3D/Mixed_Text_3D/MixedText3D.pp

@@ -47,6 +47,9 @@ begin
 	glEnd();										// Done Drawing The Quad
 end;
 
+var
+  keys: integer;
+
 begin
 	// initialize the geometry engine
 	glInit();	
@@ -98,6 +101,10 @@ begin
  
 		// wait for the screen to refresh
 		swiWaitForVBlank();
+   
+    scanKeys();
+		keys := keysDown();
+		if (keys and KEY_START) <> 0 then break;
 
 		printf(#$1b'[15;5H rtri  = %f     '#10, rtri);
 		printf(#$1b'[16;5H rquad = %f     '#10, rquad);

+ 8 - 2
packages/libndsfpc/examples/graphics/3D/Ortho/Ortho.pp

@@ -84,6 +84,9 @@ begin
   result := true;
 end;
 
+var
+  held: integer;
+
 begin
   // Setup the Main screen for 3D
   videoSetMode(MODE_0_3D);
@@ -132,13 +135,14 @@ begin
   while true do
   begin
     scanKeys();
+    held := keysHeld();
 
     //reset the projection matrix
     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();
 
     // set the projection matrix as either ortho or perspective
-    if (keysHeld() and KEY_R) = 0 then
+    if (held and KEY_R) = 0 then
       gluPerspective(70, 256.0 / 192.0, 0.1, 100)
     else
       glOrtho(-3, 3,-2, 2, 0.1, 100);
@@ -147,7 +151,7 @@ begin
     glMatrixMode(GL_MODELVIEW);
 
     //ds specific, several attributes can be set here
-    if (keysHeld() and KEY_L) <> 0 then
+    if (held and KEY_L) <> 0 then
       glPolyFmt(POLY_ALPHA(0) or POLY_CULL_NONE or POLY_FORMAT_LIGHT0 or POLY_FORMAT_LIGHT1 or POLY_FORMAT_LIGHT2)
     else
       glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE or POLY_FORMAT_LIGHT0 or POLY_FORMAT_LIGHT1 or POLY_FORMAT_LIGHT2);
@@ -163,5 +167,7 @@ begin
 
     // flush to screen
     glFlush(0);
+    
+    if (held and KEY_START) <> 0 then break;
   end;
 end.

+ 4 - 2
packages/libndsfpc/examples/graphics/3D/Paletted_Cube/PalettedCube.pp

@@ -308,7 +308,7 @@ begin
         nTexture := 10;
     end;
 
-    glBindTexture(nTexture, textureIDS[nTexture]);
+    glBindTexture(0, textureIDS[nTexture]);
 
     //draw the obj
     glBegin(GL_QUAD);
@@ -320,6 +320,8 @@ begin
 
     glFlush(0);
     swiWaitForVBlank();
+    
+    if (keysPressed and KEY_START) <> 0 then break;
   end;
 
-end.
+end.

+ 134 - 132
packages/libndsfpc/examples/graphics/3D/Picking/Picking.pp

@@ -23,154 +23,156 @@ var
 // run before starting to draw an object while picking
 procedure startCheck();
 begin
-	while PosTestBusy() do; // wait for the position test to finish
-	while GFX_BUSY do; // wait for all the polygons from the last object to be drawn
-	PosTest_Asynch(0,0,0); // start a position test at the current translated position
-	polyCount := GFX_POLYGON_RAM_USAGE^; // save the polygon count
+  while PosTestBusy() do; // wait for the position test to finish
+  while GFX_BUSY do; // wait for all the polygons from the last object to be drawn
+  PosTest_Asynch(0,0,0); // start a position test at the current translated position
+  polyCount := GFX_POLYGON_RAM_USAGE^; // save the polygon count
 end;
 
 // run afer drawing an object while picking
 procedure endCheck(obj: TClickable);
 begin
-	while GFX_BUSY do; // wait for all the polygons to get drawn
-	while PosTestBusy() do; // wait for the position test to finish
-	if (GFX_POLYGON_RAM_USAGE^ > polyCount) then // if a polygon was drawn
-	begin
-		if PosTestWresult() <= closeW then
-		begin
-			// this is currently the closest object under the cursor!
-			closeW := PosTestWresult();
-			clicked := obj;
-		end;
-	end;
+  while GFX_BUSY do; // wait for all the polygons to get drawn
+  while PosTestBusy() do; // wait for the position test to finish
+  if (GFX_POLYGON_RAM_USAGE^ > polyCount) then // if a polygon was drawn
+  begin
+    if PosTestWresult() <= closeW then
+    begin
+      // this is currently the closest object under the cursor!
+      closeW := PosTestWresult();
+      clicked := obj;
+    end;
+  end;
 end;
 
 
 var
-	rotateX: cuint32 = 0;
-	rotateY: cuint32 = 0;
+  rotateX: cuint32 = 0;
+  rotateY: cuint32 = 0;
   touchXY: touchPosition;
   viewport: array [0..3] of cint32 = (0,0,255,191); // used later for gluPickMatrix()
-	keys: u16;
+  keys: u16;
 
 begin
-	// initialize gl
-	glInit();
-
-	//set mode 0, enable BG0 and set it to 3D
-	videoSetMode(MODE_0_3D);
-	
-	lcdMainOnBottom(); // we are going to be touching the 3D display
-	
-	// enable edge outlining, this will be used to show which object is selected
-	glEnable(GL_OUTLINE);
-	
-	//set the first outline color to white
-	glSetOutlineColor(0,RGB15(31,31,31));
-
-	// setup the rear plane
-	glClearColor(0,0,0,0); // set BG to black and clear
-	glClearPolyID(0); // the BG and polygons will have the same ID unless a polygon is highlighted
-	glClearDepth($7FFF);
-	
-	// setup the camera
-	gluLookAt( 0.0, 0.0, 1.0,		//camera possition
-				     0.0, 0.0, 0.0,		//look at
-				     0.0, 1.0, 0.0);	//up
-	
-	glLight(0, RGB15(31,31,31) , 0, floattov10(-1.0), 0); // setup the light
-	
-	while true do
-	begin
-		// handle key input
-		scanKeys();
-		keys := keysHeld();
-		if ((keys and KEY_UP)) = 0 then rotateX := rotateX +3;
-		if((keys and KEY_DOWN)) = 0 then rotateX := rotateX -3;
-		if((keys and KEY_LEFT)) = 0 then rotateY := rotateY +3;
-		if((keys and KEY_RIGHT)) = 0 then rotateY := rotateY -3;
-
-		// get touchscreen position
-		touchXY := touchReadXY();
-
-		glViewPort(0,0,255,191); // set the viewport to fullscreen
-
-		// setup the projection matrix for regular drawing
-		glMatrixMode(GL_PROJECTION);
-		glLoadIdentity();
-		gluPerspective(60, 256.0 / 192.0, 0.1, 20); 
-		
-		glMatrixMode(GL_MODELVIEW); // use the modelview matrix while drawing
-		
-		glPushMatrix(); // save the state of the current matrix(the modelview matrix)
-			glTranslate3f32(0,0,floattof32(-6));
-			glRotateXi(rotateX); // add X rotation to the modelview matrix
-			glRotateYi(rotateY); // add Y rotation to the modelview matrix
-			
-			glPushMatrix(); // save the state of the modelview matrix while making the first pass
-				// draw the scene for displaying
-				
-				glTranslatef32(floattof32(2.9),floattof32(0),floattof32(0)); // translate the modelview matrix to the drawing location
-				if (clicked = clCone) then
-					glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(1)) // set a poly ID for outlining
-				else
-					glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(0)); // set a poly ID for no outlining (same as BG)
-
-				glCallList((@cone_bin)); // draw a green cone from a predefined packed command list
-
-				
-				glTranslatef32(floattof32(-3),floattof32(1.8),floattof32(2)); // translate the modelview matrix to the drawing location
-				if (clicked = clCylinder) then
-					glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(1)) // set a poly ID for outlining
-				else
-					glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(0)); // set a poly ID for no outlining (same as BG)
+  // initialize gl
+  glInit();
+
+  //set mode 0, enable BG0 and set it to 3D
+  videoSetMode(MODE_0_3D);
+  
+  lcdMainOnBottom(); // we are going to be touching the 3D display
+  
+  // enable edge outlining, this will be used to show which object is selected
+  glEnable(GL_OUTLINE);
+  
+  //set the first outline color to white
+  glSetOutlineColor(0,RGB15(31,31,31));
+
+  // setup the rear plane
+  glClearColor(0,0,0,0); // set BG to black and clear
+  glClearPolyID(0); // the BG and polygons will have the same ID unless a polygon is highlighted
+  glClearDepth($7FFF);
+  
+  // setup the camera
+  gluLookAt( 0.0, 0.0, 1.0,   //camera possition
+             0.0, 0.0, 0.0,   //look at
+             0.0, 1.0, 0.0);  //up
+  
+  glLight(0, RGB15(31,31,31) , 0, floattov10(-1.0), 0); // setup the light
+  
+  while true do
+  begin
+    // handle key input
+    scanKeys();
+    keys := keysHeld();
+    if ((keys and KEY_UP)) = 0 then rotateX := rotateX +3;
+    if((keys and KEY_DOWN)) = 0 then rotateX := rotateX -3;
+    if((keys and KEY_LEFT)) = 0 then rotateY := rotateY +3;
+    if((keys and KEY_RIGHT)) = 0 then rotateY := rotateY -3;
+
+    // get touchscreen position
+    touchXY := touchReadXY();
+
+    glViewPort(0,0,255,191); // set the viewport to fullscreen
+
+    // setup the projection matrix for regular drawing
+    glMatrixMode(GL_PROJECTION);
+    glLoadIdentity();
+    gluPerspective(60, 256.0 / 192.0, 0.1, 20); 
+    
+    glMatrixMode(GL_MODELVIEW); // use the modelview matrix while drawing
+    
+    glPushMatrix(); // save the state of the current matrix(the modelview matrix)
+      glTranslate3f32(0,0,floattof32(-6));
+      glRotateXi(rotateX); // add X rotation to the modelview matrix
+      glRotateYi(rotateY); // add Y rotation to the modelview matrix
+      
+      glPushMatrix(); // save the state of the modelview matrix while making the first pass
+        // draw the scene for displaying
+        
+        glTranslatef32(floattof32(2.9),floattof32(0),floattof32(0)); // translate the modelview matrix to the drawing location
+        if (clicked = clCone) then
+          glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(1)) // set a poly ID for outlining
+        else
+          glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(0)); // set a poly ID for no outlining (same as BG)
+
+        glCallList((@cone_bin)); // draw a green cone from a predefined packed command list
+
+        
+        glTranslatef32(floattof32(-3),floattof32(1.8),floattof32(2)); // translate the modelview matrix to the drawing location
+        if (clicked = clCylinder) then
+          glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(1)) // set a poly ID for outlining
+        else
+          glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(0)); // set a poly ID for no outlining (same as BG)
 
         glCallList((@cylinder_bin)); // draw a blue cylinder from a predefined packed command list
 
 
-				glTranslatef32(floattof32(0.5),floattof32(-2.6),floattof32(-4)); // translate the modelview matrix to the drawing location
-				if(clicked = clSphere) then
-					glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(1)) // set a poly ID for outlining
-				else
-					glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(0)); // set a poly ID for no outlining (same as BG)
-
-				glCallList((@sphere_bin)); // draw a red sphere from a predefined packed command list
-
-			glPopMatrix(1); // restores the modelview matrix to where it was just rotated
-			
-			// draw the scene again for picking
-				clicked := clNothing; //reset what was clicked on
-				closeW := $7FFFFFFF; //reset the distance
-
-				//set the viewport to just off-screen, this hides all rendering that will be done during picking
-				glViewport(0,192,0,192);
-				
-				// setup the projection matrix for picking
-				glMatrixMode(GL_PROJECTION);
-				glLoadIdentity();
-				gluPickMatrix((touchXY.px),(191-touchXY.py),4,4,viewport); // render only what is below the cursor
-				gluPerspective(60, 256.0 / 192.0, 0.1, 20); // this must be the same as the original perspective matrix
-				
-				glMatrixMode(GL_MODELVIEW); // switch back to modifying the modelview matrix for drawing
-				
-				glTranslatef32(floattof32(2.9),floattof32(0),floattof32(0)); // translate the modelview matrix to the drawing location
-				startCheck();
-				glCallList((@cone_bin)); // draw a cone from a predefined packed command list
-				endCheck(clCone);
-
-				glTranslatef32(floattof32(-3),floattof32(1.8),floattof32(2)); // translate the modelview matrix to the drawing location
-				startCheck();
-				glCallList((@cylinder_bin)); // draw a cylinder from a predefined packed command list
-				endCheck(clCylinder);
-
-				glTranslatef32(floattof32(0.5),floattof32(-2.6),floattof32(-4)); // translate the modelview matrix to the drawing location
-				startCheck();
-				glCallList((@sphere_bin)); // draw a sphere from a predefined packed command list
-				endCheck(clSphere);
-
-		glPopMatrix(1); // restores the modelview matrix to its original state
-
-		glFlush(0); // wait for everything to be drawn before starting on the next frame
-	end;
+        glTranslatef32(floattof32(0.5),floattof32(-2.6),floattof32(-4)); // translate the modelview matrix to the drawing location
+        if(clicked = clSphere) then
+          glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(1)) // set a poly ID for outlining
+        else
+          glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_ID(0)); // set a poly ID for no outlining (same as BG)
+
+        glCallList((@sphere_bin)); // draw a red sphere from a predefined packed command list
+
+      glPopMatrix(1); // restores the modelview matrix to where it was just rotated
+      
+      // draw the scene again for picking
+        clicked := clNothing; //reset what was clicked on
+        closeW := $7FFFFFFF; //reset the distance
+
+        //set the viewport to just off-screen, this hides all rendering that will be done during picking
+        glViewport(0,192,0,192);
+        
+        // setup the projection matrix for picking
+        glMatrixMode(GL_PROJECTION);
+        glLoadIdentity();
+        gluPickMatrix((touchXY.px),(191-touchXY.py),4,4,viewport); // render only what is below the cursor
+        gluPerspective(60, 256.0 / 192.0, 0.1, 20); // this must be the same as the original perspective matrix
+        
+        glMatrixMode(GL_MODELVIEW); // switch back to modifying the modelview matrix for drawing
+        
+        glTranslatef32(floattof32(2.9),floattof32(0),floattof32(0)); // translate the modelview matrix to the drawing location
+        startCheck();
+        glCallList((@cone_bin)); // draw a cone from a predefined packed command list
+        endCheck(clCone);
+
+        glTranslatef32(floattof32(-3),floattof32(1.8),floattof32(2)); // translate the modelview matrix to the drawing location
+        startCheck();
+        glCallList((@cylinder_bin)); // draw a cylinder from a predefined packed command list
+        endCheck(clCylinder);
+
+        glTranslatef32(floattof32(0.5),floattof32(-2.6),floattof32(-4)); // translate the modelview matrix to the drawing location
+        startCheck();
+        glCallList((@sphere_bin)); // draw a sphere from a predefined packed command list
+        endCheck(clSphere);
+
+    glPopMatrix(1); // restores the modelview matrix to its original state
+
+    glFlush(0); // wait for everything to be drawn before starting on the next frame
+   
+    if (keys and KEY_START) <> 0 then break;
+  end;
 
 end.

+ 2 - 0
packages/libndsfpc/examples/graphics/3D/Simple_Quad/SimpleQuad.pp

@@ -86,6 +86,8 @@ begin
     glFlush(0);
 
     swiWaitForVBlank();
+    
+    if (keys and KEY_START) <> 0 then break;
   end;
 
 end.

+ 2 - 0
packages/libndsfpc/examples/graphics/3D/Simple_Tri/SimpleTri.pp

@@ -85,6 +85,8 @@ begin
     glFlush(0);
 
     swiWaitForVBlank();
+    
+    if (keys and KEY_START) <> 0 then break;
   end;
 
 end.

+ 16 - 14
packages/libndsfpc/examples/graphics/3D/Textured_Cube/TexturedCube.pp

@@ -206,10 +206,10 @@ begin
 
     keys := keysHeld();
 
-		if((keys and KEY_UP)) <> 0 then rotateX := rotateX +3;
-		if((keys and KEY_DOWN)) <> 0 then rotateX := rotateX -3;
-		if((keys and KEY_LEFT)) <> 0 then rotateY := rotateY +3;
-		if((keys and KEY_RIGHT)) <> 0 then rotateY := rotateY -3;
+    if((keys and KEY_UP)) <> 0 then rotateX := rotateX +3;
+    if((keys and KEY_DOWN)) <> 0 then rotateX := rotateX -3;
+    if((keys and KEY_LEFT)) <> 0 then rotateY := rotateY +3;
+    if((keys and KEY_RIGHT)) <> 0 then rotateY := rotateY -3;
 
     if (keysDown() and KEY_A) <> 0 then
     begin
@@ -220,21 +220,23 @@ begin
         DisplayEnableNormal();
     end;
 
-		glBindTexture(0, textureID);
+    glBindTexture(0, textureID);
 
-		//draw the obj
-		glBegin(GL_QUAD);
-			for i := 0 to 5 do
-				drawQuad(i);
-		glEnd();
+    //draw the obj
+    glBegin(GL_QUAD);
+      for i := 0 to 5 do
+        drawQuad(i);
+    glEnd();
 
-		glPopMatrix(1);
+    glPopMatrix(1);
 
-		glFlush(0);
+    glFlush(0);
 
-		swiWaitForVBlank();
+    swiWaitForVBlank();
+    
+    if (keys and KEY_START) <> 0 then break;
     
     //the display capture enable bit must be set again each frame if you want to continue capturing.
-    REG_DISPCAPCNT^ := REG_DISPCAPCNT^ or DCAP_ENABLE;		
+    REG_DISPCAPCNT^ := REG_DISPCAPCNT^ or DCAP_ENABLE;    
   end;
 end.

+ 7 - 5
packages/libndsfpc/examples/graphics/3D/Textured_Quad/TexturedQuad.pp

@@ -10,7 +10,7 @@ uses
 {$include inc/texture.bin.inc}
 
 var
-	textureID: integer;
+  textureID: integer;
   rotateX: cfloat = 0.0;
   rotateY: cfloat = 0.0;
   keys: cuint16;
@@ -80,10 +80,10 @@ begin
 
     keys := keysHeld();
 
-		if((keys and KEY_UP)) <> 0 then rotateX := rotateX +3;
-		if((keys and KEY_DOWN)) <> 0 then rotateX := rotateX -3;
-		if((keys and KEY_LEFT)) <> 0 then rotateY := rotateY +3;
-		if((keys and KEY_RIGHT)) <> 0 then rotateY := rotateY -3;
+    if((keys and KEY_UP)) <> 0 then rotateX := rotateX +3;
+    if((keys and KEY_DOWN)) <> 0 then rotateX := rotateX -3;
+    if((keys and KEY_LEFT)) <> 0 then rotateY := rotateY +3;
+    if((keys and KEY_RIGHT)) <> 0 then rotateY := rotateY -3;
 
     glBindTexture(0, textureID);
 
@@ -110,6 +110,8 @@ begin
     glFlush(0);
 
     swiWaitForVBlank();
+    
+    if (keys and KEY_START) <> 0 then break;
   end;
 
 end.

+ 101 - 99
packages/libndsfpc/examples/graphics/3D/Toon_Shading/ToonShading.pp

@@ -11,115 +11,117 @@ uses
 {$include inc/statue.bin.inc}
 
 var
-	prev_pen: array [0..1] of cint = ( $7FFFFFFF, $7FFFFFFF );
+  prev_pen: array [0..1] of cint = ( $7FFFFFFF, $7FFFFFFF );
 
 
 procedure get_pen_delta(var dx, dy: cint);
 var
-	keys: cuint32;
+  keys: cuint32;
   touchXY: touchPosition;
 begin
-	keys := keysHeld();
-
-	if( keys and KEY_TOUCH ) <> 0 then
-	begin
-		touchXY := touchReadXY();
-
-		if ( prev_pen[0] <> $7FFFFFFF ) then
-		begin
-			dx := (prev_pen[0] - touchXY.rawx);
-			dy := (prev_pen[1] - touchXY.rawy);
-		end;
-
-		prev_pen[0] := touchXY.rawx;
-		prev_pen[1] := touchXY.rawy;
-	end else
-	begin
-		prev_pen[0] := $7FFFFFFF;
+  keys := keysHeld();
+
+  if( keys and KEY_TOUCH ) <> 0 then
+  begin
+    touchXY := touchReadXY();
+
+    if ( prev_pen[0] <> $7FFFFFFF ) then
+    begin
+      dx := (prev_pen[0] - touchXY.rawx);
+      dy := (prev_pen[1] - touchXY.rawy);
+    end;
+
+    prev_pen[0] := touchXY.rawx;
+    prev_pen[1] := touchXY.rawy;
+  end else
+  begin
+    prev_pen[0] := $7FFFFFFF;
     prev_pen[1] := $7FFFFFFF;
-		dx := 0;
-		dy := 0;
-	end;
+    dx := 0;
+    dy := 0;
+  end;
 end;
 
 var
-	rotateX: integer = 0;
-	rotateY: integer = 0;
-	keys: cuint32;
-	pen_delta: array [0..1] of cint;
+  rotateX: integer = 0;
+  rotateY: integer = 0;
+  keys: cuint32;
+  pen_delta: array [0..1] of cint;
 
 begin
-	//set mode 0, enable BG0 and set it to 3D
-	videoSetMode(MODE_0_3D);
-
-	// initialize gl
-	glInit();
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
-	
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-
-	//this should work the same as the normal gl call
-	glViewport(0,0,255,191);
-
-	//toon-table entry 0 is for completely unlit pixels, going up to entry 31 for completely lit
-	//We block-fill it in two halves, we get cartoony 2-tone lighting
-	glSetToonTableRange( 0, 15, RGB15(8,8,8) );
-	glSetToonTableRange( 16, 31, RGB15(24,24,24) );
-	
-	//any floating point gl call is being converted to fixed prior to being implemented
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 40);
-	
-	//NB: When toon-shading, the hw ignores lights 2 and 3
-	//Also note that the hw uses the RED component of the lit vertex to index the toon-table
-	glLight(0, RGB15(16,16,16) , 0,		floattov10(-1.0),		0);
-	glLight(1, RGB15(16,16,16),   floattov10(-1.0),	0,		0);
-	
-	gluLookAt(	0.0, 0.0, -3.0,		//camera possition 
-				0.0, 0.0, 0.0,		//look at
-				0.0, 1.0, 0.0);		//up
-	
-	while true do
-	begin
-
-		glMatrixMode(GL_MODELVIEW);
-		glPushMatrix();
-			glRotateXi(rotateX);
-			glRotateYi(rotateY);
-
-
-			glMaterialf(GL_AMBIENT, RGB15(8,8,8));
-			glMaterialf(GL_DIFFUSE, RGB15(24,24,24));
-			glMaterialf(GL_SPECULAR, RGB15(0,0,0));
-			glMaterialf(GL_EMISSION, RGB15(0,0,0));
-
-			glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_FORMAT_LIGHT1 or POLY_TOON_HIGHLIGHT);
-
-
-			scanKeys();
-			keys := keysHeld();
-
-			if( keys and KEY_UP ) <> 0 then rotateX := rotateX +1;
-			if( keys and KEY_DOWN ) <> 0 then rotateX := rotateX -1;
-			if( keys and KEY_LEFT ) <> 0 then rotateY := rotateY +1;
-			if( keys and KEY_RIGHT ) <> 0 then rotateY := rotateY -1;
-
-			get_pen_delta( pen_delta[0], pen_delta[1] );
-			rotateY := rotateY - pen_delta[0];
-			rotateX := rotateY - pen_delta[1];
-
-
-			glCallList(@statue_bin);
-			glPopMatrix(1);
-
-		glFlush(0);
-
-		swiWaitForVBlank();
-	end;
+  //set mode 0, enable BG0 and set it to 3D
+  videoSetMode(MODE_0_3D);
+
+  // initialize gl
+  glInit();
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+  
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+
+  //this should work the same as the normal gl call
+  glViewport(0,0,255,191);
+
+  //toon-table entry 0 is for completely unlit pixels, going up to entry 31 for completely lit
+  //We block-fill it in two halves, we get cartoony 2-tone lighting
+  glSetToonTableRange( 0, 15, RGB15(8,8,8) );
+  glSetToonTableRange( 16, 31, RGB15(24,24,24) );
+  
+  //any floating point gl call is being converted to fixed prior to being implemented
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70, 256.0 / 192.0, 0.1, 40);
+  
+  //NB: When toon-shading, the hw ignores lights 2 and 3
+  //Also note that the hw uses the RED component of the lit vertex to index the toon-table
+  glLight(0, RGB15(16,16,16) , 0,   floattov10(-1.0),   0);
+  glLight(1, RGB15(16,16,16),   floattov10(-1.0), 0,    0);
+  
+  gluLookAt(  0.0, 0.0, -3.0,   //camera possition 
+        0.0, 0.0, 0.0,    //look at
+        0.0, 1.0, 0.0);   //up
+  
+  while true do
+  begin
+
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+      glRotateXi(rotateX);
+      glRotateYi(rotateY);
+
+
+      glMaterialf(GL_AMBIENT, RGB15(8,8,8));
+      glMaterialf(GL_DIFFUSE, RGB15(24,24,24));
+      glMaterialf(GL_SPECULAR, RGB15(0,0,0));
+      glMaterialf(GL_EMISSION, RGB15(0,0,0));
+
+      glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0 or POLY_FORMAT_LIGHT1 or POLY_TOON_HIGHLIGHT);
+
+
+      scanKeys();
+      keys := keysHeld();
+
+      if( keys and KEY_UP ) <> 0 then rotateX := rotateX +1;
+      if( keys and KEY_DOWN ) <> 0 then rotateX := rotateX -1;
+      if( keys and KEY_LEFT ) <> 0 then rotateY := rotateY +1;
+      if( keys and KEY_RIGHT ) <> 0 then rotateY := rotateY -1;
+
+      get_pen_delta( pen_delta[0], pen_delta[1] );
+      rotateY := rotateY - pen_delta[0];
+      rotateX := rotateY - pen_delta[1];
+
+
+      glCallList(@statue_bin);
+      glPopMatrix(1);
+
+    glFlush(0);
+
+    swiWaitForVBlank();
+   
+    if (keys and KEY_START) <> 0 then break;
+  end;
 end.

+ 7 - 1
packages/libndsfpc/examples/graphics/3D/nehe/lesson01/lesson01.pp

@@ -19,6 +19,9 @@ begin
 	result := true;
 end;
 
+var
+  keys: integer;
+
 begin	
 	// Setup the Main screen for 3D 
 	videoSetMode(MODE_0_3D);
@@ -65,7 +68,10 @@ begin
 		swiWaitForVBlank();
 
 		// flush to screen	
-		glFlush(0);	
+		glFlush(0);
+    scanKeys();
+		keys := keysDown();
+		if (keys and KEY_START) <> 0 then break;
 	end;
 	
 end.

+ 65 - 59
packages/libndsfpc/examples/graphics/3D/nehe/lesson02/lesson02.pp

@@ -1,6 +1,6 @@
 (****************************************
- * 		NDS NeHe Lesson 02    			*
- * 		Author: Dovoto					*
+ *    NDS NeHe Lesson 02          *
+ *    Author: Dovoto          *
  ****************************************)
 
 program Lesson02;
@@ -12,72 +12,78 @@ uses
 
 function DrawGLScene(): boolean;
 begin
-	glLoadIdentity();									// Reset The Current Modelview Matrix
+  glLoadIdentity();                 // Reset The Current Modelview Matrix
 
-	glTranslatef(-1.5,0.0,-6.0);						// Move Left 1.5 Units And Into The Screen 6.0
-	glBegin(GL_TRIANGLES);								// Drawing Using Triangles
-		glVertex3f( 0.0, 1.0, 0.0);					// Top
-		glVertex3f(-1.0,-1.0, 0.0);					// Bottom Left
-		glVertex3f( 1.0,-1.0, 0.0);					// Bottom Right
-	glEnd();											// Finished Drawing The Triangle
+  glTranslatef(-1.5,0.0,-6.0);            // Move Left 1.5 Units And Into The Screen 6.0
+  glBegin(GL_TRIANGLES);                // Drawing Using Triangles
+    glVertex3f( 0.0, 1.0, 0.0);         // Top
+    glVertex3f(-1.0,-1.0, 0.0);         // Bottom Left
+    glVertex3f( 1.0,-1.0, 0.0);         // Bottom Right
+  glEnd();                      // Finished Drawing The Triangle
 
-	glTranslatef(3.0,0.0,0.0);						// Move Right 3 Units
-	glBegin(GL_QUADS);									// Draw A Quad
-		glVertex3f(-1.0, 1.0, 0.0);					// Top Left
-		glVertex3f( 1.0, 1.0, 0.0);					// Top Right
-		glVertex3f( 1.0,-1.0, 0.0);					// Bottom Right
-		glVertex3f(-1.0,-1.0, 0.0);					// Bottom Left
-	glEnd();											// Done Drawing The Quad
+  glTranslatef(3.0,0.0,0.0);            // Move Right 3 Units
+  glBegin(GL_QUADS);                  // Draw A Quad
+    glVertex3f(-1.0, 1.0, 0.0);         // Top Left
+    glVertex3f( 1.0, 1.0, 0.0);         // Top Right
+    glVertex3f( 1.0,-1.0, 0.0);         // Bottom Right
+    glVertex3f(-1.0,-1.0, 0.0);         // Bottom Left
+  glEnd();                      // Done Drawing The Quad
 
-	result := true;										// Keep Going
+  result := true;                   // Keep Going
 end;
 
-begin	
+var
+  keys: integer;
 
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
+begin 
 
-	// initialize the geometry engine
-	glInit();
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
 
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-	
-	// Set our viewport to be the same size as the screen
-	glViewPort(0,0,255,191);
-	
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
-	// Set the color of the vertices
-	glColor3f(1, 1, 1);
-	
+  // initialize the geometry engine
+  glInit();
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+  
+  // Set our viewport to be the same size as the screen
+  glViewPort(0,0,255,191);
+  
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  // Set the color of the vertices
+  glColor3f(1, 1, 1);
+  
   while true do
-	begin
-		//ds specific, several attributes can be set here	
-		glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
-		
-		// Set the current matrix to be the model matrix
-		glMatrixMode(GL_MODELVIEW);
-		
-		//Push our original Matrix onto the stack (save state)
-		glPushMatrix();	
+  begin
+    //ds specific, several attributes can be set here 
+    glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
+    
+    // Set the current matrix to be the model matrix
+    glMatrixMode(GL_MODELVIEW);
+    
+    //Push our original Matrix onto the stack (save state)
+    glPushMatrix(); 
  
-		DrawGLScene();
-		
-		// Pop our Matrix from the stack (restore state)
-		glPopMatrix(1);
+    DrawGLScene();
+    
+    // Pop our Matrix from the stack (restore state)
+    glPopMatrix(1);
 
-		//a handy little built in function to wait for a screen refresh
-		swiWaitForVBlank();
-		
-		// flush to screen	
-		glFlush(0);
-	end;
-	
+    //a handy little built in function to wait for a screen refresh
+    swiWaitForVBlank();
+    
+    // flush to screen  
+    glFlush(0);
+    scanKeys();
+    keys := keysDown();
+    if (keys and KEY_START) <> 0 then break;
+  end;
+  
 end.

+ 51 - 48
packages/libndsfpc/examples/graphics/3D/nehe/lesson03/lesson03.pp

@@ -1,6 +1,6 @@
 (****************************************
- * 		NDS NeHe Lesson 03    			*
- * 		Author: Dovoto					*
+ *    NDS NeHe Lesson 03          *
+ *    Author: Dovoto          *
  ****************************************)
 
 program Lesson03;
@@ -12,28 +12,29 @@ uses
 
 function DrawGLScene(): boolean;
 begin
-	glLoadIdentity();									// Reset The Current Modelview Matrix
-	glTranslatef(-1.5,0.0,-6.0);						// Move Left 1.5 Units And Into The Screen 6.0
-	glBegin(GL_TRIANGLES);								// Drawing Using Triangles
-		glColor3f(1.0,0.0,0.0);						// Set The Color To Red
-		glVertex3f( 0.0, 1.0, 0.0);					// Top
-		glColor3f(0.0,1.0,0.0);						// Set The Color To Green
-		glVertex3f(-1.0,-1.0, 0.0);					// Bottom Left
-		glColor3f(0.0,0.0,1.0);						// Set The Color To Blue
-		glVertex3f( 1.0,-1.0, 0.0);					// Bottom Right
-	glEnd();											// Finished Drawing The Triangle
-	glTranslatef(3.0,0.0,0.0);						// Move Right 3 Units
-	glColor3f(0.5,0.5,1.0);							// Set The Color To Blue One Time Only
-	glBegin(GL_QUADS);									// Draw A Quad
-		glVertex3f(-1.0, 1.0, 0.0);					// Top Left
-		glVertex3f( 1.0, 1.0, 0.0);					// Top Right
-		glVertex3f( 1.0,-1.0, 0.0);					// Bottom Right
-		glVertex3f(-1.0,-1.0, 0.0);					// Bottom Left
-	glEnd();											// Done Drawing The Quad
-	result := true;										// Keep Going
+  glLoadIdentity();                 // Reset The Current Modelview Matrix
+  glTranslatef(-1.5,0.0,-6.0);            // Move Left 1.5 Units And Into The Screen 6.0
+  glBegin(GL_TRIANGLES);                // Drawing Using Triangles
+    glColor3f(1.0,0.0,0.0);           // Set The Color To Red
+    glVertex3f( 0.0, 1.0, 0.0);         // Top
+    glColor3f(0.0,1.0,0.0);           // Set The Color To Green
+    glVertex3f(-1.0,-1.0, 0.0);         // Bottom Left
+    glColor3f(0.0,0.0,1.0);           // Set The Color To Blue
+    glVertex3f( 1.0,-1.0, 0.0);         // Bottom Right
+  glEnd();                      // Finished Drawing The Triangle
+  glTranslatef(3.0,0.0,0.0);            // Move Right 3 Units
+  glColor3f(0.5,0.5,1.0);             // Set The Color To Blue One Time Only
+  glBegin(GL_QUADS);                  // Draw A Quad
+    glVertex3f(-1.0, 1.0, 0.0);         // Top Left
+    glVertex3f( 1.0, 1.0, 0.0);         // Top Right
+    glVertex3f( 1.0,-1.0, 0.0);         // Bottom Right
+    glVertex3f(-1.0,-1.0, 0.0);         // Bottom Left
+  glEnd();                      // Done Drawing The Quad
+  result := true;                   // Keep Going
 end;
 
-
+var
+  keys: integer;
 begin
   // Setup the Main screen for 3D 
   videoSetMode(MODE_0_3D);
@@ -43,38 +44,40 @@ begin
   // enable antialiasing
   glEnable(GL_ANTIALIAS);
   
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
   glClearDepth($7FFF);
    
-	// Set our viewport to be the same size as the screen
-	glViewPort(0,0,255,191);
-	
+  // Set our viewport to be the same size as the screen
+  glViewPort(0,0,255,191);
+  
 
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
 
-	//ds specific, several attributes can be set here	
-	glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
-		
-	// Set the current matrix to be the model matrix
-	glMatrixMode(GL_MODELVIEW);
-	
-  glColor3f(1, 1, 1);									// Set the color..not in nehe source...ds gl default will be black
-	
-	while true do 
-	begin
+  //ds specific, several attributes can be set here 
+  glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
+    
+  // Set the current matrix to be the model matrix
+  glMatrixMode(GL_MODELVIEW);
+  
+  glColor3f(1, 1, 1);                 // Set the color..not in nehe source...ds gl default will be black
+  
+  while true do 
+  begin
 
-		DrawGLScene();
-		
-		// flush to screen	
-		glFlush(0);
+    DrawGLScene();
+    
+    // flush to screen  
+    glFlush(0);
 
-		//a handy little built in function to wait for a screen refresh
-		swiWaitForVBlank();
-		
-	end;
-	
+    //a handy little built in function to wait for a screen refresh
+    swiWaitForVBlank();
+    scanKeys();
+    keys := keysDown();
+    if (keys and KEY_START) <> 0 then break;    
+  end;
+  
 end.

+ 62 - 58
packages/libndsfpc/examples/graphics/3D/nehe/lesson04/lesson04.pp

@@ -1,6 +1,6 @@
 (****************************************
- * 		NDS NeHe Lesson 04    			*
- * 		Author: Dovoto					*
+ *    NDS NeHe Lesson 04          *
+ *    Author: Dovoto          *
  ****************************************)
 
 program Lesson04;
@@ -17,75 +17,79 @@ var
 
 function DrawGLScene(): boolean;
 begin
-	glLoadIdentity();									// Reset The Current Modelview Matrix
-	glTranslatef(-1.5,0.0,-6.0);						// Move Left 1.5 Units And Into The Screen 6.0
-	glRotatef(rtri,0.0,1.0,0.0);						// Rotate The Triangle On The Y axis ( NEW )
-	glColor3f(1, 1, 1);									// set the vertex color
-	glBegin(GL_TRIANGLES);								// Drawing Using Triangles
-		glColor3f(1.0,0.0,0.0);						// Set The Color To Red
-		glVertex3f( 0.0, 1.0, 0.0);					// Top
-		glColor3f(0.0,1.0,0.0);						// Set The Color To Green
-		glVertex3f(-1.0,-1.0, 0.0);					// Bottom Left
-		glColor3f(0.0,0.0,1.0);						// Set The Color To Blue
-		glVertex3f( 1.0,-1.0, 0.0);					// Bottom Right
-	glEnd();											// Finished Drawing The Triangle
-	glLoadIdentity();									// Reset The Current Modelview Matrix
-	glTranslatef(1.5,0.0,-6.0);						// Move Right 3 Units
-	glRotatef(rquad,1.0,0.0,0.0);					// Rotate The Quad On The X axis ( NEW )
-	glColor3f(0.5,0.5,1.0);							// Set The Color To Blue One Time Only
-	glBegin(GL_QUADS);									// Draw A Quad
-		glVertex3f(-1.0, 1.0, 0.0);					// Top Left
-		glVertex3f( 1.0, 1.0, 0.0);					// Top Right
-		glVertex3f( 1.0,-1.0, 0.0);					// Bottom Right
-		glVertex3f(-1.0,-1.0, 0.0);					// Bottom Left
-	glEnd();											// Done Drawing The Quad
-	rtri := rtri + 0.9;											// Increase The Rotation Variable For The Triangle ( NEW )
-	rquad := rquad - 0.75;										// Decrease The Rotation Variable For The Quad ( NEW )
-  result := true;										// Keep Going
+  glLoadIdentity();                 // Reset The Current Modelview Matrix
+  glTranslatef(-1.5,0.0,-6.0);            // Move Left 1.5 Units And Into The Screen 6.0
+  glRotatef(rtri,0.0,1.0,0.0);            // Rotate The Triangle On The Y axis ( NEW )
+  glColor3f(1, 1, 1);                 // set the vertex color
+  glBegin(GL_TRIANGLES);                // Drawing Using Triangles
+    glColor3f(1.0,0.0,0.0);           // Set The Color To Red
+    glVertex3f( 0.0, 1.0, 0.0);         // Top
+    glColor3f(0.0,1.0,0.0);           // Set The Color To Green
+    glVertex3f(-1.0,-1.0, 0.0);         // Bottom Left
+    glColor3f(0.0,0.0,1.0);           // Set The Color To Blue
+    glVertex3f( 1.0,-1.0, 0.0);         // Bottom Right
+  glEnd();                      // Finished Drawing The Triangle
+  glLoadIdentity();                 // Reset The Current Modelview Matrix
+  glTranslatef(1.5,0.0,-6.0);           // Move Right 3 Units
+  glRotatef(rquad,1.0,0.0,0.0);         // Rotate The Quad On The X axis ( NEW )
+  glColor3f(0.5,0.5,1.0);             // Set The Color To Blue One Time Only
+  glBegin(GL_QUADS);                  // Draw A Quad
+    glVertex3f(-1.0, 1.0, 0.0);         // Top Left
+    glVertex3f( 1.0, 1.0, 0.0);         // Top Right
+    glVertex3f( 1.0,-1.0, 0.0);         // Bottom Right
+    glVertex3f(-1.0,-1.0, 0.0);         // Bottom Left
+  glEnd();                      // Done Drawing The Quad
+  rtri := rtri + 0.9;                     // Increase The Rotation Variable For The Triangle ( NEW )
+  rquad := rquad - 0.75;                    // Decrease The Rotation Variable For The Quad ( NEW )
+  result := true;                   // Keep Going
 end;
 
-
+var
+  keys: integer;
 
 begin
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
-	
-	// initialize the geometry engine
-	glInit();
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
+  
+  // initialize the geometry engine
+  glInit();
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
 
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
 
-	// Set our viewport to be the same size as the screen
-	glViewPort(0,0,255,191);
+  // Set our viewport to be the same size as the screen
+  glViewPort(0,0,255,191);
 
-	
+  
 
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   gluPerspective(70, 256.0 / 192.0, 0.1, 100);
 
 
-	//ds specific, several attributes can be set here	
-	glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
-	
+  //ds specific, several attributes can be set here 
+  glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
+  
   // Set the current matrix to be the model matrix
-	glMatrixMode(GL_MODELVIEW);	
-	
+  glMatrixMode(GL_MODELVIEW); 
+  
   while true do
-	begin
-		// draw the scene
-		DrawGLScene();
-		
-		// flush to screen	
-		glFlush(0);
-		
-		// wait for the screen to refresh
-		swiWaitForVBlank();
-	end;
+  begin
+    // draw the scene
+    DrawGLScene();
+    
+    // flush to screen  
+    glFlush(0);
+    
+    // wait for the screen to refresh
+    swiWaitForVBlank();
+    scanKeys();
+    keys := keysDown();
+    if (keys and KEY_START) <> 0 then break;
+  end;
 end.

+ 112 - 107
packages/libndsfpc/examples/graphics/3D/nehe/lesson05/lesson05.pp

@@ -1,6 +1,6 @@
 (****************************************
- * 		NDS NeHe Lesson 05    			*
- * 		Author: Dovoto					*
+ *    NDS NeHe Lesson 05          *
+ *    Author: Dovoto          *
  ****************************************)
 
 program Lesson05;
@@ -17,119 +17,124 @@ var
 
 function DrawGLScene(): boolean;
 begin
-	glLoadIdentity();									// Reset The Current Modelview Matrix
-	glTranslatef(-1.5,0.0,-6.0);						// Move Left 1.5 Units And Into The Screen 6.0
-	glRotatef(rtri,0.0,1.0,0.0);						// Rotate The Triangle On The Y axis ( NEW )
-	glBegin(GL_TRIANGLES);								// Start Drawing A Triangle
-		glColor3f(1.0,0.0,0.0);						// Red
-		glVertex3f( 0.0, 1.0, 0.0);					// Top Of Triangle (Front)
-		glColor3f(0.0,1.0,0.0);						// Green
-		glVertex3f(-1.0,-1.0, 1.0);					// Left Of Triangle (Front)
-		glColor3f(0.0,0.0,1.0);						// Blue
-		glVertex3f( 1.0,-1.0, 1.0);					// Right Of Triangle (Front)
-		glColor3f(1.0,0.0,0.0);						// Red
-		glVertex3f( 0.0, 1.0, 0.0);					// Top Of Triangle (Right)
-		glColor3f(0.0,0.0,1.0);						// Blue
-		glVertex3f( 1.0,-1.0, 1.0);					// Left Of Triangle (Right)
-		glColor3f(0.0,1.0,0.0);						// Green
-		glVertex3f( 1.0,-1.0, -1.0);					// Right Of Triangle (Right)
-		glColor3f(1.0,0.0,0.0);						// Red
-		glVertex3f( 0.0, 1.0, 0.0);					// Top Of Triangle (Back)
-		glColor3f(0.0,1.0,0.0);						// Green
-		glVertex3f( 1.0,-1.0, -1.0);					// Left Of Triangle (Back)
-		glColor3f(0.0,0.0,1.0);						// Blue
-		glVertex3f(-1.0,-1.0, -1.0);					// Right Of Triangle (Back)
-		glColor3f(1.0,0.0,0.0);						// Red
-		glVertex3f( 0.0, 1.0, 0.0);					// Top Of Triangle (Left)
-		glColor3f(0.0,0.0,1.0);						// Blue
-		glVertex3f(-1.0,-1.0,-1.0);					// Left Of Triangle (Left)
-		glColor3f(0.0,1.0,0.0);						// Green
-		glVertex3f(-1.0,-1.0, 1.0);					// Right Of Triangle (Left)
-	glEnd();											// Done Drawing The Pyramid
+  glLoadIdentity();                 // Reset The Current Modelview Matrix
+  glTranslatef(-1.5,0.0,-6.0);            // Move Left 1.5 Units And Into The Screen 6.0
+  glRotatef(rtri,0.0,1.0,0.0);            // Rotate The Triangle On The Y axis ( NEW )
+  glBegin(GL_TRIANGLES);                // Start Drawing A Triangle
+    glColor3f(1.0,0.0,0.0);           // Red
+    glVertex3f( 0.0, 1.0, 0.0);         // Top Of Triangle (Front)
+    glColor3f(0.0,1.0,0.0);           // Green
+    glVertex3f(-1.0,-1.0, 1.0);         // Left Of Triangle (Front)
+    glColor3f(0.0,0.0,1.0);           // Blue
+    glVertex3f( 1.0,-1.0, 1.0);         // Right Of Triangle (Front)
+    glColor3f(1.0,0.0,0.0);           // Red
+    glVertex3f( 0.0, 1.0, 0.0);         // Top Of Triangle (Right)
+    glColor3f(0.0,0.0,1.0);           // Blue
+    glVertex3f( 1.0,-1.0, 1.0);         // Left Of Triangle (Right)
+    glColor3f(0.0,1.0,0.0);           // Green
+    glVertex3f( 1.0,-1.0, -1.0);          // Right Of Triangle (Right)
+    glColor3f(1.0,0.0,0.0);           // Red
+    glVertex3f( 0.0, 1.0, 0.0);         // Top Of Triangle (Back)
+    glColor3f(0.0,1.0,0.0);           // Green
+    glVertex3f( 1.0,-1.0, -1.0);          // Left Of Triangle (Back)
+    glColor3f(0.0,0.0,1.0);           // Blue
+    glVertex3f(-1.0,-1.0, -1.0);          // Right Of Triangle (Back)
+    glColor3f(1.0,0.0,0.0);           // Red
+    glVertex3f( 0.0, 1.0, 0.0);         // Top Of Triangle (Left)
+    glColor3f(0.0,0.0,1.0);           // Blue
+    glVertex3f(-1.0,-1.0,-1.0);         // Left Of Triangle (Left)
+    glColor3f(0.0,1.0,0.0);           // Green
+    glVertex3f(-1.0,-1.0, 1.0);         // Right Of Triangle (Left)
+  glEnd();                      // Done Drawing The Pyramid
 
-	glLoadIdentity();									// Reset The Current Modelview Matrix
-	glTranslatef(1.5,0.0,-7.0);						// Move Right 1.5 Units And Into The Screen 7.0
-	glRotatef(rquad,1.0,1.0,1.0);					// Rotate The Quad On The X axis ( NEW )
-	glBegin(GL_QUADS);									// Draw A Quad
-		glColor3f(0.0,1.0,0.0);						// Set The Color To Green
-		glVertex3f( 1.0, 1.0,-1.0);					// Top Right Of The Quad (Top)
-		glVertex3f(-1.0, 1.0,-1.0);					// Top Left Of The Quad (Top)
-		glVertex3f(-1.0, 1.0, 1.0);					// Bottom Left Of The Quad (Top)
-		glVertex3f( 1.0, 1.0, 1.0);					// Bottom Right Of The Quad (Top)
-		glColor3f(1.0,0.5,0.0); 					// Set The Color To Orange
-		glVertex3f( 1.0,-1.0, 1.0);					// Top Right Of The Quad (Bottom)
-		glVertex3f(-1.0,-1.0, 1.0);					// Top Left Of The Quad (Bottom)
-		glVertex3f(-1.0,-1.0,-1.0);					// Bottom Left Of The Quad (Bottom)
-		glVertex3f( 1.0,-1.0,-1.0);					// Bottom Right Of The Quad (Bottom)
-		glColor3f(1.0,0.0,0.0);						// Set The Color To Red
-		glVertex3f( 1.0, 1.0, 1.0);					// Top Right Of The Quad (Front)
-		glVertex3f(-1.0, 1.0, 1.0);					// Top Left Of The Quad (Front)
-		glVertex3f(-1.0,-1.0, 1.0);					// Bottom Left Of The Quad (Front)
-		glVertex3f( 1.0,-1.0, 1.0);					// Bottom Right Of The Quad (Front)
-		glColor3f(1.0,1.0,0.0);						// Set The Color To Yellow
-		glVertex3f( 1.0,-1.0,-1.0);					// Top Right Of The Quad (Back)
-		glVertex3f(-1.0,-1.0,-1.0);					// Top Left Of The Quad (Back)
-		glVertex3f(-1.0, 1.0,-1.0);					// Bottom Left Of The Quad (Back)
-		glVertex3f( 1.0, 1.0,-1.0);					// Bottom Right Of The Quad (Back)
-		glColor3f(0.0,0.0,1.0);						// Set The Color To Blue
-		glVertex3f(-1.0, 1.0, 1.0);					// Top Right Of The Quad (Left)
-		glVertex3f(-1.0, 1.0,-1.0);					// Top Left Of The Quad (Left)
-		glVertex3f(-1.0,-1.0,-1.0);					// Bottom Left Of The Quad (Left)
-		glVertex3f(-1.0,-1.0, 1.0);					// Bottom Right Of The Quad (Left)
-		glColor3f(1.0,0.0,1.0);						// Set The Color To Violet
-		glVertex3f( 1.0, 1.0,-1.0);					// Top Right Of The Quad (Right)
-		glVertex3f( 1.0, 1.0, 1.0);					// Top Left Of The Quad (Right)
-		glVertex3f( 1.0,-1.0, 1.0);					// Bottom Left Of The Quad (Right)
-		glVertex3f( 1.0,-1.0,-1.0);					// Bottom Right Of The Quad (Right)
-	glEnd();											// Done Drawing The Quad
+  glLoadIdentity();                 // Reset The Current Modelview Matrix
+  glTranslatef(1.5,0.0,-7.0);           // Move Right 1.5 Units And Into The Screen 7.0
+  glRotatef(rquad,1.0,1.0,1.0);         // Rotate The Quad On The X axis ( NEW )
+  glBegin(GL_QUADS);                  // Draw A Quad
+    glColor3f(0.0,1.0,0.0);           // Set The Color To Green
+    glVertex3f( 1.0, 1.0,-1.0);         // Top Right Of The Quad (Top)
+    glVertex3f(-1.0, 1.0,-1.0);         // Top Left Of The Quad (Top)
+    glVertex3f(-1.0, 1.0, 1.0);         // Bottom Left Of The Quad (Top)
+    glVertex3f( 1.0, 1.0, 1.0);         // Bottom Right Of The Quad (Top)
+    glColor3f(1.0,0.5,0.0);           // Set The Color To Orange
+    glVertex3f( 1.0,-1.0, 1.0);         // Top Right Of The Quad (Bottom)
+    glVertex3f(-1.0,-1.0, 1.0);         // Top Left Of The Quad (Bottom)
+    glVertex3f(-1.0,-1.0,-1.0);         // Bottom Left Of The Quad (Bottom)
+    glVertex3f( 1.0,-1.0,-1.0);         // Bottom Right Of The Quad (Bottom)
+    glColor3f(1.0,0.0,0.0);           // Set The Color To Red
+    glVertex3f( 1.0, 1.0, 1.0);         // Top Right Of The Quad (Front)
+    glVertex3f(-1.0, 1.0, 1.0);         // Top Left Of The Quad (Front)
+    glVertex3f(-1.0,-1.0, 1.0);         // Bottom Left Of The Quad (Front)
+    glVertex3f( 1.0,-1.0, 1.0);         // Bottom Right Of The Quad (Front)
+    glColor3f(1.0,1.0,0.0);           // Set The Color To Yellow
+    glVertex3f( 1.0,-1.0,-1.0);         // Top Right Of The Quad (Back)
+    glVertex3f(-1.0,-1.0,-1.0);         // Top Left Of The Quad (Back)
+    glVertex3f(-1.0, 1.0,-1.0);         // Bottom Left Of The Quad (Back)
+    glVertex3f( 1.0, 1.0,-1.0);         // Bottom Right Of The Quad (Back)
+    glColor3f(0.0,0.0,1.0);           // Set The Color To Blue
+    glVertex3f(-1.0, 1.0, 1.0);         // Top Right Of The Quad (Left)
+    glVertex3f(-1.0, 1.0,-1.0);         // Top Left Of The Quad (Left)
+    glVertex3f(-1.0,-1.0,-1.0);         // Bottom Left Of The Quad (Left)
+    glVertex3f(-1.0,-1.0, 1.0);         // Bottom Right Of The Quad (Left)
+    glColor3f(1.0,0.0,1.0);           // Set The Color To Violet
+    glVertex3f( 1.0, 1.0,-1.0);         // Top Right Of The Quad (Right)
+    glVertex3f( 1.0, 1.0, 1.0);         // Top Left Of The Quad (Right)
+    glVertex3f( 1.0,-1.0, 1.0);         // Bottom Left Of The Quad (Right)
+    glVertex3f( 1.0,-1.0,-1.0);         // Bottom Right Of The Quad (Right)
+  glEnd();                      // Done Drawing The Quad
 
-	rtri:=rtri+0.2;											// Increase The Rotation Variable For The Triangle ( NEW )
-	rquad:=rquad-0.15;										// Decrease The Rotation Variable For The Quad ( NEW )
-	result := true;										// Keep Going
+  rtri:=rtri+0.2;                     // Increase The Rotation Variable For The Triangle ( NEW )
+  rquad:=rquad-0.15;                    // Decrease The Rotation Variable For The Quad ( NEW )
+  result := true;                   // Keep Going
 end;
 
-
-begin	
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
-	
-	// initialize the geometry engine
-	glInit();
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
-	
-	// Specify the Clear Color and Depth 
-	glClearColor(0,0,0,31);
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-	
-		// Set our viewport to be the same size as the screen
-	glViewPort(0,0,255,191);
+var
+  keys: integer;
+begin 
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
+  
+  // initialize the geometry engine
+  glInit();
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+  
+  // Specify the Clear Color and Depth 
+  glClearColor(0,0,0,31);
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+  
+    // Set our viewport to be the same size as the screen
+  glViewPort(0,0,255,191);
 
   glMatrixMode(GL_PROJECTION);
-  glLoadIdentity();	
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
-	
-	//ds specific, several attributes can be set here	
-	glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
-		
+  glLoadIdentity(); 
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  
+  //ds specific, several attributes can be set here 
+  glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE);
+    
   while true do
-	begin
-		// Set the current matrix to be the model matrix
-		glMatrixMode(GL_MODELVIEW);
-		
-		//Push our original Matrix onto the stack (save state)
-		glPushMatrix();	
+  begin
+    // Set the current matrix to be the model matrix
+    glMatrixMode(GL_MODELVIEW);
+    
+    //Push our original Matrix onto the stack (save state)
+    glPushMatrix(); 
 
-		DrawGLScene();
-		
-		// Pop our Matrix from the stack (restore state)
-		glPopMatrix(1);
+    DrawGLScene();
+    
+    // Pop our Matrix from the stack (restore state)
+    glPopMatrix(1);
 
-		// flush to screen	
-		glFlush(0);
+    // flush to screen  
+    glFlush(0);
+    
+    swiWaitForVBlank();
     
-    swiWaitForVBlank();	
-	end;
+    scanKeys();
+    keys := keysDown();
+    if (keys and KEY_START) <> 0 then break;  
+  end;
 end.

+ 130 - 124
packages/libndsfpc/examples/graphics/3D/nehe/lesson06/lesson06.pp

@@ -1,6 +1,6 @@
 (****************************************
- * 		NDS NeHe Lesson 06    			*
- * 		Author: Dovoto					*
+ *    NDS NeHe Lesson 06          *
+ *    Author: Dovoto          *
  ****************************************)
 program Lesson06;
 {$L build/drunkenlogo.pcx.o}
@@ -13,141 +13,147 @@ uses
 {$include inc/drunkenlogo.pcx.inc}
 
 var
-  xrot: cfloat;				// X Rotation ( NEW )
-  yrot: cfloat;				// Y Rotation ( NEW )
-  zrot: cfloat;				// Z Rotation ( NEW )
+  xrot: cfloat;       // X Rotation ( NEW )
+  yrot: cfloat;       // Y Rotation ( NEW )
+  zrot: cfloat;       // Z Rotation ( NEW )
   
-  texture: array [0..0] of integer;			// Storage For One Texture ( NEW )
+  texture: array [0..0] of integer;     // Storage For One Texture ( NEW )
 
 
 
-function DrawGLScene(): boolean;											// Here's Where We Do All The Drawing
+function DrawGLScene(): boolean;                      // Here's Where We Do All The Drawing
 begin
-	glLoadIdentity();									// Reset The View
-	glTranslatef(0.0,0.0,-5.0);
-
-	glRotatef(xrot,1.0,0.0,0.0);
-	glRotatef(yrot,0.0,1.0,0.0);
-	glRotatef(zrot,0.0,0.0,1.0);
-
-	glBindTexture(GL_TEXTURE_2D, texture[0]);
-
-	glBegin(GL_QUADS);
-		// Front Face
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
-		// Back Face
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
-		// Top Face
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,  1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		// Bottom Face
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0, -1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		// Right face
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		// Left Face
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-	glEnd();
-
-	xrot:=xrot+0.3;
-	yrot:=yrot+0.2;
-	zrot:=zrot+0.4;
-	result := true;			
+  glLoadIdentity();                 // Reset The View
+  glTranslatef(0.0,0.0,-5.0);
+
+  glRotatef(xrot,1.0,0.0,0.0);
+  glRotatef(yrot,0.0,1.0,0.0);
+  glRotatef(zrot,0.0,0.0,1.0);
+
+  glBindTexture(GL_TEXTURE_2D, texture[0]);
+
+  glBegin(GL_QUADS);
+    // Front Face
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
+    // Back Face
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
+    // Top Face
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,  1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    // Bottom Face
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0, -1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    // Right face
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    // Left Face
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+  glEnd();
+
+  xrot:=xrot+0.3;
+  yrot:=yrot+0.2;
+  zrot:=zrot+0.4;
+  result := true;     
 end;
 
 
-function LoadGLTextures(): boolean;									// Load PCX files And Convert To Textures
+function LoadGLTextures(): boolean;                 // Load PCX files And Convert To Textures
 var
-	pcx: sImage;                //////////////(NEW) and different from nehe.
+  pcx: sImage;                //////////////(NEW) and different from nehe.
 begin
-	//load our texture
-	loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
-	
-	image8to16(@pcx);
+  //load our texture
+  loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
+  
+  image8to16(@pcx);
 
-	glGenTextures(1, @texture[0]);
-	glBindTexture(0, texture[0]);
-	glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
+  glGenTextures(1, @texture[0]);
+  glBindTexture(0, texture[0]);
+  glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
 
-	imageDestroy(@pcx);
+  imageDestroy(@pcx);
 
-	result := true;
+  result := true;
 end;
 
-begin	
-
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
-	vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
-
-	// initialize the geometry engine
-	glInit();
-	
-	// enable textures
-	glEnable(GL_TEXTURE_2D);
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
-	
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-	
-	// Set our viewport to be the same size as the screen
-	glViewport(0,0,255,191);
-	
-	LoadGLTextures();
-	
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
-	
-	// Set the current matrix to be the model matrix
-	glMatrixMode(GL_MODELVIEW);
-	
-	//need to set up some material properties since DS does not have them set by default
-	glMaterialf(GL_AMBIENT, RGB15(16,16,16));
-	glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
-	glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
-	glMaterialf(GL_EMISSION, RGB15(16,16,16));
-	
-	//ds uses a table for shinyness..this generates a half-ass one
-	glMaterialShinyness();
-	
-	//ds specific, several attributes can be set here	
-	glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE  or POLY_FORMAT_LIGHT0 or POLY_FORMAT_LIGHT1 or POLY_FORMAT_LIGHT2);
-	
-	glLight(0, RGB15(31,31,31) , 0,				  floattov10(-1.0),		 0);
-	glLight(1, RGB15(31,31,31) , 0,				  0,	floattov10(-1.0));
-	glLight(2, RGB15(31,31,31) , 0,				  0,	floattov10(1.0));
-
-	while true do
-	begin
-
-		glColor3f(1,1,1);
-
-		DrawGLScene();
-		
-		// flush to screen	
-		glFlush(0);
-
-    swiWaitForVBlank();	
-	end;
+var
+  keys: integer;
+begin 
+
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
+  vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
+
+  // initialize the geometry engine
+  glInit();
+  
+  // enable textures
+  glEnable(GL_TEXTURE_2D);
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+  
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+  
+  // Set our viewport to be the same size as the screen
+  glViewport(0,0,255,191);
+  
+  LoadGLTextures();
+  
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  
+  // Set the current matrix to be the model matrix
+  glMatrixMode(GL_MODELVIEW);
+  
+  //need to set up some material properties since DS does not have them set by default
+  glMaterialf(GL_AMBIENT, RGB15(16,16,16));
+  glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
+  glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
+  glMaterialf(GL_EMISSION, RGB15(16,16,16));
+  
+  //ds uses a table for shinyness..this generates a half-ass one
+  glMaterialShinyness();
+  
+  //ds specific, several attributes can be set here 
+  glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE  or POLY_FORMAT_LIGHT0 or POLY_FORMAT_LIGHT1 or POLY_FORMAT_LIGHT2);
+  
+  glLight(0, RGB15(31,31,31) , 0,         floattov10(-1.0),    0);
+  glLight(1, RGB15(31,31,31) , 0,         0,  floattov10(-1.0));
+  glLight(2, RGB15(31,31,31) , 0,         0,  floattov10(1.0));
+
+  while true do
+  begin
+
+    glColor3f(1,1,1);
+
+    DrawGLScene();
+    
+    // flush to screen  
+    glFlush(0);
+
+    swiWaitForVBlank(); 
+
+    scanKeys();
+    keys := keysDown();
+    if (keys and KEY_START) <> 0 then break;
+  end;
 end.

+ 161 - 161
packages/libndsfpc/examples/graphics/3D/nehe/lesson07/lesson07.pp

@@ -1,6 +1,6 @@
 (****************************************
- * 		NDS NeHe Lesson 07    			*
- * 		Author: Ethos					*
+ *    NDS NeHe Lesson 07          *
+ *    Author: Ethos         *
  ****************************************)
 
 program Lesson07;
@@ -14,182 +14,182 @@ uses
 {$include inc/drunkenlogo.pcx.inc}
 
 var
-  light: boolean;				// Lighting ON/OFF ( NEW )
-  lp: boolean;					// L Pressed? ( NEW )
+  light: boolean;       // Lighting ON/OFF ( NEW )
+  lp: boolean;          // L Pressed? ( NEW )
 
-  xrot: cfloat;				// X Rotation
-  yrot: cfloat;				// Y Rotation
-  xspeed: cfloat;				// X Rotation Speed
-  yspeed: cfloat;				// Y Rotation Speed
-  z: cfloat = -5.0;			// Depth Into The Screen
+  xrot: cfloat;       // X Rotation
+  yrot: cfloat;       // Y Rotation
+  xspeed: cfloat;       // X Rotation Speed
+  yspeed: cfloat;       // Y Rotation Speed
+  z: cfloat = -5.0;     // Depth Into The Screen
 
-  texture: array [0..2] of integer;			// Storage For 3 Textures (only going to use 1 on the DS for this demo)
+  texture: array [0..2] of integer;     // Storage For 3 Textures (only going to use 1 on the DS for this demo)
 
 const
-  LightAmbient: array [0..3] of cfloat =		( 0.5, 0.5, 0.5, 1.0 );
-  LightDiffuse: array [0..3] of cfloat =		( 1.0, 1.0, 1.0, 1.0 );
-  LightPosition: array [0..3] of cfloat =	  ( 0.0, 0.0, 2.0, 1.0 );
+  LightAmbient: array [0..3] of cfloat =    ( 0.5, 0.5, 0.5, 1.0 );
+  LightDiffuse: array [0..3] of cfloat =    ( 1.0, 1.0, 1.0, 1.0 );
+  LightPosition: array [0..3] of cfloat =   ( 0.0, 0.0, 2.0, 1.0 );
 
   
 
-function DrawGLScene(): boolean;											// Here's Where We Do All The Drawing
+function DrawGLScene(): boolean;                      // Here's Where We Do All The Drawing
 begin
-	glLoadIdentity();									// Reset The View
-	glTranslatef(0.0,0.0,z);
-
-	glRotatef(xrot,1.0,0.0,0.0);
-	glRotatef(yrot,0.0,1.0,0.0);
-
-	glBindTexture(GL_TEXTURE_2D, texture[0]);  //no filters to swtich between
-
-	glBegin(GL_QUADS);
-		// Front Face
-		glNormal3f( 0.0, 0.0, 1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
-		// Back Face
-		glNormal3f( 0.0, 0.0,-1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
-		// Top Face
-		glNormal3f( 0.0, 1.0, 0.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,  1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		// Bottom Face
-		glNormal3f( 0.0,-1.0, 0.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0, -1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		// Right face
-		glNormal3f( 1.0, 0.0, 0.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		// Left Face
-		glNormal3f(-1.0, 0.0, 0.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-	glEnd();
-
-	xrot:=xrot+xspeed;
-	yrot:=yrot+yspeed;
-
-
-	result := true;			
+  glLoadIdentity();                 // Reset The View
+  glTranslatef(0.0,0.0,z);
+
+  glRotatef(xrot,1.0,0.0,0.0);
+  glRotatef(yrot,0.0,1.0,0.0);
+
+  glBindTexture(GL_TEXTURE_2D, texture[0]);  //no filters to swtich between
+
+  glBegin(GL_QUADS);
+    // Front Face
+    glNormal3f( 0.0, 0.0, 1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
+    // Back Face
+    glNormal3f( 0.0, 0.0,-1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
+    // Top Face
+    glNormal3f( 0.0, 1.0, 0.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,  1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    // Bottom Face
+    glNormal3f( 0.0,-1.0, 0.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0, -1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    // Right face
+    glNormal3f( 1.0, 0.0, 0.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    // Left Face
+    glNormal3f(-1.0, 0.0, 0.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+  glEnd();
+
+  xrot:=xrot+xspeed;
+  yrot:=yrot+yspeed;
+
+
+  result := true;     
 end;
 
 
-function LoadGLTextures(): boolean;									// Load PCX files And Convert To Textures
+function LoadGLTextures(): boolean;                 // Load PCX files And Convert To Textures
 var
-	pcx: sImage;                //////////////(NEW) and different from nehe.
+  pcx: sImage;                //////////////(NEW) and different from nehe.
 begin
-	//load our texture
-	loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
-	
-	image8to16(@pcx);
+  //load our texture
+  loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
+  
+  image8to16(@pcx);
 
-	glGenTextures(1, @texture[0]);
-	glBindTexture(0, texture[0]);
-	glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
+  glGenTextures(1, @texture[0]);
+  glBindTexture(0, texture[0]);
+  glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
 
-	imageDestroy(@pcx);
+  imageDestroy(@pcx);
 
-	result := true;
+  result := true;
 end;
 
+var
+  pressed: integer;
+  held: integer;
 begin
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
-	vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
-
-	// initialize the geometry engine
-	glInit();
-	
-	// enable textures
-	glEnable(GL_TEXTURE_2D);
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
-	
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-
-	// Set our viewport to be the same size as the screen
-	glViewPort(0,0,255,191);
-	
-	LoadGLTextures();
-	
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
-	
-	//set up a directional light arguments are light number (0-3), light color, 
-	//and an x,y,z vector that points in the direction of the light, the direction must be normalized
-	glLight(0, RGB15(31,31,31) , 0, floattov10(-1.0), 0);
-	
-	//need to set up some material properties since DS does not have them set by default
-	glMaterialf(GL_AMBIENT, RGB15(8,8,8));
-	glMaterialf(GL_DIFFUSE, RGB15(8,8,8));
-	glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
-	glMaterialf(GL_EMISSION, RGB15(16,16,16));
-	
-	//ds uses a table for shinyness..this generates a half-ass one
-	glMaterialShinyness();
-	
-	// Set the current matrix to be the model matrix
-	glMatrixMode(GL_MODELVIEW);
-	
-	while true do 
-	begin
-		//these little button functions are pretty handy
-		scanKeys();
-
-	
-		if ((keysDown() and KEY_A)) <> 0 then
-			light := not light;
-
-		if (keysHeld() and KEY_R) <> 0 then
-			z := z -0.02;
-		if (keysHeld() and KEY_L) <> 0 then
-			z := z+0.02;
-		if (keysHeld() and KEY_LEFT) <> 0 then
-			xspeed := xspeed-0.01;
-		if (keysHeld() and KEY_RIGHT) <> 0 then
-			xspeed := xspeed+0.01;
-		if (keysHeld() and KEY_UP) <> 0 then
-			yspeed := yspeed+0.01;
-		if (keysHeld() and KEY_DOWN) <> 0 then
-			yspeed := yspeed-0.01;
-		
-		
-		glColor3f(1,1,1);
-		
-		if (not light) then
-			//ds specific, several attributes can be set here including turning on our light	
-			glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK)
-		else
-			//ds specific, several attributes can be set here including turning on our light	
-			glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK  or POLY_FORMAT_LIGHT0);
-
-		DrawGLScene();
-
-		// flush to screen	
-		glFlush(0);
-		
-		// wait for the screen to refresh
-		swiWaitForVBlank();
-	end;
-		
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
+  vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
+
+  // initialize the geometry engine
+  glInit();
+  
+  // enable textures
+  glEnable(GL_TEXTURE_2D);
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+  
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+
+  // Set our viewport to be the same size as the screen
+  glViewPort(0,0,255,191);
+  
+  LoadGLTextures();
+  
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  
+  //set up a directional light arguments are light number (0-3), light color, 
+  //and an x,y,z vector that points in the direction of the light, the direction must be normalized
+  glLight(0, RGB15(31,31,31) , 0, floattov10(-1.0), 0);
+  
+  //need to set up some material properties since DS does not have them set by default
+  glMaterialf(GL_AMBIENT, RGB15(8,8,8));
+  glMaterialf(GL_DIFFUSE, RGB15(8,8,8));
+  glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
+  glMaterialf(GL_EMISSION, RGB15(16,16,16));
+  
+  //ds uses a table for shinyness..this generates a half-ass one
+  glMaterialShinyness();
+  
+  // Set the current matrix to be the model matrix
+  glMatrixMode(GL_MODELVIEW);
+  
+  while true do 
+  begin
+    //these little button functions are pretty handy
+    scanKeys();
+    pressed := keysDown();
+  
+    if ((pressed and KEY_A)) <> 0 then light := not light;
+
+    held := keysHeld();  
+
+    if (held and KEY_R)     <> 0 then z := z - 0.02;
+    if (held and KEY_L)     <> 0 then z := z + 0.02;
+    if (held and KEY_LEFT)  <> 0 then xspeed := xspeed - 0.01;
+    if (held and KEY_RIGHT) <> 0 then xspeed := xspeed + 0.01;
+    if (held and KEY_UP)    <> 0 then yspeed := yspeed + 0.01;
+    if (held and KEY_DOWN)  <> 0 then yspeed := yspeed - 0.01;
+    
+    
+    glColor3f(1,1,1);
+    
+    if (not light) then
+      //ds specific, several attributes can be set here including turning on our light  
+      glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK)
+    else
+      //ds specific, several attributes can be set here including turning on our light  
+      glPolyFmt(POLY_ALPHA(31) or POLY_CULL_BACK  or POLY_FORMAT_LIGHT0);
+
+    DrawGLScene();
+
+    // flush to screen  
+    glFlush(0);
+    
+    // wait for the screen to refresh
+    swiWaitForVBlank();
+    
+    if (pressed and KEY_START) <> 0 then break;
+  end;
+    
 end.

+ 162 - 162
packages/libndsfpc/examples/graphics/3D/nehe/lesson08/lesson08.pp

@@ -1,6 +1,6 @@
 (****************************************
- * 		NDS NeHe Lesson 08    			*
- * 		Author: Ethos					*
+ *    NDS NeHe Lesson 08          *
+ *    Author: Ethos         *
  ****************************************)
 
 program Lesson08;
@@ -14,183 +14,183 @@ uses
 {$include inc/drunkenlogo.pcx.inc}
 
 var
-  light: boolean;				// Lighting ON/OFF ( NEW )
-  lp: boolean;					// L Pressed? ( NEW )
+  light: boolean;       // Lighting ON/OFF ( NEW )
+  lp: boolean;          // L Pressed? ( NEW )
 
-  xrot: cfloat;				// X Rotation
-  yrot: cfloat;				// Y Rotation
-  xspeed: cfloat;				// X Rotation Speed
-  yspeed: cfloat;				// Y Rotation Speed
-  z: cfloat = -5.0;			// Depth Into The Screen
+  xrot: cfloat;       // X Rotation
+  yrot: cfloat;       // Y Rotation
+  xspeed: cfloat;       // X Rotation Speed
+  yspeed: cfloat;       // Y Rotation Speed
+  z: cfloat = -5.0;     // Depth Into The Screen
 
-  texture: array [0..2] of integer;			// Storage For 3 Textures (only going to use 1 on the DS for this demo)
+  texture: array [0..2] of integer;     // Storage For 3 Textures (only going to use 1 on the DS for this demo)
 
 const
-  LightAmbient: array [0..3] of cfloat =		( 0.5, 0.5, 0.5, 1.0 );
-  LightDiffuse: array [0..3] of cfloat =		( 1.0, 1.0, 1.0, 1.0 );
-  LightPosition: array [0..3] of cfloat = 	( 0.0, 0.0, 2.0, 1.0 );
+  LightAmbient: array [0..3] of cfloat =    ( 0.5, 0.5, 0.5, 1.0 );
+  LightDiffuse: array [0..3] of cfloat =    ( 1.0, 1.0, 1.0, 1.0 );
+  LightPosition: array [0..3] of cfloat =   ( 0.0, 0.0, 2.0, 1.0 );
 
-function DrawGLScene(): boolean;											// Here's Where We Do All The Drawing
+function DrawGLScene(): boolean;                      // Here's Where We Do All The Drawing
 begin
-	glLoadIdentity();									// Reset The View
-	glTranslatef(0.0,0.0,z);
-
-	glRotatef(xrot,1.0,0.0,0.0);
-	glRotatef(yrot,0.0,1.0,0.0);
-	
-	glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE  or POLY_FORMAT_LIGHT0);
-
-	glBindTexture(GL_TEXTURE_2D, texture[0]);  //no filters to swtich between
-	
-	glBegin(GL_QUADS);
-		// Front Face
-		glNormal3f( 0.0, 0.0, 1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
-		// Back Face
-		glNormal3f( 0.0, 0.0,-1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
-		// Top Face
-		glNormal3f( 0.0, 1.0, 0.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,  1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-	// Bottom Face
-		glNormal3f( 0.0,-1.0, 0.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0, -1.0, -1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		// Right face
-		glNormal3f( 1.0, 0.0, 0.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
-	glEnd();
-
-	glPolyFmt(POLY_ALPHA(15) or POLY_CULL_BACK  or POLY_FORMAT_LIGHT0);
-	
-	glBegin(GL_QUADS);
-	
-	// Left Face
-		glNormal3f(-1.0, 0.0, 0.0);
-		glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
-		glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
-		glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
-		glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
-	glEnd();
-
-	xrot := xrot+xspeed;
-	yrot := yrot+yspeed;
-
-	result := true;			
+  glLoadIdentity();                 // Reset The View
+  glTranslatef(0.0,0.0,z);
+
+  glRotatef(xrot,1.0,0.0,0.0);
+  glRotatef(yrot,0.0,1.0,0.0);
+  
+  glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE  or POLY_FORMAT_LIGHT0);
+
+  glBindTexture(GL_TEXTURE_2D, texture[0]);  //no filters to swtich between
+  
+  glBegin(GL_QUADS);
+    // Front Face
+    glNormal3f( 0.0, 0.0, 1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
+    // Back Face
+    glNormal3f( 0.0, 0.0,-1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
+    // Top Face
+    glNormal3f( 0.0, 1.0, 0.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,  1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+  // Bottom Face
+    glNormal3f( 0.0,-1.0, 0.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0, -1.0, -1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    // Right face
+    glNormal3f( 1.0, 0.0, 0.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, -1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f( 1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0,  1.0);
+  glEnd();
+
+  glPolyFmt(POLY_ALPHA(15) or POLY_CULL_BACK  or POLY_FORMAT_LIGHT0);
+  
+  glBegin(GL_QUADS);
+  
+  // Left Face
+    glNormal3f(-1.0, 0.0, 0.0);
+    glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);
+    glTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0,  1.0);
+    glTexCoord2f(1.0, 1.0); glVertex3f(-1.0,  1.0,  1.0);
+    glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, -1.0);
+  glEnd();
+
+  xrot := xrot+xspeed;
+  yrot := yrot+yspeed;
+
+  result := true;     
 end;
 
 
-function LoadGLTextures(): boolean;									// Load PCX files And Convert To Textures
+function LoadGLTextures(): boolean;                 // Load PCX files And Convert To Textures
 var
-	pcx: sImage;                //////////////(NEW) and different from nehe.
+  pcx: sImage;                //////////////(NEW) and different from nehe.
 begin
-	//load our texture
-	loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
-	
-	image8to16(@pcx);
+  //load our texture
+  loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
+  
+  image8to16(@pcx);
 
-	glGenTextures(1, @texture[0]);
-	glBindTexture(0, texture[0]);
-	glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
+  glGenTextures(1, @texture[0]);
+  glBindTexture(0, texture[0]);
+  glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
 
-	imageDestroy(@pcx);
+  imageDestroy(@pcx);
 
-	result := true;
+  result := true;
 end;
 
+var
+  pressed: integer;
+  held: integer;
 
 begin
-	
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
-	vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
-
-	// initialize the geometry engine
-	glInit();
-	
-	// enable textures
-	glEnable(GL_TEXTURE_2D);
-	
-	glEnable(GL_BLEND);
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
-	
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-	
-	// Set our viewport to be the same size as the screen
-	glViewPort(0,0,255,191);
-	
-	LoadGLTextures();
-	
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
-	
-	//set up a directional ligth arguments are light number (0-3), light color, 
-	//and an x,y,z vector that points in the direction of the light
-	glLight(0, RGB15(31,31,31) , 0, floattov10(-1.0), 0);
-	
-	
-	glColor3f(1,1,1);
-	
-	glMatrixMode(GL_MODELVIEW);
-	
-	//need to set up some material properties since DS does not have them set by default
-	
-	glMaterialf(GL_AMBIENT, RGB15(16,16,16));
-	glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
-	glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
-	glMaterialf(GL_EMISSION, RGB15(16,16,16));
-	
-	//ds uses a table for shinyness..this generates a half-ass one
-	glMaterialShinyness();
-	
-	// Set the current matrix to be the model matrix
-	glMatrixMode(GL_MODELVIEW);
+  
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
+  vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
+
+  // initialize the geometry engine
+  glInit();
+  
+  // enable textures
+  glEnable(GL_TEXTURE_2D);
+  
+  glEnable(GL_BLEND);
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+  
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+  
+  // Set our viewport to be the same size as the screen
+  glViewPort(0,0,255,191);
+  
+  LoadGLTextures();
+  
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  
+  //set up a directional ligth arguments are light number (0-3), light color, 
+  //and an x,y,z vector that points in the direction of the light
+  glLight(0, RGB15(31,31,31) , 0, floattov10(-1.0), 0);
+  
+  
+  glColor3f(1,1,1);
+  
+  glMatrixMode(GL_MODELVIEW);
+  
+  //need to set up some material properties since DS does not have them set by default
+  
+  glMaterialf(GL_AMBIENT, RGB15(16,16,16));
+  glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
+  glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
+  glMaterialf(GL_EMISSION, RGB15(16,16,16));
+  
+  //ds uses a table for shinyness..this generates a half-ass one
+  glMaterialShinyness();
+  
+  // Set the current matrix to be the model matrix
+  glMatrixMode(GL_MODELVIEW);
   while true do
-	begin
-		//these little button functions are pretty handy
-		scanKeys();
-				
-		if (keysHeld() and KEY_R) <> 0 then
-			z := z -0.02;
-		if (keysHeld() and KEY_L) <> 0 then
-			z := z+0.02;
-		if (keysHeld() and KEY_LEFT) <> 0 then
-			xspeed := xspeed-0.01;
-		if (keysHeld() and KEY_RIGHT) <> 0 then
-			xspeed := xspeed+0.01;
-		if (keysHeld() and KEY_UP) <> 0 then
-			yspeed := yspeed+0.01;
-		if (keysHeld() and KEY_DOWN) <> 0 then
-			yspeed := yspeed-0.01;
-
-		DrawGLScene();
-
-		// flush to screen	
-		glFlush(0);
-		
-		// wait for the screen to refresh
-		swiWaitForVBlank();
-	
-	end;
-	
+  begin
+    //these little button functions are pretty handy
+    scanKeys();
+    held := keysHeld();
+    pressed := keysDown();
+        
+    if (held and KEY_R)     <> 0 then z := z - 0.02;
+    if (held and KEY_L)     <> 0 then z := z + 0.02;
+    if (held and KEY_LEFT)  <> 0 then xspeed := xspeed - 0.01;
+    if (held and KEY_RIGHT) <> 0 then xspeed := xspeed + 0.01;
+    if (held and KEY_UP)    <> 0 then yspeed := yspeed + 0.01;
+    if (held and KEY_DOWN)  <> 0 then yspeed := yspeed - 0.01;
+
+    DrawGLScene();
+
+    // flush to screen  
+    glFlush(0);
+    
+    // wait for the screen to refresh
+    swiWaitForVBlank();
+  
+    if (pressed and KEY_START) then break;
+  end;
+  
 end.

+ 134 - 130
packages/libndsfpc/examples/graphics/3D/nehe/lesson09/lesson09.pp

@@ -1,8 +1,8 @@
 (****************************************
- * 		NDS NeHe Lesson 09    			*
- * 		Author: dovoto
- *		DS does not appear to support 
-		the features needed for this demo
+ *    NDS NeHe Lesson 09          *
+ *    Author: dovoto
+ *    DS does not appear to support 
+    the features needed for this demo
  ****************************************)
 
 program Lesson09;
@@ -25,154 +25,158 @@ type
 
 
 var
-  twinkle: boolean;		// Twinkling Stars
-  tp: boolean;				// 'T' Key Pressed?
+  twinkle: boolean;   // Twinkling Stars
+  tp: boolean;        // 'T' Key Pressed?
 
-const	
-  num = 50;		// Number Of Stars To Draw
+const 
+  num = 50;   // Number Of Stars To Draw
 
 
 var
-  star: array [0..num-1] of TStars;		// Need To Keep Track Of 'num' Stars
-  zoom: cfloat = -15.0;	// Distance Away From Stars
-  tilt: cfloat = 90.0;		// Tilt The View
-  spin: cfloat;			// Spin Stars
+  star: array [0..num-1] of TStars;   // Need To Keep Track Of 'num' Stars
+  zoom: cfloat = -15.0; // Distance Away From Stars
+  tilt: cfloat = 90.0;    // Tilt The View
+  spin: cfloat;     // Spin Stars
 
-  loop: integer;			// General Loop Variable
-  texture: array [0..0] of integer;			// Storage For One textures
+  loop: integer;      // General Loop Variable
+  texture: array [0..0] of integer;     // Storage For One textures
 
 
 
 // Load PCX files And Convert To Textures
-function LoadGLTextures(): boolean;									// Load PCX files And Convert To Textures
+function LoadGLTextures(): boolean;                 // Load PCX files And Convert To Textures
 var
-	pcx: sImage;                //////////////(NEW) and different from nehe.
+  pcx: sImage;                //////////////(NEW) and different from nehe.
 begin
-	//load our texture
-	loadPCX(pcuint8(Star_pcx), @pcx);
-	
-	image8to16(@pcx);
+  //load our texture
+  loadPCX(pcuint8(Star_pcx), @pcx);
+  
+  image8to16(@pcx);
 
-	glGenTextures(1, @texture[0]);
-	glBindTexture(0, texture[0]);
-	glTexImage2D(0, 0, GL_RGBA, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
+  glGenTextures(1, @texture[0]);
+  glBindTexture(0, texture[0]);
+  glTexImage2D(0, 0, GL_RGBA, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
 
-	imageDestroy(@pcx);
+  imageDestroy(@pcx);
 
-	result := true;
+  result := true;
 end;
 
-function DrawGLScene(): boolean;											// Here's Where We Do All The Drawing
+function DrawGLScene(): boolean;                      // Here's Where We Do All The Drawing
 var
   loop: integer;
 begin
-	glBindTexture(GL_TEXTURE_2D, texture[0]);			// Select Our Texture
-
-	for loop := 0 to num - 1 do						// Loop Through All The Stars
-	begin
-		glLoadIdentity();								// Reset The View Before We Draw Each Star
-		glTranslatef(0.0, 0.0, zoom);					// Zoom Into The Screen (Using The Value In 'zoom')
-		glRotatef(tilt, 1.0, 0.0, 0.0);					// Tilt The View (Using The Value In 'tilt')
-		glRotatef(star[loop].angle, 0.0, 1.0, 0.0);		// Rotate To The Current Stars Angle
-		glTranslatef(star[loop].dist, 0.0, 0.0);		// Move Forward On The X Plane
-		glRotatef(-star[loop].angle, 0.0, 1.0, 0.0);	// Cancel The Current Stars Angle
-		glRotatef(-tilt, 1.0, 0.0, 0.0);				// Cancel The Screen Tilt
-		
-		if (twinkle) then
-		begin
-			glColor3b(star[(num-loop)-1].r,star[(num-loop)-1].g,star[(num-loop)-1].b);  ///different
-			glBegin(GL_QUADS);
-				glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,-1.0, 0.0);
-				glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,-1.0, 0.0);
-				glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, 0.0);
-				glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, 0.0);
-			glEnd();
-		end;
-
-		glRotatef(spin, 0.0, 0.0, 1.0);
-		glColor3b(star[loop].r,star[loop].g,star[loop].b);                            //different
-		glBegin(GL_QUADS);
-			glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,-1.0, 0.0);
-			glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,-1.0, 0.0);
-			glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, 0.0);
-			glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, 0.0);
-		glEnd();
-
-		spin := spin + 0.01;
-		star[loop].angle := star[loop].angle + cfloat(loop) / num;
-		star[loop].dist := star[loop].dist - 0.01;
-		if (star[loop].dist < 0.0) then
-		begin
-			star[loop].dist := star[loop].dist + 5.0;
-			star[loop].r := random(256);
-			star[loop].g := random(256);
-			star[loop].b := random(256);
-		end;
-	end;
-	result := true;															// Keep Going
+  glBindTexture(GL_TEXTURE_2D, texture[0]);     // Select Our Texture
+
+  for loop := 0 to num - 1 do           // Loop Through All The Stars
+  begin
+    glLoadIdentity();               // Reset The View Before We Draw Each Star
+    glTranslatef(0.0, 0.0, zoom);         // Zoom Into The Screen (Using The Value In 'zoom')
+    glRotatef(tilt, 1.0, 0.0, 0.0);         // Tilt The View (Using The Value In 'tilt')
+    glRotatef(star[loop].angle, 0.0, 1.0, 0.0);   // Rotate To The Current Stars Angle
+    glTranslatef(star[loop].dist, 0.0, 0.0);    // Move Forward On The X Plane
+    glRotatef(-star[loop].angle, 0.0, 1.0, 0.0);  // Cancel The Current Stars Angle
+    glRotatef(-tilt, 1.0, 0.0, 0.0);        // Cancel The Screen Tilt
+    
+    if (twinkle) then
+    begin
+      glColor3b(star[(num-loop)-1].r,star[(num-loop)-1].g,star[(num-loop)-1].b);  ///different
+      glBegin(GL_QUADS);
+        glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,-1.0, 0.0);
+        glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,-1.0, 0.0);
+        glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, 0.0);
+        glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, 0.0);
+      glEnd();
+    end;
+
+    glRotatef(spin, 0.0, 0.0, 1.0);
+    glColor3b(star[loop].r,star[loop].g,star[loop].b);                            //different
+    glBegin(GL_QUADS);
+      glTexCoord2f(0.0, 0.0); glVertex3f(-1.0,-1.0, 0.0);
+      glTexCoord2f(1.0, 0.0); glVertex3f( 1.0,-1.0, 0.0);
+      glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, 0.0);
+      glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, 0.0);
+    glEnd();
+
+    spin := spin + 0.01;
+    star[loop].angle := star[loop].angle + cfloat(loop) / num;
+    star[loop].dist := star[loop].dist - 0.01;
+    if (star[loop].dist < 0.0) then
+    begin
+      star[loop].dist := star[loop].dist + 5.0;
+      star[loop].r := random(256);
+      star[loop].g := random(256);
+      star[loop].b := random(256);
+    end;
+  end;
+  result := true;                             // Keep Going
 
 end;
 
-
+var
+  pressed: integer;
 begin
   Randomize;
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
-	vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
-
-	// initialize the geometry engine
-	glInit();
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
-	
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-	
-	// enable textures
-	glEnable(GL_TEXTURE_2D);
-	
-	// enable alpha blending
-	glEnable(GL_BLEND);
-
-	// Set our viewport to be the same size as the screen
-	glViewport(0,0,255,191);
-	
-	LoadGLTextures();
-	
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
-	glColor3f(1,1,1);
-	
-	//set up a directional ligth arguments are light number (0-3), light color, 
-	//and an x,y,z vector that points in the direction of the light
-	glLight(0, RGB15(31,31,31), 0, 0, floattov10(-1.0));
-	
-	//need to set up some material properties since DS does not have them set by default
-	glMaterialf(GL_AMBIENT, RGB15(16,16,16));
-	glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
-	glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
-	glMaterialf(GL_EMISSION, RGB15(16,16,16));
-	
-	//ds uses a table for shinyness..this generates a half-ass one
-	glMaterialShinyness();
-	
-	glPolyFmt(POLY_ALPHA(15) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0);
-
-	glMatrixMode(GL_MODELVIEW);
-	
-	while true do
-	begin
-		DrawGLScene();
-		
-		// flush to screen	
-		glFlush(0);
-		
-		// wait for the screen to refresh
-		swiWaitForVBlank();
-	end;
-	
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
+  vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
+
+  // initialize the geometry engine
+  glInit();
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+  
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+  
+  // enable textures
+  glEnable(GL_TEXTURE_2D);
+  
+  // enable alpha blending
+  glEnable(GL_BLEND);
+
+  // Set our viewport to be the same size as the screen
+  glViewport(0,0,255,191);
+  
+  LoadGLTextures();
+  
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  glColor3f(1,1,1);
+  
+  //set up a directional ligth arguments are light number (0-3), light color, 
+  //and an x,y,z vector that points in the direction of the light
+  glLight(0, RGB15(31,31,31), 0, 0, floattov10(-1.0));
+  
+  //need to set up some material properties since DS does not have them set by default
+  glMaterialf(GL_AMBIENT, RGB15(16,16,16));
+  glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
+  glMaterialf(GL_SPECULAR, BIT(15) or RGB15(8,8,8));
+  glMaterialf(GL_EMISSION, RGB15(16,16,16));
+  
+  //ds uses a table for shinyness..this generates a half-ass one
+  glMaterialShinyness();
+  
+  glPolyFmt(POLY_ALPHA(15) or POLY_CULL_BACK or POLY_FORMAT_LIGHT0);
+
+  glMatrixMode(GL_MODELVIEW);
+  
+  while true do
+  begin
+    DrawGLScene();
+    
+    // flush to screen  
+    glFlush(0);
+    
+    // wait for the screen to refresh
+    swiWaitForVBlank();
+    scanKeys();
+    pressed := keysDown();
+    if (pressed and KEY_START) <> 0 then break;
+  end;
+  
 end.

+ 11 - 7
packages/libndsfpc/examples/graphics/3D/nehe/lesson10/lesson10.pp

@@ -226,7 +226,7 @@ end;
 procedure EmitCube();
 begin
   glPushMatrix();
-  glScalef(0.03, 0.03, 0.03);	
+  glScalef(0.03, 0.03, 0.03); 
   
   glRotatef(cubeRot.x, 1.0, 0.0, 0.0);
   glRotatef(cubeRot.y, 0.0, 1.0, 0.0);
@@ -313,6 +313,7 @@ var
   lastXY: touchPosition;
   dx, dy: cint16;
   i: integer;
+  held: integer;
 begin
   MyFile := pchar(@World_txt);
   // Setup the Main screen for 3D
@@ -383,24 +384,25 @@ begin
   begin
     //these little button functions are pretty handy
     scanKeys();
+    held := keysHeld();
 
-    if (keysHeld() and KEY_A) <> 0 then lookupdown := lookupdown - 1.0;
+    if (held and KEY_A) <> 0 then lookupdown := lookupdown - 1.0;
 
-    if (keysHeld() and KEY_B) <> 0 then lookupdown := lookupdown + 1.0;
+    if (held and KEY_B) <> 0 then lookupdown := lookupdown + 1.0;
 
-    if (keysHeld() and KEY_LEFT) <> 0 then
+    if (held and KEY_LEFT) <> 0 then
     begin
       heading := heading + 1.0;
       yrot := heading;
     end;
 
-    if (keysHeld() and KEY_RIGHT) <> 0 then
+    if (held and KEY_RIGHT) <> 0 then
     begin
       heading := heading - 1.0;
       yrot := heading;
     end;
 
-    if (keysHeld() and KEY_DOWN) <> 0 then
+    if (held and KEY_DOWN) <> 0 then
     begin
       xpos := xpos + (tsin(heading)) * 0.05;
       zpos := zpos + (tcos(heading)) * 0.05;
@@ -412,7 +414,7 @@ begin
       walkbias := tsin(walkbiasangle) / 20.0;
     end;
 
-    if (keysHeld() and KEY_UP) <> 0 then
+    if (held and KEY_UP) <> 0 then
     begin
       xpos := xpos - (tsin(heading)) * 0.05;
       zpos := zpos - (tcos(heading)) * 0.05;
@@ -434,6 +436,8 @@ begin
 
     // wait for the screen to refresh
     swiWaitForVBlank();
+    
+    if (held and KEY_START) <> 0 then break;
   end;
 
 end.

+ 2 - 0
packages/libndsfpc/examples/graphics/3D/nehe/lesson10b/lesson10b.pp

@@ -285,6 +285,8 @@ begin
 
     // wait for the screen to refresh
     swiWaitForVBlank();
+    
+    if (held and KEY_START) <> 0 then break;
   end;
 
 end.

+ 145 - 139
packages/libndsfpc/examples/graphics/3D/nehe/lesson11/lesson11.pp

@@ -10,14 +10,14 @@ uses
 
 var
   points: array [0..63, 0..31, 0..2] of v16;    // The Array For The Points On The Grid Of Our "Wave"
-  wiggle_count: integer = 0;		// Counter Used To Control How Fast Flag Waves
+  wiggle_count: integer = 0;    // Counter Used To Control How Fast Flag Waves
 
-  xrot: cfloat;				// X Rotation ( NEW )
-  yrot: cfloat;				// Y Rotation ( NEW )
-  zrot: cfloat;				// Z Rotation ( NEW )
-  hold: v16;				  // Temporarily Holds A Floating Point Value
+  xrot: cfloat;       // X Rotation ( NEW )
+  yrot: cfloat;       // Y Rotation ( NEW )
+  zrot: cfloat;       // Z Rotation ( NEW )
+  hold: v16;          // Temporarily Holds A Floating Point Value
 
-  texture: array [0..0] of integer;			// Storage For 3 Textures (only going to use 1 on the DS for this demo)
+  texture: array [0..0] of integer;     // Storage For 3 Textures (only going to use 1 on the DS for this demo)
 
 function sin(angle: cfloat): cfloat;
 var
@@ -35,160 +35,166 @@ begin
   result := f32tofloat(c);
 end;
 
-function DrawGLScene(): boolean;											// Here's Where We Do All The Drawing
+function DrawGLScene(): boolean;                      // Here's Where We Do All The Drawing
 var
   x, y: integer;
   float_x, float_y, float_xb, float_yb: t16;
 begin
 
-	glColor3b(255,255,255);    // set the vertex color
-	
-	glLoadIdentity();									// Reset The View
-
-	glTranslatef(0.0,0.0,-12.0);
-	  
-	glRotatef(xrot,1.0,0.0,0.0);
-	glRotatef(yrot,0.0,1.0,0.0);  
-	glRotatef(zrot,0.0,0.0,1.0);
-
-	glBindTexture(GL_TEXTURE_2D, texture[0]);
-
-	glBegin(GL_QUADS);
-	for x := 0 to 30 do
-	begin
-		for  y := 0 to 30 do
-		begin
-			float_x := inttot16(x) shl 2;
-			float_y := inttot16(y) shl 2;
-			float_xb := inttot16(x+1) shl 2;
-			float_yb := inttot16(y+1) shl 2;
-
-			glTexCoord2t16( float_x, float_y);
-			glVertex3v16( points[x][y][0], points[x][y][1], points[x][y][2] );
-
-			glTexCoord2t16( float_x, float_yb );
-			glVertex3v16( points[x][y+1][0], points[x][y+1][1], points[x][y+1][2] );
-
-			glTexCoord2t16( float_xb, float_yb );
-			glVertex3v16( points[x+1][y+1][0], points[x+1][y+1][1], points[x+1][y+1][2] );
-
-			glTexCoord2t16( float_xb, float_y );
-			glVertex3v16( points[x+1][y][0], points[x+1][y][1], points[x+1][y][2] );
-		end;
-	end;
-	glEnd();
-
-	if ( wiggle_count = 2 ) then
-	begin
-		for y := 0 to 31 do
-		begin
-			hold := points[0][y][2];
-			for x := 0 to 31 do
-			begin
-				points[x][y][2] := points[x+1][y][2];
-			end;
-			points[31][y][2]:=hold;
-		end;
-		wiggle_count := 0;
-	end;
-
-	inc(wiggle_count);
-
-	xrot:=xrot+0.3;
-	yrot:=yrot+0.2;
-	zrot:=zrot+0.4;
-
-	result := true;											// Everything Went OK
+  glColor3b(255,255,255);    // set the vertex color
+  
+  glLoadIdentity();                 // Reset The View
+
+  glTranslatef(0.0,0.0,-12.0);
+    
+  glRotatef(xrot,1.0,0.0,0.0);
+  glRotatef(yrot,0.0,1.0,0.0);  
+  glRotatef(zrot,0.0,0.0,1.0);
+
+  glBindTexture(GL_TEXTURE_2D, texture[0]);
+
+  glBegin(GL_QUADS);
+  for x := 0 to 30 do
+  begin
+    for  y := 0 to 30 do
+    begin
+      float_x := inttot16(x) shl 2;
+      float_y := inttot16(y) shl 2;
+      float_xb := inttot16(x+1) shl 2;
+      float_yb := inttot16(y+1) shl 2;
+
+      glTexCoord2t16( float_x, float_y);
+      glVertex3v16( points[x][y][0], points[x][y][1], points[x][y][2] );
+
+      glTexCoord2t16( float_x, float_yb );
+      glVertex3v16( points[x][y+1][0], points[x][y+1][1], points[x][y+1][2] );
+
+      glTexCoord2t16( float_xb, float_yb );
+      glVertex3v16( points[x+1][y+1][0], points[x+1][y+1][1], points[x+1][y+1][2] );
+
+      glTexCoord2t16( float_xb, float_y );
+      glVertex3v16( points[x+1][y][0], points[x+1][y][1], points[x+1][y][2] );
+    end;
+  end;
+  glEnd();
+
+  if ( wiggle_count = 2 ) then
+  begin
+    for y := 0 to 31 do
+    begin
+      hold := points[0][y][2];
+      for x := 0 to 31 do
+      begin
+        points[x][y][2] := points[x+1][y][2];
+      end;
+      points[31][y][2]:=hold;
+    end;
+    wiggle_count := 0;
+  end;
+
+  inc(wiggle_count);
+
+  xrot:=xrot+0.3;
+  yrot:=yrot+0.2;
+  zrot:=zrot+0.4;
+
+  result := true;                     // Everything Went OK
 
 end;
 
 
  
-function LoadGLTextures(): boolean;									// Load PCX files And Convert To Textures
+function LoadGLTextures(): boolean;                 // Load PCX files And Convert To Textures
 var
-	pcx: sImage;                //////////////(NEW) and different from nehe.
+  pcx: sImage;                //////////////(NEW) and different from nehe.
 begin
-	//load our texture
-	loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
+  //load our texture
+  loadPCX(pcuint8(drunkenlogo_pcx), @pcx);
 
-	image8to16(@pcx);
+  image8to16(@pcx);
 
-	glGenTextures(1, @texture[0]);
-	glBindTexture(0, texture[0]);
-	glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
+  glGenTextures(1, @texture[0]);
+  glBindTexture(0, texture[0]);
+  glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, pcx.image.data8);
 
-	result := true;
+  result := true;
 end;
 
 procedure InitGL();
 var
   x, y:integer;
 begin
-	// Setup the Main screen for 3D 
-	videoSetMode(MODE_0_3D);
-	vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
-	
-	// initialize the geometry engine
-	glInit();
-	
-	// enable textures
-	glEnable(GL_TEXTURE_2D);
-	
-	// Set our viewport to be the same size as the screen
-	glViewPort(0,0,255,191);
-	
-	// enable antialiasing
-	glEnable(GL_ANTIALIAS);
-	
-	// setup the rear plane
-	glClearColor(0,0,0,31); // BG must be opaque for AA to work
-	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
-	glClearDepth($7FFF);
-	
-	LoadGLTextures();
-	
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
-	
-	//need to set up some material properties since DS does not have them set by default
-	glMaterialf(GL_AMBIENT, RGB15(31,31,31));
-	glMaterialf(GL_DIFFUSE, RGB15(31,31,31));
-	glMaterialf(GL_SPECULAR, BIT(15) or RGB15(16,16,16));
-	glMaterialf(GL_EMISSION, RGB15(31,31,31));
-	
-	//ds uses a table for shinyness..this generates a half-ass one
-	glMaterialShinyness();
-	
-	//ds specific, several attributes can be set here	
-	glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE );
-	
-
-	for x:=0 to 31 do
-	begin
-		for y:=0 to 31 do
-		begin
-			points[x][y][0] := (inttov16(x) div 4);
-			points[x][y][1] := (inttov16(y) div 4);
-			points[x][y][2] := sinLerp(x * (DEGREES_IN_CIRCLE div 32));
-		end;
-	end;
+  // Setup the Main screen for 3D 
+  videoSetMode(MODE_0_3D);
+  vramSetBankA(VRAM_A_TEXTURE);                        //NEW  must set up some memory for textures
+  
+  // initialize the geometry engine
+  glInit();
+  
+  // enable textures
+  glEnable(GL_TEXTURE_2D);
+  
+  // Set our viewport to be the same size as the screen
+  glViewPort(0,0,255,191);
+  
+  // enable antialiasing
+  glEnable(GL_ANTIALIAS);
+  
+  // setup the rear plane
+  glClearColor(0,0,0,31); // BG must be opaque for AA to work
+  glClearPolyID(63); // BG must have a unique polygon ID for AA to work
+  glClearDepth($7FFF);
+  
+  LoadGLTextures();
+  
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  gluPerspective(70, 256.0 / 192.0, 0.1, 100);
+  
+  //need to set up some material properties since DS does not have them set by default
+  glMaterialf(GL_AMBIENT, RGB15(31,31,31));
+  glMaterialf(GL_DIFFUSE, RGB15(31,31,31));
+  glMaterialf(GL_SPECULAR, BIT(15) or RGB15(16,16,16));
+  glMaterialf(GL_EMISSION, RGB15(31,31,31));
+  
+  //ds uses a table for shinyness..this generates a half-ass one
+  glMaterialShinyness();
+  
+  //ds specific, several attributes can be set here 
+  glPolyFmt(POLY_ALPHA(31) or POLY_CULL_NONE );
+  
+
+  for x:=0 to 31 do
+  begin
+    for y:=0 to 31 do
+    begin
+      points[x][y][0] := (inttov16(x) div 4);
+      points[x][y][1] := (inttov16(y) div 4);
+      points[x][y][2] := sinLerp(x * (DEGREES_IN_CIRCLE div 32));
+    end;
+  end;
 end;
 
-
-begin	
-	InitGL();
-	
-	glMatrixMode(GL_MODELVIEW);
-
-	while true do
-	begin	
-		DrawGLScene();
-		
-		// flush to screen	
-		glFlush(0);
-		
-		// wait for the screen to refresh
-		swiWaitForVBlank();
-	end;
+var
+  pressed: integer;
+
+begin 
+  InitGL();
+  
+  glMatrixMode(GL_MODELVIEW);
+
+  while true do
+  begin 
+    DrawGLScene();
+    
+    // flush to screen  
+    glFlush(0);
+    
+    // wait for the screen to refresh
+    swiWaitForVBlank();
+
+    scanKeys();
+    pressed := keysDown();
+    if (pressed and KEY_START) <> 0 then break;
+  end;
 end.

+ 55 - 53
packages/libndsfpc/examples/graphics/Backgrounds/all_in_one/BackgroundAllInOne.pp

@@ -76,7 +76,8 @@ var
     (name: 'Basic';     demos: @basicExamples;      count: sizeof(basicExamples) div sizeof(Demo);),
     (name: 'Bitmap';    demos: @bitmapExamples;     count: sizeof(bitmapExamples) div sizeof(Demo);),
     (name: 'Scrolling'; demos: @scrollingExamples;  count: sizeof(scrollingExamples) div sizeof(Demo);),
-    (name: 'Advanced';  demos: @advancedExamples;   count: sizeof(advancedExamples) div sizeof(Demo);)
+    (name: 'Advanced';  demos: @advancedExamples;   count: sizeof(advancedExamples) div sizeof(Demo);),
+    (name: 'Exit';      demos: nil;                 count: 0;)
   );
 
 
@@ -85,82 +86,83 @@ var
   selectedCategory: integer = 0;
   selectedDemo: integer = 0;
   selected: boolean = false;
-	catCount: integer;
+  catCount: integer;
   demoCount: integer = 0;
   ci: integer;
   di: integer;
 
 begin
 
-	while true do
-	begin
-		catCount := sizeof(categories) div sizeof(Category);
-		demoCount := 0;
+  while true do
+  begin
+    catCount := sizeof(categories) div sizeof(Category);
+    demoCount := 0;
 
-		videoSetModeSub(MODE_0_2D);
-		consoleDemoInit();
+    videoSetModeSub(MODE_0_2D);
+    consoleDemoInit();
 
-		while not selected do
-		begin
-			scanKeys();
+    while not selected do
+    begin
+      scanKeys();
 
-			keys := keysDown();
+      keys := keysDown();
 
-			if (keys and KEY_UP) <> 0 then dec(selectedCategory);
-			if (keys and KEY_DOWN) <> 0 then inc(selectedCategory);
-			if (keys and KEY_A) <> 0 then selected := true;
+      if (keys and KEY_UP) <> 0 then dec(selectedCategory);
+      if (keys and KEY_DOWN) <> 0 then inc(selectedCategory);
+      if (keys and KEY_A) <> 0 then selected := true;
 
-			if (selectedCategory < 0) then selectedCategory := catCount - 1;
-			if (selectedCategory >= catCount) then selectedCategory := 0;
+      if (selectedCategory < 0) then selectedCategory := catCount - 1;
+      if (selectedCategory >= catCount) then selectedCategory := 0;
 
-			swiWaitForVBlank();
-			consoleClear();
-			for ci := 0 to catCount - 1 do
-			begin
+      swiWaitForVBlank();
+      consoleClear();
+      for ci := 0 to catCount - 1 do
+      begin
         if ci = selectedCategory then
-				  iprintf('%c%d: %s'#10, '*', ci + 1, categories[ci].name)
+          iprintf('%c%d: %s'#10, '*', ci + 1, categories[ci].name)
         else
-				  iprintf('%c%d: %s'#10, ' ', ci + 1, categories[ci].name);
-			end;
-		end;
+          iprintf('%c%d: %s'#10, ' ', ci + 1, categories[ci].name);
+      end;
+    end;
 
-		selected := false;
+    selected := false;
 
-		demoCount := categories[selectedCategory].count;
+    demoCount := categories[selectedCategory].count;
+    if demoCount = o then exit;
+    
+    while not (selected) do
+    begin
+      scanKeys();
 
-		while not (selected) do
-		begin
-			scanKeys();
+      keys := keysDown();
 
-			keys := keysDown();
+      if (keys and KEY_UP) <> 0 then dec(selectedDemo);
+      if (keys and KEY_DOWN) <> 0 then inc(selectedDemo);
+      if (keys and KEY_A) <> 0 then selected := true;
+      if (keys and KEY_B) <> 0 then break;
 
-			if (keys and KEY_UP) <> 0 then dec(selectedDemo);
-			if (keys and KEY_DOWN) <> 0 then inc(selectedDemo);
-			if (keys and KEY_A) <> 0 then selected := true;
-			if (keys and KEY_B) <> 0 then break;
+      if (selectedDemo < 0) then selectedDemo := demoCount - 1;
+      if (selectedDemo >= demoCount) then selectedDemo := 0;
 
-			if (selectedDemo < 0) then selectedDemo := demoCount - 1;
-			if (selectedDemo >= demoCount) then selectedDemo := 0;
+      swiWaitForVBlank();
+      consoleClear();
 
-			swiWaitForVBlank();
-			consoleClear();
-
-			for di := 0 to demoCount - 1 do
-			begin
+      for di := 0 to demoCount - 1 do
+      begin
         if di = selectedDemo then
-				  iprintf('%c%d: %s'#10, '*', di + 1, categories[selectedCategory].demos[di].name)
+          iprintf('%c%d: %s'#10, '*', di + 1, categories[selectedCategory].demos[di].name)
         else
           iprintf('%c%d: %s'#10, ' ', di + 1, categories[selectedCategory].demos[di].name);
-			end;
-		end;
-
-		if (selected) then
-		begin
-			consoleClear();
-			iprintf('Use arrow keys to scroll'#10'Press ''B'' to exit');
-			categories[selectedCategory].demos[selectedDemo].go();
-		end;
-	end;
+      end;
+    end;
+
+    if (selected) then
+    begin
+      consoleClear();
+      iprintf('Use arrow keys to scroll'#10'Press ''B'' to exit');
+      categories[selectedCategory].demos[selectedDemo].go();
+    end;
+  end;
 
 end.
 

+ 1 - 1
packages/libndsfpc/examples/graphics/Makefile.fpc

@@ -3,7 +3,7 @@
 #
 
 [target]
-dirs=3D Backgrounds Effects Ext_Palettes Printing Sprites
+dirs=3D Backgrounds Effects Ext_Palettes grit Printing Sprites
 
 [require]
 packages=libndsfpc

+ 8 - 2
packages/libndsfpc/examples/graphics/Printing/ansi_console/AnsiConsole.pp

@@ -4,7 +4,9 @@ program AnsiConsole;
 
 uses
   ctypes, nds9;
-
+var
+  keys: integer;
+  
 begin
 
   consoleDemoInit();
@@ -34,6 +36,10 @@ begin
   iprintf(#27 + '[5C' + 'Column 20');
 
   while true do
+  begin
     swiWaitForVBlank();
-
+    scanKeys();
+		keys := keysDown();
+		if (keys and KEY_START) <> 0 then break;
+  end;
 end.

+ 1 - 1
packages/libndsfpc/examples/graphics/Printing/console_windows/ConsoleWindows.pp

@@ -47,7 +47,7 @@ begin
 	begin
 		scanKeys();
 		keys := keysHeld();
-
+    if (keys and KEY_START) <> 0 then break;
 		if (keys and KEY_TOUCH) <> 0 then
 		begin
 			touchRead(touch);

+ 29 - 24
packages/libndsfpc/examples/graphics/Printing/custom_font/CustomFont.pp

@@ -17,30 +17,35 @@ var
   fontPal: array [0..255] of cushort; cvar; external;
 
   console: pPrintConsole;
-	font: ConsoleFont;
-
+  font: ConsoleFont;
+  keys: integer;
 
 begin
-	videoSetModeSub(MODE_0_2D);
-	vramSetBankC(VRAM_C_SUB_BG);
-
-	console := consoleInit(nil, 0, BgType_Text4bpp, BgSize_T_256x256, map_base, tile_base, false, false);
-
-	font.gfx := pcuint16(fontTiles);
-	font.pal := pcuint16(fontPal);
-	font.numChars := 95;
-	font.numColors :=  fontPalLen div 2;
-	font.bpp := 4;
-	font.asciiOffset := 32;
-	font.convertSingleColor := false;
-
-	consoleSetFont(console, @font);
-
-	printf('Custom Font Demo'#10);
-	printf('   by Poffy'#10);
-	printf('modified by WinterMute'#10);
-	printf('for libnds examples'#10);
-
-	while true do
-		swiWaitForVBlank();
+  videoSetModeSub(MODE_0_2D);
+  vramSetBankC(VRAM_C_SUB_BG);
+
+  console := consoleInit(nil, 0, BgType_Text4bpp, BgSize_T_256x256, map_base, tile_base, false, false);
+
+  font.gfx := pcuint16(fontTiles);
+  font.pal := pcuint16(fontPal);
+  font.numChars := 95;
+  font.numColors :=  fontPalLen div 2;
+  font.bpp := 4;
+  font.asciiOffset := 32;
+  font.convertSingleColor := false;
+
+  consoleSetFont(console, @font);
+
+  printf('Custom Font Demo'#10);
+  printf('   by Poffy'#10);
+  printf('modified by WinterMute'#10);
+  printf('for libnds examples'#10);
+
+  while true do
+  begin
+    swiWaitForVBlank();
+    scanKeys();
+		keys := keysDown();
+		if (keys and KEY_START) <> 0 then break;
+  end;
 end.

+ 25 - 21
packages/libndsfpc/examples/graphics/Printing/print_both_screens/printBothScreens.pp

@@ -6,35 +6,39 @@ uses
   ctypes, nds9;
 
 var
-	touch: touchPosition;
-	topScreen, bottomScreen: PrintConsole;
+  keys: integer;
+  touch: touchPosition;
+  topScreen, bottomScreen: PrintConsole;
 
 begin
-	videoSetMode(MODE_0_2D);
-	videoSetModeSub(MODE_0_2D);
+  videoSetMode(MODE_0_2D);
+  videoSetModeSub(MODE_0_2D);
 
-	vramSetBankA(VRAM_A_MAIN_BG);
-	vramSetBankC(VRAM_C_SUB_BG);
+  vramSetBankA(VRAM_A_MAIN_BG);
+  vramSetBankC(VRAM_C_SUB_BG);
 
-	consoleInit(@topScreen, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
-	consoleInit(@bottomScreen, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, false, true);
+  consoleInit(@topScreen, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
+  consoleInit(@bottomScreen, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, false, true);
 
-	consoleSelect(@topScreen);
-	
-	iprintf(#10#10#9'Hello DS dev''rs'#10);
-	iprintf(#9'www.drunkencoders.com'#10);
-	iprintf(#9'www.devkitpro.org');
+  consoleSelect(@topScreen);
+  
+  iprintf(#10#10#9'Hello DS dev''rs'#10);
+  iprintf(#9'www.drunkencoders.com'#10);
+  iprintf(#9'www.devkitpro.org');
 
   consoleSelect(@bottomScreen);
 
-	while true do
-	begin
-		touchRead(touch);
-		iprintf(#27'[10;0H' + 'Touch x = %04i, %04i'#10, touch.rawx, touch.px);
-		iprintf('Touch y = %04i, %04i'#10, touch.rawy, touch.py);
-
-		swiWaitForVBlank();
-	end;
+  while true do
+  begin
+    touchRead(touch);
+    iprintf(#27'[10;0H' + 'Touch x = %04i, %04i'#10, touch.rawx, touch.px);
+    iprintf('Touch y = %04i, %04i'#10, touch.rawy, touch.py);
+
+    swiWaitForVBlank();
+    scanKeys();
+    keys := keysDown();
+    if (keys and KEY_START) <> 0 then break;
+  end;
 
 end.
 

+ 43 - 42
packages/libndsfpc/examples/graphics/Printing/rotscale_text/RotscaleText.pp

@@ -10,7 +10,7 @@ const
   fontPalLen = 32;
   fontTilesLen = 3072;
   tile_base = 0;
-	map_base = 20;
+  map_base = 20;
 
 var
   fontTiles: array [0..767] of cushort; cvar; external;
@@ -22,66 +22,67 @@ var
   keys: cuint32;
 
   console: pPrintConsole;
-	font: ConsoleFont;
-	bg3: cint;
+  font: ConsoleFont;
+  bg3: cint;
 
 begin
-	videoSetMode(0);	
+  videoSetMode(0);  
 
-	videoSetModeSub(MODE_5_2D);	
-	vramSetBankC(VRAM_C_SUB_BG); 
+  videoSetModeSub(MODE_5_2D); 
+  vramSetBankC(VRAM_C_SUB_BG); 
 
-	console := consoleInit(nil, 3, BgType_ExRotation, BgSize_ER_256x256, map_base, tile_base, false, false);
+  console := consoleInit(nil, 3, BgType_ExRotation, BgSize_ER_256x256, map_base, tile_base, false, false);
 
-	font.gfx := pcuint16(fontTiles);
-	font.pal := pcuint16(fontPal);
-	font.numChars := 95;
-	font.numColors :=  fontPalLen div 2;
-	font.bpp := 8;
-	font.asciiOffset := 32;
-	font.convertSingleColor := false;
+  font.gfx := pcuint16(fontTiles);
+  font.pal := pcuint16(fontPal);
+  font.numChars := 95;
+  font.numColors :=  fontPalLen div 2;
+  font.bpp := 8;
+  font.asciiOffset := 32;
+  font.convertSingleColor := false;
 
-	consoleSetFont(console, @font);
+  consoleSetFont(console, @font);
 
-	bg3 := console^.bgId;
+  bg3 := console^.bgId;
 
-	printf('Custom Font Demo'#10);
-	printf('   by Poffy'#10);
-	printf('modified by WinterMute and Dovoto'#10);
-	printf('for libnds examples'#10);
+  printf('Custom Font Demo'#10);
+  printf('   by Poffy'#10);
+  printf('modified by WinterMute and Dovoto'#10);
+  printf('for libnds examples'#10);
 
-	
-	angle := 0;
+  
+  angle := 0;
   scrollX := 0;
   scrollY := 0;
   scaleX := intToFixed(1,8);
   scaleY := intToFixed(1,8);
 
-	while true do
-	begin
-		scanKeys();
-		keys := keysHeld();
+  while true do
+  begin
+    scanKeys();
+    keys := keysHeld();
+    if (keys and KEY_START) <> 0 then break;
+    
+    if ( keys and KEY_L ) <> 0 then angle := angle + 64;
+    if ( keys and KEY_R )  <> 0 then angle := angle - 64;
 
-		if ( keys and KEY_L ) <> 0 then angle := angle + 64;
-		if ( keys and KEY_R )  <> 0 then angle := angle - 64;
+    if ( keys and KEY_LEFT )  <> 0 then scrollX := scrollX + 1;
+    if ( keys and KEY_RIGHT )  <> 0 then scrollX := scrollX - 1;
+    if ( keys and KEY_UP )  <> 0 then scrollY := scrollY + 1;
+    if ( keys and KEY_DOWN )  <> 0 then scrollY := scrollY - 1;
 
-		if ( keys and KEY_LEFT )  <> 0 then scrollX := scrollX + 1;
-		if ( keys and KEY_RIGHT )  <> 0 then scrollX := scrollX - 1;
-		if ( keys and KEY_UP )  <> 0 then scrollY := scrollY + 1;
-		if ( keys and KEY_DOWN )  <> 0 then scrollY := scrollY - 1;
+    if ( keys and KEY_A )  <> 0 then scaleX := scaleX + 1;
+    if ( keys and KEY_B )  <> 0 then scaleX := scaleX - 1;
 
-		if ( keys and KEY_A )  <> 0 then scaleX := scaleX + 1;
-		if ( keys and KEY_B )  <> 0 then scaleX := scaleX - 1;
+    if( keys and KEY_X )  <> 0 then scaleY := scaleY + 1;
+    if( keys and KEY_Y )  <> 0 then scaleY := scaleY - 1;
 
-		if( keys and KEY_X )  <> 0 then scaleY := scaleY + 1;
-		if( keys and KEY_Y )  <> 0 then scaleY := scaleY - 1;
+    swiWaitForVBlank();
 
-		swiWaitForVBlank();
 
-
-		bgSetRotateScale(bg3, angle, scaleX, scaleY);
-		bgSetScroll(bg3, scrollX, scrollY);
-		bgUpdate();
-	end;
+    bgSetRotateScale(bg3, angle, scaleX, scaleY);
+    bgSetScroll(bg3, scrollX, scrollY);
+    bgUpdate();
+  end;
 
 end.

+ 7 - 4
packages/libndsfpc/examples/graphics/Sprites/allocation_test/AllocationTest.pp

@@ -180,6 +180,7 @@ end;
 
 var
   memUsageTemp: longint;// = $FFFFFFFF;
+  keys: integer;
 
 begin
   randomize;
@@ -226,7 +227,9 @@ begin
 		updateSprites();
 
 		swiWaitForVBlank();
-		
+    scanKeys();
+		keys := keysDown();
+		if (keys and KEY_START) <> 0 then break;
 		//api: updates real oam memory 
 		oamUpdate(oam^);
 
@@ -236,9 +239,9 @@ begin
 
 		consoleClear();
 
-    printf('Memory usage: %i %i%% '#10,  spriteMemoryUsage, 100 * spriteMemoryUsage div (spriteMemSize));
-    printf('Percentage fail: %i%% '#10, oomCount * 100 div allocationCount);
-    printf('Lowest Usage at fail %i %i%% '#10, memUsageTemp, 100 * memUsageTemp div (spriteMemSize));
+    printf('Memory usage: %li %li%% '#10,  spriteMemoryUsage, 100 * spriteMemoryUsage div (spriteMemSize));
+    printf('Percentage fail: %li%% '#10, oomCount * 100 div allocationCount);
+    printf('Lowest Usage at fail %li %li%% '#10, memUsageTemp, 100 * memUsageTemp div (spriteMemSize));
   end;
 end.
 		

+ 5 - 0
packages/libndsfpc/examples/graphics/Sprites/bitmap_sprites/BitmapSprites.pp

@@ -21,6 +21,7 @@ type
   end;
 
 var
+  keys: integer;
   sprites: array [0..2] of TMySprite;
   i, angle: integer;
 
@@ -119,6 +120,10 @@ begin
 
     swiWaitForVBlank();
 
+   
+    scanKeys();
+    keys := keysDown();
+    if (keys and KEY_START) <> 0 then break;
     //send the updates to the hardware
     oamUpdate(oamSub);
   end;

+ 149 - 117
packages/libndsfpc/examples/graphics/Sprites/fire_and_sprites/FireAndSprites.pp

@@ -16,10 +16,10 @@ var
 
 type
   TSprite = record
-    x, y: cint;				//location
-    dx, dy: cint;			//speed
+    x, y: cint;       //location
+    dx, dy: cint;     //speed
     oam: PSpriteEntry;
-    gfxID: integer; 				//graphics location
+    gfxID: integer;         //graphics location
   end;
   PSprite = ^TSprite;
 
@@ -30,7 +30,7 @@ var
 begin
   x := sp.x shr 8;
   y := sp.y shr 8;
-	sp.oam^.y := y;
+  sp.oam^.y := y;
   sp.oam^.x := x;
 end;
 
@@ -48,42 +48,86 @@ begin
   //dmaCopy(@OAMCopySub, OAM_SUB, 128 * sizeof(SpriteEntry));
 end;
 
+// HSV to RGB conversion function with only integer math
+function hsl2rgb(hue, sat, lum: cuint8): cuint16;
+var
+  v: cint;
+  m: cint;
+  sextant: cint;
+  fract, vsf, mid1, mid2: cint;
+begin
+  if lum < 128 then
+    v := lum * (256 + sat) shr 8
+  else
+    v := (((lum + sat) shl 8) - lum * sat) shr 8;
+  
+  if (v <= 0) then
+    hsl2rgb := RGB8(0,0,0)
+  else 
+ begin
+
+    m := lum + lum - v;
+    hue := hue * 6;
+    sextant := hue shr 8;
+    fract := hue - (sextant shl 8);
+    vsf := v * fract * (v - m) div v shr 8;
+    mid1 := m + vsf;
+    mid2 := v - vsf;
+    case sextant of
+      0: hsl2rgb := RGB8(v,mid1,m); 
+      1: hsl2rgb := RGB8(mid2,v,m);
+      2: hsl2rgb := RGB8(m,v,mid1); 
+      3: hsl2rgb := RGB8(m,mid2,v); 
+      4: hsl2rgb := RGB8(mid1,m,v); 
+    else hsl2rgb := RGB8(v,m,mid2);
+    end; 
+  end;
+end;
+
+const
+  WIDTH = 256;   
+  HEIGHT = 196;
 
 var
-	back, front: pcuint16;
+  fire: array [0..HEIGHT, 0..WIDTH - 1] of cuint8;
+
+  x, y: integer;
+  w: integer = WIDTH; 
+  h: integer = HEIGHT;
   sprites: array [0..NUM_SPRITES - 1] of TSprite;
   i, delta: integer;
   ix, iy: integer;
-  screen: integer;
+  
+  temp: cint;
+  pressed: integer;
+  
   map0, map1: pcuint16;
   red: cuint16;
   ball: sImage;
 
 begin
   randomize;
-	back := VRAM_A;
-	front := VRAM_B;
 
-	i := 0;
+  i := 0;
   delta := 0;
-	ix := 0;
-	iy := 0;
-	screen := 1;
-	map0 := pcuint16(SCREEN_BASE_BLOCK_SUB(1));
-	map1 := pcuint16(SCREEN_BASE_BLOCK_SUB(2));
+  ix := 0;
+  iy := 0;
 
-	//set main display to render directly from the frame buffer
-	videoSetMode(MODE_FB1);
+  map0 := pcuint16(SCREEN_BASE_BLOCK_SUB(1));
+  map1 := pcuint16(SCREEN_BASE_BLOCK_SUB(2));
 
-	//set up the sub display
-	videoSetModeSub(MODE_0_2D or
+  //set main display to render 256 color bitmap
+  videoSetMode(MODE_5_2D or DISPLAY_BG3_ACTIVE);
+
+  //set up the sub display
+  videoSetModeSub(MODE_0_2D or
           DISPLAY_SPR_1D_LAYOUT or
           DISPLAY_SPR_ACTIVE or
           DISPLAY_BG0_ACTIVE or
           DISPLAY_BG1_ACTIVE );
 
-	//vram banks are somewhat complex
-	vramSetPrimaryBanks(VRAM_A_LCD, VRAM_B_LCD, VRAM_C_SUB_BG, VRAM_D_SUB_SPRITE);
+  //vram banks are somewhat complex
+  vramSetPrimaryBanks(VRAM_A_MAIN_BG_0x06000000, VRAM_B_MAIN_SPRITE, VRAM_C_SUB_BG, VRAM_D_SUB_SPRITE);
 
   //load our ball pcx file into an image
   loadPCX(pcuint8(ball_pcx), @ball);
@@ -98,7 +142,7 @@ begin
   for i := 0 to 32*16 - 1 do
     SPRITE_GFX_SUB[i] := cuint32(ball.image.data16[i]);
 
-	//turn off sprites
+  //turn off sprites
   initOAM();
 
   for i := 0 to NUM_SPRITES - 1 do
@@ -123,113 +167,101 @@ begin
     sprites[i].oam^.attribute[2] := sprites[i].gfxID;
   end;
 
-	//set up two backgrounds to scroll around
-	REG_BG0CNT_SUB^ := BG_COLOR_256 or (1 shl MAP_BASE_SHIFT);
-	REG_BG1CNT_SUB^ := BG_COLOR_256 or (2 shl MAP_BASE_SHIFT);
-
-	BG_PALETTE_SUB[0] := RGB15(10,10,10);
-	BG_PALETTE_SUB[1] := RGB15(0,16,0);
-	BG_PALETTE_SUB[2] := RGB15(0,0,31);
-
-	//load the maps with alternating tiles (0,1 for bg0 and 0,2 for bg1)
-	for iy := 0 to 31 do
-		for ix := 0 to 31 do
-		begin
-			map0[iy * 32 + ix] := (ix xor iy) and 1;
-			map1[iy * 32 + ix] := ((ix xor iy) and 1) shl 1;
-		end;
+  //set up two backgrounds to scroll around
+  REG_BG0CNT_SUB^ := BG_COLOR_256 or (1 shl MAP_BASE_SHIFT);
+  REG_BG1CNT_SUB^ := BG_COLOR_256 or (2 shl MAP_BASE_SHIFT);
 
-	//fill 2 tiles with different colors
-	for i := 0 to (64 div 2) - 1 do
-	begin
-		BG_GFX_SUB[i+32] := $0101;
-		BG_GFX_SUB[i+32+32] := $0202;
-	end;
+  BG_PALETTE_SUB[0] := RGB15(10,10,10);
+  BG_PALETTE_SUB[1] := RGB15(0,16,0);
+  BG_PALETTE_SUB[2] := RGB15(0,0,31);
 
-	while (true) do
-	begin
-		//scroll the background
-		REG_BG0HOFS^ := delta;
-		inc(delta);
-		REG_BG0VOFS^ := delta;
+  //load the maps with alternating tiles (0,1 for bg0 and 0,2 for bg1)
+  for iy := 0 to 31 do
+    for ix := 0 to 31 do
+    begin
+      map0[iy * 32 + ix] := (ix xor iy) and 1;
+      map1[iy * 32 + ix] := ((ix xor iy) and 1) shl 1;
+    end;
 
-		//move the sprites
-		for i := 0 to NUM_SPRITES - 1 do
-		begin
-			sprites[i].x := sprites[i].x + sprites[i].dx;
-			sprites[i].y := sprites[i].y + sprites[i].dy;
-
-			//check for collision with the screen boundries
-			if (sprites[i].x < (1 shl 8)) or (sprites[i].x > (247 shl 8)) then
-				sprites[i].dx := -sprites[i].dx;
-
-			if (sprites[i].y < (1 shl 8)) or (sprites[i].y > (182 shl 8)) then
-				sprites[i].dy := -sprites[i].dy;
-
-			//reposition the sprites
-			MoveSprite(sprites[i]);
-		end;
-
-
-
-		//do the plasma/fire
-		for ix := 0 to SCREEN_WIDTH - 1 do
-		begin
-			back[ix + SCREEN_WIDTH * (SCREEN_HEIGHT - 1)] := random($FFFF);
-			back[ix + SCREEN_WIDTH * (SCREEN_HEIGHT - 2)] := random($FFFF);
-		end;
+  //fill 2 tiles with different colors
+  for i := 0 to (64 div 2) - 1 do
+  begin
+    BG_GFX_SUB[i+32] := $0101;
+    BG_GFX_SUB[i+32+32] := $0202;
+  end;
 
-		back := back + 1;
+	FillChar(fire, 256*192, 0);
 
-		for iy := 1 to SCREEN_HEIGHT - 3 do
-		begin
-			for ix := 1 to SCREEN_WIDTH - 2 do
-			begin
-				red := 0;
+	// Set up palette for fire effect
+	for x := 0 to 256 do
+  begin 
+    if x * 2 > 255 then
+      BG_PALETTE[x] := hsl2rgb(x div 3,255, 255)
+    else
+      BG_PALETTE[x] := hsl2rgb(x div 3, 255, x * 2);
+  end;
 
-				red := red + front[0];
-				red := red + front[2];
+	// Set up background for 8bit bitmap
+	REG_BG3CNT^ := BG_BMP8_256x256;
 
-				front := front + SCREEN_WIDTH;
+	// and 1:1 scaling
+	REG_BG3PA^ := 1 shl 8;
+	REG_BG3PB^ := 0; // BG SCALING X
+	REG_BG3PC^ := 0; // BG SCALING Y
+	REG_BG3PD^ := 1 shl 8;
+	REG_BG3X^ := 0;
+	REG_BG3Y^ := 0;
 
-				red := red + front[0];
-				red := red + front[1];
-				red := red + front[2];
+  while (true) do
+  begin
+    //scroll the background
+    REG_BG0HOFS_SUB^ := delta;
+    inc(delta);
+    REG_BG0VOFS_SUB^ := delta;
+
+    //move the sprites
+    for i := 0 to NUM_SPRITES - 1 do
+    begin
+      sprites[i].x := sprites[i].x + sprites[i].dx;
+      sprites[i].y := sprites[i].y + sprites[i].dy;
+
+      //check for collision with the screen boundries
+      if (sprites[i].x < (1 shl 8)) or (sprites[i].x > (247 shl 8)) then
+        sprites[i].dx := -sprites[i].dx;
+
+      if (sprites[i].y < (1 shl 8)) or (sprites[i].y > (182 shl 8)) then
+        sprites[i].dy := -sprites[i].dy;
+
+      //reposition the sprites
+      MoveSprite(sprites[i]);
+    end;
+
+ 
+
+    //do the plasma/fire
+		//randomize the bottom row of the fire buffer
+		for x := 0 to w - 1 do
+      //fire[h-1, x] := abs(32768 + random(high(cint))) mod 256;
+      fire[h-1, x] := abs(32768 + random(32767)) mod 256;
+    
+		//do the fire calculations for every pixel, from top to bottom
+		for y := 0 to h - 2 do
+			for x := 0 to w - 1 do
+      begin
+        temp := fire[y + 1, (x - 1) mod w] + fire[y + 2, (x) mod w] + fire[y + 1, (x + 1) mod w] + fire[y + 3, (x) mod w];
+			end;
 
-				front := front + SCREEN_WIDTH;
+		dmaCopy(@fire, pointer($06000000), 256 * 192);
+  
+    swiWaitForVBlank();
 
-				red := red + front[0];
-				red := red + front[1];
-				red := red + front[2];
+   
+    scanKeys();
+		pressed := keysDown();
+		if (pressed and KEY_START) <> 0 then break;
 
-				front := front - ((2 * SCREEN_WIDTH) - 1);
+    updateOAM();
 
-				back[0] :=  (red shr 3);
-		    back := back + 1;
-			end;
-		  back := back + 2;
-			front := front + 2;
-
-		end;
-
-		swiWaitForVBlank();
-
-		updateOAM();
-
-		//flip screens
-		if (screen) <> 0 then
-		begin
-			videoSetMode(MODE_FB1);
-			front := VRAM_B;
-			back := VRAM_A;
-			screen := 0;
-		end else
-		begin
-			videoSetMode(MODE_FB0);
-			front := VRAM_A;
-			back := VRAM_B;
-			screen := 1;
-		end;
-	end;
+  end;
 end.
 

BIN
packages/libndsfpc/examples/graphics/Sprites/fire_and_sprites/data/ball.pcx


+ 1679 - 0
packages/libndsfpc/examples/graphics/grit/256colorTilemap/Makefile

@@ -0,0 +1,1679 @@
+#
+# Don't edit, this file is generated by FPCMake Version 2.0.0 [2017-02-13 rev 35434]
+#
+default: all
+MAKEFILETARGETS=arm-nds
+BSDs = freebsd netbsd openbsd darwin dragonfly
+UNIXs = linux $(BSDs) solaris qnx haiku aix
+LIMIT83fs = go32v2 os2 emx watcom msdos
+OSNeedsComspecToRunBatch = go32v2 watcom
+FORCE:
+.PHONY: FORCE
+override PATH:=$(patsubst %/,%,$(subst \,/,$(PATH)))
+ifneq ($(findstring darwin,$(OSTYPE)),)
+inUnix=1 #darwin
+SEARCHPATH:=$(filter-out .,$(subst :, ,$(PATH)))
+else
+ifeq ($(findstring ;,$(PATH)),)
+inUnix=1
+SEARCHPATH:=$(filter-out .,$(subst :, ,$(PATH)))
+else
+SEARCHPATH:=$(subst ;, ,$(PATH))
+endif
+endif
+SEARCHPATH+=$(patsubst %/,%,$(subst \,/,$(dir $(MAKE))))
+PWD:=$(strip $(wildcard $(addsuffix /pwd.exe,$(SEARCHPATH))))
+ifeq ($(PWD),)
+PWD:=$(strip $(wildcard $(addsuffix /pwd,$(SEARCHPATH))))
+ifeq ($(PWD),)
+$(error You need the GNU utils package to use this Makefile)
+else
+PWD:=$(firstword $(PWD))
+SRCEXEEXT=
+endif
+else
+PWD:=$(firstword $(PWD))
+SRCEXEEXT=.exe
+endif
+ifndef inUnix
+ifeq ($(OS),Windows_NT)
+inWinNT=1
+else
+ifdef OS2_SHELL
+inOS2=1
+endif
+endif
+else
+ifneq ($(findstring cygdrive,$(PATH)),)
+inCygWin=1
+endif
+endif
+ifdef inUnix
+SRCBATCHEXT=.sh
+else
+ifdef inOS2
+SRCBATCHEXT=.cmd
+else
+SRCBATCHEXT=.bat
+endif
+endif
+ifdef COMSPEC
+ifneq ($(findstring $(OS_SOURCE),$(OSNeedsComspecToRunBatch)),)
+ifndef RUNBATCH
+RUNBATCH=$(COMSPEC) /C
+endif
+endif
+endif
+ifdef inUnix
+PATHSEP=/
+else
+PATHSEP:=$(subst /,\,/)
+ifdef inCygWin
+PATHSEP=/
+endif
+endif
+ifdef PWD
+BASEDIR:=$(subst \,/,$(shell $(PWD)))
+ifdef inCygWin
+ifneq ($(findstring /cygdrive/,$(BASEDIR)),)
+BASENODIR:=$(patsubst /cygdrive%,%,$(BASEDIR))
+BASEDRIVE:=$(firstword $(subst /, ,$(BASENODIR)))
+BASEDIR:=$(subst /cygdrive/$(BASEDRIVE)/,$(BASEDRIVE):/,$(BASEDIR))
+endif
+endif
+else
+BASEDIR=.
+endif
+ifdef inOS2
+ifndef ECHO
+ECHO:=$(strip $(wildcard $(addsuffix /gecho$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(ECHO),)
+ECHO:=$(strip $(wildcard $(addsuffix /echo$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(ECHO),)
+ECHO=echo
+else
+ECHO:=$(firstword $(ECHO))
+endif
+else
+ECHO:=$(firstword $(ECHO))
+endif
+endif
+export ECHO
+endif
+override OS_TARGET_DEFAULT=nds
+override CPU_TARGET_DEFAULT=arm
+override DEFAULT_FPCDIR=../../../../../..
+ifndef FPC
+ifdef PP
+FPC=$(PP)
+endif
+endif
+ifndef FPC
+FPCPROG:=$(strip $(wildcard $(addsuffix /fpc$(SRCEXEEXT),$(SEARCHPATH))))
+ifneq ($(FPCPROG),)
+FPCPROG:=$(firstword $(FPCPROG))
+ifneq ($(CPU_TARGET),)
+FPC:=$(shell $(FPCPROG) -P$(CPU_TARGET) -PB)
+else
+FPC:=$(shell $(FPCPROG) -PB)
+endif
+ifneq ($(findstring Error,$(FPC)),)
+override FPC=$(firstword $(strip $(wildcard $(addsuffix /ppc386$(SRCEXEEXT),$(SEARCHPATH)))))
+else
+ifeq ($(strip $(wildcard $(FPC))),)
+FPC:=$(firstword $(FPCPROG))
+endif
+endif
+else
+override FPC=$(firstword $(strip $(wildcard $(addsuffix /ppc386$(SRCEXEEXT),$(SEARCHPATH)))))
+endif
+endif
+override FPC:=$(subst $(SRCEXEEXT),,$(FPC))
+override FPC:=$(subst \,/,$(FPC))$(SRCEXEEXT)
+FOUNDFPC:=$(strip $(wildcard $(FPC)))
+ifeq ($(FOUNDFPC),)
+FOUNDFPC=$(strip $(wildcard $(addsuffix /$(FPC),$(SEARCHPATH))))
+ifeq ($(FOUNDFPC),)
+$(error Compiler $(FPC) not found)
+endif
+endif
+ifndef FPC_COMPILERINFO
+FPC_COMPILERINFO:=$(shell $(FPC) -iVSPTPSOTO)
+endif
+ifndef FPC_VERSION
+FPC_VERSION:=$(word 1,$(FPC_COMPILERINFO))
+endif
+export FPC FPC_VERSION FPC_COMPILERINFO
+unexport CHECKDEPEND ALLDEPENDENCIES
+ifndef CPU_TARGET
+ifdef CPU_TARGET_DEFAULT
+CPU_TARGET=$(CPU_TARGET_DEFAULT)
+endif
+endif
+ifndef OS_TARGET
+ifdef OS_TARGET_DEFAULT
+OS_TARGET=$(OS_TARGET_DEFAULT)
+endif
+endif
+ifndef CPU_SOURCE
+CPU_SOURCE:=$(word 2,$(FPC_COMPILERINFO))
+endif
+ifndef CPU_TARGET
+CPU_TARGET:=$(word 3,$(FPC_COMPILERINFO))
+endif
+ifndef OS_SOURCE
+OS_SOURCE:=$(word 4,$(FPC_COMPILERINFO))
+endif
+ifndef OS_TARGET
+OS_TARGET:=$(word 5,$(FPC_COMPILERINFO))
+endif
+FULL_TARGET=$(CPU_TARGET)-$(OS_TARGET)
+FULL_SOURCE=$(CPU_SOURCE)-$(OS_SOURCE)
+ifeq ($(CPU_TARGET),armeb)
+ARCH=arm
+override FPCOPT+=-Cb
+else
+ifeq ($(CPU_TARGET),armel)
+ARCH=arm
+override FPCOPT+=-CaEABI
+else
+ARCH=$(CPU_TARGET)
+endif
+endif
+ifeq ($(FULL_TARGET),arm-embedded)
+ifeq ($(SUBARCH),)
+$(error When compiling for arm-embedded, a sub-architecture (e.g. SUBARCH=armv4t or SUBARCH=armv7m) must be defined)
+endif
+override FPCOPT+=-Cp$(SUBARCH)
+endif
+ifeq ($(FULL_TARGET),mipsel-embedded)
+ifeq ($(SUBARCH),)
+$(error When compiling for mipsel-embedded, a sub-architecture (e.g. SUBARCH=pic32mx) must be defined)
+endif
+override FPCOPT+=-Cp$(SUBARCH)
+endif
+ifneq ($(findstring $(OS_SOURCE),$(LIMIT83fs)),)
+TARGETSUFFIX=$(OS_TARGET)
+SOURCESUFFIX=$(OS_SOURCE)
+else
+ifneq ($(findstring $(OS_TARGET),$(LIMIT83fs)),)
+TARGETSUFFIX=$(OS_TARGET)
+else
+TARGETSUFFIX=$(FULL_TARGET)
+endif
+SOURCESUFFIX=$(FULL_SOURCE)
+endif
+ifneq ($(FULL_TARGET),$(FULL_SOURCE))
+CROSSCOMPILE=1
+endif
+ifeq ($(findstring makefile,$(MAKECMDGOALS)),)
+ifeq ($(findstring $(FULL_TARGET),$(MAKEFILETARGETS)),)
+$(error The Makefile doesn't support target $(FULL_TARGET), please run fpcmake first)
+endif
+endif
+ifneq ($(findstring $(OS_TARGET),$(BSDs)),)
+BSDhier=1
+endif
+ifeq ($(OS_TARGET),linux)
+linuxHier=1
+endif
+ifndef CROSSCOMPILE
+BUILDFULLNATIVE=1
+export BUILDFULLNATIVE
+endif
+ifdef BUILDFULLNATIVE
+BUILDNATIVE=1
+export BUILDNATIVE
+endif
+export OS_TARGET OS_SOURCE ARCH CPU_TARGET CPU_SOURCE FULL_TARGET FULL_SOURCE TARGETSUFFIX SOURCESUFFIX CROSSCOMPILE
+ifdef FPCDIR
+override FPCDIR:=$(subst \,/,$(FPCDIR))
+ifeq ($(wildcard $(addprefix $(FPCDIR)/,rtl units)),)
+override FPCDIR=wrong
+endif
+else
+override FPCDIR=wrong
+endif
+ifdef DEFAULT_FPCDIR
+ifeq ($(FPCDIR),wrong)
+override FPCDIR:=$(subst \,/,$(DEFAULT_FPCDIR))
+ifeq ($(wildcard $(addprefix $(FPCDIR)/,rtl units)),)
+override FPCDIR=wrong
+endif
+endif
+endif
+ifeq ($(FPCDIR),wrong)
+ifdef inUnix
+override FPCDIR=/usr/local/lib/fpc/$(FPC_VERSION)
+ifeq ($(wildcard $(FPCDIR)/units),)
+override FPCDIR=/usr/lib/fpc/$(FPC_VERSION)
+endif
+else
+override FPCDIR:=$(subst /$(FPC),,$(firstword $(strip $(wildcard $(addsuffix /$(FPC),$(SEARCHPATH))))))
+override FPCDIR:=$(FPCDIR)/..
+ifeq ($(wildcard $(addprefix $(FPCDIR)/,rtl units)),)
+override FPCDIR:=$(FPCDIR)/..
+ifeq ($(wildcard $(addprefix $(FPCDIR)/,rtl units)),)
+override FPCDIR:=$(BASEDIR)
+ifeq ($(wildcard $(addprefix $(FPCDIR)/,rtl units)),)
+override FPCDIR=c:/pp
+endif
+endif
+endif
+endif
+endif
+ifndef CROSSBINDIR
+CROSSBINDIR:=$(wildcard $(FPCDIR)/bin/$(TARGETSUFFIX))
+endif
+ifneq ($(findstring $(OS_TARGET),darwin iphonesim),)
+ifeq ($(OS_SOURCE),darwin)
+DARWIN2DARWIN=1
+endif
+endif
+ifndef BINUTILSPREFIX
+ifndef CROSSBINDIR
+ifdef CROSSCOMPILE
+ifneq ($(OS_TARGET),msdos)
+ifndef DARWIN2DARWIN
+ifneq ($(CPU_TARGET),jvm)
+BINUTILSPREFIX=$(CPU_TARGET)-$(OS_TARGET)-
+ifeq ($(OS_TARGET),android)
+ifeq ($(CPU_TARGET),arm)
+BINUTILSPREFIX=arm-linux-androideabi-
+else
+ifeq ($(CPU_TARGET),i386)
+BINUTILSPREFIX=i686-linux-android-
+else
+ifeq ($(CPU_TARGET),mipsel)
+BINUTILSPREFIX=mipsel-linux-android-
+endif
+endif
+endif
+endif
+endif
+endif
+else
+BINUTILSPREFIX=$(OS_TARGET)-
+endif
+endif
+endif
+endif
+UNITSDIR:=$(wildcard $(FPCDIR)/units/$(TARGETSUFFIX))
+ifeq ($(UNITSDIR),)
+UNITSDIR:=$(wildcard $(FPCDIR)/units/$(OS_TARGET))
+endif
+PACKAGESDIR:=$(wildcard $(FPCDIR) $(FPCDIR)/packages $(FPCDIR)/packages/base $(FPCDIR)/packages/extra)
+ifndef FPCFPMAKE
+ifdef CROSSCOMPILE
+ifeq ($(strip $(wildcard $(addsuffix /compiler/ppc$(SRCEXEEXT),$(FPCDIR)))),)
+FPCPROG:=$(strip $(wildcard $(addsuffix /fpc$(SRCEXEEXT),$(SEARCHPATH))))
+ifneq ($(FPCPROG),)
+FPCPROG:=$(firstword $(FPCPROG))
+FPCFPMAKE:=$(shell $(FPCPROG) -PB)
+ifeq ($(strip $(wildcard $(FPCFPMAKE))),)
+FPCFPMAKE:=$(firstword $(FPCPROG))
+endif
+else
+override FPCFPMAKE=$(firstword $(strip $(wildcard $(addsuffix /ppc386$(SRCEXEEXT),$(SEARCHPATH)))))
+endif
+else
+FPCFPMAKE=$(strip $(wildcard $(addsuffix /compiler/ppc$(SRCEXEEXT),$(FPCDIR))))
+FPMAKE_SKIP_CONFIG=-n
+export FPCFPMAKE
+export FPMAKE_SKIP_CONFIG
+endif
+else
+FPMAKE_SKIP_CONFIG=-n
+FPCFPMAKE=$(FPC)
+endif
+endif
+BIN = bin
+BUILD = build
+DATA = data
+FILESYSTEM = filesystem
+GFX = gfx
+INC = inc
+AUDIO_FILES = $(foreach dir, $(notdir $(wildcard audio/*.*)), $(CURDIR)/audio/$(dir))
+GFX_FILES   = $(foreach dir, $(GFX), $(notdir $(wildcard $(dir)/*.bmp $(dir)/*.png)))
+BIN_FILES   = $(foreach dir, $(DATA), $(notdir $(wildcard $(dir)/*)))
+GBFS_FILES  = $(foreach dir, GBFS, $(notdir $(wildcard $(dir)/*)))
+ifeq ($(FULL_TARGET),arm-nds)
+override TARGET_PROGRAMS+=tilemap_256_color
+endif
+ifeq ($(FULL_TARGET),arm-nds)
+override CLEAN_UNITS+=*
+endif
+ifeq ($(FULL_TARGET),arm-nds)
+override CLEAN_FILES+=*.elf *.o *.s *.nds *.nef *.h *.bin *.map $(BUILD)/* $(INC)/* $(BIN)/*
+endif
+override INSTALL_FPCPACKAGE=y
+ifeq ($(FULL_TARGET),arm-nds)
+override COMPILER_OPTIONS+=-Xm
+endif
+ifeq ($(FULL_TARGET),arm-nds)
+override COMPILER_TARGETDIR+=$(BIN)
+endif
+ifeq ($(FULL_TARGET),arm-nds)
+override COMPILER_UNITTARGETDIR+=$(BUILD)
+endif
+ifdef REQUIRE_UNITSDIR
+override UNITSDIR+=$(REQUIRE_UNITSDIR)
+endif
+ifdef REQUIRE_PACKAGESDIR
+override PACKAGESDIR+=$(REQUIRE_PACKAGESDIR)
+endif
+ifdef ZIPINSTALL
+ifneq ($(findstring $(OS_TARGET),$(UNIXs)),)
+UNIXHier=1
+endif
+else
+ifneq ($(findstring $(OS_SOURCE),$(UNIXs)),)
+UNIXHier=1
+endif
+endif
+ifndef INSTALL_PREFIX
+ifdef PREFIX
+INSTALL_PREFIX=$(PREFIX)
+endif
+endif
+ifndef INSTALL_PREFIX
+ifdef UNIXHier
+INSTALL_PREFIX=/usr/local
+else
+ifdef INSTALL_FPCPACKAGE
+INSTALL_BASEDIR:=/pp
+else
+INSTALL_BASEDIR:=/$(PACKAGE_NAME)
+endif
+endif
+endif
+export INSTALL_PREFIX
+ifdef INSTALL_FPCSUBDIR
+export INSTALL_FPCSUBDIR
+endif
+ifndef DIST_DESTDIR
+DIST_DESTDIR:=$(BASEDIR)
+endif
+export DIST_DESTDIR
+ifndef COMPILER_UNITTARGETDIR
+ifdef PACKAGEDIR_MAIN
+COMPILER_UNITTARGETDIR=$(PACKAGEDIR_MAIN)/units/$(TARGETSUFFIX)
+else
+COMPILER_UNITTARGETDIR=units/$(TARGETSUFFIX)
+endif
+endif
+ifndef COMPILER_TARGETDIR
+COMPILER_TARGETDIR=.
+endif
+ifndef INSTALL_BASEDIR
+ifdef UNIXHier
+ifdef INSTALL_FPCPACKAGE
+INSTALL_BASEDIR:=$(INSTALL_PREFIX)/lib/fpc/$(FPC_VERSION)
+else
+INSTALL_BASEDIR:=$(INSTALL_PREFIX)/lib/$(PACKAGE_NAME)
+endif
+else
+INSTALL_BASEDIR:=$(INSTALL_PREFIX)
+endif
+endif
+ifndef INSTALL_BINDIR
+ifdef UNIXHier
+INSTALL_BINDIR:=$(INSTALL_PREFIX)/bin
+else
+INSTALL_BINDIR:=$(INSTALL_BASEDIR)/bin
+ifdef INSTALL_FPCPACKAGE
+ifdef CROSSCOMPILE
+ifdef CROSSINSTALL
+INSTALL_BINDIR:=$(INSTALL_BINDIR)/$(SOURCESUFFIX)
+else
+INSTALL_BINDIR:=$(INSTALL_BINDIR)/$(TARGETSUFFIX)
+endif
+else
+INSTALL_BINDIR:=$(INSTALL_BINDIR)/$(TARGETSUFFIX)
+endif
+endif
+endif
+endif
+ifndef INSTALL_UNITDIR
+INSTALL_UNITDIR:=$(INSTALL_BASEDIR)/units/$(TARGETSUFFIX)
+ifdef INSTALL_FPCPACKAGE
+ifdef PACKAGE_NAME
+INSTALL_UNITDIR:=$(INSTALL_UNITDIR)/$(PACKAGE_NAME)
+endif
+endif
+endif
+ifndef INSTALL_LIBDIR
+ifdef UNIXHier
+INSTALL_LIBDIR:=$(INSTALL_PREFIX)/lib
+else
+INSTALL_LIBDIR:=$(INSTALL_UNITDIR)
+endif
+endif
+ifndef INSTALL_SOURCEDIR
+ifdef UNIXHier
+ifdef BSDhier
+SRCPREFIXDIR=share/src
+else
+ifdef linuxHier
+SRCPREFIXDIR=share/src
+else
+SRCPREFIXDIR=src
+endif
+endif
+ifdef INSTALL_FPCPACKAGE
+ifdef INSTALL_FPCSUBDIR
+INSTALL_SOURCEDIR:=$(INSTALL_PREFIX)/$(SRCPREFIXDIR)/fpc-$(FPC_VERSION)/$(INSTALL_FPCSUBDIR)/$(PACKAGE_NAME)
+else
+INSTALL_SOURCEDIR:=$(INSTALL_PREFIX)/$(SRCPREFIXDIR)/fpc-$(FPC_VERSION)/$(PACKAGE_NAME)
+endif
+else
+INSTALL_SOURCEDIR:=$(INSTALL_PREFIX)/$(SRCPREFIXDIR)/$(PACKAGE_NAME)-$(PACKAGE_VERSION)
+endif
+else
+ifdef INSTALL_FPCPACKAGE
+ifdef INSTALL_FPCSUBDIR
+INSTALL_SOURCEDIR:=$(INSTALL_BASEDIR)/source/$(INSTALL_FPCSUBDIR)/$(PACKAGE_NAME)
+else
+INSTALL_SOURCEDIR:=$(INSTALL_BASEDIR)/source/$(PACKAGE_NAME)
+endif
+else
+INSTALL_SOURCEDIR:=$(INSTALL_BASEDIR)/source
+endif
+endif
+endif
+ifndef INSTALL_DOCDIR
+ifdef UNIXHier
+ifdef BSDhier
+DOCPREFIXDIR=share/doc
+else
+ifdef linuxHier
+DOCPREFIXDIR=share/doc
+else
+DOCPREFIXDIR=doc
+endif
+endif
+ifdef INSTALL_FPCPACKAGE
+INSTALL_DOCDIR:=$(INSTALL_PREFIX)/$(DOCPREFIXDIR)/fpc-$(FPC_VERSION)/$(PACKAGE_NAME)
+else
+INSTALL_DOCDIR:=$(INSTALL_PREFIX)/$(DOCPREFIXDIR)/$(PACKAGE_NAME)-$(PACKAGE_VERSION)
+endif
+else
+ifdef INSTALL_FPCPACKAGE
+INSTALL_DOCDIR:=$(INSTALL_BASEDIR)/doc/$(PACKAGE_NAME)
+else
+INSTALL_DOCDIR:=$(INSTALL_BASEDIR)/doc
+endif
+endif
+endif
+ifndef INSTALL_EXAMPLEDIR
+ifdef UNIXHier
+ifdef INSTALL_FPCPACKAGE
+ifdef BSDhier
+INSTALL_EXAMPLEDIR:=$(INSTALL_PREFIX)/share/examples/fpc-$(FPC_VERSION)/$(PACKAGE_NAME)
+else
+ifdef linuxHier
+INSTALL_EXAMPLEDIR:=$(INSTALL_DOCDIR)/examples
+else
+INSTALL_EXAMPLEDIR:=$(INSTALL_PREFIX)/doc/fpc-$(FPC_VERSION)/examples/$(PACKAGE_NAME)
+endif
+endif
+else
+ifdef BSDhier
+INSTALL_EXAMPLEDIR:=$(INSTALL_PREFIX)/share/examples/$(PACKAGE_NAME)-$(PACKAGE_VERSION)
+else
+ifdef linuxHier
+INSTALL_EXAMPLEDIR:=$(INSTALL_DOCDIR)/examples/$(PACKAGE_NAME)-$(PACKAGE_VERSION)
+else
+INSTALL_EXAMPLEDIR:=$(INSTALL_PREFIX)/doc/$(PACKAGE_NAME)-$(PACKAGE_VERSION)
+endif
+endif
+endif
+else
+ifdef INSTALL_FPCPACKAGE
+INSTALL_EXAMPLEDIR:=$(INSTALL_BASEDIR)/examples/$(PACKAGE_NAME)
+else
+INSTALL_EXAMPLEDIR:=$(INSTALL_BASEDIR)/examples
+endif
+endif
+endif
+ifndef INSTALL_DATADIR
+INSTALL_DATADIR=$(INSTALL_BASEDIR)
+endif
+ifndef INSTALL_SHAREDDIR
+INSTALL_SHAREDDIR=$(INSTALL_PREFIX)/lib
+endif
+ifdef CROSSCOMPILE
+ifndef CROSSBINDIR
+CROSSBINDIR:=$(wildcard $(CROSSTARGETDIR)/bin/$(SOURCESUFFIX))
+ifeq ($(CROSSBINDIR),)
+CROSSBINDIR:=$(wildcard $(INSTALL_BASEDIR)/cross/$(TARGETSUFFIX)/bin/$(FULL_SOURCE))
+endif
+endif
+else
+CROSSBINDIR=
+endif
+BATCHEXT=.bat
+LOADEREXT=.as
+EXEEXT=.exe
+PPLEXT=.ppl
+PPUEXT=.ppu
+OEXT=.o
+ASMEXT=.s
+SMARTEXT=.sl
+STATICLIBEXT=.a
+SHAREDLIBEXT=.so
+SHAREDLIBPREFIX=libfp
+STATICLIBPREFIX=libp
+IMPORTLIBPREFIX=libimp
+RSTEXT=.rst
+EXEDBGEXT=.dbg
+ifeq ($(OS_TARGET),go32v1)
+STATICLIBPREFIX=
+SHORTSUFFIX=v1
+endif
+ifeq ($(OS_TARGET),go32v2)
+STATICLIBPREFIX=
+SHORTSUFFIX=dos
+IMPORTLIBPREFIX=
+endif
+ifeq ($(OS_TARGET),watcom)
+STATICLIBPREFIX=
+OEXT=.obj
+ASMEXT=.asm
+SHAREDLIBEXT=.dll
+SHORTSUFFIX=wat
+IMPORTLIBPREFIX=
+endif
+ifneq ($(CPU_TARGET),jvm)
+ifeq ($(OS_TARGET),android)
+BATCHEXT=.sh
+EXEEXT=
+HASSHAREDLIB=1
+SHORTSUFFIX=lnx
+endif
+endif
+ifeq ($(OS_TARGET),linux)
+BATCHEXT=.sh
+EXEEXT=
+HASSHAREDLIB=1
+SHORTSUFFIX=lnx
+endif
+ifeq ($(OS_TARGET),dragonfly)
+BATCHEXT=.sh
+EXEEXT=
+HASSHAREDLIB=1
+SHORTSUFFIX=df
+endif
+ifeq ($(OS_TARGET),freebsd)
+BATCHEXT=.sh
+EXEEXT=
+HASSHAREDLIB=1
+SHORTSUFFIX=fbs
+endif
+ifeq ($(OS_TARGET),netbsd)
+BATCHEXT=.sh
+EXEEXT=
+HASSHAREDLIB=1
+SHORTSUFFIX=nbs
+endif
+ifeq ($(OS_TARGET),openbsd)
+BATCHEXT=.sh
+EXEEXT=
+HASSHAREDLIB=1
+SHORTSUFFIX=obs
+endif
+ifeq ($(OS_TARGET),win32)
+SHAREDLIBEXT=.dll
+SHORTSUFFIX=w32
+endif
+ifeq ($(OS_TARGET),os2)
+BATCHEXT=.cmd
+AOUTEXT=.out
+STATICLIBPREFIX=
+SHAREDLIBEXT=.dll
+SHORTSUFFIX=os2
+ECHO=echo
+IMPORTLIBPREFIX=
+endif
+ifeq ($(OS_TARGET),emx)
+BATCHEXT=.cmd
+AOUTEXT=.out
+STATICLIBPREFIX=
+SHAREDLIBEXT=.dll
+SHORTSUFFIX=emx
+ECHO=echo
+IMPORTLIBPREFIX=
+endif
+ifeq ($(OS_TARGET),amiga)
+EXEEXT=
+SHAREDLIBEXT=.library
+SHORTSUFFIX=amg
+endif
+ifeq ($(OS_TARGET),aros)
+EXEEXT=
+SHAREDLIBEXT=.library
+SHORTSUFFIX=aros
+endif
+ifeq ($(OS_TARGET),morphos)
+EXEEXT=
+SHAREDLIBEXT=.library
+SHORTSUFFIX=mos
+endif
+ifeq ($(OS_TARGET),atari)
+EXEEXT=.ttp
+SHORTSUFFIX=ata
+endif
+ifeq ($(OS_TARGET),beos)
+BATCHEXT=.sh
+EXEEXT=
+SHORTSUFFIX=be
+endif
+ifeq ($(OS_TARGET),haiku)
+BATCHEXT=.sh
+EXEEXT=
+SHORTSUFFIX=hai
+endif
+ifeq ($(OS_TARGET),solaris)
+BATCHEXT=.sh
+EXEEXT=
+SHORTSUFFIX=sun
+endif
+ifeq ($(OS_TARGET),qnx)
+BATCHEXT=.sh
+EXEEXT=
+SHORTSUFFIX=qnx
+endif
+ifeq ($(OS_TARGET),netware)
+EXEEXT=.nlm
+STATICLIBPREFIX=
+SHORTSUFFIX=nw
+IMPORTLIBPREFIX=imp
+endif
+ifeq ($(OS_TARGET),netwlibc)
+EXEEXT=.nlm
+STATICLIBPREFIX=
+SHORTSUFFIX=nwl
+IMPORTLIBPREFIX=imp
+endif
+ifeq ($(OS_TARGET),macos)
+BATCHEXT=
+EXEEXT=
+DEBUGSYMEXT=.xcoff
+SHORTSUFFIX=mac
+IMPORTLIBPREFIX=imp
+endif
+ifneq ($(findstring $(OS_TARGET),darwin iphonesim),)
+BATCHEXT=.sh
+EXEEXT=
+HASSHAREDLIB=1
+SHORTSUFFIX=dwn
+EXEDBGEXT=.dSYM
+endif
+ifeq ($(OS_TARGET),gba)
+EXEEXT=.gba
+SHAREDLIBEXT=.so
+SHORTSUFFIX=gba
+endif
+ifeq ($(OS_TARGET),symbian)
+SHAREDLIBEXT=.dll
+SHORTSUFFIX=symbian
+endif
+ifeq ($(OS_TARGET),NativeNT)
+SHAREDLIBEXT=.dll
+SHORTSUFFIX=nativent
+endif
+ifeq ($(OS_TARGET),wii)
+EXEEXT=.dol
+SHAREDLIBEXT=.so
+SHORTSUFFIX=wii
+endif
+ifeq ($(OS_TARGET),aix)
+BATCHEXT=.sh
+EXEEXT=
+SHORTSUFFIX=aix
+endif
+ifeq ($(OS_TARGET),java)
+OEXT=.class
+ASMEXT=.j
+SHAREDLIBEXT=.jar
+SHORTSUFFIX=java
+endif
+ifeq ($(CPU_TARGET),jvm)
+ifeq ($(OS_TARGET),android)
+OEXT=.class
+ASMEXT=.j
+SHAREDLIBEXT=.jar
+SHORTSUFFIX=android
+endif
+endif
+ifeq ($(OS_TARGET),msdos)
+STATICLIBPREFIX=
+STATICLIBEXT=.a
+SHORTSUFFIX=d16
+endif
+ifneq ($(findstring $(OS_SOURCE),$(LIMIT83fs)),)
+FPCMADE=fpcmade.$(SHORTSUFFIX)
+ZIPSUFFIX=$(SHORTSUFFIX)
+ZIPCROSSPREFIX=
+ZIPSOURCESUFFIX=src
+ZIPEXAMPLESUFFIX=exm
+else
+FPCMADE=fpcmade.$(TARGETSUFFIX)
+ZIPSOURCESUFFIX=.source
+ZIPEXAMPLESUFFIX=.examples
+ifdef CROSSCOMPILE
+ZIPSUFFIX=.$(SOURCESUFFIX)
+ZIPCROSSPREFIX=$(TARGETSUFFIX)-
+else
+ZIPSUFFIX=.$(TARGETSUFFIX)
+ZIPCROSSPREFIX=
+endif
+endif
+ifndef ECHO
+ECHO:=$(strip $(wildcard $(addsuffix /gecho$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(ECHO),)
+ECHO:=$(strip $(wildcard $(addsuffix /echo$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(ECHO),)
+ECHO= __missing_command_ECHO
+else
+ECHO:=$(firstword $(ECHO))
+endif
+else
+ECHO:=$(firstword $(ECHO))
+endif
+endif
+export ECHO
+ifndef DATE
+DATE:=$(strip $(wildcard $(addsuffix /gdate$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(DATE),)
+DATE:=$(strip $(wildcard $(addsuffix /date$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(DATE),)
+DATE= __missing_command_DATE
+else
+DATE:=$(firstword $(DATE))
+endif
+else
+DATE:=$(firstword $(DATE))
+endif
+endif
+export DATE
+ifndef GINSTALL
+GINSTALL:=$(strip $(wildcard $(addsuffix /ginstall$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(GINSTALL),)
+GINSTALL:=$(strip $(wildcard $(addsuffix /install$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(GINSTALL),)
+GINSTALL= __missing_command_GINSTALL
+else
+GINSTALL:=$(firstword $(GINSTALL))
+endif
+else
+GINSTALL:=$(firstword $(GINSTALL))
+endif
+endif
+export GINSTALL
+ifndef CPPROG
+CPPROG:=$(strip $(wildcard $(addsuffix /cp$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(CPPROG),)
+CPPROG= __missing_command_CPPROG
+else
+CPPROG:=$(firstword $(CPPROG))
+endif
+endif
+export CPPROG
+ifndef RMPROG
+RMPROG:=$(strip $(wildcard $(addsuffix /rm$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(RMPROG),)
+RMPROG= __missing_command_RMPROG
+else
+RMPROG:=$(firstword $(RMPROG))
+endif
+endif
+export RMPROG
+ifndef MVPROG
+MVPROG:=$(strip $(wildcard $(addsuffix /mv$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(MVPROG),)
+MVPROG= __missing_command_MVPROG
+else
+MVPROG:=$(firstword $(MVPROG))
+endif
+endif
+export MVPROG
+ifndef MKDIRPROG
+MKDIRPROG:=$(strip $(wildcard $(addsuffix /gmkdir$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(MKDIRPROG),)
+MKDIRPROG:=$(strip $(wildcard $(addsuffix /mkdir$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(MKDIRPROG),)
+MKDIRPROG= __missing_command_MKDIRPROG
+else
+MKDIRPROG:=$(firstword $(MKDIRPROG))
+endif
+else
+MKDIRPROG:=$(firstword $(MKDIRPROG))
+endif
+endif
+export MKDIRPROG
+ifndef ECHOREDIR
+ifndef inUnix
+ECHOREDIR=echo
+else
+ECHOREDIR=$(ECHO)
+endif
+endif
+ifndef COPY
+COPY:=$(CPPROG) -fp
+endif
+ifndef COPYTREE
+COPYTREE:=$(CPPROG) -Rfp
+endif
+ifndef MKDIRTREE
+MKDIRTREE:=$(MKDIRPROG) -p
+endif
+ifndef MOVE
+MOVE:=$(MVPROG) -f
+endif
+ifndef DEL
+DEL:=$(RMPROG) -f
+endif
+ifndef DELTREE
+DELTREE:=$(RMPROG) -rf
+endif
+ifndef INSTALL
+ifdef inUnix
+INSTALL:=$(GINSTALL) -c -m 644
+else
+INSTALL:=$(COPY)
+endif
+endif
+ifndef INSTALLEXE
+ifdef inUnix
+INSTALLEXE:=$(GINSTALL) -c -m 755
+else
+INSTALLEXE:=$(COPY)
+endif
+endif
+ifndef MKDIR
+MKDIR:=$(GINSTALL) -m 755 -d
+endif
+export ECHOREDIR COPY COPYTREE MOVE DEL DELTREE INSTALL INSTALLEXE MKDIR
+ifndef PPUMOVE
+PPUMOVE:=$(strip $(wildcard $(addsuffix /ppumove$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(PPUMOVE),)
+PPUMOVE= __missing_command_PPUMOVE
+else
+PPUMOVE:=$(firstword $(PPUMOVE))
+endif
+endif
+export PPUMOVE
+ifndef FPCMAKE
+FPCMAKE:=$(strip $(wildcard $(addsuffix /fpcmake$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(FPCMAKE),)
+FPCMAKE= __missing_command_FPCMAKE
+else
+FPCMAKE:=$(firstword $(FPCMAKE))
+endif
+endif
+export FPCMAKE
+ifndef ZIPPROG
+ZIPPROG:=$(strip $(wildcard $(addsuffix /zip$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(ZIPPROG),)
+ZIPPROG= __missing_command_ZIPPROG
+else
+ZIPPROG:=$(firstword $(ZIPPROG))
+endif
+endif
+export ZIPPROG
+ifndef TARPROG
+TARPROG:=$(strip $(wildcard $(addsuffix /gtar$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(TARPROG),)
+TARPROG:=$(strip $(wildcard $(addsuffix /tar$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(TARPROG),)
+TARPROG= __missing_command_TARPROG
+else
+TARPROG:=$(firstword $(TARPROG))
+endif
+else
+TARPROG:=$(firstword $(TARPROG))
+endif
+endif
+export TARPROG
+ASNAME=$(BINUTILSPREFIX)as
+LDNAME=$(BINUTILSPREFIX)ld
+ARNAME=$(BINUTILSPREFIX)ar
+RCNAME=$(BINUTILSPREFIX)rc
+NASMNAME=$(BINUTILSPREFIX)nasm
+ifndef ASPROG
+ifdef CROSSBINDIR
+ASPROG=$(CROSSBINDIR)/$(ASNAME)$(SRCEXEEXT)
+else
+ASPROG=$(ASNAME)
+endif
+endif
+ifndef LDPROG
+ifdef CROSSBINDIR
+LDPROG=$(CROSSBINDIR)/$(LDNAME)$(SRCEXEEXT)
+else
+LDPROG=$(LDNAME)
+endif
+endif
+ifndef RCPROG
+ifdef CROSSBINDIR
+RCPROG=$(CROSSBINDIR)/$(RCNAME)$(SRCEXEEXT)
+else
+RCPROG=$(RCNAME)
+endif
+endif
+ifndef ARPROG
+ifdef CROSSBINDIR
+ARPROG=$(CROSSBINDIR)/$(ARNAME)$(SRCEXEEXT)
+else
+ARPROG=$(ARNAME)
+endif
+endif
+ifndef NASMPROG
+ifdef CROSSBINDIR
+NASMPROG=$(CROSSBINDIR)/$(NASMNAME)$(SRCEXEEXT)
+else
+NASMPROG=$(NASMNAME)
+endif
+endif
+AS=$(ASPROG)
+LD=$(LDPROG)
+RC=$(RCPROG)
+AR=$(ARPROG)
+NASM=$(NASMPROG)
+ifdef inUnix
+PPAS=./ppas$(SRCBATCHEXT)
+else
+PPAS=ppas$(SRCBATCHEXT)
+endif
+ifdef inUnix
+LDCONFIG=ldconfig
+else
+LDCONFIG=
+endif
+ifdef DATE
+DATESTR:=$(shell $(DATE) +%Y%m%d)
+else
+DATESTR=
+endif
+ZIPOPT=-9
+ZIPEXT=.zip
+ifeq ($(USETAR),bz2)
+TAROPT=vj
+TAREXT=.tar.bz2
+else
+TAROPT=vz
+TAREXT=.tar.gz
+endif
+override REQUIRE_PACKAGES=libndsfpc
+ifeq ($(FULL_TARGET),arm-nds)
+REQUIRE_PACKAGES_LIBNDSFPC=1
+endif
+ifdef REQUIRE_PACKAGES_LIBNDSFPC
+PACKAGEDIR_LIBNDSFPC:=$(firstword $(subst /Makefile.fpc,,$(strip $(wildcard $(addsuffix /libndsfpc/Makefile.fpc,$(PACKAGESDIR))))))
+ifneq ($(PACKAGEDIR_LIBNDSFPC),)
+ifneq ($(wildcard $(PACKAGEDIR_LIBNDSFPC)/units/$(TARGETSUFFIX)),)
+UNITDIR_LIBNDSFPC=$(PACKAGEDIR_LIBNDSFPC)/units/$(TARGETSUFFIX)
+else
+UNITDIR_LIBNDSFPC=$(PACKAGEDIR_LIBNDSFPC)
+endif
+ifneq ($(wildcard $(PACKAGEDIR_LIBNDSFPC)/units/$(SOURCESUFFIX)),)
+UNITDIR_FPMAKE_LIBNDSFPC=$(PACKAGEDIR_LIBNDSFPC)/units/$(SOURCESUFFIX)
+else
+ifneq ($(wildcard $(PACKAGEDIR_LIBNDSFPC)/units_bs/$(SOURCESUFFIX)),)
+UNITDIR_FPMAKE_LIBNDSFPC=$(PACKAGEDIR_LIBNDSFPC)/units_bs/$(SOURCESUFFIX)
+else
+UNITDIR_FPMAKE_LIBNDSFPC=$(PACKAGEDIR_LIBNDSFPC)
+endif
+endif
+ifdef CHECKDEPEND
+$(PACKAGEDIR_LIBNDSFPC)/$(FPCMADE):
+	$(MAKE) -C $(PACKAGEDIR_LIBNDSFPC) $(FPCMADE)
+override ALLDEPENDENCIES+=$(PACKAGEDIR_LIBNDSFPC)/$(FPCMADE)
+endif
+else
+PACKAGEDIR_LIBNDSFPC=
+UNITDIR_LIBNDSFPC:=$(subst /Package.fpc,,$(strip $(wildcard $(addsuffix /libndsfpc/Package.fpc,$(UNITSDIR)))))
+ifneq ($(UNITDIR_LIBNDSFPC),)
+UNITDIR_LIBNDSFPC:=$(firstword $(UNITDIR_LIBNDSFPC))
+else
+UNITDIR_LIBNDSFPC=
+endif
+endif
+ifdef UNITDIR_LIBNDSFPC
+override COMPILER_UNITDIR+=$(UNITDIR_LIBNDSFPC)
+endif
+ifdef UNITDIR_FPMAKE_LIBNDSFPC
+override COMPILER_FPMAKE_UNITDIR+=$(UNITDIR_FPMAKE_LIBNDSFPC)
+endif
+endif
+ifndef NOCPUDEF
+override FPCOPTDEF=$(ARCH)
+endif
+ifneq ($(OS_TARGET),$(OS_SOURCE))
+override FPCOPT+=-T$(OS_TARGET)
+endif
+ifneq ($(CPU_TARGET),$(CPU_SOURCE))
+override FPCOPT+=-P$(ARCH)
+endif
+ifeq ($(OS_SOURCE),openbsd)
+override FPCOPT+=-FD$(NEW_BINUTILS_PATH)
+override FPCMAKEOPT+=-FD$(NEW_BINUTILS_PATH)
+endif
+ifndef CROSSBOOTSTRAP
+ifneq ($(BINUTILSPREFIX),)
+override FPCOPT+=-XP$(BINUTILSPREFIX)
+endif
+ifneq ($(BINUTILSPREFIX),)
+override FPCOPT+=-Xr$(RLINKPATH)
+endif
+endif
+ifndef CROSSCOMPILE
+ifneq ($(BINUTILSPREFIX),)
+override FPCMAKEOPT+=-XP$(BINUTILSPREFIX)
+endif
+endif
+ifdef UNITDIR
+override FPCOPT+=$(addprefix -Fu,$(UNITDIR))
+endif
+ifdef LIBDIR
+override FPCOPT+=$(addprefix -Fl,$(LIBDIR))
+endif
+ifdef OBJDIR
+override FPCOPT+=$(addprefix -Fo,$(OBJDIR))
+endif
+ifdef INCDIR
+override FPCOPT+=$(addprefix -Fi,$(INCDIR))
+endif
+ifdef LINKSMART
+override FPCOPT+=-XX
+endif
+ifdef CREATESMART
+override FPCOPT+=-CX
+endif
+ifdef DEBUG
+override FPCOPT+=-gl
+override FPCOPTDEF+=DEBUG
+endif
+ifdef RELEASE
+ifneq ($(findstring 2.0.,$(FPC_VERSION)),)
+ifeq ($(CPU_TARGET),i386)
+FPCCPUOPT:=-OG2p3
+endif
+ifeq ($(CPU_TARGET),powerpc)
+FPCCPUOPT:=-O1r
+endif
+else
+FPCCPUOPT:=-O2
+endif
+override FPCOPT+=-Ur -Xs $(FPCCPUOPT) -n
+override FPCOPTDEF+=RELEASE
+endif
+ifdef STRIP
+override FPCOPT+=-Xs
+endif
+ifdef OPTIMIZE
+override FPCOPT+=-O2
+endif
+ifdef VERBOSE
+override FPCOPT+=-vwni
+endif
+ifdef COMPILER_OPTIONS
+override FPCOPT+=$(COMPILER_OPTIONS)
+endif
+ifdef COMPILER_UNITDIR
+override FPCOPT+=$(addprefix -Fu,$(COMPILER_UNITDIR))
+endif
+ifdef COMPILER_LIBRARYDIR
+override FPCOPT+=$(addprefix -Fl,$(COMPILER_LIBRARYDIR))
+endif
+ifdef COMPILER_OBJECTDIR
+override FPCOPT+=$(addprefix -Fo,$(COMPILER_OBJECTDIR))
+endif
+ifdef COMPILER_INCLUDEDIR
+override FPCOPT+=$(addprefix -Fi,$(COMPILER_INCLUDEDIR))
+endif
+ifdef CROSSBINDIR
+override FPCOPT+=-FD$(CROSSBINDIR)
+endif
+ifdef COMPILER_TARGETDIR
+override FPCOPT+=-FE$(COMPILER_TARGETDIR)
+ifeq ($(COMPILER_TARGETDIR),.)
+override TARGETDIRPREFIX=
+else
+override TARGETDIRPREFIX=$(COMPILER_TARGETDIR)/
+endif
+endif
+ifdef COMPILER_UNITTARGETDIR
+override FPCOPT+=-FU$(COMPILER_UNITTARGETDIR)
+ifeq ($(COMPILER_UNITTARGETDIR),.)
+override UNITTARGETDIRPREFIX=
+else
+override UNITTARGETDIRPREFIX=$(COMPILER_UNITTARGETDIR)/
+endif
+else
+ifdef COMPILER_TARGETDIR
+override COMPILER_UNITTARGETDIR=$(COMPILER_TARGETDIR)
+override UNITTARGETDIRPREFIX=$(TARGETDIRPREFIX)
+endif
+endif
+ifdef CREATESHARED
+override FPCOPT+=-Cg
+endif
+ifneq ($(findstring $(OS_TARGET),dragonfly freebsd openbsd netbsd linux solaris),)
+ifneq ($(findstring $(CPU_TARGET),x86_64 mips mipsel),)
+override FPCOPT+=-Cg
+endif
+endif
+ifdef LINKSHARED
+endif
+ifdef OPT
+override FPCOPT+=$(OPT)
+endif
+ifdef FPCOPTDEF
+override FPCOPT+=$(addprefix -d,$(FPCOPTDEF))
+endif
+ifdef CFGFILE
+override FPCOPT+=@$(CFGFILE)
+endif
+ifdef USEENV
+override FPCEXTCMD:=$(FPCOPT)
+override FPCOPT:=!FPCEXTCMD
+export FPCEXTCMD
+endif
+override AFULL_TARGET=$(CPU_TARGET)-$(OS_TARGET)
+override AFULL_SOURCE=$(CPU_SOURCE)-$(OS_SOURCE)
+ifneq ($(AFULL_TARGET),$(AFULL_SOURCE))
+override ACROSSCOMPILE=1
+endif
+ifdef ACROSSCOMPILE
+override FPCOPT+=$(CROSSOPT)
+endif
+override COMPILER:=$(strip $(FPC) $(FPCOPT))
+ifneq (,$(findstring -sh ,$(COMPILER)))
+UseEXECPPAS=1
+endif
+ifneq (,$(findstring -s ,$(COMPILER)))
+ifeq ($(FULL_SOURCE),$(FULL_TARGET))
+UseEXECPPAS=1
+endif
+endif
+ifneq ($(UseEXECPPAS),1)
+EXECPPAS=
+else
+ifdef RUNBATCH
+EXECPPAS:=@$(RUNBATCH) $(PPAS)
+else
+EXECPPAS:=@$(PPAS)
+endif
+endif
+.PHONY: fpc_exes
+ifndef CROSSINSTALL
+ifneq ($(TARGET_PROGRAMS),)
+override EXEFILES=$(addsuffix $(EXEEXT),$(TARGET_PROGRAMS))
+override EXEOFILES:=$(addsuffix $(OEXT),$(TARGET_PROGRAMS)) $(addprefix $(STATICLIBPREFIX),$(addsuffix $(STATICLIBEXT),$(TARGET_PROGRAMS))) $(addprefix $(IMPORTLIBPREFIX),$(addsuffix $(STATICLIBEXT),$(TARGET_PROGRAMS)))
+override EXEDBGFILES:=$(addsuffix $(EXEDBGEXT),$(TARGET_PROGRAMS))
+override ALLTARGET+=fpc_exes
+override INSTALLEXEFILES+=$(EXEFILES)
+override CLEANEXEFILES+=$(EXEFILES) $(EXEOFILES)
+override CLEANEXEDBGFILES+=$(EXEDBGFILES)
+ifeq ($(OS_TARGET),os2)
+override CLEANEXEFILES+=$(addsuffix $(AOUTEXT),$(TARGET_PROGRAMS))
+endif
+ifeq ($(OS_TARGET),emx)
+override CLEANEXEFILES+=$(addsuffix $(AOUTEXT),$(TARGET_PROGRAMS))
+endif
+endif
+endif
+fpc_exes: $(COMPILER_TARGETDIR) $(COMPILER_UNITTARGETDIR) $(EXEFILES)
+ifdef TARGET_RSTS
+override RSTFILES=$(addsuffix $(RSTEXT),$(TARGET_RSTS))
+override CLEANRSTFILES+=$(RSTFILES)
+endif
+.PHONY: fpc_all fpc_smart fpc_debug fpc_release fpc_shared
+$(FPCMADE): $(ALLDEPENDENCIES) $(ALLTARGET)
+	@$(ECHOREDIR) Compiled > $(FPCMADE)
+fpc_all: $(FPCMADE)
+fpc_smart:
+	$(MAKE) all LINKSMART=1 CREATESMART=1
+fpc_debug:
+	$(MAKE) all DEBUG=1
+fpc_release:
+	$(MAKE) all RELEASE=1
+.SUFFIXES: $(EXEEXT) $(PPUEXT) $(OEXT) .pas .lpr .dpr .pp .rc .res
+$(COMPILER_UNITTARGETDIR):
+	$(MKDIRTREE) $(COMPILER_UNITTARGETDIR)
+$(COMPILER_TARGETDIR):
+	$(MKDIRTREE) $(COMPILER_TARGETDIR)
+%$(PPUEXT): %.pp
+	$(COMPILER) $<
+	$(EXECPPAS)
+%$(PPUEXT): %.pas
+	$(COMPILER) $<
+	$(EXECPPAS)
+%$(EXEEXT): %.pp
+	$(COMPILER) $<
+	$(EXECPPAS)
+%$(EXEEXT): %.pas
+	$(COMPILER) $<
+	$(EXECPPAS)
+%$(EXEEXT): %.lpr
+	$(COMPILER) $<
+	$(EXECPPAS)
+%$(EXEEXT): %.dpr
+	$(COMPILER) $<
+	$(EXECPPAS)
+%.res: %.rc
+	windres -i $< -o $@
+vpath %.pp $(COMPILER_SOURCEDIR) $(COMPILER_INCLUDEDIR)
+vpath %.pas $(COMPILER_SOURCEDIR) $(COMPILER_INCLUDEDIR)
+vpath %.lpr $(COMPILER_SOURCEDIR) $(COMPILER_INCLUDEDIR)
+vpath %.dpr $(COMPILER_SOURCEDIR) $(COMPILER_INCLUDEDIR)
+vpath %.inc $(COMPILER_INCLUDEDIR)
+vpath %$(OEXT) $(COMPILER_UNITTARGETDIR)
+vpath %$(PPUEXT) $(COMPILER_UNITTARGETDIR)
+.PHONY: fpc_shared
+override INSTALLTARGET+=fpc_shared_install
+ifndef SHARED_LIBVERSION
+SHARED_LIBVERSION=$(FPC_VERSION)
+endif
+ifndef SHARED_LIBNAME
+SHARED_LIBNAME=$(PACKAGE_NAME)
+endif
+ifndef SHARED_FULLNAME
+SHARED_FULLNAME=$(SHAREDLIBPREFIX)$(SHARED_LIBNAME)-$(SHARED_LIBVERSION)$(SHAREDLIBEXT)
+endif
+ifndef SHARED_LIBUNITS
+SHARED_LIBUNITS:=$(TARGET_UNITS) $(TARGET_IMPLICITUNITS)
+override SHARED_LIBUNITS:=$(filter-out $(INSTALL_BUILDUNIT),$(SHARED_LIBUNITS))
+endif
+fpc_shared:
+ifdef HASSHAREDLIB
+	$(MAKE) all CREATESHARED=1 LINKSHARED=1 CREATESMART=1
+ifneq ($(SHARED_BUILD),n)
+	$(PPUMOVE) -q $(SHARED_LIBUNITS) -i$(COMPILER_UNITTARGETDIR) -o$(SHARED_FULLNAME) -d$(COMPILER_UNITTARGETDIR)
+endif
+else
+	@$(ECHO) Shared Libraries not supported
+endif
+fpc_shared_install:
+ifneq ($(SHARED_BUILD),n)
+ifneq ($(SHARED_LIBUNITS),)
+ifneq ($(wildcard $(COMPILER_UNITTARGETDIR)/$(SHARED_FULLNAME)),)
+	$(INSTALL) $(COMPILER_UNITTARGETDIR)/$(SHARED_FULLNAME) $(INSTALL_SHAREDDIR)
+endif
+endif
+endif
+.PHONY: fpc_install fpc_sourceinstall fpc_exampleinstall
+ifdef INSTALL_UNITS
+override INSTALLPPUFILES+=$(addsuffix $(PPUEXT),$(INSTALL_UNITS))
+endif
+ifdef INSTALL_BUILDUNIT
+override INSTALLPPUFILES:=$(filter-out $(INSTALL_BUILDUNIT)$(PPUEXT),$(INSTALLPPUFILES))
+endif
+ifdef INSTALLPPUFILES
+override INSTALLPPULINKFILES:=$(subst $(PPUEXT),$(OEXT),$(INSTALLPPUFILES)) $(addprefix $(STATICLIBPREFIX),$(subst $(PPUEXT),$(STATICLIBEXT),$(INSTALLPPUFILES))) $(addprefix $(IMPORTLIBPREFIX),$(subst $(PPUEXT),$(STATICLIBEXT),$(INSTALLPPUFILES)))
+ifneq ($(UNITTARGETDIRPREFIX),)
+override INSTALLPPUFILES:=$(addprefix $(UNITTARGETDIRPREFIX),$(notdir $(INSTALLPPUFILES)))
+override INSTALLPPULINKFILES:=$(wildcard $(addprefix $(UNITTARGETDIRPREFIX),$(notdir $(INSTALLPPULINKFILES))))
+endif
+override INSTALL_CREATEPACKAGEFPC=1
+endif
+ifdef INSTALLEXEFILES
+ifneq ($(TARGETDIRPREFIX),)
+override INSTALLEXEFILES:=$(addprefix $(TARGETDIRPREFIX),$(notdir $(INSTALLEXEFILES)))
+endif
+endif
+fpc_install: all $(INSTALLTARGET)
+ifdef INSTALLEXEFILES
+	$(MKDIR) $(INSTALL_BINDIR)
+	$(INSTALLEXE) $(INSTALLEXEFILES) $(INSTALL_BINDIR)
+endif
+ifdef INSTALL_CREATEPACKAGEFPC
+ifdef FPCMAKE
+ifdef PACKAGE_VERSION
+ifneq ($(wildcard Makefile.fpc),)
+	$(FPCMAKE) -p -T$(CPU_TARGET)-$(OS_TARGET) Makefile.fpc
+	$(MKDIR) $(INSTALL_UNITDIR)
+	$(INSTALL) Package.fpc $(INSTALL_UNITDIR)
+endif
+endif
+endif
+endif
+ifdef INSTALLPPUFILES
+	$(MKDIR) $(INSTALL_UNITDIR)
+	$(INSTALL) $(INSTALLPPUFILES) $(INSTALL_UNITDIR)
+ifneq ($(INSTALLPPULINKFILES),)
+	$(INSTALL) $(INSTALLPPULINKFILES) $(INSTALL_UNITDIR)
+endif
+ifneq ($(wildcard $(LIB_FULLNAME)),)
+	$(MKDIR) $(INSTALL_LIBDIR)
+	$(INSTALL) $(LIB_FULLNAME) $(INSTALL_LIBDIR)
+ifdef inUnix
+	ln -sf $(LIB_FULLNAME) $(INSTALL_LIBDIR)/$(LIB_NAME)
+endif
+endif
+endif
+ifdef INSTALL_FILES
+	$(MKDIR) $(INSTALL_DATADIR)
+	$(INSTALL) $(INSTALL_FILES) $(INSTALL_DATADIR)
+endif
+fpc_sourceinstall: distclean
+	$(MKDIR) $(INSTALL_SOURCEDIR)
+	$(COPYTREE) $(BASEDIR)/* $(INSTALL_SOURCEDIR)
+fpc_exampleinstall: $(addsuffix _distclean,$(TARGET_EXAMPLEDIRS))
+ifdef HASEXAMPLES
+	$(MKDIR) $(INSTALL_EXAMPLEDIR)
+endif
+ifdef EXAMPLESOURCEFILES
+	$(COPY) $(EXAMPLESOURCEFILES) $(INSTALL_EXAMPLEDIR)
+endif
+ifdef TARGET_EXAMPLEDIRS
+	$(COPYTREE) $(addsuffix /*,$(TARGET_EXAMPLEDIRS)) $(INSTALL_EXAMPLEDIR)
+endif
+.PHONY: fpc_clean fpc_cleanall fpc_distclean
+ifdef EXEFILES
+override CLEANEXEFILES:=$(addprefix $(TARGETDIRPREFIX),$(CLEANEXEFILES))
+override CLEANEXEDBGFILES:=$(addprefix $(TARGETDIRPREFIX),$(CLEANEXEDBGFILES))
+endif
+ifdef CLEAN_PROGRAMS
+override CLEANEXEFILES+=$(addprefix $(TARGETDIRPREFIX),$(addsuffix $(EXEEXT), $(CLEAN_PROGRAMS)))
+override CLEANEXEDBGFILES+=$(addprefix $(TARGETDIRPREFIX),$(addsuffix $(EXEDBGEXT), $(CLEAN_PROGRAMS)))
+endif
+ifdef CLEAN_UNITS
+override CLEANPPUFILES+=$(addsuffix $(PPUEXT),$(CLEAN_UNITS))
+endif
+ifdef CLEANPPUFILES
+override CLEANPPULINKFILES:=$(subst $(PPUEXT),$(OEXT),$(CLEANPPUFILES)) $(addprefix $(STATICLIBPREFIX),$(subst $(PPUEXT),$(STATICLIBEXT),$(CLEANPPUFILES))) $(addprefix $(IMPORTLIBPREFIX),$(subst $(PPUEXT),$(STATICLIBEXT),$(CLEANPPUFILES)))
+ifdef DEBUGSYMEXT
+override CLEANPPULINKFILES+=$(subst $(PPUEXT),$(DEBUGSYMEXT),$(CLEANPPUFILES))
+endif
+override CLEANPPUFILES:=$(addprefix $(UNITTARGETDIRPREFIX),$(CLEANPPUFILES))
+override CLEANPPULINKFILES:=$(wildcard $(addprefix $(UNITTARGETDIRPREFIX),$(CLEANPPULINKFILES)))
+endif
+fpc_clean: $(CLEANTARGET)
+ifdef CLEANEXEFILES
+	-$(DEL) $(CLEANEXEFILES)
+endif
+ifdef CLEANEXEDBGFILES
+	-$(DELTREE) $(CLEANEXEDBGFILES)
+endif
+ifdef CLEANPPUFILES
+	-$(DEL) $(CLEANPPUFILES)
+endif
+ifneq ($(CLEANPPULINKFILES),)
+	-$(DEL) $(CLEANPPULINKFILES)
+endif
+ifdef CLEANRSTFILES
+	-$(DEL) $(addprefix $(UNITTARGETDIRPREFIX),$(CLEANRSTFILES))
+endif
+ifdef CLEAN_FILES
+	-$(DEL) $(CLEAN_FILES)
+endif
+ifdef LIB_NAME
+	-$(DEL) $(LIB_NAME) $(LIB_FULLNAME)
+endif
+	-$(DEL) $(FPCMADE) Package.fpc $(PPAS) script.res link.res $(FPCEXTFILE) $(REDIRFILE)
+	-$(DEL) *$(ASMEXT) *_ppas$(BATCHEXT)
+fpc_cleanall: $(CLEANTARGET)
+ifdef CLEANEXEFILES
+	-$(DEL) $(CLEANEXEFILES)
+endif
+ifdef COMPILER_UNITTARGETDIR
+ifdef CLEANPPUFILES
+	-$(DEL) $(CLEANPPUFILES)
+endif
+ifneq ($(CLEANPPULINKFILES),)
+	-$(DEL) $(CLEANPPULINKFILES)
+endif
+ifdef CLEANRSTFILES
+	-$(DEL) $(addprefix $(UNITTARGETDIRPREFIX),$(CLEANRSTFILES))
+endif
+endif
+ifdef CLEAN_FILES
+	-$(DEL) $(CLEAN_FILES)
+endif
+	-$(DELTREE) units
+	-$(DEL) *$(OEXT) *$(PPUEXT) *$(RSTEXT) *$(ASMEXT) *$(STATICLIBEXT) *$(SHAREDLIBEXT) *$(PPLEXT)
+ifneq ($(PPUEXT),.ppu)
+	-$(DEL) *.o *.ppu *.a
+endif
+	-$(DELTREE) *$(SMARTEXT)
+	-$(DEL) fpcmade.* Package.fpc $(PPAS) script.res link.res $(FPCEXTFILE) $(REDIRFILE)
+	-$(DEL) *_ppas$(BATCHEXT)
+ifdef AOUTEXT
+	-$(DEL) *$(AOUTEXT)
+endif
+ifdef DEBUGSYMEXT
+	-$(DEL) *$(DEBUGSYMEXT)
+endif
+fpc_distclean: cleanall
+.PHONY: fpc_baseinfo
+override INFORULES+=fpc_baseinfo
+fpc_baseinfo:
+	@$(ECHO)
+	@$(ECHO)  == Package info ==
+	@$(ECHO)  Package Name..... $(PACKAGE_NAME)
+	@$(ECHO)  Package Version.. $(PACKAGE_VERSION)
+	@$(ECHO)
+	@$(ECHO)  == Configuration info ==
+	@$(ECHO)
+	@$(ECHO)  FPC.......... $(FPC)
+	@$(ECHO)  FPC Version.. $(FPC_VERSION)
+	@$(ECHO)  Source CPU... $(CPU_SOURCE)
+	@$(ECHO)  Target CPU... $(CPU_TARGET)
+	@$(ECHO)  Source OS.... $(OS_SOURCE)
+	@$(ECHO)  Target OS.... $(OS_TARGET)
+	@$(ECHO)  Full Source.. $(FULL_SOURCE)
+	@$(ECHO)  Full Target.. $(FULL_TARGET)
+	@$(ECHO)  SourceSuffix. $(SOURCESUFFIX)
+	@$(ECHO)  TargetSuffix. $(TARGETSUFFIX)
+	@$(ECHO)  FPC fpmake... $(FPCFPMAKE)
+	@$(ECHO)
+	@$(ECHO)  == Directory info ==
+	@$(ECHO)
+	@$(ECHO)  Required pkgs... $(REQUIRE_PACKAGES)
+	@$(ECHO)
+	@$(ECHO)  Basedir......... $(BASEDIR)
+	@$(ECHO)  FPCDir.......... $(FPCDIR)
+	@$(ECHO)  CrossBinDir..... $(CROSSBINDIR)
+	@$(ECHO)  UnitsDir........ $(UNITSDIR)
+	@$(ECHO)  PackagesDir..... $(PACKAGESDIR)
+	@$(ECHO)
+	@$(ECHO)  GCC library..... $(GCCLIBDIR)
+	@$(ECHO)  Other library... $(OTHERLIBDIR)
+	@$(ECHO)
+	@$(ECHO)  == Tools info ==
+	@$(ECHO)
+	@$(ECHO)  As........ $(AS)
+	@$(ECHO)  Ld........ $(LD)
+	@$(ECHO)  Ar........ $(AR)
+	@$(ECHO)  Rc........ $(RC)
+	@$(ECHO)
+	@$(ECHO)  Mv........ $(MVPROG)
+	@$(ECHO)  Cp........ $(CPPROG)
+	@$(ECHO)  Rm........ $(RMPROG)
+	@$(ECHO)  GInstall.. $(GINSTALL)
+	@$(ECHO)  Echo...... $(ECHO)
+	@$(ECHO)  Shell..... $(SHELL)
+	@$(ECHO)  Date...... $(DATE)
+	@$(ECHO)  FPCMake... $(FPCMAKE)
+	@$(ECHO)  PPUMove... $(PPUMOVE)
+	@$(ECHO)  Zip....... $(ZIPPROG)
+	@$(ECHO)
+	@$(ECHO)  == Object info ==
+	@$(ECHO)
+	@$(ECHO)  Target Loaders........ $(TARGET_LOADERS)
+	@$(ECHO)  Target Units.......... $(TARGET_UNITS)
+	@$(ECHO)  Target Implicit Units. $(TARGET_IMPLICITUNITS)
+	@$(ECHO)  Target Programs....... $(TARGET_PROGRAMS)
+	@$(ECHO)  Target Dirs........... $(TARGET_DIRS)
+	@$(ECHO)  Target Examples....... $(TARGET_EXAMPLES)
+	@$(ECHO)  Target ExampleDirs.... $(TARGET_EXAMPLEDIRS)
+	@$(ECHO)
+	@$(ECHO)  Clean Units......... $(CLEAN_UNITS)
+	@$(ECHO)  Clean Files......... $(CLEAN_FILES)
+	@$(ECHO)
+	@$(ECHO)  Install Units....... $(INSTALL_UNITS)
+	@$(ECHO)  Install Files....... $(INSTALL_FILES)
+	@$(ECHO)
+	@$(ECHO)  == Install info ==
+	@$(ECHO)
+	@$(ECHO)  DateStr.............. $(DATESTR)
+	@$(ECHO)  ZipName.............. $(ZIPNAME)
+	@$(ECHO)  ZipPrefix............ $(ZIPPREFIX)
+	@$(ECHO)  ZipCrossPrefix....... $(ZIPCROSSPREFIX)
+	@$(ECHO)  ZipSuffix............ $(ZIPSUFFIX)
+	@$(ECHO)  FullZipName.......... $(FULLZIPNAME)
+	@$(ECHO)  Install FPC Package.. $(INSTALL_FPCPACKAGE)
+	@$(ECHO)
+	@$(ECHO)  Install base dir..... $(INSTALL_BASEDIR)
+	@$(ECHO)  Install binary dir... $(INSTALL_BINDIR)
+	@$(ECHO)  Install library dir.. $(INSTALL_LIBDIR)
+	@$(ECHO)  Install units dir.... $(INSTALL_UNITDIR)
+	@$(ECHO)  Install source dir... $(INSTALL_SOURCEDIR)
+	@$(ECHO)  Install doc dir...... $(INSTALL_DOCDIR)
+	@$(ECHO)  Install example dir.. $(INSTALL_EXAMPLEDIR)
+	@$(ECHO)  Install data dir..... $(INSTALL_DATADIR)
+	@$(ECHO)
+	@$(ECHO)  Dist destination dir. $(DIST_DESTDIR)
+	@$(ECHO)  Dist zip name........ $(DIST_ZIPNAME)
+	@$(ECHO)
+.PHONY: fpc_info
+fpc_info: $(INFORULES)
+.PHONY: fpc_makefile fpc_makefiles fpc_makefile_sub1 fpc_makefile_sub2 \
+	fpc_makefile_dirs
+fpc_makefile:
+	$(FPCMAKE) -w -T$(OS_TARGET) Makefile.fpc
+fpc_makefile_sub1:
+ifdef TARGET_DIRS
+	$(FPCMAKE) -w -T$(OS_TARGET) $(addsuffix /Makefile.fpc,$(TARGET_DIRS))
+endif
+ifdef TARGET_EXAMPLEDIRS
+	$(FPCMAKE) -w -T$(OS_TARGET) $(addsuffix /Makefile.fpc,$(TARGET_EXAMPLEDIRS))
+endif
+fpc_makefile_sub2: $(addsuffix _makefile_dirs,$(TARGET_DIRS) $(TARGET_EXAMPLEDIRS))
+fpc_makefile_dirs: fpc_makefile_sub1 fpc_makefile_sub2
+fpc_makefiles: fpc_makefile fpc_makefile_dirs
+ifndef BIN2S
+BIN2S:=$(strip $(wildcard $(addsuffix /bin2s$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(BIN2S),)
+BIN2S= __missing_command_BIN2S
+else
+BIN2S:=$(firstword $(BIN2S))
+endif
+endif
+export BIN2S
+ifndef MMUTIL
+MMUTIL:=$(strip $(wildcard $(addsuffix /mmutil$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(MMUTIL),)
+MMUTIL= __missing_command_MMUTIL
+else
+MMUTIL:=$(firstword $(MMUTIL))
+endif
+endif
+export MMUTIL
+ifndef GRIT_FPC
+GRIT_FPC:=$(strip $(wildcard $(addsuffix /grit_fpc$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(GRIT_FPC),)
+GRIT_FPC= __missing_command_GRIT_FPC
+else
+GRIT_FPC:=$(firstword $(GRIT_FPC))
+endif
+endif
+export GRIT_FPC
+ifndef RMDIR
+RMDIR:=$(strip $(wildcard $(addsuffix /rmdir$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(RMDIR),)
+RMDIR= __missing_command_RMDIR
+else
+RMDIR:=$(firstword $(RMDIR))
+endif
+endif
+export RMDIR
+ifndef MV
+MV:=$(strip $(wildcard $(addsuffix /mv$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(MV),)
+MV= __missing_command_MV
+else
+MV:=$(firstword $(MV))
+endif
+endif
+export MV
+ifndef NDSTOOL
+NDSTOOL:=$(strip $(wildcard $(addsuffix /ndstool$(SRCEXEEXT),$(SEARCHPATH))))
+ifeq ($(NDSTOOL),)
+NDSTOOL= __missing_command_NDSTOOL
+else
+NDSTOOL:=$(firstword $(NDSTOOL))
+endif
+endif
+export NDSTOOL
+debug: fpc_debug
+smart: fpc_smart
+release: fpc_release
+units: fpc_units
+examples:
+shared: fpc_shared
+install: fpc_install
+sourceinstall: fpc_sourceinstall
+exampleinstall: fpc_exampleinstall
+distinstall:
+zipinstall:
+zipsourceinstall:
+zipexampleinstall:
+zipdistinstall:
+distclean: fpc_distclean
+cleanall: fpc_cleanall
+info: fpc_info
+makefiles: fpc_makefiles
+.PHONY: debug smart release units examples shared install sourceinstall exampleinstall distinstall zipinstall zipsourceinstall zipexampleinstall zipdistinstall distclean cleanall info makefiles
+ifneq ($(wildcard fpcmake.loc),)
+include fpcmake.loc
+endif
+.NOTPARALLEL:
+clean: dir_delete fpc_clean fpc_cleanall
+all: dir_make $(BIN_FILES) $(GFX_FILES) fpc_all 
+filesystem: all make_filesystem
+dir_delete:
+	@$(DELTREE) $(CURDIR)/$(BUILD) 
+	@$(DELTREE) $(CURDIR)/$(INC) 
+	@$(DELTREE) $(CURDIR)/$(BIN) 
+dir_make:
+ifneq ($(BUILD), $(CURDIR))
+	@$(MKDIR) $(BUILD)
+endif
+ifneq ($(INC), $(CURDIR))
+	@$(MKDIR) $(INC)
+endif
+ifneq ($(BIN), $(CURDIR))
+	@$(MKDIR) $(BIN)
+endif
+soundbank.bin.o : $(AUDIO_FILES)
+	@$(MMUTIL) $^ -d -o$(BUILD)/soundbank.bin -h$(BUILD)/soundbank.h
+	$(BIN2S) $(BUILD)/soundbank.bin > $(BUILD)/soundbank.bin.s
+	$(AS) -o $(BUILD)/soundbank.bin.o $(BUILD)/soundbank.bin.s
+$(GFX_FILES): $(wildcard %.bmp %.png)
+	@echo 'Converting $(@) file to asm...'
+	$(GRIT_FPC) $(GFX)/$(@) -fp -fts -ff $(GFX)/$(basename $(@)).grit -o$(BUILD)/$(@)
+	@echo 'Assembling $(@).s file...'
+	$(AS) -o $(BUILD)/$(basename $(@)).o $(BUILD)/$(basename $(@)).s
+	$(MV) -f $(BUILD)/$(basename $(@)).inc $(INC)/$(basename $(@)).inc           
+	@echo 'Done!'
+$(BIN_FILES): $(wildcard %.*)
+	@echo 'Converting $(@) file to asm...'
+	@$(BIN2S) $(DATA)/$(@) > $(BUILD)/$(@).s
+	@echo 'Creating $(@).inc include file...'
+	@echo "var" > `(echo "$(INC)/"$(@F) | tr . .)`.inc
+	@echo " " `(echo $(@F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"_end: array [0..0] of cuint8; cvar; external;" >> `(echo "$(INC)/"$(@F) | tr . .)`.inc
+	@echo " " `(echo $(@F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`": array [0..0] of cuint8; cvar; external;" >> `(echo "$(INC)/"$(@F) | tr . .)`.inc
+	@echo " " `(echo $(@F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`_size": cuint32; cvar; external;" >> `(echo "$(INC)/"$(@F) | tr . .)`.inc
+	@echo 'Assembling $(@).s file...'
+	@$(AS) -o $(BUILD)/$(@).o $(BUILD)/$(@).s
+	@echo 'Done!'
+data.gbfs.o:
+	@cd GBFS && gbfs ../$(BUILD)/data.gbfs $(GBFS_FILES)
+	$(BIN2S) $(BUILD)/data.gbfs > $(BUILD)/data.gbfs.s
+	$(AS) -o $(BUILD)/data.gbfs.o $(BUILD)/data.gbfs.s
+make_filesystem:
+	@$(NDSTOOL) -c $(BIN)/$(TARGET_PROGRAMS).fs.nds -9 $(BIN)/$(TARGET_PROGRAMS).nef.bin -d $(CURDIR)/$(FILESYSTEM)

+ 124 - 0
packages/libndsfpc/examples/graphics/grit/256colorTilemap/Makefile.fpc

@@ -0,0 +1,124 @@
+#
+#   Makefile.fpc for Free Pascal libndsfpc 2.x.y Examples
+#
+
+[target]
+loaders= 
+programs=tilemap_256_color
+
+[require]
+packages=libndsfpc
+tools=bin2s mmutil grit_fpc rmdir mv ndstool
+nortl=y
+
+[install]
+fpcpackage=y
+
+[default]
+cpu=arm
+target=nds
+fpcdir=../../../../../..
+
+[compiler]
+options=-Xm
+targetdir=$(BIN)  
+unittargetdir=$(BUILD)
+
+[clean]
+files=*.elf *.o *.s *.nds *.nef *.h *.bin *.map \
+       $(BUILD)/* \
+       $(INC)/* \
+       $(BIN)/*
+units=*
+
+
+[prerules]
+BIN = bin
+BUILD = build
+DATA = data
+FILESYSTEM = filesystem
+GFX = gfx
+INC = inc
+AUDIO_FILES = $(foreach dir, $(notdir $(wildcard audio/*.*)), $(CURDIR)/audio/$(dir))
+GFX_FILES   = $(foreach dir, $(GFX), $(notdir $(wildcard $(dir)/*.bmp $(dir)/*.png)))
+BIN_FILES   = $(foreach dir, $(DATA), $(notdir $(wildcard $(dir)/*)))
+GBFS_FILES  = $(foreach dir, GBFS, $(notdir $(wildcard $(dir)/*)))
+
+[rules]
+.NOTPARALLEL:
+clean: dir_delete fpc_clean fpc_cleanall
+all: dir_make $(BIN_FILES) $(GFX_FILES) fpc_all 
+filesystem: all make_filesystem
+
+
+
+#
+# Delete temp directories
+#
+dir_delete:
+        @$(DELTREE) $(CURDIR)/$(BUILD) 
+        @$(DELTREE) $(CURDIR)/$(INC) 
+        @$(DELTREE) $(CURDIR)/$(BIN) 
+                
+#
+# Create temp directories
+#
+dir_make:
+ifneq ($(BUILD), $(CURDIR))
+        @$(MKDIR) $(BUILD)
+endif
+ifneq ($(INC), $(CURDIR))
+        @$(MKDIR) $(INC)
+endif
+ifneq ($(BIN), $(CURDIR))
+        @$(MKDIR) $(BIN)
+endif
+
+#
+# Audio files processing rule
+#
+soundbank.bin.o : $(AUDIO_FILES)
+        @$(MMUTIL) $^ -d -o$(BUILD)/soundbank.bin -h$(BUILD)/soundbank.h
+        $(BIN2S) $(BUILD)/soundbank.bin > $(BUILD)/soundbank.bin.s
+        $(AS) -o $(BUILD)/soundbank.bin.o $(BUILD)/soundbank.bin.s
+
+#
+# Png files processing rule
+#
+$(GFX_FILES): $(wildcard %.bmp %.png)
+        @echo 'Converting $(@) file to asm...'
+        $(GRIT_FPC) $(GFX)/$(@) -fp -fts -ff $(GFX)/$(basename $(@)).grit -o$(BUILD)/$(@)
+        @echo 'Assembling $(@).s file...'
+        $(AS) -o $(BUILD)/$(basename $(@)).o $(BUILD)/$(basename $(@)).s
+        $(MV) -f $(BUILD)/$(basename $(@)).inc $(INC)/$(basename $(@)).inc           
+        @echo 'Done!'
+
+#
+# Binary files processing rule
+# 
+$(BIN_FILES): $(wildcard %.*)
+        @echo 'Converting $(@) file to asm...'
+        @$(BIN2S) $(DATA)/$(@) > $(BUILD)/$(@).s
+        @echo 'Creating $(@).inc include file...'
+        @echo "var" > `(echo "$(INC)/"$(@F) | tr . .)`.inc
+        @echo " " `(echo $(@F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"_end: array [0..0] of cuint8; cvar; external;" >> `(echo "$(INC)/"$(@F) | tr . .)`.inc
+        @echo " " `(echo $(@F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`": array [0..0] of cuint8; cvar; external;" >> `(echo "$(INC)/"$(@F) | tr . .)`.inc
+        @echo " " `(echo $(@F) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`_size": cuint32; cvar; external;" >> `(echo "$(INC)/"$(@F) | tr . .)`.inc
+        @echo 'Assembling $(@).s file...'
+        @$(AS) -o $(BUILD)/$(@).o $(BUILD)/$(@).s
+        @echo 'Done!'
+
+
+#
+# GBFS files processing rule
+#
+data.gbfs.o:
+        @cd GBFS && gbfs ../$(BUILD)/data.gbfs $(GBFS_FILES)
+        $(BIN2S) $(BUILD)/data.gbfs > $(BUILD)/data.gbfs.s
+        $(AS) -o $(BUILD)/data.gbfs.o $(BUILD)/data.gbfs.s
+
+#
+# Nitro Filesystem processing rule
+# 
+make_filesystem:
+	@$(NDSTOOL) -c $(BIN)/$(TARGET_PROGRAMS).fs.nds -9 $(BIN)/$(TARGET_PROGRAMS).nef.bin -d $(CURDIR)/$(FILESYSTEM)

+ 21 - 0
packages/libndsfpc/examples/graphics/grit/256colorTilemap/gfx/tilemap.grit

@@ -0,0 +1,21 @@
+#-------------------------------------------------------
+# graphics in tile format
+#-------------------------------------------------------
+-gt
+
+#-------------------------------------------------------
+# tile reduction by tiles, palette and hflip/vflip
+#-------------------------------------------------------
+-mRtf
+
+#-------------------------------------------------------
+# graphics bit depth is 8 (256 color)
+#-------------------------------------------------------
+-gB8
+
+-p
+
+#-------------------------------------------------------
+# map layout standard bg format
+#-------------------------------------------------------
+-mLs

BIN
packages/libndsfpc/examples/graphics/grit/256colorTilemap/gfx/tilemap.png


+ 39 - 0
packages/libndsfpc/examples/graphics/grit/256colorTilemap/tilemap_256_color.pp

@@ -0,0 +1,39 @@
+program tilemap;
+
+{$L build/tilemap.o}
+
+{$mode objfpc}
+
+uses
+  ctypes, nds9;
+
+{$include inc/tilemap.inc}
+
+
+begin
+
+	// enable the main screen with background 0 active
+	videoSetMode(MODE_0_2D or DISPLAY_BG0_ACTIVE);
+
+	// map bank A for use with the background
+	vramSetBankA(VRAM_A_MAIN_BG);
+
+	// enable background 0 in 256 color mode with a 256x256 map
+	// BG_TILE_BASE changes the offset where tile data is stored
+	// BG_MAP_BASE gives the offset to the map data
+	BGCTRL[0] := BG_TILE_BASE(1) or BG_MAP_BASE(0) or BG_COLOR_256 or BG_32x32;
+
+	// use dma to copy the tile, map and palette data to VRAM
+	// CHAR_BASE_BLOCK gives us the actual address of the tile data
+	// SCREEN_BASE_BLOCK does the same thing for maps
+	// these should match the BG_TILE_BASE and BG_MAP base numbers above
+	dmaCopy(@tilemapTiles, CHAR_BASE_BLOCK(1), tilemapTilesLen);
+	dmaCopy(@tilemapMap, SCREEN_BASE_BLOCK(0), tilemapMapLen);
+	dmaCopy(@tilemapPal, BG_PALETTE, tilemapPalLen);
+ 
+	// finally, hang around in an infinite loop
+	// using swiWaitForVBlank here puts the DS into a low power loop
+	while true do
+		swiWaitForVBlank();
+
+end.

+ 18 - 0
packages/libndsfpc/examples/graphics/grit/Makefile.fpc

@@ -0,0 +1,18 @@
+#
+#   Makefile.fpc for Free Pascal libndsfpc 2.x.y Examples
+#
+
+[target]
+dirs=256colorTilemap
+
+[require]
+packages=libndsfpc
+
+[install]
+fpcpackage=y
+
+[default]
+fpcdir=../../../../..
+
+[rules]
+.NOTPARALLEL:

+ 15 - 1
packages/libndsfpc/examples/hello_world/helloWorld.pp

@@ -9,6 +9,12 @@ var
   frame: integer;
 	touchXY: touchPosition;
 
+  REG_DIVPCNT       : pcuint8 = pointer($4000280);
+  DIV_NUMER   : pcuint32 = pointer($4000290);
+  DIV_DENOM : pcuint32 = pointer($4000298);
+  DIV_RESULT : pcuint32 = pointer($40002A0);
+  DIVREM_RESULT : pcuint32 = pointer($40002A8);
+
 procedure Vblank();
 begin
   inc(frame);
@@ -19,7 +25,15 @@ begin
   irqSet(IRQ_VBLANK, @Vblank);
 
 	consoleDemoInit();
-
+  iprintf('%i div %i'#10, DIV_NUMER^, DIV_DENOM^ );
+  iprintf('%i, %i'#10, DIV_RESULT^, DIVREM_RESULT^);
+  
+  DIV_NUMER^ := 5;
+  DIV_DENOM^ := 0;  
+  iprintf('%i div %i'#10, DIV_NUMER^, DIV_DENOM^ );
+
+  iprintf('%i'#10,DIV_RESULT^ );
+  iprintf('%i'#10,DIVREM_RESULT^ );
 	iprintf('      Hello DS dev''rs'#10);
 	iprintf(#27'[32m' + 'www.devkitpro.org'#10);
 	iprintf(#27'[32;1m' + 'www.drunkencoders.com'#27'[39m');

+ 1 - 1
packages/libndsfpc/examples/time/RealTimeClock/Makefile.fpc

@@ -4,7 +4,7 @@
 
 [target]
 loaders=
-programs=RealTimeClock
+programs=realtimeclock
 
 [require]
 packages=libndsfpc

+ 2 - 2
packages/libndsfpc/src/dswifi/inc/dswifi9.inc

@@ -51,8 +51,8 @@
 const
   WIFIINIT_OPTION_USELED          = $0002;
 
-  WIFIINIT_OPTION_USEHEAP_128     = $0000;
-  WIFIINIT_OPTION_USEHEAP_64      = $1000;
+  WIFIINIT_OPTION_USEHEAP_64      = $0000;
+  WIFIINIT_OPTION_USEHEAP_128     = $1000;
   WIFIINIT_OPTION_USEHEAP_256     = $2000;
   WIFIINIT_OPTION_USEHEAP_512     = $3000;
   WIFIINIT_OPTION_USECUSTOMALLOC  = $4000;

+ 2 - 1
packages/libndsfpc/src/fat/fat.inc

@@ -60,7 +60,8 @@ const
 // Methods to modify DOS File Attributes
 
 function FAT_getAttr(const _file: pcchar): cint; cdecl; external;
-function FAT_setAttr(const _file: pcchar; attr: cint): cint; cdecl; external;
+function FAT_setAttr(const _file: pcchar; attr: cuint8): cint; cdecl; external;
+
 
 {$define LIBFAT_FEOS_MULTICWD}
 

+ 3 - 0
packages/libndsfpc/src/fat/gbfs.pp

@@ -1,4 +1,7 @@
 unit gbfs;
+
+{$error  gbfs is no longer supported on  nds}
+
 {$mode objfpc} 
 {$apptype arm9}
 {$define arm9}

+ 76 - 0
packages/libndsfpc/src/nds/arm7/aes.inc

@@ -0,0 +1,76 @@
+{$ifdef NDS_INTERFACE}
+type
+  _aes_keyslot = packed record
+	normalkey: array [0..15] of pcuint8;
+	key_x: array [0..15] of pcuint8;
+	key_y: array [0..15] of pcuint8;
+  end; 
+  aes_keyslot_t = _aes_keyslot;
+  Taes_keyslot_t = aes_keyslot_t;
+  Paes_keyslot_t = ^Taes_keyslot_t;
+
+
+const 
+  REG_AES_CNT: pcuint32  = pointer($04004400);
+  AES_WRFIFO_FLUSH = (1 shl 10);
+  AES_RDFIFO_FLUSH = (1 shl 11);
+
+function AES_CNT_DMA_WRITE_SIZE(size: cint): cint; inline;
+function AES_CNT_DMA_READ_SIZE(size: cint): cint; inline;
+
+function AES_CNT_CCM_SIZE(size: cint): cint; inline;
+
+const
+  AES_CCM_PASSTRHOUGH = (1 shl 19);
+  AES_CNT_KEY_APPLY = (1 shl 24);
+
+function AES_CNT_KEYSLOT(slot: cint): cint; inline;
+
+function AES_CNT_MODE(mode: cint): cint; inline;
+
+const
+  AES_CNT_IRQ       = (1 shl 30);
+  AES_CNT_ENABLE    = (1 shl 31);
+  
+  REG_AES_BLKCNT: pcuint32 = pointer($4004404);
+
+  REG_AES_WRFIFO: pcuint32 = pointer($4004408);
+  REG_AES_RDFIFO: pcuint32 = pointer($400440c);
+
+  REG_AES_IV: pcuint8 = pointer($4004420);
+  REG_AES_MAC: pcuint8 = pointer($4004430);
+
+  AES_KEYSLOT  :  Paes_keyslot_t = pointer($4004440);
+  AES_KEYSLOT0 :  Paes_keyslot_t = pointer($4004440);
+  AES_KEYSLOT1 :  Paes_keyslot_t = pointer($4004470);
+  AES_KEYSLOT2 :  Paes_keyslot_t = pointer($40044A0);
+  AES_KEYSLOT3 :  Paes_keyslot_t = pointer($40044D0);
+{$endif NDS_INTERFACE}
+
+{$ifdef NDS_IMPLEMENTATION}
+function AES_CNT_DMA_WRITE_SIZE(size: cint): cint; inline; 
+begin
+  AES_CNT_DMA_WRITE_SIZE := ((size and 3) shl 12);
+end;
+
+function AES_CNT_DMA_READ_SIZE(size: cint): cint; inline;  
+begin
+  AES_CNT_DMA_READ_SIZE := ((size and 3) shl 14);
+end;
+
+function AES_CNT_CCM_SIZE(size: cint): cint; inline;
+begin
+  AES_CNT_CCM_SIZE := ((size and 3) shl 16);
+end;
+
+function AES_CNT_KEYSLOT(slot: cint): cint; inline; 
+begin
+  AES_CNT_KEYSLOT := ((slot and 3) shl 26);
+end;
+
+function AES_CNT_MODE(mode: cint): cint; inline;
+begin
+  AES_CNT_MODE := ((mode and 3) shl 28);
+end;
+
+{$endif NDS_IMPLEMENTATION}

+ 46 - 0
packages/libndsfpc/src/nds/arm7/audio.inc

@@ -46,6 +46,37 @@ const
 type
   MIC_BUF_SWAP_CB = procedure(completedBuffer: pcuint8; length: cint);
 
+
+//---------------------------------------------------------------------------------
+// DSi Registers
+//---------------------------------------------------------------------------------
+const
+  REG_SNDEXTCNT : pcuint16 = pointer($04004700);
+  REG_MICCNT    : pcuint16 = pointer($04004600);
+  REG_MICDATA   : pcuint32 = pointer($04004604);
+
+function SNDEXTCNT_RATIO(n: cint): cint32; inline;
+const  
+  SNDEXTCNT_FREQ_32KHZ  = (0 shl 13); // output freq 32.73kHz
+  SNDEXTCNT_FREQ_47KHZ  = (1 shl 13); // output freq 47.61kHz
+  SNDEXTCNT_MUTE        = (1 shl 14);
+  SNDEXTCNT_ENABLE      = (1 shl 15);
+
+function MICCNT_FORMAT(n: cint): cint; inline;
+function MICCNT_FREQ_DIV(n: cint): cint; inline;
+
+const
+  MICCNT_EMPTY        = (1 shl 8);
+  MICCNT_NOT_EMPTY    = (1 shl 9);
+  MICCNT_MORE_DATA    = (1 shl 10);
+  MICCNT_OVERRUN      = (1 shl 11);
+  MICCNT_CLEAR_FIFO	  = (1 shl 12);
+  MICCNT_ENABLE_IRQ   = (1 shl 13);
+  MICCNT_ENABLE_IRQ2  = (1 shl 14);
+  MICCNT_ENABLE       = (1 shl 15);
+
+
+
 function micReadData8(): cuint8; cdecl; external;
 function micReadData12(): cuint16; cdecl; external;
 
@@ -125,4 +156,19 @@ procedure micOff(); inline;
 begin
   micSetAmp(PM_AMP_OFF, 0);
 end;
+
+function SNDEXTCNT_RATIO(n: cint): cint;  inline;
+begin
+  SNDEXTCNT_RATIO := (n and $F);
+end;
+
+function MICCNT_FORMAT(n: cint): cint; inline;
+begin
+  MICCNT_FORMAT := (n and 3); // unknown, always set to '2'
+end;
+
+function MICCNT_FREQ_DIV(n: cint): cint; inline;
+begin
+  MICCNT_FREQ_DIV := (n and 3) shl 2; // F/(n+1) where F is SNDEXTCNT output freq
+end;
 {$endif NDS_IMPLEMENTATION}

+ 2 - 2
packages/libndsfpc/src/nds/arm7/clock.inc

@@ -40,8 +40,8 @@ const
   WRITE_INT_REG1     = $68;
   READ_INT_REG1      = $69;
 
-  READ_INT_REG2      = $6A;
-  WRITE_INT_REG2     = $6B;
+  WRITE_INT_REG2      = $6A;
+  READ_INT_REG2       = $6B;
 
   READ_CLOCK_ADJUST_REG  = $6C;
   WRITE_CLOCK_ADJUST_REG = $6D;

+ 38 - 0
packages/libndsfpc/src/nds/arm7/codec.inc

@@ -0,0 +1,38 @@
+{$ifdef NDS_INTERFACE}
+{$ifndef ARM7}
+  {$error DSi TSC is only available on the ARM7}
+{$endif ARM7}
+
+function cdcIsAvailable(): boolean; inline;
+
+type
+  cdcBanks = integer;
+const
+  CDC_CONTROL: cdcBanks = $00; // Chip control
+  CDC_SOUND: cdcBanks = $01; // ADC/DAC control
+  CDC_TOUCHCNT: cdcBanks = $03; // TSC control
+  CDC_TOUCHDATA: cdcBanks = $FC; // TSC data buffer
+
+
+// Direct register functions
+function cdcReadReg(bank, reg: cuint8): cuint8; cdecl; external;
+procedure cdcReadRegArray(bank, reg: cuint8; data: pointer; size: cuint8); cdecl; external;
+procedure cdcWriteReg(bank, reg, value: cuint8); cdecl; external;
+procedure cdcWriteRegMask(bank, reg, mask, value: cuint8); cdecl; external;
+procedure cdcWriteRegArray(bank, reg: cuint8; data: pointer; size: cuint8); cdecl; external;
+
+// Touchscreen functions
+procedure cdcTouchInit(); cdecl; external;
+function cdcTouchPenDown(): cbool; cdecl; external;
+function cdcTouchRead(pos: PtouchPosition): cbool; cdecl; external;
+
+{$endif NDS_INTERFACE}
+
+{$ifdef NDS_IMPLEMENTATION}
+
+function cdcIsAvailable(): boolean; inline; 
+begin
+	cdcIsAvailable := isDSiMode() and ((__DSiHeader^.appflags and $01) <> 0);
+end;
+
+{$endif NDS_IMPLEMENTATION}

+ 25 - 3
packages/libndsfpc/src/nds/arm7/sdmmc.inc

@@ -120,18 +120,30 @@ type
     res: cuint32;
   end;
   mmcdevice = TMMCDevice;  
-  
 
-procedure sdmmc_controller_init(); cdecl; external;
+const
+  MMC_DEVICE_SDCARD = 0;
+  MMC_DEVICE_NAND = 1;  
+
+procedure sdmmc_controller_init(force_init: cbool); cdecl; external;
 procedure sdmmc_initirq(); cdecl; external;
 function sdmmc_cardinserted(): cint; cdecl; external;
 
 function sdmmc_sdcard_init(): cint; cdecl; external;
+
+function sdmmc_nand_init(): cint; cdecl; external;
+procedure sdmmc_get_cid(devicenumber: cint; cid: pcuint32); cdecl; external;
+
+procedure sdmmc_nand_cid(cid: pcuint32); inline; 
+procedure sdmmc_sdcard_cid(cid: pcuint32); inline; 
+
 function sdmmc_sdcard_readsectors(sector_no: cuint32; numsectors: cuint32; _out: pointer): cint; cdecl; external;
 function sdmmc_sdcard_writesectors(sector_no: cuint32; numsectors: cuint32; _in: pointer): cint; cdecl; external;
+function sdmmc_nand_readsectors(sector_no: cuint32; numsectors: cuint32; _out: pointer): cint; cdecl; external;
+function sdmmc_nand_writesectors(sector_no: cuint32; numsectors: cuint32; _in: pointer): cint; cdecl; external;
 
 
-var
+var                 
   sdmmc_curdevice: cint; cvar; external;
   sdmmc_cid: pcuint32; cvar; external;
 
@@ -183,5 +195,15 @@ begin
   sdmmc_mask16(REG_SDCLKCTL, $0, $100);
 end;
 
+procedure sdmmc_nand_cid(cid: pcuint32); inline; 
+begin
+    sdmmc_get_cid(MMC_DEVICE_NAND,cid);
+end;
+
+procedure sdmmc_sdcard_cid(cid: pcuint32); inline; 
+begin
+    sdmmc_get_cid(MMC_DEVICE_SDCARD,cid);
+end;
+
 {$endif NDS_IMPLEMENTATION}
 

+ 1 - 1
packages/libndsfpc/src/nds/arm7/touch.inc

@@ -17,7 +17,7 @@ const
   TSC_MEASURE_AUX      = $E4;
   TSC_MEASURE_TEMP2    = $F4;
 
-
+procedure touchInit(); cdecl; external;
 procedure touchReadXY(var touchPos: touchPosition); cdecl; external;
 
 function touchRead(command: cuint32): cuint16; cdecl; external;

+ 37 - 0
packages/libndsfpc/src/nds/arm9/cache_asm.inc

@@ -0,0 +1,37 @@
+{$ifdef NDS_INTERFACE}
+const
+  PAGE_4K		= (%01011 shl 1);
+  PAGE_8K		= (%01100 shl 1);
+  PAGE_16K	= (%01101 shl 1);
+  PAGE_32K	= (%01110 shl 1);
+  PAGE_64K	= (%01111 shl 1);
+  PAGE_128K	= (%10000 shl 1);
+  PAGE_256K	= (%10001 shl 1);
+  PAGE_512K	= (%10010 shl 1);
+  PAGE_1M		= (%10011 shl 1);
+  PAGE_2M		= (%10100 shl 1);
+  PAGE_4M		= (%10101 shl 1);
+  PAGE_8M		= (%10110 shl 1);
+  PAGE_16M	= (%10111 shl 1);
+  PAGE_32M	= (%11000 shl 1);
+  PAGE_64M	= (%11001 shl 1);
+  PAGE_128M	= (%11010 shl 1);
+  PAGE_256M	= (%11011 shl 1);
+  PAGE_512M	= (%11100 shl 1);
+  PAGE_1G		= (%11101 shl 1);
+  PAGE_2G		= (%11110 shl 1);
+  PAGE_4G		= (%11111 shl 1);
+
+  ITCM_LOAD	= (1 shl 19);
+  ITCM_ENABLE	= (1 shl 18);
+  DTCM_LOAD	= (1 shl 17);
+  DTCM_ENABLE	= (1 shl 16);
+  DISABLE_TBIT	= (1 shl 15);
+  ROUND_ROBIN	= (1 shl 14);
+  ALT_VECTORS	= (1 shl 13);
+  ICACHE_ENABLE	= (1 shl 12);
+  BIG_ENDIAN	= (1 shl 7);
+  DCACHE_ENABLE	= (1 shl 2);
+  PROTECT_ENABLE	= (1 shl 0);
+
+{$endif NDS_INTERFACE}

+ 4 - 4
packages/libndsfpc/src/nds/arm9/dldi.inc

@@ -1,10 +1,10 @@
 {$ifdef NDS_INTERFACE}
 
 const
-  FIX_ALL = $01;
-  FIX_GLUE = $02;
-  FIX_GOT = $04;
-  FIX_BSS = $08;
+//  FIX_ALL = $01;
+//  FIX_GLUE = $02;
+//  FIX_GOT = $04;
+//  FIX_BSS = $08;
 
   DLDI_MAGIC_STRING_LEN = 8;
   DLDI_FRIENDLY_NAME_LEN = 48;

+ 20 - 0
packages/libndsfpc/src/nds/arm9/dldi_asm.inc

@@ -0,0 +1,20 @@
+{$ifdef NDS_INTERFACE}
+const
+  FEATURE_MEDIUM_CANREAD  = $00000001;
+  FEATURE_MEDIUM_CANWRITE = $00000002;
+  FEATURE_SLOT_GBA = $00000010;
+  FEATURE_SLOT_NDS = $00000020;
+
+  FIX_ALL  = $01;
+  FIX_GLUE = $02;
+  FIX_GOT  = $04;
+  FIX_BSS  = $08;
+
+  DLDI_SIZE_32KB = $0f;
+  DLDI_SIZE_16KB = $0e;
+  DLDI_SIZE_8KB  = $0d;
+  DLDI_SIZE_4KB  = $0c;
+  DLDI_SIZE_1KB  = $0a;
+
+
+{$endif NDS_INTERFACE}

+ 2 - 2
packages/libndsfpc/src/nds/arm9/guitarGrip.inc

@@ -11,7 +11,7 @@ function guitarGripIsInserted(): cbool; cdecl; external;
 procedure guitarGripScanKeys(); cdecl; external;
 
 function guitarGripKeysHeld(): cuint8; cdecl; external;
-function guitarGripKeysDown(): cuint8; cdecl; external;
-function guitarGripKeysUp(): cuint8; cdecl; external;
+function guitarGripKeysDown(): cuint16; cdecl; external;
+function guitarGripKeysUp(): cuint16; cdecl; external;
 
 {$endif NDS_INTERFACE}

+ 2 - 2
packages/libndsfpc/src/nds/arm9/math.inc

@@ -53,12 +53,12 @@ procedure normalizef32(a: pcint32); inline;
 {$ifdef NDS_IMPLEMENTATION}
 function inttof32(n: cint): cint32; inline;
 begin
-  inttof32 := ((n) shl 12);
+  inttof32 := n * (1 shl 12);
 end;
 
 function f32toint(n: cint32): cint; inline;
 begin
-  f32toint := ((n) shr 12);
+  f32toint := n div (1 shl 12);
 end;
 
 function floattof32(n: cfloat): cint32; inline;

+ 6 - 0
packages/libndsfpc/src/nds/arm9/nand.inc

@@ -0,0 +1,6 @@
+{$ifdef NDS_INTERFACE}
+function nand_ReadSectors(sector: sec_t; numSectors: sec_t; buffer: pointer): cbool; cdecl; external;
+function nand_WriteSectors(sector: sec_t; numSectors: sec_t; buffer: pointer): cbool; cdecl; external;
+function nand_GetSize(): ssize_t; cdecl; external;
+
+{$endif NDS_INTERFACE}

+ 1 - 1
packages/libndsfpc/src/nds/arm9/sassert.inc

@@ -29,7 +29,7 @@ end;
 
 procedure sassert2(e: boolean; msg: pchar); inline;
 var
-  i: integer;
+  i: integer = 0;
   s: string;
 begin
   if e then 

+ 1 - 1
packages/libndsfpc/src/nds/arm9/sprite.inc

@@ -211,7 +211,7 @@ const
   SpriteMapping_Bmp_1D_128: TSpriteMapping = integer(DISPLAY_SPR_1D) or integer(DISPLAY_SPR_1D_SIZE_128) or integer(DISPLAY_SPR_1D_BMP) or integer(DISPLAY_SPR_1D_BMP_SIZE_128) or (5 shl 28) or 2;
   SpriteMapping_Bmp_1D_256: TSpriteMapping = integer(DISPLAY_SPR_1D) or integer(DISPLAY_SPR_1D_SIZE_256) or integer(DISPLAY_SPR_1D_BMP) or integer(DISPLAY_SPR_1D_BMP_SIZE_256) or (6 shl 28) or 3;
   SpriteMapping_Bmp_2D_128: TSpriteMapping = integer(DISPLAY_SPR_2D) or integer(DISPLAY_SPR_2D_BMP_128)  or (7 shl 28) or 2;
-  SpriteMapping_Bmp_2D_256: TSpriteMapping = integer(DISPLAY_SPR_2D) or integer(DISPLAY_SPR_2D_BMP_256)  or (8 shl 28) or 3;
+  SpriteMapping_Bmp_2D_256: TSpriteMapping = integer(DISPLAY_SPR_2D) or integer(DISPLAY_SPR_2D_BMP_256)  or cint(cuint(8) shl 28) or 3;
 
 type
   SpriteColorFormat = integer;

+ 5 - 5
packages/libndsfpc/src/nds/arm9/video.inc

@@ -36,8 +36,8 @@ const
 
 function RGB15(r, g, b: cint): cuint16; inline; 
 function RGB5(r, g, b: cint): cuint16; inline;
-function RGB8(r, g, b: cint): cuint8; inline;
-function ARGB16(a, r, g, b: cint): cuint16; inline;
+function RGB8(r, g, b: cint): cuint16; inline;
+function ARGB16(a, r, g, b: cint): cuint32; inline;
 
 const
   SCREEN_HEIGHT = 192;
@@ -507,12 +507,12 @@ begin
   RGB5 := ((r) or ((g) shl 5) or ((b) shl 10));
 end;
 
-function RGB8(r, g, b: cint): cuint8; inline;
-begin
+function RGB8(r, g, b: cint): cuint16; inline;
+begin                
   RGB8 := (((r) shr 3) or (((g) shr 3) shl 5) or (((b) shr 3) shl 10));
 end;
 
-function ARGB16(a, r, g, b: cint): cuint16; inline;
+function ARGB16(a, r, g, b: cint): cuint32; inline;
 begin
   ARGB16 := ((a shl 15) or r or (g shl 5) or (b shl 10));
 end;

+ 9 - 8
packages/libndsfpc/src/nds/card.inc

@@ -1,13 +1,13 @@
 {$ifdef NDS_INTERFACE}
 const  
   // Card bus
-  CARD_COMMAND   : pcuint8  = pointer($040001A8);
-  REG_ROMCTRL    : pcuint32 = pointer($040001A4);
-  REG_AUXSPICNT  : pcuint16 = pointer($040001A0);
-  REG_AUXSPICNTH : pcuint8  = pointer($040001A1);
-  REG_AUXSPIDATA : pcuint8  = pointer($040001A2);
-  CARD_DATA_RD   : pcuint32 = pointer($04100010);
-
+  REG_CARD_DATA_RD   : pcuint32 = pointer($04100010);  
+  REG_AUXSPICNT      : pcuint16 = pointer($040001A0);
+  REG_AUXSPICNTH     : pcuint8  = pointer($040001A1);
+  REG_AUXSPIDATA     : pcuint8  = pointer($040001A2);
+  REG_ROMCTRL        : pcuint32 = pointer($040001A4);
+  REG_CARD_COMMAND   : pcuint8  = pointer($040001A8);
+  
   CARD_1B0       : pcuint32 = pointer($040001B0);
   CARD_1B4       : pcuint32 = pointer($040001B4);
   CARD_1B8       : pcuint16 = pointer($040001B8);
@@ -80,7 +80,8 @@ const
   CARD_SPICNTH_IRQ    = (1 shl 6);  // in byte 1, i.e. 0x4000
 
 
-
+procedure enableSlot1(); cdecl; external;
+procedure disableSlot1(); cdecl; external;
 
 procedure cardWriteCommand(const command: pcuint8); cdecl; external;
 procedure cardPolledTransfer(flags: cuint32;  destination: pcuint32;  length: cuint32; const command: pcuint8); cdecl; external; 

+ 9 - 9
packages/libndsfpc/src/nds/disc_io.inc

@@ -1,10 +1,10 @@
 {$ifdef NDS_INTERFACE}
 
-const
-  FEATURE_MEDIUM_CANREAD		= $00000001;
-  FEATURE_MEDIUM_CANWRITE		= $00000002;
-  FEATURE_SLOT_GBA			= $00000010;
-  FEATURE_SLOT_NDS			= $00000020;
+//const
+//  FEATURE_MEDIUM_CANREAD	= $00000001;
+//  FEATURE_MEDIUM_CANWRITE	= $00000002;
+//  FEATURE_SLOT_GBA			= $00000010;
+//  FEATURE_SLOT_NDS			= $00000020;
 
 function DEVICE_TYPE_DSI_SD(): cuint32; inline;
 
@@ -30,6 +30,8 @@ type
   DISC_INTERFACE = DISC_INTERFACE_STRUCT;
   TDISC_INTERFACE = DISC_INTERFACE_STRUCT;
   PDISC_INTERFACE = ^DISC_INTERFACE_STRUCT;
+  
+
 (*
   PARTITION_INTERFACE = (
     PI_DEFAULT = 0,
@@ -39,16 +41,14 @@ type
   );
 *)
 
-var
-  __io_dsisd: DISC_INTERFACE; cvar; external;
-
+function get_io_dsisd(): PDISC_INTERFACE; cdecl; external;
 {$endif NDS_INTERFACE}
 
 {$ifdef NDS_IMPLEMENTATION}
 
 function DEVICE_TYPE_DSI_SD(): cuint32; inline; 
 begin
-  DEVICE_TYPE_DSI_SD := ord('i') or (ord('_') shl 8) or (ord('S') shl 16) or (ord('D') shl 24);
+  DEVICE_TYPE_DSI_SD := ord('_') or (ord('S') shl 8) or (ord('D') shl 16) or (ord('_') shl 24);
 end;
 
 

+ 2 - 2
packages/libndsfpc/src/nds/dma.inc

@@ -166,10 +166,10 @@ end;
 procedure dmaFillHalfWords(value: cuint16; dest: pointer; size: cuint32); inline;
 begin
   {$ifdef ARM7}
-    pcuint32($027FFE04)^ := value;	         
+    pcuint32($027FFE04)^ := cuint32(value);
     DMA_SRC(3)^ := $027FFE04;	 
   {$else ARM7}
-    DMA_FILL(3)^ := value;
+    DMA_FILL(3)^ := cuint32(value);
 //    pcuint32(DMA_SRC(3)^) := pcuint32(DMA_FILL(3));
     DMA_SRC(3)^ := cuint32(DMA_FILL(3));
   {$endif ARM7}

+ 8 - 7
packages/libndsfpc/src/nds/fifocommon.inc

@@ -51,12 +51,12 @@ type
  FifoSdmmcCommands = integer;
 const
   SDMMC_HAVE_SD        : FifoSystemCommands = 0;
-	SDMMC_SD_START       : FifoSystemCommands = 1;
-	SDMMC_SD_IS_INSERTED : FifoSystemCommands = 2;
-	SDMMC_SD_STOP        : FifoSystemCommands = 3;
-	SDMMC_NAND_START     : FifoSystemCommands = 4;
-	SDMMC_NAND_STOP      : FifoSystemCommands = 5;
-
+  SDMMC_SD_START       : FifoSystemCommands = 1;
+  SDMMC_SD_IS_INSERTED : FifoSystemCommands = 2;
+  SDMMC_SD_STOP        : FifoSystemCommands = 3;
+  SDMMC_NAND_START     : FifoSystemCommands = 4;
+  SDMMC_NAND_STOP      : FifoSystemCommands = 5;
+  SDMMC_NAND_SIZE      : FifoSystemCommands = 6;
 type
   FifoFirmwareCommands = integer;
 const
@@ -73,7 +73,8 @@ const
   PM_REQ_SLEEP_DISABLE  : FifoPMCommands = (5 shl 16);
   PM_REQ_SLEEP_ENABLE   : FifoPMCommands = (6 shl 16);
   PM_REQ_BATTERY        : FifoPMCommands = (7 shl 16);
-  PM_DSI_HACK           : FifoPMCommands = (8 shl 16);
+  PM_REQ_SLOT1_DISABLE  : FifoPMCommands = (8 shl 16);
+  PM_REQ_SLOT1_ENABLE   : FifoPMCommands = (9 shl 16);
 	
 type
   FifoWifiCommands = integer;

+ 1 - 1
packages/libndsfpc/src/nds/fifomessages.inc

@@ -69,7 +69,7 @@ type
 			  end;
 		  );
       6: (
-        fwParams: record
+        blockParams: record
           buffer: pointer;
           address: cuint32;
           length: cuint32;

+ 1 - 1
packages/libndsfpc/src/nds/interrupts.inc

@@ -25,7 +25,7 @@ const
   IRQ_LID				      : IRQ_MASK =	(1 shl 22);	  (* interrupt mask hinge *)
   IRQ_SPI				      : IRQ_MASK =	(1 shl 23);	  (* SPI interrupt mask *)
   IRQ_WIFI			      : IRQ_MASK =	(1 shl 24);	  (* WIFI interrupt mask (ARM7)*)
-  IRQ_ALL				      : IRQ_MASK =	(not 0);      //$FFFFFF ?
+  IRQ_ALL				      : IRQ_MASK =	$FFFFFFFF;//(not 0);      //$FFFFFF ?
 
 
 type

+ 3 - 3
packages/libndsfpc/src/nds/libversion.inc

@@ -1,10 +1,10 @@
 {$ifdef NDS_INTERFACE}
 const
   _LIBNDS_MAJOR_ = 1;
-  _LIBNDS_MINOR_ = 5;
-  _LIBNDS_PATCH_ = 12;
+  _LIBNDS_MINOR_ = 7;
+  _LIBNDS_PATCH_ = 3;
 
-  _LIBNDS_STRING = 'libNDS Release 1.5.12';
+  _LIBNDS_STRING = 'libNDS Release 1.7.3';
 {$endif NDS_INTERFACE}
 
 {$ifdef NDS_IMPLEMENTATION}

+ 88 - 10
packages/libndsfpc/src/nds/memory.inc

@@ -11,6 +11,16 @@ const
   ARM7_OWNS_ROM           = (1 shl 7);
 
 
+  REG_MBK1: pcuint8 = pointer($04004040); // WRAM_A 0..3 
+  REG_MBK2: pcuint8 = pointer($04004044); // WRAM_B 0..3 
+  REG_MBK3: pcuint8 = pointer($04004048); // WRAM_B 4..7 
+  REG_MBK4: pcuint8 = pointer($0400404C); // WRAM_C 0..3 
+  REG_MBK5: pcuint8 = pointer($04004050); // WRAM_C 4..7 
+  REG_MBK6: pcuint32 = pointer($04004054);
+  REG_MBK7: pcuint32 = pointer($04004058);
+  REG_MBK8: pcuint32 = pointer($0400405C);
+  REG_MBK9: pcuint32 = pointer($04004060);
+
 // Protection register (write-once sadly)
 {$ifdef ARM7}
   PROTECTION    : pcuint32 = pointer($04000308);
@@ -69,13 +79,13 @@ type
     flags: cuint8;                // auto-boot flag
     
     arm9romOffset: cuint32;
-    arm9executeAddress: cuint32;
-    arm9destination: cuint32;
+    arm9executeAddress: pointer;
+    arm9destination: pointer;
     arm9binarySize: cuint32;
     
     arm7romOffset: cuint32;
-    arm7executeAddress: cuint32;
-    arm7destination: cuint32;
+    arm7executeAddress: pointer;
+    arm7destination: pointer;
     arm7binarySize: cuint32;
     
     filenameOffset: cuint32;
@@ -108,20 +118,88 @@ type
     gbaLogo: array [0..155] of cuint8;
     logoCRC16: cuint16;
     headerCRC16: cuint16;
-    
+  end;
+  tNDSHeader = sNDSHeader;
+  pNDSHeader = ^tNDSHeader;
+  
+  DSiHeader = packed record  
+    ndshdr: tNDSHeader;  
     debugRomSource: cuint32;
     debugRomSize: cuint32;
     debugRomDestination: cuint32;
     offset_0x16C: cuint32;
     
-    zero: array [0..143] of cuint8;
+    zero: array [0..15] of cuint8;
+      
+   	global_mbk_setting: array [0..4, 0..3] of cuint8;
+  	arm9_mbk_setting: array [0..2] of cuint32;
+  	arm7_mbk_setting: array [0..2] of cuint32;
+  	mbk9_wramcnt_setting: cuint32;
+  
+  	region_flags: cuint32;
+  	access_control: cuint32;
+  	scfg_ext_mask: cuint32;
+  	offset_0x1BC: array [0..2] of cuint8;
+  	appflags: cuint8;
+  
+  	arm9iromOffset: pointer;
+  	offset_0x1C4: cuint32;
+  	arm9idestination: pointer;
+  	arm9ibinarySize: cuint32;
+  	arm7iromOffset: pointer;
+  	offset_0x1D4: cuint32;
+  	arm7idestination: pointer;
+  	arm7ibinarySize: cuint32;
+  
+  	digest_ntr_start: cuint32;
+  	digest_ntr_size: cuint32;
+  	digest_twl_start: cuint32;
+  	digest_twl_size: cuint32;
+  	sector_hashtable_start: cuint32;
+  	sector_hashtable_size: cuint32;
+  	block_hashtable_start: cuint32;
+  	block_hashtable_size: cuint32;
+  	digest_sector_size: cuint32;
+  	digest_block_sectorcount: cuint32;
+  
+  	banner_size: cuint32;
+  	offset_0x20C: cuint32;
+  	total_rom_size: cuint32;
+  	offset_0x214: cuint32;
+  	offset_0x218: cuint32;
+  	offset_0x21C: cuint32;
+  
+  	modcrypt1_start: cuint32;
+  	modcrypt1_size: cuint32;
+  	modcrypt2_start: cuint32;
+  	modcrypt2_size: cuint32;
+  
+  	tid_low: cuint32;
+  	tid_high: cuint32;
+  	public_sav_size: cuint32;
+  	private_sav_size: cuint32;
+  	reserved3: array [0..175] of cuint8;
+  	age_ratings: array [0..15] of cuint8;
+  
+  	hmac_arm9: array [0..19] of cuint8;
+  	hmac_arm7: array [0..19] of cuint8;
+  	hmac_digest_master: array [0..19] of cuint8;
+  	hmac_icon_title: array [0..19] of cuint8;
+  	hmac_arm9i: array [0..19] of cuint8;
+  	hmac_arm7i: array [0..19] of cuint8;
+  	reserved4: array [0..39] of cuint8;
+  	hmac_arm9_no_secure: array [0..19] of cuint8;
+  	reserved5: array [0..2635] of cuint8;
+  	debug_args: array [0..383] of cuint8;
+  	rsa_signature: array [0..127] of cuint8;  
   end;
-  tNDSHeader = sNDSHeader;
-  pNDSHeader = ^tNDSHeader;
+  T__DSiHeader = DSiHeader;
+  P__DSiHeader = ^T__DSiHeader;
+  
   
 const
-  __NDSHeader : pNDSHeader = pointer($02FFFE00);
-
+  __NDSHeader : pNDSHeader   = pointer($02FFFE00);
+  __DSiHeader : P__DSiHeader = pointer($02FFE000);
 
 type
   sNDSBanner = packed record

+ 7 - 0
packages/libndsfpc/src/nds/ndsinclude.inc

@@ -17,12 +17,15 @@
 {$include timers.inc}
 {$include fifomessages.inc} 
 {$include input.inc} 
+{$include rsa.inc} 
+{$include sha1.inc} 
  
 {$ifdef ARM9}
   {$include arm9/dynamicArray.inc}
   {$include arm9/linkedlist.inc}
   {$include arm9/sassert.inc}
   {$include arm9/background.inc}
+  {$include arm9/cache_asm.inc}
   {$include arm9/cache.inc}
   {$include arm9/console.inc}
   {$include arm9/keyboard.inc}
@@ -30,6 +33,7 @@
   {$include arm9/image.inc}
   {$include arm9/input.inc}
   {$include arm9/math.inc}
+  {$include arm9/nand.inc}
   {$include arm9/pcx.inc}
   {$include arm9/rumble.inc}
   {$include arm9/sound.inc}
@@ -44,13 +48,16 @@
   {$include arm9/guitarGrip.inc}
   {$include arm9/paddle.inc}
   {$include arm9/piano.inc}
+  {$include arm9/dldi_asm.inc}
   {$include arm9/dldi.inc}
   {$include arm9/window.inc}
 {$endif ARM9}
 
 {$ifdef ARM7}
+  {$include arm7/aes.inc}
   {$include arm7/audio.inc}
   {$include arm7/clock.inc}
+  {$include arm7/codec.inc}
   {$include arm7/input.inc}
   {$include arm7/i2c.inc}
   {$include arm7/serial.inc}

+ 8 - 1
packages/libndsfpc/src/nds/ndstypes.inc

@@ -7,6 +7,11 @@
 
 #define DTCM_DATA	__attribute__((section(".dtcm")))
 #define DTCM_BSS	__attribute__((section(".sbss")))
+
+#define TWL_CODE	__attribute__((section(".twl")))
+#define TWL_DATA	__attribute__((section(".twl")))
+#define TWL_BSS		__attribute__((section(".twl_bss")))
+
 #define ALIGN(m)	__attribute__((aligned (m)))
 
 #define PACKED __attribute__ ((packed))
@@ -96,7 +101,9 @@ typedef volatile s16          vs16;
 typedef volatile s32          vs32;
 typedef volatile s64          vs64;
 }
-
+  sec_t = cuint32;
+  ssize_t = cint;
+  size_t = cuint;
 
   //IntFn = function: pointer;
   VoidFn = function: pointer; cdecl;

+ 8 - 8
packages/libndsfpc/src/nds/registers_alt.inc

@@ -270,14 +270,14 @@ const
   CARD_CR2     = REG_ROMCTRL;
   CARD_EEPDATA = REG_AUXSPIDATA;
   
-  REG_CARD_DATA		: pcuint32 = pointer($04100000);
-  REG_CARD_DATA_RD	: pcuint32 = pointer($04100010);
-  
-  REG_CARD_1B0		: pcuint32 = pointer($040001B0);
-  REG_CARD_1B4		: pcuint32 = pointer($040001B4);
-  REG_CARD_1B8		: pcuint16 = pointer($040001B8);
-  REG_CARD_1BA		: pcuint16 = pointer($040001BA);
-  
+  CARD_COMMAND = REG_CARD_COMMAND;
+  CARD_DATA_RD = REG_CARD_DATA_RD;
+
+  CARD_1B0 = REG_CARD_1B0;
+  CARD_1B4 = REG_CARD_1B4;
+  CARD_1B8 = REG_CARD_1B8;
+  CARD_1BA = REG_CARD_1BA;
+
   SOUND_CR          = REG_SOUNDCNT;
   SOUND_MASTER_VOL  = REG_MASTER_VOLUME;
   SOUND_BIAS        = REG_SOUNDBIAS;

+ 31 - 0
packages/libndsfpc/src/nds/rsa.inc

@@ -0,0 +1,31 @@
+{$ifdef NDS_INTERFACE}
+type
+  swiRSAHeapContext = packed record 
+    heapStart: pointer;
+	heapEnd: pointer;
+	heapSize: size_t;
+  end;
+  swiRSAHeapContext_t = swiRSAHeapContext;
+  TswiRSAHeapContext = swiRSAHeapContext;
+  PswiRSAHeapContext = ^TswiRSAHeapContext;
+
+
+  swiRSAbuffers = packed record
+	dst: pointer;
+	sig: pointer;
+	key: pointer;
+  end;
+  swiRSAbuffers_t = swiRSAbuffers;
+  TswiRSAbuffers = swiRSAbuffers;
+  PswiRSAbuffers = ^TswiRSAbuffers;
+
+function swiRSAInitHeap(ctx: PswiRSAHeapContext; heapStart: pointer; heapSize: size_t): cint; cdecl; external;
+function swiRSADecryptRAW(ctx: PswiRSAHeapContext; rsabuffers: PswiRSAbuffers; len: size_t): cint; cdecl; external;
+function swiRSADecrypt(ctx: PswiRSAHeapContext; dst: pointer; const sig: pointer; const key: pointer): cint; cdecl; external;
+function swiRSADecryptPGP(ctx: PswiRSAHeapContext; dst: pointer; const sig: pointer; const key: pointer): cint; cdecl; external;
+{$endif NDS_INTERFACE}
+
+{$ifdef NDS_IMPLEMENTATION} 
+
+
+{$endif NDS_IMPLEMENTATION}

+ 30 - 0
packages/libndsfpc/src/nds/sha1.inc

@@ -0,0 +1,30 @@
+{$ifdef NDS_INTERFACE}
+
+type
+  swiSHA1context = packed record 
+  type
+  TSHA_Block = procedure(var ctx: swiSHA1context; src: pointer; len: size_t);
+  PSHA_Block = ^TSHA_Block;
+  var
+	state: array [0..4] of cuint32;
+	total: array [0..1] of cuint32;
+	buffer: array [0..63] of cuint8;
+	fragment_size: cuint32;
+	sha_block: PSHA_Block;
+  end;
+  swiSHA1context_t =  swiSHA1context;
+  TswiSHA1context_t = swiSHA1context_t;
+  PswiSHA1context_t = ^TswiSHA1context_t;
+  
+
+procedure swiSHA1Init(var ctx: TswiSHA1context_t); cdecl; external;
+procedure swiSHA1Update(var ctx: TswiSHA1context_t; data: pointer; len: size_t); cdecl; external;
+procedure swiSHA1Final(digest: pointer; var ctx: TswiSHA1context_t); cdecl; external;
+procedure swiSHA1Calc(digest: pointer; data: pointer; len: size_t); cdecl; external;
+procedure swiSHA1Verify(digest1, digest2: pointer); cdecl; external;
+{$endif NDS_INTERFACE}
+
+{$ifdef NDS_IMPLEMENTATION} 
+
+
+{$endif NDS_IMPLEMENTATION}

+ 33 - 10
packages/libndsfpc/src/nds/system.inc

@@ -15,7 +15,18 @@ const
   REG_VCOUNT		: pcuint16 = pointer($04000006);
   HALT_CR       : pcuint16 = pointer($04000300);
   REG_POWERCNT  : pcuint16 = pointer($04000304);
-  REG_DSIMODE		: pcuint32 = pointer($04004000);  
+  
+  REG_SCFG_ROM		: pcuint16 = pointer($04004000);  
+
+{$ifdef ARM7}
+  REG_SCFG_A9ROM : pcuint8 = pointer($4004000);
+  REG_SCFG_A7ROM : pcuint8 = pointer($4004001);  // ??
+{$endif ARM7}
+
+  REG_SCFG_CLK : pcuint16 = pointer($4004004);
+  REG_SCFG_RST : pcuint16 = pointer($4004006);
+  REG_SCFG_EXT : pcuint32 = pointer($4004008);
+  REG_SCFG_MC  : pcuint16 = pointer($4004010);
 
 procedure SetYtrigger(Yvalue: cint); inline;
 
@@ -45,8 +56,7 @@ const
 //procedure SystemSleep(); cdecl; external;
 procedure ledBlink(bm: cint); cdecl; external;
 
-var
-  __dsimode: cbool; cvar; external;
+function isDSiMode(): cbool; inline;
 
 {$ifdef ARM9}
 procedure SystemSleep(); cdecl; external;
@@ -72,12 +82,12 @@ procedure setVectorBase(highVector: cint); cdecl; external;
 
 type 
   sysVectors_t = packed record
-    reset: cuint32;
-    undefined: cuint32;
-    swi: cuint32;
-    prefetch_abort: cuint32;
-    data_abort: cuint32;
-    fiq: cuint32;
+    reset: VoidFn;
+    undefined: VoidFn;
+    swi: VoidFn;
+    prefetch_abort: VoidFn;
+    data_abort: VoidFn;
+    fiq: VoidFn;
   end; 
   sysVectors = sysVectors_t;
   PsysVectors = ^sysVectors;
@@ -88,6 +98,8 @@ var
 //void setSDcallback(void(*callback)(int));
 procedure setSDcallback(callback: pointer); cdecl; external; // ??
 
+function setCpuClock(speed: cbool): cbool; cdecl; external;
+
 // Helper functions for heap size
 //! returns current start of heap space
 function getHeapStart(): pcuint8; cdecl; external;
@@ -100,6 +112,9 @@ function getHeapLimit(): pcuint8; cdecl; external;
 
 
 {$ifdef ARM7}
+const
+  REG_CONSOLEID	: pcuint64 = pointer($04004D00);
+
 type
   ARM7_power = cint;
 const
@@ -226,7 +241,7 @@ const
   __system_argv: Pargv = pointer($02FFFE70);
 
 const
-  BOOTSIG: cardinal = $62757473746F6F62; // ULL?
+  BOOTSIG: cuint64 = $62757473746F6F62; // ULL?
 
 
 type
@@ -308,5 +323,13 @@ begin
 end;
 {$endif ARM7}
 
+
+var
+  __dsimode: cbool; cvar; external;
+function isDSiMode(): cbool; inline;
+begin
+	isDSiMode := __dsimode;
+end;
+
 {$endif NDS_IMPLEMENTATION}
 

+ 1 - 1
packages/libndsfpc/src/nds7.pp

@@ -39,7 +39,7 @@ unit nds7;
 {$INLINE ON}
 {$MACRO ON}
 {$PACKRECORDS C}
-
+{$modeswitch ADVANCEDRECORDS}
 interface
 
 uses

+ 1 - 0
packages/libndsfpc/src/nds9.pp

@@ -39,6 +39,7 @@ unit nds9;
 {$MACRO ON}
 {$PACKRECORDS C}
 {$ASSERTIONS ON}
+{$modeswitch ADVANCEDRECORDS}
 interface
 
 uses

+ 93 - 4
rtl/nds/cprt07.as

@@ -1,5 +1,11 @@
+/*--------------------------------------------------------------------------------
+	This Source Code Form is subject to the terms of the Mozilla Public License,
+	v. 2.0. If a copy of the MPL was not distributed with this file, You can
+	obtain one at https://mozilla.org/MPL/2.0/.
+--------------------------------------------------------------------------------*/
+
 @---------------------------------------------------------------------------------
-	.section ".init"
+	.section ".crt0","ax"
 	.global _start
 @---------------------------------------------------------------------------------
 	.align	4
@@ -23,11 +29,53 @@ _start:
 	msr	cpsr, r0
 	ldr	sp, =__sp_usr		@ Set user stack
 
+#ifndef VRAM
+	adr	r1, __sync_start	@ Perform ARM7<->ARM9 sync code
+	ldr	r2, =__arm7_start__
+	mov	r3, #(__sync_end-__sync_start)
+	mov	r8, r2
+	bl	CopyMem
+	mov	r3, r8
+	bl	_blx_r3_stub
+
+@---------------------------------------------------------------------------------
+@ Copy arm7 binary from LMA to VMA (EWRAM to IWRAM)
+@---------------------------------------------------------------------------------
+	adr	r0, arm7lma		@ Calculate ARM7 LMA
+	ldr	r1, [r0]
+	add	r1, r1, r0
+	ldr	r2, =__arm7_start__
+	ldr	r4, =__arm7_end__
+	bl	CopyMemCheck
+
+#else
+	bl	__sync_start
+#endif
+
 	ldr	r0, =__bss_start__	@ Clear BSS section to 0x00
 	ldr	r1, =__bss_end__
 	sub	r1, r1, r0
 	bl	ClearMem
 
+	cmp	r10, #1
+	bne	NotTWL
+	ldr	r1, =__dsimode		@ set DSi mode flag
+	strb	r10, [r1]
+
+#ifndef VRAM
+	ldr	r1, =0x02ffe1d8		@ Get ARM7i LMA from header
+	ldr	r1, [r1]
+	ldr	r2, =__arm7i_start__
+	ldr	r4, =__arm7i_end__
+	bl	CopyMemCheck
+
+	ldr	r0, =__twl_bss_start__	@ Clear TWL BSS section to 0x00
+	ldr	r1, =__twl_bss_end__
+	sub	r1, r1, r0
+	bl	ClearMem
+#endif
+
+NotTWL:
 	ldr	r3, =__libc_init_array	@ global constructors
 	bl	_blx_r3_stub
 
@@ -35,13 +83,51 @@ _start:
 	mov	r1, #0			@ char *argv[]
 	ldr	r3, =main
 	ldr	lr,=__libnds_exit
+	mov	r12, #0x4000000		@ tell arm9 we are ready
+	mov	r9, #0
+	str	r9, [r12, #0x180]
+_blx_r3_stub:
 	bx	r3
 
+#ifndef VRAM
+arm7lma:
+	.word	__arm7_lma__ - .
+#endif
+	.pool
+
 @---------------------------------------------------------------------------------
- _blx_r3_stub:
+@ ARM7<->ARM9 synchronization code
 @---------------------------------------------------------------------------------
-	bx	r3
- 
+
+__sync_start:
+	push	{lr}
+	mov	r12, #0x4000000
+	mov	r9, #0x0
+	bl	IPCSync
+	mov	r9, #(0x9<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xA
+	bl	IPCSync
+	mov	r9, #(0xB<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xC
+	bl	IPCSync
+	mov	r9, #(0xD<<8)
+	str	r9, [r12, #0x180]
+IPCRecvFlag:
+	ldr	r10, [r12, #0x180]
+	and	r10, r10, #0xF
+	cmp	r10, #0xC
+	beq	IPCRecvFlag
+	pop	{pc}
+IPCSync:
+	ldr	r10, [r12, #0x180]
+	and	r10, r10, #0xF
+	cmp	r10, r9
+	bne	IPCSync
+	bx	lr
+__sync_end:
+
 @---------------------------------------------------------------------------------
 @ Clear memory to 0x00 if length != 0
 @  r0 = Start Address
@@ -69,6 +155,9 @@ ClrLoop:
 @---------------------------------------------------------------------------------
 CopyMemCheck:
 @---------------------------------------------------------------------------------
+	cmp	r1, r2
+	bxeq	lr
+
 	sub	r3, r4, r2		@ Is there any data to copy?
 @---------------------------------------------------------------------------------
 @ Copy memory

+ 110 - 44
rtl/nds/cprt09.as

@@ -1,3 +1,9 @@
+/*--------------------------------------------------------------------------------
+	This Source Code Form is subject to the terms of the Mozilla Public License,
+	v. 2.0. If a copy of the MPL was not distributed with this file, You can
+	obtain one at https://mozilla.org/MPL/2.0/.
+--------------------------------------------------------------------------------*/
+
 @---------------------------------------------------------------------------------
 @ DS processor selection
 @---------------------------------------------------------------------------------
@@ -8,7 +14,7 @@
 	.equ	_libnds_argv,0x02FFFE70
 
 @---------------------------------------------------------------------------------
-	.section ".init"
+	.section ".crt0","ax"
 	.global _start
 @---------------------------------------------------------------------------------
 	.align	4
@@ -16,7 +22,7 @@
 @---------------------------------------------------------------------------------
 _start:
 @---------------------------------------------------------------------------------
-	mov	r0, #0x04000000			@ IME = 0;
+	mov	r0, #0x04000000		@ IME = 0;
 	str	r0, [r0, #0x208]
 	
 	@ set sensible stacks to allow bios call
@@ -31,7 +37,7 @@ _start:
 	sub	r1,r1,#0x100
 	mov	sp,r1
 
-	ldr	r3,=__libnds_mpu_setup
+	ldr	r3, =__libnds_mpu_setup
 	blx	r3
 
 	mov	r0, #0x12		@ Switch to IRQ Mode
@@ -46,23 +52,47 @@ _start:
 	msr	cpsr, r0
 	ldr	sp, =__sp_usr		@ Set user stack
 
+	mov	r12, #0x4000000		@ Read system ROM status (NTR/TWL)
+	ldrb	r11, [r12,r12,lsr #12]
+	and	r11, r11, #0x3
+
+	mov	r9, #(0x0<<8)		@ Synchronize with ARM7
+	str	r9, [r12, #0x180]
+	mov	r9, #0x9
+	bl	IPCSync
+	mov	r9, #(0xA<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xB
+	bl	IPCSync
+	mov	r9, #(0xC<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xD
+	bl	IPCSync
+	mov	r9, r11, lsl #8
+	str	r9, [r12, #0x180]
+	mov	r9, #0
+	bl	IPCSync
+	str	r9, [r12, #0x180]
+
 	ldr	r1, =__itcm_lma		@ Copy instruction tightly coupled memory (itcm section) from LMA to VMA
 	ldr	r2, =__itcm_start
 	ldr	r4, =__itcm_end
 	bl	CopyMemCheck
 
-	ldr     r1, =__vectors_lma              @ Copy reserved vectors area (itcm section) from LMA to VMA
-	ldr     r2, =__vectors_start
-	ldr     r4, =__vectors_end
-
-	bl      CopyMemCheck
+	ldr	r1, =__vectors_lma	@ Copy reserved vectors area (itcm section) from LMA to VMA
+	ldr	r2, =__vectors_start
+	ldr	r4, =__vectors_end
+	bl	CopyMemCheck
 
 	ldr	r1, =__dtcm_lma		@ Copy data tightly coupled memory (dtcm section) from LMA to VMA
 	ldr	r2, =__dtcm_start
 	ldr	r4, =__dtcm_end
 	bl	CopyMemCheck
 
-	bl	checkARGV					@	check and process argv trickery
+	cmp	r11, #1
+	ldrne	r10, =__end__		@ (DS mode) heap start
+	ldreq	r10, =__twl_end__	@ (DSi mode) heap start
+	bl	checkARGV		@ check and process argv trickery
 
 	ldr	r0, =__bss_start__	@ Clear BSS section
 	ldr	r1, =__bss_end__
@@ -73,64 +103,88 @@ _start:
 	ldr	r1, =__sbss_end
 	sub	r1, r1, r0
 	bl	ClearMem
-	
-	ldr	r0,	=_libnds_argv
+
+	cmp	r11, #1
+	bne	NotTWL
+	ldr	r9, =__dsimode		@ set DSi mode flag
+	strb	r11, [r9]
+
+	@ Copy TWL area (arm9i section) from LMA to VMA
+	ldr	r1, =0x02ffe1c8		@ Get ARM9i LMA from header
+	ldr	r1, [r1]
+
+	ldr	r2, =__arm9i_start__
+	cmp	r1, r2			@ skip copy if LMA=VMA
+	ldrne	r4, =__arm9i_end__
+	blne	CopyMemCheck
+
+	ldr	r0, =__twl_bss_start__	@ Clear TWL BSS section
+	ldr	r1, =__twl_bss_end__
+	sub	r1, r1, r0
+	bl	ClearMem
+
+NotTWL:
+	ldr	r0, =_libnds_argv
 
 	@ reset heap base
-	ldr	r2, [r0,#20]            @ newheap base
-	ldr	r1,=fake_heap_start
-	str	r2,[r1]
+	ldr	r2, [r0,#20]		@ newheap base
+	cmp	r2, #0
+	moveq	r2, r10
+	ldr	r1, =fake_heap_start	@ set heap start
+	str	r2, [r1]
 
 	ldr	r1, =fake_heap_end	@ set heap end
-	sub	r8,r8,#0xc000
+	sub	r8, r8,#0xc000
 	str	r8, [r1]
 
-	push    {r0}
-	ldr     r3, =initSystem
-	blx     r3                      @ system initialisation
-	ldr     r3, =__libc_init_array  @ global constructors
-	blx     r3	
-	pop     {r0}
+	push	{r0}
+	ldr	r0, =__secure_area__
+	ldr	r3, =initSystem
+	blx	r3			@ system initialisation
+
+	ldr	r3, =__libc_init_array	@ global constructors
+	blx	r3
 
-	ldr	r1, [r0,#16]            @ argv
-	ldr	r0, [r0,#12]            @ argc
+	pop	{r0}
 
+	ldr	r1, [r0,#16]		@ argv
+	ldr	r0, [r0,#12]		@ argc
 
 	ldr	r3, =main
-	ldr	lr,=__libnds_exit
+	ldr	lr, =__libnds_exit
 	bx	r3			@ jump to user code
 
 @---------------------------------------------------------------------------------
-@ check for a commandline
+@ check for a commandline 
 @---------------------------------------------------------------------------------
 checkARGV:
 @---------------------------------------------------------------------------------
-	ldr	r0, =_libnds_argv       @ argv structure
+	ldr	r0, =_libnds_argv	@ argv structure
 	mov	r1, #0
-	str	r1, [r0,#12]            @ clear argc
-	str	r1, [r0,#16]            @ clear argv
- 	  	 
+	str	r1, [r0,#12]		@ clear argc
+	str	r1, [r0,#16]		@ clear argv
+	
 	ldr	r3, [r0]		@ argv magic number
 	ldr	r2, =0x5f617267		@ '_arg'
 	cmp	r3, r2
-	strne	r1,[r0,#20]
-  bxne	lr                      @ bail out if no magic
-
-	ldr	r1, [r0, #4]            @ command line address
-	ldr	r2, [r0, #8]            @ length of command line
+	strne	r1, [r0,#20]
+	bxne	lr			@ bail out if no magic
+	
+	ldr	r1, [r0, #4]		@ command line address
+	ldr	r2, [r0, #8]		@ length of command line
 
 	@ copy to heap
-	ldr	r3, =__end__            @ initial heap base
-	str	r3, [r0, #4]            @ set command line address
- 	  	 
-	cmp	r2, #0
-	subnes	r4, r3, r1              @ dst-src
-	bxeq	lr                      @ dst == src || len==0 : nothing to do.
+	mov	r3, r10			@ initial heap base
+	str	r3, [r0, #4]		@ set command line address
 
-	cmphi	r2, r4                  @ len > (dst-src)
+	cmp	r2, #0
+	subnes	r4, r3, r1		@ dst-src
+	bxeq	lr			@ dst == src || len==0 : nothing to do.
+	
+	cmphi	r2, r4			@ len > (dst-src)
 	bhi	.copybackward
 
-.copyforward:
+.copyforward:		
 	ldrb	r4, [r1], #1
 	strb	r4, [r3], #1
 	subs	r2, r2, #1
@@ -148,7 +202,7 @@ checkARGV:
 	ldr	r3, =build_argv
 	blx	r3
 	pop	{lr}
-	bx	lr
+	bx	lr	
 
 
 @---------------------------------------------------------------------------------
@@ -199,8 +253,20 @@ CIDLoop:
 	bne	CIDLoop
 
 	bx	lr
+
+@---------------------------------------------------------------------------------
+@ Synchronize with ARM7
+@---------------------------------------------------------------------------------
+IPCSync:
+@---------------------------------------------------------------------------------
+	ldr	r10, [r12, #0x180]
+	and	r10, r10, #0xF
+	cmp	r10, r9
+	bne	IPCSync
+	bx	lr
+
 @---------------------------------------------------------------------------------
 	.align
 	.pool
 	.end
-@---------------------------------------------------------------------------------
+@---------------------------------------------------------------------------------

+ 99 - 2
rtl/nds/prt07.as

@@ -1,5 +1,11 @@
+/*--------------------------------------------------------------------------------
+	This Source Code Form is subject to the terms of the Mozilla Public License,
+	v. 2.0. If a copy of the MPL was not distributed with this file, You can
+	obtain one at https://mozilla.org/MPL/2.0/.
+--------------------------------------------------------------------------------*/
+
 @---------------------------------------------------------------------------------
-	.section ".init"
+	.section ".crt0","ax"
 	.global _start
 @---------------------------------------------------------------------------------
 	.align	4
@@ -23,17 +29,105 @@ _start:
 	msr	cpsr, r0
 	ldr	sp, =__sp_usr		@ Set user stack
 
+#ifndef VRAM
+	adr	r1, __sync_start	@ Perform ARM7<->ARM9 sync code
+	ldr	r2, =__arm7_start__
+	mov	r3, #(__sync_end-__sync_start)
+	mov	r8, r2
+	bl	CopyMem
+	mov	r3, r8
+	bl	_blx_r3_stub
+
+@---------------------------------------------------------------------------------
+@ Copy arm7 binary from LMA to VMA (EWRAM to IWRAM)
+@---------------------------------------------------------------------------------
+	adr	r0, arm7lma		@ Calculate ARM7 LMA
+	ldr	r1, [r0]
+	add	r1, r1, r0
+	ldr	r2, =__arm7_start__
+	ldr	r4, =__arm7_end__
+	bl	CopyMemCheck
+
+#else
+	bl	__sync_start
+#endif
+
 	ldr	r0, =__bss_start__	@ Clear BSS section to 0x00
 	ldr	r1, =__bss_end__
 	sub	r1, r1, r0
 	bl	ClearMem
 
+	cmp	r10, #1
+	bne	NotTWL
+	ldr	r1, =__dsimode		@ set DSi mode flag
+	strb	r10, [r1]
+
+#ifndef VRAM
+	ldr	r1, =0x02ffe1d8		@ Get ARM7i LMA from header
+	ldr	r1, [r1]
+	ldr	r2, =__arm7i_start__
+	ldr	r4, =__arm7i_end__
+	bl	CopyMemCheck
+
+	ldr	r0, =__twl_bss_start__	@ Clear TWL BSS section to 0x00
+	ldr	r1, =__twl_bss_end__
+	sub	r1, r1, r0
+	bl	ClearMem
+#endif
+
+NotTWL:
+	ldr	r3, =__libc_init_array	@ global constructors
+	bl	_blx_r3_stub
+
 	mov	r0, #0			@ int argc
 	mov	r1, #0			@ char *argv[]
 	ldr	r3, =main
 	ldr	lr,=__libnds_exit
+	mov	r12, #0x4000000		@ tell arm9 we are ready
+	mov	r9, #0
+	str	r9, [r12, #0x180]
+_blx_r3_stub:
 	bx	r3
 
+#ifndef VRAM
+arm7lma:
+	.word	__arm7_lma__ - .
+#endif
+	.pool
+
+@---------------------------------------------------------------------------------
+@ ARM7<->ARM9 synchronization code
+@---------------------------------------------------------------------------------
+
+__sync_start:
+	push	{lr}
+	mov	r12, #0x4000000
+	mov	r9, #0x0
+	bl	IPCSync
+	mov	r9, #(0x9<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xA
+	bl	IPCSync
+	mov	r9, #(0xB<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xC
+	bl	IPCSync
+	mov	r9, #(0xD<<8)
+	str	r9, [r12, #0x180]
+IPCRecvFlag:
+	ldr	r10, [r12, #0x180]
+	and	r10, r10, #0xF
+	cmp	r10, #0xC
+	beq	IPCRecvFlag
+	pop	{pc}
+IPCSync:
+	ldr	r10, [r12, #0x180]
+	and	r10, r10, #0xF
+	cmp	r10, r9
+	bne	IPCSync
+	bx	lr
+__sync_end:
+
 @---------------------------------------------------------------------------------
 @ Clear memory to 0x00 if length != 0
 @  r0 = Start Address
@@ -61,6 +155,9 @@ ClrLoop:
 @---------------------------------------------------------------------------------
 CopyMemCheck:
 @---------------------------------------------------------------------------------
+	cmp	r1, r2
+	bxeq	lr
+
 	sub	r3, r4, r2		@ Is there any data to copy?
 @---------------------------------------------------------------------------------
 @ Copy memory
@@ -85,4 +182,4 @@ CIDLoop:
 	.align
 	.pool
 	.end
-@---------------------------------------------------------------------------------
+@---------------------------------------------------------------------------------

+ 112 - 46
rtl/nds/prt09.as

@@ -1,3 +1,9 @@
+/*--------------------------------------------------------------------------------
+	This Source Code Form is subject to the terms of the Mozilla Public License,
+	v. 2.0. If a copy of the MPL was not distributed with this file, You can
+	obtain one at https://mozilla.org/MPL/2.0/.
+--------------------------------------------------------------------------------*/
+
 @---------------------------------------------------------------------------------
 @ DS processor selection
 @---------------------------------------------------------------------------------
@@ -8,7 +14,7 @@
 	.equ	_libnds_argv,0x02FFFE70
 
 @---------------------------------------------------------------------------------
-	.section ".init"
+	.section ".crt0","ax"
 	.global _start
 @---------------------------------------------------------------------------------
 	.align	4
@@ -16,7 +22,7 @@
 @---------------------------------------------------------------------------------
 _start:
 @---------------------------------------------------------------------------------
-	mov	r0, #0x04000000			@ IME = 0;
+	mov	r0, #0x04000000		@ IME = 0;
 	str	r0, [r0, #0x208]
 	
 	@ set sensible stacks to allow bios call
@@ -30,8 +36,8 @@ _start:
 	msr	cpsr, r0
 	sub	r1,r1,#0x100
 	mov	sp,r1
-	
-	ldr	r3,=__libnds_mpu_setup
+
+	ldr	r3, =__libnds_mpu_setup
 	blx	r3
 
 	mov	r0, #0x12		@ Switch to IRQ Mode
@@ -46,23 +52,47 @@ _start:
 	msr	cpsr, r0
 	ldr	sp, =__sp_usr		@ Set user stack
 
-	ldr	r1, =__itcm_lma		@ Copy instruction tightly coupled memory (itcm section) from LMA to VMA (ROM to RAM)
+	mov	r12, #0x4000000		@ Read system ROM status (NTR/TWL)
+	ldrb	r11, [r12,r12,lsr #12]
+	and	r11, r11, #0x3
+
+	mov	r9, #(0x0<<8)		@ Synchronize with ARM7
+	str	r9, [r12, #0x180]
+	mov	r9, #0x9
+	bl	IPCSync
+	mov	r9, #(0xA<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xB
+	bl	IPCSync
+	mov	r9, #(0xC<<8)
+	str	r9, [r12, #0x180]
+	mov	r9, #0xD
+	bl	IPCSync
+	mov	r9, r11, lsl #8
+	str	r9, [r12, #0x180]
+	mov	r9, #0
+	bl	IPCSync
+	str	r9, [r12, #0x180]
+
+	ldr	r1, =__itcm_lma		@ Copy instruction tightly coupled memory (itcm section) from LMA to VMA
 	ldr	r2, =__itcm_start
 	ldr	r4, =__itcm_end
 	bl	CopyMemCheck
 
-	ldr     r1, =__vectors_lma              @ Copy reserved vectors area (itcm section) from LMA to VMA
-	ldr     r2, =__vectors_start
-	ldr     r4, =__vectors_end
-
-	bl      CopyMemCheck
+	ldr	r1, =__vectors_lma	@ Copy reserved vectors area (itcm section) from LMA to VMA
+	ldr	r2, =__vectors_start
+	ldr	r4, =__vectors_end
+	bl	CopyMemCheck
 
 	ldr	r1, =__dtcm_lma		@ Copy data tightly coupled memory (dtcm section) from LMA to VMA
 	ldr	r2, =__dtcm_start
 	ldr	r4, =__dtcm_end
 	bl	CopyMemCheck
-	
-	bl	checkARGV					@	check and process argv trickery
+
+	cmp	r11, #1
+	ldrne	r10, =__end__		@ (DS mode) heap start
+	ldreq	r10, =__twl_end__	@ (DSi mode) heap start
+	bl	checkARGV		@ check and process argv trickery
 
 	ldr	r0, =__bss_start__	@ Clear BSS section
 	ldr	r1, =__bss_end__
@@ -74,63 +104,87 @@ _start:
 	sub	r1, r1, r0
 	bl	ClearMem
 
-	ldr	r0,	=_libnds_argv
+	cmp	r11, #1
+	bne	NotTWL
+	ldr	r9, =__dsimode		@ set DSi mode flag
+	strb	r11, [r9]
+
+	@ Copy TWL area (arm9i section) from LMA to VMA
+	ldr	r1, =0x02ffe1c8		@ Get ARM9i LMA from header
+	ldr	r1, [r1]
+
+	ldr	r2, =__arm9i_start__
+	cmp	r1, r2			@ skip copy if LMA=VMA
+	ldrne	r4, =__arm9i_end__
+	blne	CopyMemCheck
+
+	ldr	r0, =__twl_bss_start__	@ Clear TWL BSS section
+	ldr	r1, =__twl_bss_end__
+	sub	r1, r1, r0
+	bl	ClearMem
+
+NotTWL:
+	ldr	r0, =_libnds_argv
 
 	@ reset heap base
-	ldr	r2, [r0,#20]            @ newheap base
-	ldr	r1,=fake_heap_start
-	str	r2,[r1]
+	ldr	r2, [r0,#20]		@ newheap base
+	cmp	r2, #0
+	moveq	r2, r10
+	ldr	r1, =fake_heap_start	@ set heap start
+	str	r2, [r1]
 
 	ldr	r1, =fake_heap_end	@ set heap end
-	sub	r8,r8,#0xc000
+	sub	r8, r8,#0xc000
 	str	r8, [r1]
 
-	push    {r0}
-	ldr     r3, =initSystem
-	blx     r3                      @ system initialisation
-@	ldr     r3, =__libc_init_array  @ global constructors
-@	blx     r3	
-	pop     {r0}
+	push	{r0}
+	ldr	r0, =__secure_area__
+	ldr	r3, =initSystem
+	blx	r3			@ system initialisation
+
+	ldr	r3, =__libc_init_array	@ global constructors
+	blx	r3
 
-	ldr	r1, [r0,#16]            @ argv
-	ldr	r0, [r0,#12]            @ argc
+	pop	{r0}
 
+	ldr	r1, [r0,#16]		@ argv
+	ldr	r0, [r0,#12]		@ argc
 
 	ldr	r3, =main
-	ldr	lr,=__libnds_exit
+	ldr	lr, =__libnds_exit
 	bx	r3			@ jump to user code
 
 @---------------------------------------------------------------------------------
-@ check for a commandline
+@ check for a commandline 
 @---------------------------------------------------------------------------------
 checkARGV:
 @---------------------------------------------------------------------------------
-	ldr	r0, =_libnds_argv       @ argv structure
+	ldr	r0, =_libnds_argv	@ argv structure
 	mov	r1, #0
-	str	r1, [r0,#12]            @ clear argc
-	str	r1, [r0,#16]            @ clear argv
- 	  	 
+	str	r1, [r0,#12]		@ clear argc
+	str	r1, [r0,#16]		@ clear argv
+	
 	ldr	r3, [r0]		@ argv magic number
 	ldr	r2, =0x5f617267		@ '_arg'
 	cmp	r3, r2
-	strne	r1,[r0,#20]
-  bxne	lr                      @ bail out if no magic
-
-	ldr	r1, [r0, #4]            @ command line address
-	ldr	r2, [r0, #8]            @ length of command line
+	strne	r1, [r0,#20]
+	bxne	lr			@ bail out if no magic
+	
+	ldr	r1, [r0, #4]		@ command line address
+	ldr	r2, [r0, #8]		@ length of command line
 
 	@ copy to heap
-	ldr	r3, =__end__            @ initial heap base
-	str	r3, [r0, #4]            @ set command line address
- 	  	 
-	cmp	r2, #0
-	subnes	r4, r3, r1              @ dst-src
-	bxeq	lr                      @ dst == src || len==0 : nothing to do.
+	mov	r3, r10			@ initial heap base
+	str	r3, [r0, #4]		@ set command line address
 
-	cmphi	r2, r4                  @ len > (dst-src)
+	cmp	r2, #0
+	subnes	r4, r3, r1		@ dst-src
+	bxeq	lr			@ dst == src || len==0 : nothing to do.
+	
+	cmphi	r2, r4			@ len > (dst-src)
 	bhi	.copybackward
 
-.copyforward:
+.copyforward:		
 	ldrb	r4, [r1], #1
 	strb	r4, [r3], #1
 	subs	r2, r2, #1
@@ -148,7 +202,7 @@ checkARGV:
 	ldr	r3, =build_argv
 	blx	r3
 	pop	{lr}
-	bx	lr
+	bx	lr	
 
 
 @---------------------------------------------------------------------------------
@@ -199,8 +253,20 @@ CIDLoop:
 	bne	CIDLoop
 
 	bx	lr
+
+@---------------------------------------------------------------------------------
+@ Synchronize with ARM7
+@---------------------------------------------------------------------------------
+IPCSync:
+@---------------------------------------------------------------------------------
+	ldr	r10, [r12, #0x180]
+	and	r10, r10, #0xF
+	cmp	r10, r9
+	bne	IPCSync
+	bx	lr
+
 @---------------------------------------------------------------------------------
 	.align
 	.pool
 	.end
-@---------------------------------------------------------------------------------
+@---------------------------------------------------------------------------------

+ 3 - 0
rtl/nds/system.pp

@@ -25,6 +25,9 @@ interface
 {$define FPC_HAS_FEATURE_FILEIO}
 {$define FPC_HAS_FEATURE_THREADING}
 
+{$define CPUARM_HAS_UMULL} 
+{$define CPUARM_HAS_CLZ}
+
 {$i systemh.inc}
 {$i ndsbiosh.inc}
 {$i ndsh.inc}