Commit for 2020.07.04.7z

This commit is contained in:
mrq 2020-07-04 00:00:00 -05:00
parent 9aa1808ae2
commit 830566ab5f
1837 changed files with 31092 additions and 852725 deletions

289
Makefile
View File

@ -1,232 +1,109 @@
ARCH = win64
PREFIX = gcc
.PHONY: win64
TARGET_NAME = program
TARGET_EXTENSION = exe
TARGET_LIB_EXTENSION = dll
BIN_DIR = ./bin
include makefiles/$(ARCH).$(PREFIX).make
ENGINE_SRC_DIR = ./engine/src
ENGINE_INC_DIR = ./engine/inc
ENGINE_LIB_DIR = ./engine/lib
.PHONY: $(ARCH)-$(PREFIX)
EXT_SRC_DIR = ./ext
CLIENT_SRC_DIR = ./client
BIN_DIR += ./bin
UF_LIBS =
# EXT_LIBS = -lpng16 -lz -lsfml-main -lsfml-system -lsfml-window -lsfml-graphics
# EXT_LIBS = -lpng16 -lz -lassimp -lsfml-main -lsfml-system -lsfml-window -lsfml-graphics -llua52
# EXT_LIBS = -lpng16 -lz -lassimp -ljsoncpp -lopenal32 -lalut -lvorbis -lvorbisfile -logg -lfreetype
EXT_LIBS =
#FLAGS = -std=c++0x -Wall -g -DUF_USE_JSON -DUF_USE_NCURSES -DUF_USE_OPENGL -DUF_USE_GLEW
FLAGS = -Og -std=c++17 -Wall -g -DVK_USE_PLATFORM_WIN32_KHR -DUF_USE_VULKAN -DGLM_ENABLE_EXPERIMENTAL -DUF_USE_JSON -DUF_USE_NCURSES -DUF_USE_OPENAL -DUF_USE_VORBIS -DUF_USE_FREETYPE -DUSE_OPENVR_MINGW
#-march=native
LIB_NAME = uf
EXT_LIB_NAME = ext
ENGINE_SRC_DIR += ./engine/src
ENGINE_INC_DIR += ./engine/inc
ENGINE_LIB_DIR += ./engine/lib
EXT_SRC_DIR += ./ext
CLIENT_SRC_DIR += ./client
UF_LIBS +=
EXT_LIBS +=
FLAGS += -Wno-unknown-pragmas -std=c++17 -g
LIB_NAME += uf
EXT_LIB_NAME += ext
#VULKAN_SDK_PATH += /c/VulkanSDK/1.2.154.0/
VULKAN_SDK_PATH += /c/VulkanSDK/1.2.162.0/
GLSL_VALIDATOR += $(VULKAN_SDK_PATH)/Bin32/glslangValidator
#VULKAN_WIN64_SDK_PATH = /cygdrive/c/VulkanSDK/1.1.101.0/
#VULKAN_WIN64_SDK_PATH = /cygdrive/c/VulkanSDK/1.1.108.0/
#VULKAN_WIN64_SDK_PATH = /cygdrive/c/VulkanSDK/1.1.114.0/
VULKAN_WIN64_SDK_PATH = /cygdrive/c/VulkanSDK/1.2.141.0/
#WIN64_CC = i686-w64-mingw32-g++
WIN64_CC = x86_64-w64-mingw32-g++
WIN64_GLSL_VALIDATOR = $(VULKAN_WIN64_SDK_PATH)/Bin32/glslangValidator
# Base Engine's DLL
INC_DIR += $(ENGINE_INC_DIR)/$(ARCH)/$(PREFIX)
DEPS +=
ifneq (,$(findstring win64,$(ARCH)))
REQ_DEPS += vulkan json:nlohmann png openal ogg freetype ncurses curl openvr luajit ultralight-ux bullet meshoptimizer # discord
FLAGS +=
DEPS += -lgdi32
else ifneq (,$(findstring dreamcast,$(ARCH)))
REQ_DEPS += opengl json:nlohmann freetype ogg openal meshoptimizer # luajit ultralight-ux ncurses curl openvr discord
FLAGS += $(KOS_CPPFLAGS) -frtti -fexceptions
INCS += $(KOS_INC_PATHS) -I/opt/dreamcast/sh-elf/sh-elf/include
LIBS += $(KOS_LIB_PATHS) -L/opt/dreamcast/sh-elf/sh-elf/lib
endif
ifneq (,$(findstring vulkan,$(REQ_DEPS)))
FLAGS += -DVK_USE_PLATFORM_WIN32_KHR -DUF_USE_VULKAN
DEPS += -lvulkan -lspirv-cross
endif
ifneq (,$(findstring opengl,$(REQ_DEPS)))
FLAGS += -DUF_USE_OPENGL -DUF_USE_GLEW
ifneq (,$(findstring dreamcast,$(ARCH)))
DEPS += -lGLdc
else
DEPS += -lglew32 -lopengl32 -lglu32
endif
endif
ifneq (,$(findstring json,$(REQ_DEPS)))
FLAGS += -DUF_USE_JSON
DEPS +=
ifneq (,$(findstring nlohmann,$(REQ_DEPS)))
FLAGS += -DUF_JSON_USE_NLOHMANN
endif
endif
ifneq (,$(findstring png,$(REQ_DEPS)))
FLAGS += -DUF_USE_PNG
DEPS += -lpng -lz
endif
ifneq (,$(findstring openal,$(REQ_DEPS)))
FLAGS += -DUF_USE_OPENAL
ifneq (,$(findstring dreamcast,$(ARCH)))
DEPS += -lAL
else
FLAGS += -DUF_USE_ALUT
DEPS += -lopenal -lalut
endif
endif
ifneq (,$(findstring ogg,$(REQ_DEPS)))
FLAGS += -DUF_USE_VORBIS
DEPS += -lvorbis -lvorbisfile -logg
endif
ifneq (,$(findstring freetype,$(REQ_DEPS)))
FLAGS += -DUF_USE_FREETYPE
DEPS += -lfreetype
endif
ifneq (,$(findstring ncurses,$(REQ_DEPS)))
FLAGS += -DUF_USE_NCURSES
DEPS += -lncursesw
endif
ifneq (,$(findstring curl,$(REQ_DEPS)))
FLAGS += -DUF_USE_CURL
DEPS += -lcurl
endif
ifneq (,$(findstring discord,$(REQ_DEPS)))
FLAGS += -DUF_USE_DISCORD
DEPS += -ldiscord_game_sdk
endif
ifneq (,$(findstring openvr,$(REQ_DEPS)))
FLAGS += -DUF_USE_OPENVR -DUSE_OPENVR_MINGW
DEPS += -lopenvr_api
endif
ifneq (,$(findstring lua,$(REQ_DEPS)))
FLAGS += -DUF_USE_LUA
ifneq (,$(findstring luajit,$(REQ_DEPS)))
FLAGS += -DUF_USE_LUAJIT
DEPS += -lluajit-5.1
INCS += -I/mingw64/include/luajit-2.1
else
DEPS += -llua-5.1
endif
endif
ifneq (,$(findstring ultralight-ux,$(REQ_DEPS)))
FLAGS += -DUF_USE_ULTRALIGHT_UX
DEPS += -lUltralight -lUltralightCore -lWebCore -lAppCore
endif
ifneq (,$(findstring bullet,$(REQ_DEPS)))
FLAGS += -DUF_USE_BULLET
ifneq (,$(findstring dreamcast,$(ARCH)))
DEPS += -lbulletdynamics -lbulletcollision -lbulletmath
else
DEPS += -lBulletDynamics -lBulletCollision -lLinearMath
INCS += -I$(ENGINE_INC_DIR)/bullet/
endif
endif
ifneq (,$(findstring simd,$(REQ_DEPS)))
FLAGS += -DUF_USE_SIMD #-march=native
endif
ifneq (,$(findstring meshoptimizer,$(REQ_DEPS)))
FLAGS += -DUF_USE_MESHOPTIMIZER
DEPS += -lmeshoptimizer
endif
#DEPS += -lvulkan -lncursesw
LINKS += $(UF_LIBS) $(EXT_LIBS) $(DEPS)
WIN64_INC_DIR = $(ENGINE_INC_DIR)/win64
WIN64_LB_FLAGS = $(ENGINE_LIB_DIR)/win64
WIN64_DEPS = -lgdi32 -lvulkan-1 -lpng -lz -lassimp -ljsoncpp -lopenal32 -lalut -lvorbis -lvorbisfile -logg -lfreetype -lncursesw -lcurl -ldiscord_game_sdk -lopenvr_api
#WIN64_DEPS = -lvulkan -lncursesw
WIN64_LINKS = $(UF_LIBS) $(EXT_LIBS) $(WIN64_DEPS)
WIN64_FLAGS = $(FLAGS) -g
#-Wl,-subsystem,windows
LIB_DIR += $(ENGINE_LIB_DIR)/$(ARCH)
INCS += -I$(ENGINE_INC_DIR) -I$(INC_DIR) -I$(VULKAN_SDK_PATH)/include -I/mingw64/include
LIBS += -L$(ENGINE_LIB_DIR) -L$(LIB_DIR) -L$(LIB_DIR)/$(PREFIX) -L$(VULKAN_SDK_PATH)/Lib
WIN64_LIB_DIR = $(ENGINE_LIB_DIR)/win64/
WIN64_INCS = -I$(ENGINE_INC_DIR) -I$(WIN64_INC_DIR) -I$(VULKAN_WIN64_SDK_PATH)/include
WIN64_LIBS = -L$(ENGINE_LIB_DIR) -L$(WIN64_LIB_DIR) -L$(VULKAN_WIN64_SDK_PATH)/Lib
SRCS_DLL += $(wildcard $(ENGINE_SRC_DIR)/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*/*/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*/*/*/*.cpp)
OBJS_DLL += $(patsubst %.cpp,%.$(ARCH).$(PREFIX).o,$(SRCS_DLL))
BASE_DLL += lib$(LIB_NAME)
IM_DLL += $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_DLL).$(TARGET_LIB_EXTENSION).a
EX_DLL += $(BIN_DIR)/exe/lib/$(ARCH)/$(PREFIX)/$(BASE_DLL).$(TARGET_LIB_EXTENSION)
SRCS_WIN64_DLL = $(wildcard $(ENGINE_SRC_DIR)/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*/*/*.cpp) $(wildcard $(ENGINE_SRC_DIR)/*/*/*/*/*.cpp)
OBJS_WIN64_DLL = $(patsubst %.cpp,%.win64.o,$(SRCS_WIN64_DLL))
BASE_WIN64_DLL = lib$(LIB_NAME)
IM_WIN64_DLL = $(ENGINE_LIB_DIR)/win64/$(BASE_WIN64_DLL).dll.a
EX_WIN64_DLL = $(BIN_DIR)/lib/win64/$(BASE_WIN64_DLL).dll
# External Engine's DLL
EXT_INC_DIR += $(INC_DIR)
EXT_LB_FLAGS += $(LIB_DIR)
EXT_DEPS += -l$(LIB_NAME) $(DEPS)
EXT_LINKS += $(UF_LIBS) $(EXT_LIBS) $(EXT_DEPS)
EXT_WIN64_INC_DIR = $(WIN64_INC_DIR)
EXT_WIN64_LB_FLAGS = $(WIN64_LIB_DIR)
EXT_WIN64_DEPS = -l$(LIB_NAME) $(WIN64_DEPS)
EXT_WIN64_LINKS = $(UF_LIBS) $(EXT_LIBS) $(EXT_WIN64_DEPS)
EXT_WIN64_FLAGS = $(FLAGS)
#-Wl,-subsystem,windows
EXT_LIB_DIR += $(ENGINE_LIB_DIR)/$(ARCH)
EXT_INCS += -I$(ENGINE_INC_DIR) -I$(EXT_INC_DIR) -I$(VULKAN_SDK_PATH)/include -I/mingw64/include
EXT_LIBS += -L$(ENGINE_LIB_DIR) -L$(EXT_LIB_DIR) -L$(EXT_LIB_DIR)/$(PREFIX) -L$(VULKAN_SDK_PATH)/Lib -L/mingw64/lib
EXT_WIN64_LIB_DIR = $(ENGINE_LIB_DIR)/win64/
EXT_WIN64_INCS = -I$(ENGINE_INC_DIR) -I$(EXT_WIN64_INC_DIR) -I$(VULKAN_WIN64_SDK_PATH)/include
EXT_WIN64_LIBS = -L$(ENGINE_LIB_DIR) -L$(EXT_WIN64_LIB_DIR) -L$(VULKAN_WIN64_SDK_PATH)/Lib
SRCS_EXT_DLL += $(wildcard $(EXT_SRC_DIR)/*.cpp) $(wildcard $(EXT_SRC_DIR)/*/*.cpp) $(wildcard $(EXT_SRC_DIR)/*/*/*.cpp) $(wildcard $(EXT_SRC_DIR)/*/*/*/*.cpp) $(wildcard $(EXT_SRC_DIR)/*/*/*/*/*.cpp)
OBJS_EXT_DLL += $(patsubst %.cpp,%.$(ARCH).$(PREFIX).o,$(SRCS_EXT_DLL))
BASE_EXT_DLL += lib$(EXT_LIB_NAME)
EXT_IM_DLL += $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_EXT_DLL).$(TARGET_LIB_EXTENSION).a
EXT_EX_DLL += $(BIN_DIR)/exe/lib/$(ARCH)/$(PREFIX)/$(BASE_EXT_DLL).$(TARGET_LIB_EXTENSION)
SRCS_EXT_WIN64_DLL = $(wildcard $(EXT_SRC_DIR)/*.cpp) $(wildcard $(EXT_SRC_DIR)/*/*.cpp) $(wildcard $(EXT_SRC_DIR)/*/*/*.cpp)
OBJS_EXT_WIN64_DLL = $(patsubst %.cpp,%.win64.o,$(SRCS_EXT_WIN64_DLL))
BASE_EXT_WIN64_DLL = lib$(EXT_LIB_NAME)
EXT_IM_WIN64_DLL = $(ENGINE_LIB_DIR)/win64/$(BASE_EXT_WIN64_DLL).dll.a
EXT_EX_WIN64_DLL = $(BIN_DIR)/lib/win64/$(BASE_EXT_WIN64_DLL).dll
# Client EXE
SRCS += $(wildcard $(CLIENT_SRC_DIR)/*.cpp) $(wildcard $(CLIENT_SRC_DIR)/*/*.cpp)
OBJS += $(patsubst %.cpp,%.$(ARCH).$(PREFIX).o,$(SRCS))
TARGET += $(BIN_DIR)/exe/$(TARGET_NAME).$(PREFIX).$(TARGET_EXTENSION)
SRCS_WIN64 = $(wildcard $(CLIENT_SRC_DIR)/*.cpp) $(wildcard $(CLIENT_SRC_DIR)/*/*.cpp)
OBJS_WIN64 = $(patsubst %.cpp,%.win64.o,$(SRCS_WIN64))
TARGET_WIN64 = $(BIN_DIR)/$(TARGET_NAME).exe
# Shaders
SRCS_SHADERS += $(wildcard bin/data/shaders/*.glsl)
TARGET_SHADERS += $(patsubst %.glsl,%.spv,$(SRCS_SHADERS))
SRCS_SHADERS = $(wildcard bin/data/shaders/*.glsl)
TARGET_SHADERS = $(patsubst %.glsl,%.spv,$(SRCS_SHADERS))
ifneq (,$(findstring dreamcast,$(ARCH)))
$(ARCH): $(EX_DLL) $(EXT_EX_DLL) $(TARGET) $(TARGET_SHADERS)
win64: $(EX_WIN64_DLL) $(EXT_EX_WIN64_DLL) $(TARGET_WIN64) $(TARGET_SHADERS)
%.$(ARCH).$(PREFIX).o: %.cpp
$(CC) $(FLAGS) $(INCS) -c $< -o $@
rm-exe64:
-rm $(EX_WIN64_DLL)
-rm $(EXT_EX_WIN64_DLL)
-rm $(TARGET_WIN64)
-rm $(TARGET_SHADERS)
$(EX_DLL): FLAGS += -DUF_EXPORTS -DJSON_DLL_BUILD
$(EX_DLL): $(OBJS_DLL)
$(KOS_AR) cru $@ $^
$(KOS_RANLIB) $@
cp $@ $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_DLL).a
%.win64.o: %.cpp
$(WIN64_CC) $(WIN64_FLAGS) $(WIN64_INCS) -c $< -o $@
$(EXT_EX_DLL): FLAGS += -DEXT_EXPORTS -DJSON_DLL_BUILD
$(EXT_EX_DLL): $(OBJS_EXT_DLL)
$(KOS_AR) cru $@ $^
$(KOS_RANLIB) $@
cp $@ $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_EXT_DLL).a
$(EX_WIN64_DLL): WIN64_FLAGS += -DUF_EXPORTS
$(EX_WIN64_DLL): $(OBJS_WIN64_DLL)
$(WIN64_CC) -shared -o $(EX_WIN64_DLL) -g -Wl,--out-implib=$(IM_WIN64_DLL) $(OBJS_WIN64_DLL) $(WIN64_LIBS) $(WIN64_INCS) $(WIN64_LINKS)
cp $(ENGINE_LIB_DIR)/win64/$(BASE_WIN64_DLL).dll.a $(ENGINE_LIB_DIR)/win64/$(BASE_WIN64_DLL).a
$(TARGET): $(OBJS)
$(CC) -O2 -fomit-frame-pointer -ml -m4-single-only -ffunction-sections -fdata-sections $(KOS_INC_PATHS) $(INCS) -D_arch_dreamcast -D_arch_sub_pristine -Wall -g -fno-builtin -ml -m4-single-only -Wl,-Ttext=0x8c010000 -Wl,--gc-sections -T/opt/dreamcast/kos/utils/ldscripts/shlelf.xc -nodefaultlibs $(KOS_LIB_PATHS) $(LIBS) -o $(TARGET) $(OBJS) -Wl,--start-group -lkallisti -lc -lm -lgcc -lstdc++ -l$(LIB_NAME) -l$(EXT_LIB_NAME) -Wl,--end-group
else
$(ARCH): $(EX_DLL) $(EXT_EX_DLL) $(TARGET) $(TARGET_SHADERS)
$(EXT_EX_WIN64_DLL): WIN64_FLAGS += -DEXT_EXPORTS
$(EXT_EX_WIN64_DLL): $(OBJS_EXT_WIN64_DLL)
$(WIN64_CC) -shared -o $(EXT_EX_WIN64_DLL) -g -Wl,--out-implib=$(EXT_IM_WIN64_DLL) $(OBJS_EXT_WIN64_DLL) $(EXT_WIN64_LIBS) $(EXT_WIN64_INCS) $(EXT_WIN64_LINKS)
cp $(ENGINE_LIB_DIR)/win64/$(BASE_EXT_WIN64_DLL).dll.a $(ENGINE_LIB_DIR)/win64/$(BASE_EXT_WIN64_DLL).a
%.$(ARCH).$(PREFIX).o: %.cpp
$(CC) $(FLAGS) $(INCS) -c $< -o $@
$(EX_DLL): FLAGS += -DUF_EXPORTS -DJSON_DLL_BUILD
$(EX_DLL): $(OBJS_DLL)
$(CC) -shared -o $(EX_DLL) -g -Wl,--out-implib=$(IM_DLL) $(OBJS_DLL) $(LIBS) $(INCS) $(LINKS)
cp $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_DLL).$(TARGET_LIB_EXTENSION).a $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_DLL).a
$(EXT_EX_DLL): FLAGS += -DEXT_EXPORTS -DJSON_DLL_BUILD
$(EXT_EX_DLL): $(OBJS_EXT_DLL)
$(CC) -shared -o $(EXT_EX_DLL) -g -Wl,--out-implib=$(EXT_IM_DLL) $(OBJS_EXT_DLL) $(EXT_LIBS) $(EXT_INCS) $(EXT_LINKS)
cp $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_EXT_DLL).$(TARGET_LIB_EXTENSION).a $(ENGINE_LIB_DIR)/$(ARCH)/$(PREFIX)/$(BASE_EXT_DLL).a
$(TARGET): $(OBJS)
$(CC) $(FLAGS) $(OBJS) $(LIBS) $(INCS) $(LINKS) -l$(LIB_NAME) -l$(EXT_LIB_NAME) -o $(TARGET)
endif
$(TARGET_WIN64): $(OBJS_WIN64)
$(WIN64_CC) $(WIN64_FLAGS) $(OBJS_WIN64) $(WIN64_LIBS) $(WIN64_INCS) $(WIN64_LINKS) -l$(LIB_NAME) -l$(EXT_LIB_NAME) -o $(TARGET_WIN64)
%.spv: %.glsl
$(GLSL_VALIDATOR) -V $< -o $@
$(WIN64_GLSL_VALIDATOR) -V $< -o $@
clean:
@-rm $(EX_DLL)
@-rm $(EXT_EX_DLL)
@-rm $(TARGET)
clean-win64:
@-rm $(EX_WIN64_DLL)
@-rm $(EXT_EX_WIN64_DLL)
@-rm $(TARGET_WIN64)
@-rm -f $(OBJS_DLL)
@-rm -f $(OBJS_EXT_DLL)
@-rm -f $(OBJS)
clean-uf:
@-rm $(EX_DLL)
@-rm -f $(OBJS_DLL)
clean-exf:
@-rm $(EXT_EX_DLL)
@-rm -f $(OBJS_EXT_DLL)
clean-exe:
-rm $(EX_DLL)
-rm $(EXT_EX_DLL)
-rm $(TARGET)
-rm $(TARGET_SHADERS)
@-rm -f $(OBJS_WIN64_DLL)
@-rm -f $(OBJS_EXT_WIN64_DLL)
@-rm -f $(OBJS_WIN64)

View File

@ -1,44 +0,0 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec4 inColor;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[PASSES];
mat4 projection[PASSES];
};
layout (binding = 0) uniform UBO {
Matrices matrices;
vec4 color;
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec4 outColor;
layout (location = 2) out vec3 outNormal;
layout (location = 3) out vec3 outPosition;
out gl_PerVertex {
vec4 gl_Position;
};
void main() {
outUv = inUv;
outColor = inColor.rgba;
outPosition = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outNormal = normalize(outNormal);
gl_Position = ubo.matrices.projection[PushConstant.pass] * ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0);
}

View File

@ -0,0 +1,294 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec3 inPositionEye;
layout (location = 2) in vec3 inNormalEye;
layout (location = 3) in vec4 inColor;
layout (location = 0) out vec4 outFragColor;
void fog( inout vec3 i ) {
vec3 color = vec3( 0, 0, 0 );
float inner = 8, outer = 64;
float distance = length(-inPositionEye);
float factor = (distance - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
i = mix(i.rgb, color, factor);
}
void phong( inout vec3 i ) {
vec3 Ls = vec3(1.0, 1.0, 1.0); // light specular
vec3 Ld = vec3(0.4, 0.4, 1.0); // light color
vec3 La = vec3(0.1, 0.1, 0.1);
vec3 Ks = vec3(0.6, 0.6, 0.9); // material specular
vec3 Kd = i; // material diffuse
vec3 Ka = vec3(0.7, 0.7, 0.7);
float Kexp = 1000.0;
vec3 dist_light_eye = vec3(0, 0, 0) - inPositionEye;
vec3 dir_light_eye = normalize(dist_light_eye);
float d_dot = max(dot( dir_light_eye, inNormalEye ), 0.0);
vec3 reflection_eye = reflect( -dir_light_eye, inNormalEye );
vec3 surface_eye = normalize(-inPositionEye);
float s_dot = max(dot( reflection_eye, surface_eye ), 0.0);
float s_factor = pow( s_dot, Kexp );
vec3 Ia = La * Ka;
vec3 Id = Ld * Kd * d_dot;
vec3 Is = Ls * Ks * s_factor;
i = Is + Id + Ia;
}
const int indexMatrix16x16[256] = int[](0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255,
128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127,
32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223,
160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95,
8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247,
136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119,
40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215,
168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87,
2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253,
130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125,
34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221,
162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93,
10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245,
138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117,
42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213,
170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85);
float indexValue16x16() {
int x = int(mod(gl_FragCoord.x, 16));
int y = int(mod(gl_FragCoord.y, 16));
return indexMatrix16x16[(x + y * 16)] / 256.0;
}
/*
const int paletteSize = 16;
const vec3 palette[paletteSize] = vec3[](
vec3( 0x00/255.0, 0x00/255.0, 0x18/255.0),
vec3( 0x60/255.0, 0x60/255.0, 0x78/255.0),
vec3( 0x00/255.0, 0x18/255.0, 0x30/255.0),
vec3( 0x18/255.0, 0x18/255.0, 0x30/255.0),
vec3( 0x30/255.0, 0x30/255.0, 0x48/255.0),
vec3( 0x30/255.0, 0x30/255.0, 0x30/255.0),
vec3( 0x18/255.0, 0x18/255.0, 0x48/255.0),
vec3( 0x00/255.0, 0x00/255.0, 0x00/255.0),
vec3( 0x18/255.0, 0x00/255.0, 0x00/255.0),
vec3( 0x48/255.0, 0x48/255.0, 0x60/255.0),
vec3( 0x30/255.0, 0x00/255.0, 0x18/255.0),
vec3( 0x00/255.0, 0x18/255.0, 0x48/255.0),
vec3( 0x90/255.0, 0x90/255.0, 0xa8/255.0),
vec3( 0x48/255.0, 0x18/255.0, 0x30/255.0),
vec3( 0x18/255.0, 0x30/255.0, 0x48/255.0),
vec3( 0x18/255.0, 0x00/255.0, 0x18/255.0)
);
*/
const int paletteSize = 40;
const vec3 palette[paletteSize] = vec3[](
vec3( 0, 0, 0),
vec3( 0, 0, 0.502),
vec3( 0, 0, 0.753),
vec3( 0, 0, 1),
vec3( 0, 1, 0.251),
vec3( 0, 1, 0.50),
vec3( 24.0/360.0, 1, 0.251),
vec3( 24.0/360.0, 1, 0.5),
vec3( 24.0/360.0, 1, 0.625),
vec3( 24.0/360.0, 1, 0.751),
vec3( 30.0/360.0, 1, 0.251),
vec3( 60.0/360.0, 0.333, 0.376),
vec3( 60.0/360.0, 1, 0.251),
vec3( 60.0/360.0, 1, 0.5),
vec3( 60.0/360.0, 1, 0.751),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.751),
vec3(150.0/360.0, 1, 0.251),
vec3(150.0/360.0, 1, 0.5),
vec3(150.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(210.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.751),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.251),
vec3(270.0/360.0, 1, 0.5),
vec3(270.0/360.0, 1, 0.751),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.751),
vec3(330.0/360.0, 1, 0.251),
vec3(330.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.751)
);
/*
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
*/
float hueToRgb(float f1, float f2, float hue) {
if (hue < 0.0)
hue += 1.0;
else if (hue > 1.0)
hue -= 1.0;
float res;
if ((6.0 * hue) < 1.0)
res = f1 + (f2 - f1) * 6.0 * hue;
else if ((2.0 * hue) < 1.0)
res = f2;
else if ((3.0 * hue) < 2.0)
res = f1 + (f2 - f1) * ((2.0 / 3.0) - hue) * 6.0;
else
res = f1;
return res;
}
vec3 hslToRgb(vec3 hsl) {
vec3 rgb;
if (hsl.y == 0.0) {
rgb = vec3(hsl.z); // Luminance
} else {
float f2;
if (hsl.z < 0.5)
f2 = hsl.z * (1.0 + hsl.y);
else
f2 = hsl.z + hsl.y - hsl.y * hsl.z;
float f1 = 2.0 * hsl.z - f2;
rgb.r = hueToRgb(f1, f2, hsl.x + (1.0/3.0));
rgb.g = hueToRgb(f1, f2, hsl.x);
rgb.b = hueToRgb(f1, f2, hsl.x - (1.0/3.0));
}
return rgb;
}
vec3 rgbToHcv(vec3 rgb) {
float epsilon = 1e-10;
// Based on work by Sam Hocevar and Emil Persson
vec4 p = (rgb.g < rgb.b) ? vec4(rgb.bg, -1.0, 2.0 / 3.0) : vec4(rgb.gb, 0.0, -1.0 / 3.0);
vec4 q = (rgb.r < p.x) ? vec4(p.xyw, rgb.r) : vec4(rgb.r, p.yzx);
float c = q.x - min(q.w, q.y);
float h = abs((q.w - q.y) / (6.0 * c + epsilon) + q.z);
return vec3(h, c, q.x);
}
vec3 rgbToHsl(vec3 rgb) {
float epsilon = 1e-10;
vec3 hcv = rgbToHcv(rgb);
float l = hcv.z - hcv.y * 0.5;
float s = hcv.y / (1.0 - abs(l * 2.0 - 1.0) + epsilon);
return vec3(hcv.x, s, l);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = rgbToHsl(palette[i]);
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 8.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue16x16();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue16x16();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
outFragColor = texture(samplerColor, inUv);
phong(outFragColor.rgb);
fog(outFragColor.rgb);
outFragColor.rgb = mix( outFragColor.rgb, inColor.rgb, inColor.a );
if ( outFragColor.a < 0.001 ) discard;
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -0,0 +1,189 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec3 inPositionEye;
layout (location = 2) in vec3 inNormalEye;
layout (location = 3) in vec4 inColor;
layout (location = 0) out vec4 outFragColor;
void fog( inout vec3 i ) {
vec3 color = vec3( 0, 0, 0 );
float inner = 8, outer = 64;
float distance = length(-inPositionEye);
float factor = (distance - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
i = mix(i.rgb, color, factor);
}
void phong( inout vec3 i ) {
vec3 Ls = vec3(1.0, 1.0, 1.0); // light specular
vec3 Ld = vec3(0.4, 0.4, 1.0); // light color
vec3 La = vec3(0.1, 0.1, 0.1);
vec3 Ks = vec3(0.6, 0.6, 0.9); // material specular
vec3 Kd = i; // material diffuse
vec3 Ka = vec3(0.7, 0.7, 0.7);
float Kexp = 1000.0;
vec3 dist_light_eye = vec3(0, 0, 0) - inPositionEye;
vec3 dir_light_eye = normalize(dist_light_eye);
float d_dot = max(dot( dir_light_eye, inNormalEye ), 0.0);
vec3 reflection_eye = reflect( -dir_light_eye, inNormalEye );
vec3 surface_eye = normalize(-inPositionEye);
float s_dot = max(dot( reflection_eye, surface_eye ), 0.0);
float s_factor = pow( s_dot, Kexp );
vec3 Ia = La * Ka;
vec3 Id = Ld * Kd * d_dot;
vec3 Is = Ls * Ks * s_factor;
i = Is + Id + Ia;
}
const int indexMatrix4x4[16] = int[](0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5);
float indexValue4x4() {
int x = int(mod(gl_FragCoord.x, 4));
int y = int(mod(gl_FragCoord.y, 4));
return indexMatrix4x4[(x + y * 4)] / 16.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue4x4();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue4x4();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
outFragColor = texture(samplerColor, inUv);
phong(outFragColor.rgb);
fog(outFragColor.rgb);
outFragColor.rgb = mix( outFragColor.rgb, inColor.rgb, inColor.a );
if ( outFragColor.a < 0.001 ) discard;
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -0,0 +1,194 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec3 inPositionEye;
layout (location = 2) in vec3 inNormalEye;
layout (location = 3) in vec4 inColor;
layout (location = 0) out vec4 outFragColor;
void fog( inout vec3 i ) {
vec3 color = vec3( 0, 0, 0 );
float inner = 8, outer = 64;
float distance = length(-inPositionEye);
float factor = (distance - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
i = mix(i.rgb, color, factor);
}
void phong( inout vec3 i ) {
vec3 Ls = vec3(1.0, 1.0, 1.0); // light specular
vec3 Ld = vec3(0.4, 0.4, 1.0); // light color
vec3 La = vec3(0.1, 0.1, 0.1);
vec3 Ks = vec3(0.6, 0.6, 0.9); // material specular
vec3 Kd = i; // material diffuse
vec3 Ka = vec3(0.7, 0.7, 0.7);
float Kexp = 1000.0;
vec3 dist_light_eye = vec3(0, 0, 0) - inPositionEye;
vec3 dir_light_eye = normalize(dist_light_eye);
float d_dot = max(dot( dir_light_eye, inNormalEye ), 0.0);
vec3 reflection_eye = reflect( -dir_light_eye, inNormalEye );
vec3 surface_eye = normalize(-inPositionEye);
float s_dot = max(dot( reflection_eye, surface_eye ), 0.0);
float s_factor = pow( s_dot, Kexp );
vec3 Ia = La * Ka;
vec3 Id = Ld * Kd * d_dot;
vec3 Is = Ls * Ks * s_factor;
i = Is + Id + Ia;
}
const int indexMatrix8x8[64] = int[](0, 32, 8, 40, 2, 34, 10, 42,
48, 16, 56, 24, 50, 18, 58, 26,
12, 44, 4, 36, 14, 46, 6, 38,
60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41,
51, 19, 59, 27, 49, 17, 57, 25,
15, 47, 7, 39, 13, 45, 5, 37,
63, 31, 55, 23, 61, 29, 53, 21);
float indexValue8x8() {
int x = int(mod(gl_FragCoord.x, 8));
int y = int(mod(gl_FragCoord.y, 8));
return indexMatrix8x8[(x + y * 8)] / 64.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue8x8();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue8x8();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
outFragColor = texture(samplerColor, inUv);
phong(outFragColor.rgb);
fog(outFragColor.rgb);
outFragColor.rgb = mix( outFragColor.rgb, inColor.rgb, inColor.a );
if ( outFragColor.a < 0.001 ) discard;
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -1,49 +1,54 @@
#version 450
#define UF_DEFERRED_SAMPLING 0
#define UF_CAN_DISCARD 1
layout (binding = 1) uniform sampler2D samplerTexture;
layout (binding = 1) uniform sampler2D samplerColor;
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec4 inColor;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec3 inPosition;
layout (location = 1) in vec3 inPositionEye;
layout (location = 2) in vec3 inNormalEye;
layout (location = 3) in vec4 inColor;
layout (location = 0) out vec4 outFragColor;
layout (location = 0) out uvec2 outId;
layout (location = 1) out vec2 outNormals;
#if UF_DEFERRED_SAMPLING
layout (location = 2) out vec2 outUvs;
#else
layout (location = 2) out vec4 outAlbedo;
#endif
void fog( inout vec3 i ) {
vec3 color = vec3( 0, 0, 0 );
float inner = 8, outer = 64;
float distance = length(-inPositionEye);
float factor = (distance - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
vec2 encodeNormals( vec3 n ) {
float p = sqrt(n.z*8+8);
return n.xy/p + 0.5;
i = mix(i.rgb, color, factor);
}
float mipLevel( in vec2 uv ) {
vec2 dx_vtc = dFdx(uv);
vec2 dy_vtc = dFdy(uv);
return 0.5 * log2(max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc)));
void phong( inout vec3 i ) {
vec3 Ls = vec3(1.0, 1.0, 1.0); // light specular
vec3 Ld = vec3(0.4, 0.4, 1.0); // light color
vec3 La = vec3(0.1, 0.1, 0.1);
vec3 Ks = vec3(0.6, 0.6, 0.9); // material specular
vec3 Kd = i; // material diffuse
vec3 Ka = vec3(0.7, 0.7, 0.7);
float Kexp = 1000.0;
vec3 dist_light_eye = vec3(0, 0, 0) - inPositionEye;
vec3 dir_light_eye = normalize(dist_light_eye);
float d_dot = max(dot( dir_light_eye, inNormalEye ), 0.0);
vec3 reflection_eye = reflect( -dir_light_eye, inNormalEye );
vec3 surface_eye = normalize(-inPositionEye);
float s_dot = max(dot( reflection_eye, surface_eye ), 0.0);
float s_factor = pow( s_dot, Kexp );
vec3 Ia = La * Ka;
vec3 Id = Ld * Kd * d_dot;
vec3 Is = Ls * Ks * s_factor;
i = Is + Id + Ia;
}
void main() {
float mip = mipLevel(inUv.xy);
vec2 uv = inUv.xy;
vec4 C = vec4(1, 1, 1, 1);
vec3 P = inPosition;
vec3 N = inNormal;
#if UF_DEFERRED_SAMPLING
outUvs = wrap(inUv.xy);
vec4 outAlbedo = vec4(0,0,0,0);
#endif
#if !UF_DEFERRED_SAMPLING || UF_CAN_DISCARD
C = textureLod( samplerTexture, uv, mip );
#endif
#if !UF_DEFERRED_SAMPLING
outAlbedo = C * inColor;
#endif
outNormals = encodeNormals( N );
//outId = ivec2(0, 0);
outFragColor = texture(samplerColor, inUv);
phong(outFragColor.rgb);
fog(outFragColor.rgb);
// outFragColor.rgb = mix( outFragColor.rgb, inColor.rgb, inColor.a );
outFragColor.rgb = outFragColor.rgb * inColor.rgb;
if ( outFragColor.a < 0.001 ) discard;
}

View File

@ -0,0 +1,39 @@
#version 450
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
layout( push_constant ) uniform PushBlock {
uint pass;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[2];
mat4 projection[2];
};
layout (binding = 0) uniform UBO {
Matrices matrices;
vec4 color;
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec3 outPositionEye;
layout (location = 2) out vec3 outNormalEye;
layout (location = 3) out vec4 outColor;
out gl_PerVertex {
vec4 gl_Position;
};
void main() {
outUv = inUv;
outPositionEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormalEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outColor = ubo.color;
gl_Position = ubo.matrices.projection[PushConstant.pass] * ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0);
}

View File

@ -1,19 +1,17 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[PASSES];
mat4 projection[PASSES];
mat4 view[2];
mat4 projection[2];
};
layout (binding = 0) uniform UBO {
@ -22,9 +20,9 @@ layout (binding = 0) uniform UBO {
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec4 outColor;
layout (location = 2) out vec3 outNormal;
layout (location = 3) out vec3 outPosition;
layout (location = 1) out vec3 outPositionEye;
layout (location = 2) out vec3 outNormalEye;
layout (location = 3) out vec4 outColor;
out gl_PerVertex {
vec4 gl_Position;
@ -33,11 +31,9 @@ out gl_PerVertex {
void main() {
outUv = inUv;
outPositionEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormalEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outColor = ubo.color;
outPosition = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outNormal = normalize(outNormal);
gl_Position = ubo.matrices.projection[PushConstant.pass] * ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0);
}

View File

@ -1,23 +0,0 @@
#version 450
#extension GL_EXT_samplerless_texture_functions : require
layout (binding = 1) uniform sampler samp;
layout (binding = 2) uniform texture2D albedoLeftTexture;
layout (binding = 3) uniform texture2D albedoRightTexture;
layout (location = 0) in vec2 inUv;
layout (location = 0) out vec4 outAlbedoSpecular;
layout( push_constant ) uniform PushBlock {
uint pass;
} PushConstant;
void main() {
if ( PushConstant.pass == 0 ) {
outAlbedoSpecular.rgb = texture(sampler2D(albedoLeftTexture, samp), inUv).rgb;
} else {
outAlbedoSpecular.rgb = texture(sampler2D(albedoRightTexture, samp), inUv).rgb;
}
outAlbedoSpecular.a = 1;
}

View File

@ -1,16 +0,0 @@
#version 450
layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 0) out vec2 outUv;
out gl_PerVertex {
vec4 gl_Position;
};
void main() {
outUv = inUv;
gl_Position = vec4(inPos.xy, 0.0, 1.0);
}

View File

@ -0,0 +1,12 @@
#version 450
layout (set = 0, binding = 1) uniform texture2D tex;
layout (set = 0, binding = 2) uniform sampler samp;
layout (location = 0) in vec2 inUv;
layout (location = 0) out vec4 outFragColor;
void main() {
outFragColor = texture(sampler2D(tex, samp), inUv);
// outFragColor = vec4(inUv, 1.0f, 0.0f);
}

View File

@ -1,75 +0,0 @@
#version 450
#extension GL_EXT_samplerless_texture_functions : require
#define UF_DEFERRED_SAMPLING 0
#define UF_CAN_DISCARD 1
layout (binding = 1) uniform sampler samp;
layout (binding = 2) uniform utexture2D textureId;
layout (binding = 3) uniform texture2D textureNormals;
#if UF_DEFERRED_SAMPLING
layout (binding = 4) uniform texture2D textureUvs;
#else
layout (binding = 4) uniform texture2D textureAlbedo;
#endif
struct Cursor {
vec2 position;
vec2 radius;
vec4 color;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in float inAlpha;
layout (location = 2) in Cursor inCursor;
layout (location = 0) out vec4 outAlbedo;
void main() {
if ( inCursor.radius.x <= 0 && inCursor.radius.y <= 0 ) {
vec2 uv = gl_FragCoord.xy / textureSize(textureId, 0);
outAlbedo = texture(sampler2D(textureAlbedo, samp), uv).rgba;
return;
}
float dist = pow(inUv.x - inCursor.position.x, 2) / pow(inCursor.radius.x, 2) + pow(inUv.y - inCursor.position.y, 2) / pow(inCursor.radius.y, 2);
outAlbedo = texture(sampler2D(textureAlbedo, samp), inUv);
if ( dist <= 1 ) {
float attenuation = dist;
outAlbedo.rgb = mix( inCursor.color.rgb * inCursor.color.a, outAlbedo.rgb, attenuation );
}
if ( inAlpha < 1.0 ) outAlbedo.a = inAlpha;
}
/*
layout (location = 0) out uvec2 outId;
layout (location = 1) out vec2 outNormals;
#if UF_DEFERRED_SAMPLING
layout (location = 2) out vec2 outUvs;
#else
layout (location = 2) out vec4 outAlbedo;
#endif
void main() {
if ( inCursor.radius.x <= 0 && inCursor.radius.y <= 0 ) {
vec2 uv = gl_FragCoord.xy / textureSize(textureId, 0);
outId = texture(usampler2D(textureId, samp), uv).xy;
outNormals = texture(sampler2D(textureNormals, samp), uv).xy;
#if UF_DEFERRED_SAMPLING
outUvs = texture(sampler2D(textureUvs, samp), uv).xy;
#else
outAlbedo = texture(sampler2D(textureAlbedo, samp), uv).rgba;
#endif
return;
}
float dist = pow(inUv.x - inCursor.position.x, 2) / pow(inCursor.radius.x, 2) + pow(inUv.y - inCursor.position.y, 2) / pow(inCursor.radius.y, 2);
#if !UF_DEFERRED_SAMPLING
outAlbedo = texture(sampler2D(textureAlbedo, samp), inUv);
if ( dist <= 1 ) {
float attenuation = dist;
outAlbedo.rgb = mix( inCursor.color.rgb * inCursor.color.a, outAlbedo.rgb, attenuation );
}
if ( inAlpha < 1.0 ) outAlbedo.a = inAlpha;
#endif
}
*/

View File

@ -1,693 +0,0 @@
#version 450
#extension GL_EXT_samplerless_texture_functions : require
#define SAMPLES 16
#define POISSON_DISK 16
#define RAY_MARCH_FOG 0
#define UF_DEFERRED_SAMPLING 0
layout (constant_id = 0) const uint TEXTURES = 256;
struct Matrices {
mat4 view[2];
mat4 projection[2];
mat4 iView[2];
mat4 iProjection[2];
mat4 iProjectionView[2];
};
struct Space {
vec3 eye;
vec3 world;
} position, normal, view;
struct Fog {
vec3 color;
float stepScale;
vec3 offset;
float densityScale;
float densityThreshold;
float densityMultiplier;
float absorbtion;
float padding1;
vec2 range;
float padding2;
float padding3;
};
struct Mode {
uint type;
uint scalar;
vec2 padding;
vec4 parameters;
};
struct Light {
vec3 position;
float radius;
vec3 color;
float power;
int type;
int mapIndex;
float depthBias;
float padding;
mat4 view;
mat4 projection;
};
struct Material {
vec4 colorBase;
vec4 colorEmissive;
float factorMetallic;
float factorRoughness;
float factorOcclusion;
float factorAlphaCutoff;
int indexAlbedo;
int indexNormal;
int indexEmissive;
int indexOcclusion;
int indexMetallicRoughness;
int modeAlpha;
int padding1;
int padding2;
};
struct Texture {
int index;
int samp;
int remap;
float blend;
vec4 lerp;
};
struct DrawCall {
int materialIndex;
uint materials;
int textureIndex;
uint textures;
};
layout (input_attachment_index = 0, binding = 0) uniform usubpassInputMS samplerId;
layout (input_attachment_index = 1, binding = 1) uniform subpassInputMS samplerNormal;
#if UF_DEFERRED_SAMPLING
layout (input_attachment_index = 2, binding = 2) uniform subpassInputMS samplerUv;
#else
layout (input_attachment_index = 2, binding = 2) uniform subpassInputMS samplerAlbedo;
#endif
layout (input_attachment_index = 3, binding = 4) uniform subpassInputMS samplerDepth;
layout (binding = 5) uniform sampler3D samplerNoise;
layout (binding = 6) uniform samplerCube samplerSkybox;
layout (binding = 7) uniform sampler2D samplerTextures[TEXTURES];
layout (binding = 8) uniform UBO {
Matrices matrices;
Mode mode;
Fog fog;
uint lights;
uint materials;
uint textures;
uint drawCalls;
vec3 ambient;
float kexp;
} ubo;
layout (std140, binding = 9) readonly buffer Lights {
Light lights[];
};
layout (std140, binding = 10) readonly buffer Materials {
Material materials[];
};
layout (std140, binding = 11) readonly buffer Textures {
Texture textures[];
};
layout (std140, binding = 12) readonly buffer DrawCalls {
DrawCall drawCalls[];
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat uint inPushConstantPass;
layout (location = 0) out vec4 outFragColor;
vec2 poissonDisk[16] = vec2[](
vec2( -0.94201624, -0.39906216 ),
vec2( 0.94558609, -0.76890725 ),
vec2( -0.094184101, -0.92938870 ),
vec2( 0.34495938, 0.29387760 ),
vec2( -0.91588581, 0.45771432 ),
vec2( -0.81544232, -0.87912464 ),
vec2( -0.38277543, 0.27676845 ),
vec2( 0.97484398, 0.75648379 ),
vec2( 0.44323325, -0.97511554 ),
vec2( 0.53742981, -0.47373420 ),
vec2( -0.26496911, -0.41893023 ),
vec2( 0.79197514, 0.19090188 ),
vec2( -0.24188840, 0.99706507 ),
vec2( -0.81409955, 0.91437590 ),
vec2( 0.19984126, 0.78641367 ),
vec2( 0.14383161, -0.14100790 )
);
void phong( Light light, vec4 albedoSpecular, inout vec3 i ) {
vec3 Ls = vec3(1.0, 1.0, 1.0); // light specular
vec3 Ld = light.color; // light color
vec3 La = vec3(1.0, 1.0, 1.0);
vec3 Ks = vec3(albedoSpecular.a); // material specular
vec3 Kd = albedoSpecular.rgb; // material diffuse
vec3 Ka = vec3(1.0, 1.0, 1.0);
float Kexp = ubo.kexp;
vec3 V = position.eye;
vec3 N = normal.eye;
vec3 L = light.position.xyz - V;
float dist = length(L);
// if ( light.radius > 0.001 && light.radius < dist ) return;
vec3 D = normalize(L);
float d_dot = max(dot( D, N ), 0.0);
vec3 R = reflect( -D, N );
vec3 S = normalize(-V);
float s_factor = pow( max(dot( R, S ), 0.0), Kexp );
if ( Kexp < 0.0001 ) s_factor = 0;
float radiance = light.power / (dist * dist);
vec3 Ia = La * Ka;
vec3 Id = Ld * Kd * d_dot * radiance;
vec3 Is = Ls * Ks * s_factor * radiance;
i += Id + Is;
}
const float PI = 3.14159265359;
float DistributionGGX(vec3 N, vec3 H, float roughness) {
float a = roughness*roughness;
float a2 = a*a;
float NdotH = max(dot(N, H), 0.0);
float NdotH2 = NdotH*NdotH;
float num = a2;
float denom = (NdotH2 * (a2 - 1.0) + 1.0);
denom = PI * denom * denom;
return num / denom;
}
float GeometrySchlickGGX(float NdotV, float roughness) {
float r = (roughness + 1.0);
float k = (r*r) / 8.0;
float num = NdotV;
float denom = NdotV * (1.0 - k) + k;
return num / denom;
}
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {
float NdotV = max(dot(N, V), 0.0);
float NdotL = max(dot(N, L), 0.0);
float ggx2 = GeometrySchlickGGX(NdotV, roughness);
float ggx1 = GeometrySchlickGGX(NdotL, roughness);
return ggx1 * ggx2;
}
vec3 fresnelSchlick(float cosTheta, vec3 F0) {
return F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0);
}
float random(vec3 seed, int i){
vec4 seed4 = vec4(seed,i);
float dot_product = dot(seed4, vec4(12.9898,78.233,45.164,94.673));
return fract(sin(dot_product) * 43758.5453);
}
float shadowFactor( Light light, uint shadowMap ) {
vec4 positionClip = light.projection * light.view * vec4(position.world, 1.0);
positionClip.xyz /= positionClip.w;
if ( positionClip.x < -1 || positionClip.x >= 1 ) return 0.0;
if ( positionClip.y < -1 || positionClip.y >= 1 ) return 0.0;
if ( positionClip.z <= 0 || positionClip.z >= 1 ) return 0.0;
float factor = 1.0;
// spot light
if ( light.type == 2 || light.type == 3 ) {
float dist = length( positionClip.xy );
if ( dist > 0.5 ) return 0.0;
// spot light with attenuation
if ( light.type == 3 ) {
factor = 1.0 - (pow(dist * 2,2.0));
}
}
vec2 uv = positionClip.xy * 0.5 + 0.5;
float bias = light.depthBias;
/*
if ( true ) {
float cosTheta = clamp(dot(normal.eye, normalize(light.position.xyz - position.eye)), 0, 1);
bias = clamp(bias * tan(acos(cosTheta)), 0, 0.01);
} else if ( true ) {
bias = max(bias * 10 * (1.0 - dot(normal.eye, normalize(light.position.xyz - position.eye))), bias);
}
*/
float eyeDepth = positionClip.z;
int samples = POISSON_DISK;
if ( samples <= 1 ) {
return eyeDepth < texture(samplerTextures[shadowMap], uv).r - bias ? 0.0 : factor;
}
for ( int i = 0; i < samples; ++i ) {
// int index = i;
// int index = int( float(samples) * random(gl_FragCoord.xyy, i) ) % samples;
int index = int( float(samples) * random(floor(position.world.xyz * 1000.0), i)) % samples;
float lightDepth = texture(samplerTextures[shadowMap], uv + poissonDisk[index] / 700.0 ).r;
if ( eyeDepth < lightDepth - bias ) factor -= 1.0 / samples;
}
return factor;
}
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
const int indexMatrix16x16[256] = int[](0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255,
128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127,
32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223,
160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95,
8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247,
136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119,
40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215,
168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87,
2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253,
130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125,
34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221,
162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93,
10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245,
138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117,
42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213,
170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85);
float indexValue16x16( float scale ) {
int x = int(mod(gl_FragCoord.x * scale, 16));
int y = int(mod(gl_FragCoord.y * scale, 16));
return indexMatrix16x16[(x + y * 16)] / 256.0;
}
const int indexMatrix8x8[64] = int[](0, 32, 8, 40, 2, 34, 10, 42,
48, 16, 56, 24, 50, 18, 58, 26,
12, 44, 4, 36, 14, 46, 6, 38,
60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41,
51, 19, 59, 27, 49, 17, 57, 25,
15, 47, 7, 39, 13, 45, 5, 37,
63, 31, 55, 23, 61, 29, 53, 21);
float indexValue8x8( float scale ) {
int x = int(mod(gl_FragCoord.x * scale, 8));
int y = int(mod(gl_FragCoord.y * scale, 8));
return indexMatrix8x8[(x + y * 8)] / 64.0;
}
const int indexMatrix4x4[16] = int[](0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5);
float indexValue4x4( float scale ) {
int x = int(mod(gl_FragCoord.x * scale, 4));
int y = int(mod(gl_FragCoord.y * scale, 4));
return indexMatrix4x4[(x + y * 4)] / 16.0;
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
/*
for (int i = 0; i < palette.length(); ++i) {
temp = rgbToHsl(palette[i].rgb);
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
*/
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = 1; // -0.5 - fract(ubo.mode.parameters.w / 8.0);
if ( ubo.mode.scalar == 16 ) {
d = indexValue16x16(1);
} else if ( ubo.mode.scalar == 8 ) {
d = indexValue8x8(1);
} else if ( ubo.mode.scalar == 4 ) {
d = indexValue4x4(1);
}
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
void dither(inout vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.x = dither(hsl.x);
color = hslToRgb(hsl);
}
void dither1(inout vec3 color) {
vec3 hsl = rgbToHsl(color);
float d = 0;
vec3 cs[2] = { hsl, hsl }; // closestColors(hsl.x);
float scale = 1;
if ( ubo.mode.scalar == 16 ) {
d = indexValue16x16(scale);
} else if ( ubo.mode.scalar == 8 ) {
d = indexValue8x8(scale);
} else if ( ubo.mode.scalar == 4 ) {
d = indexValue4x4(scale);
}
float hueDiff = hueDistance(hsl.x, cs[0].x) / hueDistance(cs[1].x, cs[0].x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? cs[0] : cs[1];
resultColor.z = (lightnessDiff < d) ? l1 : l2;
color = hslToRgb(resultColor);
}
vec3 dither2() {
vec3 vDither = dot( vec2( 171.0, 231.0 ), inUv.xy + ubo.mode.parameters.w ).xxx;
vDither.rgb = fract( vDither.rgb / vec3( 103.0, 71.0, 97.0 ) ) - vec3( 0.5, 0.5, 0.5 );
return ( vDither.rgb / 255.0 ) * 0.375;
}
float rand2(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 143758.5453);
}
float rand3(vec3 co){
return fract(sin(dot(co.xyz ,vec3(12.9898,78.233, 37.719))) * 143758.5453);
}
void whitenoise(inout vec3 color) {
float flicker = ubo.mode.parameters.x;
float pieces = ubo.mode.parameters.y;
float blend = ubo.mode.parameters.z;
float time = ubo.mode.parameters.w;
if ( blend < 0.0001 ) return;
float freq = sin(pow(mod(time, flicker) + flicker, 1.9));
// float whiteNoise = rand3( floor(position.world / pieces) + floor(time * 2) );
float whiteNoise = rand2( floor(gl_FragCoord.xy / pieces) + mod(time, freq) );
color = mix( color, vec3(whiteNoise), blend );
}
void pbr( Light light, vec3 albedo, float metallic, float roughness, vec3 lightPositionWorld, inout vec3 i ) {
vec3 F0 = vec3(0.04);
F0 = mix(F0, albedo, metallic);
vec3 N = normalize(normal.eye);
vec3 L = light.position.xyz - position.eye;
float dist = length(L);
L = normalize(L);
vec3 V = normalize(-position.eye);
vec3 H = normalize(V + L);
float NdotL = max(dot(N, L), 0.0);
float NdotV = max(dot(N, V), 0.0);
float attenuation = light.power / (dist * dist);
vec3 radiance = light.color.rgb * attenuation;
// cook-torrance brdf
float NDF = DistributionGGX(N, H, roughness);
float G = GeometrySmith(N, V, L, roughness);
vec3 F = fresnelSchlick(max(dot(H, V), 0.0), F0);
vec3 kD = vec3(1.0) - F;
kD *= 1.0 - metallic;
vec3 numerator = NDF * G * F;
float denominator = 4.0 * NdotV * NdotL;
vec3 specular = numerator / max(denominator, 0.001);
// add to outgoing radiance Lo
i += (kD * albedo / PI + specular) * radiance * NdotL;
}
vec2 rayBoxDst( vec3 boundsMin, vec3 boundsMax, vec3 rayO, vec3 rayD ) {
vec3 t0 = (boundsMin - rayO) / rayD;
vec3 t1 = (boundsMax - rayO) / rayD;
vec3 tmin = min(t0, t1);
vec3 tmax = max(t0, t1);
float dstA = max( max(tmin.x, tmin.y), tmin.z );
float dstB = min( tmax.x, min(tmax.y, tmax.z) );
float dstToBox = max(0, dstA);
float dstInsideBox = max(0, dstB - dstToBox);
return vec2(dstToBox, dstInsideBox);
}
float sampleDensity( vec3 position ) {
vec3 uvw = position * ubo.fog.densityScale * 0.001 + ubo.fog.offset * 0.01;
return max(0, texture(samplerNoise, uvw).r - ubo.fog.densityThreshold) * ubo.fog.densityMultiplier;
}
void fog( vec3 rayO, vec3 rayD, inout vec3 i, float scale ) {
if ( ubo.fog.stepScale <= 0 ) return;
if ( ubo.fog.range.x == 0 || ubo.fog.range.y == 0 ) return;
#if RAY_MARCH_FOG
float range = ubo.fog.range.y;
vec3 boundsMin = vec3(-range,-range,-range) + rayO;
vec3 boundsMax = vec3(range,range,range) + rayO;
int numSteps = int(length(boundsMax - boundsMin) * ubo.fog.stepScale );
vec2 rayBoxInfo = rayBoxDst( boundsMin, boundsMax, rayO, rayD );
float dstToBox = rayBoxInfo.x;
float dstInsideBox = rayBoxInfo.y;
float depth = position.eye.z;
float lightEnergy = 0;
// march
if ( 0 <= dstInsideBox && dstToBox <= depth ) {
float dstTravelled = 0;
float stepSize = dstInsideBox / numSteps;
float dstLimit = min( depth - dstToBox, dstInsideBox );
float totalDensity = 0;
float transmittance = 1;
while ( dstTravelled < dstLimit ) {
vec3 rayPos = rayO + rayD * (dstToBox + dstTravelled);
float density = sampleDensity(rayPos);
if ( density > 0 ) {
transmittance *= exp(-density * stepSize * ubo.fog.absorbtion);
if ( transmittance < 0.01 ) break;
}
dstTravelled += stepSize;
}
i.rgb = mix(ubo.fog.color.rgb, i.rgb, transmittance);
}
#endif
vec3 color = ubo.fog.color.rgb;
float inner = ubo.fog.range.x;
float outer = ubo.fog.range.y * scale;
float distance = length(-position.eye);
float factor = (distance - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
i.rgb = mix(i.rgb, color, factor);
}
vec3 decodeNormals( vec2 enc ) {
vec2 fenc = enc*4-2;
float f = dot(fenc,fenc);
float g = sqrt(1-f/4);
vec3 n;
n.xy = fenc*g;
n.z = 1-f/2;
return normalize(n);
}
float wrap( float i ) {
return fract(i);
}
vec2 wrap( vec2 uv ) {
return vec2( wrap( uv.x ), wrap( uv.y ) );
}
float mipLevel( in vec2 uv ) {
vec2 dx_vtc = dFdx(uv);
vec2 dy_vtc = dFdy(uv);
return 0.5 * log2(max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc)));
}
bool validTextureIndex( int textureIndex ) {
return 0 <= textureIndex && textureIndex < ubo.textures;
}
vec4 sampleTexture( uint drawId, int textureIndex, in vec2 uv, vec4 base ) {
if ( !validTextureIndex( textureIndex ) ) return base;
Texture t = textures[textureIndex+1];
float mip = mipLevel( uv );
return texture( samplerTextures[drawId], mix( t.lerp.xy, t.lerp.zw, wrap( uv ) ), mip );
}
void main() {
vec3 rayO = vec3(0);
vec3 rayD = vec3(0);
vec3 fragColor = vec3(0);
{
float depth = subpassLoad(samplerDepth, SAMPLES).r;
vec4 positionClip = vec4(inUv * 2.0 - 1.0, depth, 1.0);
vec4 positionEye = ubo.matrices.iProjection[inPushConstantPass] * positionClip;
positionEye /= positionEye.w;
position.eye = positionEye.xyz;
vec4 positionWorld = ubo.matrices.iView[inPushConstantPass] * positionEye;
position.world = positionWorld.xyz;
}
{
vec4 near4 = ubo.matrices.iProjectionView[inPushConstantPass] * (vec4(2.0 * inUv - 1.0, -1.0, 1.0));
vec4 far4 = ubo.matrices.iProjectionView[inPushConstantPass] * (vec4(2.0 * inUv - 1.0, 1.0, 1.0));
vec3 near3 = near4.xyz / near4.w;
vec3 far3 = far4.xyz / far4.w;
rayO = near3;
}
{
mat4 iProjectionView = inverse( ubo.matrices.projection[inPushConstantPass] * mat4(mat3(ubo.matrices.view[inPushConstantPass])) );
vec4 near4 = iProjectionView * (vec4(2.0 * inUv - 1.0, -1.0, 1.0));
vec4 far4 = iProjectionView * (vec4(2.0 * inUv - 1.0, 1.0, 1.0));
vec3 near3 = near4.xyz / near4.w;
vec3 far3 = far4.xyz / far4.w;
rayD = normalize( far3 - near3 );
}
normal.eye = decodeNormals( subpassLoad(samplerNormal, SAMPLES).xy );
uvec2 ID = subpassLoad(samplerId, SAMPLES).xy;
uint drawId = ID.x;
uint materialId = ID.y;
if ( drawId == 0 || materialId == 0 ) {
fragColor.rgb = texture( samplerSkybox, rayD ).rgb;
fog(rayO, rayD, fragColor, 0.0);
outFragColor = vec4(fragColor,1);
return;
}
--drawId;
--materialId;
DrawCall drawCall = drawCalls[drawId];
materialId += drawCall.materialIndex;
Material material = materials[materialId];
vec4 C = material.colorBase;
#if UF_DEFERRED_SAMPLING
vec2 uv = subpassLoad(samplerUv, SAMPLES).xy;
C = sampleTexture( drawId, drawCall.textureIndex + material.indexAlbedo, uv, C );
// OPAQUE
if ( material.modeAlpha == 0 ) {
C.a = 1;
// BLEND
} else if ( material.modeAlpha == 1 ) {
// MASK
} else if ( material.modeAlpha == 2 ) {
}
#else
C = subpassLoad(samplerAlbedo, SAMPLES);
#endif
float M = material.factorMetallic;
float R = material.factorRoughness * 4.0;
float AO = material.factorOcclusion;
bool usePbr = true;
bool gammaCorrect = false;
float litFactor = 1.0;
fragColor = C.rgb * ubo.ambient.rgb * AO;
for ( uint i = 0; i < ubo.lights; ++i ) {
Light light = lights[i];
if ( light.power <= 0.001 ) continue;
vec3 lightPositionWorld = light.position.xyz;
light.position.xyz = vec3(ubo.matrices.view[inPushConstantPass] * vec4(light.position.xyz, 1));
if ( 0 <= light.mapIndex && light.mapIndex < TEXTURES ) {
float factor = shadowFactor( light, light.mapIndex );
// if ( factor <= 0.0001 ) continue;
light.power *= factor;
litFactor += light.power;
}
if ( light.power <= 0.0001 ) continue;
if ( usePbr ) {
pbr( light, C.rgb, M, R, lightPositionWorld, fragColor );
} else
phong( light, C, fragColor );
}
if ( gammaCorrect ) {
fragColor = fragColor / (fragColor + vec3(1.0));
fragColor = pow(fragColor, vec3(1.0/2.2));
}
fog(rayO, rayD, fragColor, litFactor);
/*
if ( (ubo.mode.type & (0x1 << 0)) == (0x1 << 0) ) {
//dither1(fragColor);
fragColor += dither2();
}
*/
if ( (ubo.mode.type & (0x1 << 1)) == (0x1 << 1) ) {
whitenoise(fragColor);
}
outFragColor = vec4(fragColor,1);
}

View File

@ -1,559 +0,0 @@
#version 450
#extension GL_EXT_samplerless_texture_functions : require
layout (constant_id = 0) const uint LIGHTS = 256;
layout (input_attachment_index = 0, binding = 1) uniform subpassInput samplerAlbedoMetallic;
layout (input_attachment_index = 0, binding = 2) uniform subpassInput samplerNormalRoughness;
layout (input_attachment_index = 0, binding = 3) uniform subpassInput samplerDepth;
layout (binding = 5) uniform sampler3D samplerNoise;
layout (binding = 6) uniform sampler2D samplerShadows[LIGHTS];
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat uint inPushConstantPass;
layout (location = 0) out vec4 outFragColor;
/*
const vec2 poissonDisk[4] = vec2[](
vec2( -0.94201624, -0.39906216 ),
vec2( 0.94558609, -0.76890725 ),
vec2( -0.094184101, -0.92938870 ),
vec2( 0.34495938, 0.29387760 )
);
*/
vec2 poissonDisk[16] = vec2[](
vec2( -0.94201624, -0.39906216 ),
vec2( 0.94558609, -0.76890725 ),
vec2( -0.094184101, -0.92938870 ),
vec2( 0.34495938, 0.29387760 ),
vec2( -0.91588581, 0.45771432 ),
vec2( -0.81544232, -0.87912464 ),
vec2( -0.38277543, 0.27676845 ),
vec2( 0.97484398, 0.75648379 ),
vec2( 0.44323325, -0.97511554 ),
vec2( 0.53742981, -0.47373420 ),
vec2( -0.26496911, -0.41893023 ),
vec2( 0.79197514, 0.19090188 ),
vec2( -0.24188840, 0.99706507 ),
vec2( -0.81409955, 0.91437590 ),
vec2( 0.19984126, 0.78641367 ),
vec2( 0.14383161, -0.14100790 )
);
struct Light {
vec3 position;
float radius;
vec3 color;
float power;
int type;
float depthBias;
float padding1;
float padding2;
mat4 view;
mat4 projection;
};
struct Matrices {
mat4 view[2];
mat4 projection[2];
};
struct Space {
vec3 eye;
vec3 world;
} position, normal, view;
struct Fog {
vec3 color;
float stepScale;
vec3 offset;
float densityScale;
float densityThreshold;
float densityMultiplier;
float absorbtion;
float padding1;
vec2 range;
float padding2;
float padding3;
};
struct Mode {
uint type;
uint scalar;
vec2 padding;
vec4 parameters;
};
layout (binding = 0) uniform UBO {
Matrices matrices;
vec3 ambient;
float kexp;
Mode mode;
Fog fog;
Light lights[LIGHTS];
} ubo;
void phong( Light light, vec4 albedoSpecular, inout vec3 i ) {
vec3 Ls = vec3(1.0, 1.0, 1.0); // light specular
vec3 Ld = light.color; // light color
vec3 La = vec3(1.0, 1.0, 1.0);
vec3 Ks = vec3(albedoSpecular.a); // material specular
vec3 Kd = albedoSpecular.rgb; // material diffuse
vec3 Ka = vec3(1.0, 1.0, 1.0);
float Kexp = ubo.kexp;
vec3 V = position.eye;
vec3 N = normal.eye;
vec3 L = light.position.xyz - V;
float dist = length(L);
// if ( light.radius > 0.001 && light.radius < dist ) return;
vec3 D = normalize(L);
float d_dot = max(dot( D, N ), 0.0);
vec3 R = reflect( -D, N );
vec3 S = normalize(-V);
float s_factor = pow( max(dot( R, S ), 0.0), Kexp );
if ( Kexp < 0.0001 ) s_factor = 0;
float radiance = light.power / (dist * dist);
vec3 Ia = La * Ka;
vec3 Id = Ld * Kd * d_dot * radiance;
vec3 Is = Ls * Ks * s_factor * radiance;
i += Id + Is;
}
const float PI = 3.14159265359;
float DistributionGGX(vec3 N, vec3 H, float roughness) {
float a = roughness*roughness;
float a2 = a*a;
float NdotH = max(dot(N, H), 0.0);
float NdotH2 = NdotH*NdotH;
float num = a2;
float denom = (NdotH2 * (a2 - 1.0) + 1.0);
denom = PI * denom * denom;
return num / denom;
}
float GeometrySchlickGGX(float NdotV, float roughness) {
float r = (roughness + 1.0);
float k = (r*r) / 8.0;
float num = NdotV;
float denom = NdotV * (1.0 - k) + k;
return num / denom;
}
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {
float NdotV = max(dot(N, V), 0.0);
float NdotL = max(dot(N, L), 0.0);
float ggx2 = GeometrySchlickGGX(NdotV, roughness);
float ggx1 = GeometrySchlickGGX(NdotL, roughness);
return ggx1 * ggx2;
}
vec3 fresnelSchlick(float cosTheta, vec3 F0) {
return F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0);
}
float random(vec3 seed, int i){
vec4 seed4 = vec4(seed,i);
float dot_product = dot(seed4, vec4(12.9898,78.233,45.164,94.673));
return fract(sin(dot_product) * 43758.5453);
}
float shadowFactor( Light light, uint shadowMap ) {
vec4 positionClip = light.projection * light.view * vec4(position.world, 1.0);
positionClip.xyz /= positionClip.w;
if ( positionClip.x < -1 || positionClip.x >= 1 ) return 0.0;
if ( positionClip.y < -1 || positionClip.y >= 1 ) return 0.0;
if ( positionClip.z <= 0 || positionClip.z >= 1 ) return 0.0;
float factor = 1.0;
// spot light
if ( light.type == -2 || light.type == -3 ) {
float dist = length( positionClip.xy );
if ( dist > 0.5 ) return 0.0;
// spot light with attenuation
if ( light.type == -3 ) {
factor = 1.0 - (pow(dist * 2,2.0));
}
}
vec2 uv = positionClip.xy * 0.5 + 0.5;
float bias = light.depthBias;
if ( !true ) {
float cosTheta = clamp(dot(normal.eye, normalize(light.position.xyz - position.eye)), 0, 1);
bias = clamp(bias * tan(acos(cosTheta)), 0, 0.01);
} else if ( true ) {
bias = max(bias * 10 * (1.0 - dot(normal.eye, normalize(light.position.xyz - position.eye))), bias);
}
float eyeDepth = positionClip.z;
int samples = poissonDisk.length();
if ( samples <= 1 ) {
return eyeDepth < texture(samplerShadows[shadowMap], uv).r - bias ? 0.0 : factor;
}
for ( int i = 0; i < samples; ++i ) {
// int index = i;
// int index = int( float(samples) * random(gl_FragCoord.xyy, i) ) % samples;
int index = int( float(samples) * random(floor(position.world.xyz * 1000.0), i)) % samples;
float lightDepth = texture(samplerShadows[shadowMap], uv + poissonDisk[index] / 700.0 ).r;
if ( eyeDepth < lightDepth - bias ) factor -= 1.0 / samples;
}
return factor;
}
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
const int indexMatrix16x16[256] = int[](0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255,
128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127,
32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223,
160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95,
8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247,
136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119,
40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215,
168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87,
2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253,
130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125,
34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221,
162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93,
10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245,
138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117,
42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213,
170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85);
float indexValue16x16( float scale ) {
int x = int(mod(gl_FragCoord.x * scale, 16));
int y = int(mod(gl_FragCoord.y * scale, 16));
return indexMatrix16x16[(x + y * 16)] / 256.0;
}
const int indexMatrix8x8[64] = int[](0, 32, 8, 40, 2, 34, 10, 42,
48, 16, 56, 24, 50, 18, 58, 26,
12, 44, 4, 36, 14, 46, 6, 38,
60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41,
51, 19, 59, 27, 49, 17, 57, 25,
15, 47, 7, 39, 13, 45, 5, 37,
63, 31, 55, 23, 61, 29, 53, 21);
float indexValue8x8( float scale ) {
int x = int(mod(gl_FragCoord.x * scale, 8));
int y = int(mod(gl_FragCoord.y * scale, 8));
return indexMatrix8x8[(x + y * 8)] / 64.0;
}
const int indexMatrix4x4[16] = int[](0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5);
float indexValue4x4( float scale ) {
int x = int(mod(gl_FragCoord.x * scale, 4));
int y = int(mod(gl_FragCoord.y * scale, 4));
return indexMatrix4x4[(x + y * 4)] / 16.0;
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
/*
for (int i = 0; i < palette.length(); ++i) {
temp = rgbToHsl(palette[i].rgb);
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
*/
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = 1; // -0.5 - fract(ubo.mode.parameters.w / 8.0);
if ( ubo.mode.scalar == 16 ) {
d = indexValue16x16(1);
} else if ( ubo.mode.scalar == 8 ) {
d = indexValue8x8(1);
} else if ( ubo.mode.scalar == 4 ) {
d = indexValue4x4(1);
}
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
void dither(inout vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.x = dither(hsl.x);
color = hslToRgb(hsl);
}
void dither1(inout vec3 color) {
vec3 hsl = rgbToHsl(color);
float d = 0;
vec3 cs[2] = { hsl, hsl }; // closestColors(hsl.x);
float scale = 1;
if ( ubo.mode.scalar == 16 ) {
d = indexValue16x16(scale);
} else if ( ubo.mode.scalar == 8 ) {
d = indexValue8x8(scale);
} else if ( ubo.mode.scalar == 4 ) {
d = indexValue4x4(scale);
}
float hueDiff = hueDistance(hsl.x, cs[0].x) / hueDistance(cs[1].x, cs[0].x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? cs[0] : cs[1];
resultColor.z = (lightnessDiff < d) ? l1 : l2;
color = hslToRgb(resultColor);
}
vec3 dither2() {
vec3 vDither = dot( vec2( 171.0, 231.0 ), inUv.xy + ubo.mode.parameters.w ).xxx;
vDither.rgb = fract( vDither.rgb / vec3( 103.0, 71.0, 97.0 ) ) - vec3( 0.5, 0.5, 0.5 );
return ( vDither.rgb / 255.0 ) * 0.375;
}
float rand2(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 143758.5453);
}
float rand3(vec3 co){
return fract(sin(dot(co.xyz ,vec3(12.9898,78.233, 37.719))) * 143758.5453);
}
void whitenoise(inout vec3 color) {
float flicker = ubo.mode.parameters.x;
float pieces = ubo.mode.parameters.y;
float blend = ubo.mode.parameters.z;
float time = ubo.mode.parameters.w;
if ( blend < 0.0001 ) return;
float freq = sin(pow(mod(time, flicker) + flicker, 1.9));
// float whiteNoise = rand3( floor(position.world / pieces) + floor(time * 2) );
float whiteNoise = rand2( floor(gl_FragCoord.xy / pieces) + mod(time, freq) );
color = mix( color, vec3(whiteNoise), blend );
}
void pbr( Light light, vec3 albedo, float metallic, float roughness, vec3 lightPositionWorld, inout vec3 i ) {
vec3 F0 = vec3(0.04);
F0 = mix(F0, albedo, metallic);
vec3 N = normalize(normal.eye);
vec3 L = light.position.xyz - position.eye;
float dist = length(L);
// if ( light.radius > 0.001 && light.radius < dist ) return;
vec3 D = normalize(L);
vec3 V = normalize(-position.eye);
vec3 H = normalize(V + D);
float NdotD = max(dot(N, D), 0.0);
float NdotV = max(dot(N, V), 0.0);
vec3 radiance = light.color.rgb * light.power / (dist * dist);
/*
if ( light.radius > 0.0001 ) {
radiance *= clamp( light.radius / (pow(dist, 2.0) + 1.0), 0.0, 1.0 );
} else if ( false ) {
radiance /= dist * dist;
}
*/
// cook-torrance brdf
float NDF = DistributionGGX(N, H, roughness);
float G = GeometrySmith(N, V, D, roughness);
vec3 F = fresnelSchlick(max(dot(H, V), 0.0), F0);
vec3 kS = F;
vec3 kD = vec3(1.0) - kS;
kD *= 1.0 - metallic;
vec3 numerator = NDF * G * F;
float denominator = 4.0 * NdotV * NdotD;
vec3 specular = numerator / max(denominator, 0.001);
// add to outgoing radiance Lo
i += (kD * albedo / PI + specular) * radiance * NdotD;
}
vec2 rayBoxDst( vec3 boundsMin, vec3 boundsMax, vec3 rayOrigin, vec3 rayDir ) {
vec3 t0 = (boundsMin - rayOrigin) / rayDir;
vec3 t1 = (boundsMax - rayOrigin) / rayDir;
vec3 tmin = min(t0, t1);
vec3 tmax = max(t0, t1);
float dstA = max( max(tmin.x, tmin.y), tmin.z );
float dstB = min( tmax.x, min(tmax.y, tmax.z) );
float dstToBox = max(0, dstA);
float dstInsideBox = max(0, dstB - dstToBox);
return vec2(dstToBox, dstInsideBox);
}
float sampleDensity( vec3 position ) {
vec3 uvw = position * ubo.fog.densityScale * 0.001 + ubo.fog.offset * 0.01;
return max(0, texture(samplerNoise, uvw).r - ubo.fog.densityThreshold) * ubo.fog.densityMultiplier;
}
void fog( inout vec3 i, float scale ) {
if ( ubo.fog.stepScale <= 0 ) return;
if ( ubo.fog.range.x == 0 || ubo.fog.range.y == 0 ) return;
mat4 iProjView = inverse( ubo.matrices.projection[inPushConstantPass] * ubo.matrices.view[inPushConstantPass] );
vec4 near4 = iProjView * (vec4(2.0 * inUv - 1.0, -1.0, 1.0));
vec4 far4 = iProjView * (vec4(2.0 * inUv - 1.0, 1.0, 1.0));
vec3 near3 = near4.xyz / near4.w;
vec3 far3 = far4.xyz / far4.w;
vec3 rayOrigin = near3;
vec3 rayDir = normalize( far3 - near3 );
float range = ubo.fog.range.y;
vec3 boundsMin = vec3(-range,-range,-range) + rayOrigin;
vec3 boundsMax = vec3(range,range,range) + rayOrigin;
int numSteps = int(length(boundsMax - boundsMin) * ubo.fog.stepScale );
vec2 rayBoxInfo = rayBoxDst( boundsMin, boundsMax, rayOrigin, rayDir );
float dstToBox = rayBoxInfo.x;
float dstInsideBox = rayBoxInfo.y;
float depth = position.eye.z;
float lightEnergy = 0;
// march
if ( 0 <= dstInsideBox && dstToBox <= depth ) {
float dstTravelled = 0;
float stepSize = dstInsideBox / numSteps;
float dstLimit = min( depth - dstToBox, dstInsideBox );
float totalDensity = 0;
float transmittance = 1;
while ( dstTravelled < dstLimit ) {
vec3 rayPos = rayOrigin + rayDir * (dstToBox + dstTravelled);
float density = sampleDensity(rayPos);
if ( density > 0 ) {
transmittance *= exp(-density * stepSize * ubo.fog.absorbtion);
if ( transmittance < 0.01 ) break;
}
dstTravelled += stepSize;
}
i.rgb = mix(ubo.fog.color.rgb, i.rgb, transmittance);
}
vec3 color = ubo.fog.color.rgb;
float inner = ubo.fog.range.x;
float outer = ubo.fog.range.y * scale;
float distance = length(-position.eye);
float factor = (distance - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
i.rgb = mix(i.rgb, color, factor);
}
void main() {
vec4 albedoMetallic = subpassLoad(samplerAlbedoMetallic);
vec4 normalRoughness = subpassLoad(samplerNormalRoughness);
// vec4 positionAO = subpassLoad(samplerPositionAO);
normal.eye = normalRoughness.rgb;
{
mat4 iProj = inverse( ubo.matrices.projection[inPushConstantPass] );
mat4 iView = inverse( ubo.matrices.view[inPushConstantPass] );
float depth = subpassLoad(samplerDepth).r;
vec4 positionClip = vec4(inUv * 2.0 - 1.0, depth, 1.0);
vec4 positionEye = iProj * positionClip;
positionEye /= positionEye.w;
position.eye = positionEye.xyz;
vec4 positionWorld = iView * positionEye;
position.world = positionWorld.xyz;
}
bool usePbr = true;
bool gammaCorrect = false;
float litFactor = 1.0;
float ao = 1; // positionAO.a;
vec3 fragColor = albedoMetallic.rgb * ubo.ambient.rgb * ao;
for ( uint i = 0; i < LIGHTS; ++i ) {
Light light = ubo.lights[i];
if ( light.power <= 0.001 ) continue;
vec3 lightPositionWorld = light.position.xyz;
light.position.xyz = vec3(ubo.matrices.view[inPushConstantPass] * vec4(light.position.xyz, 1));
if ( light.type < 0 ) {
float factor = shadowFactor( light, i );
if ( factor <= 0.0001 ) continue;
light.power *= factor;
litFactor += light.power;
}
if ( usePbr ) {
pbr( light, albedoMetallic.rgb, albedoMetallic.a, normalRoughness.a, lightPositionWorld, fragColor );
} else
phong( light, albedoMetallic, fragColor );
}
if ( gammaCorrect ) {
fragColor = fragColor / (fragColor + vec3(1.0));
fragColor = pow(fragColor, vec3(1.0/2.2));
}
fog(fragColor, litFactor);
/*
if ( (ubo.mode.type & (0x1 << 0)) == (0x1 << 0) ) {
//dither1(fragColor);
fragColor += dither2();
}
if ( (ubo.mode.type & (0x1 << 1)) == (0x1 << 1) ) {
whitenoise(fragColor);
}
*/
outFragColor = vec4(fragColor,1);
}

View File

@ -1,24 +0,0 @@
#version 450
layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 0) out vec2 outUv;
layout (location = 1) out flat uint outPushConstantPass;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
out gl_PerVertex {
vec4 gl_Position;
};
void main() {
outUv = inUv;
outPushConstantPass = PushConstant.pass;
gl_Position = vec4(inPos.xy, 0.0, 1.0);
}

View File

@ -3,6 +3,10 @@
layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUv;
layout (binding = 0) uniform UBO {
vec2 screenSize;
} ubo;
layout (location = 0) out vec2 outUv;
out gl_PerVertex {

View File

@ -1,139 +0,0 @@
#version 450
#define UF_DEFERRED_SAMPLING 0
#define UF_CAN_DISCARD 1
layout (constant_id = 0) const uint TEXTURES = 1;
layout (binding = 0) uniform sampler2D samplerTextures[TEXTURES];
struct Material {
vec4 colorBase;
vec4 colorEmissive;
float factorMetallic;
float factorRoughness;
float factorOcclusion;
float factorAlphaCutoff;
int indexAlbedo;
int indexNormal;
int indexEmissive;
int indexOcclusion;
int indexMetallicRoughness;
int modeAlpha;
int padding1;
int padding2;
};
struct Texture {
int index;
int samp;
int remap;
float blend;
vec4 lerp;
};
layout (std140, binding = 1) readonly buffer Materials {
Material materials[];
};
layout (std140, binding = 2) readonly buffer Textures {
Texture textures[];
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec4 inColor;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in mat3 inTBN;
layout (location = 6) in vec3 inPosition;
layout (location = 7) flat in ivec4 inId;
layout (location = 0) out uvec2 outId;
layout (location = 1) out vec2 outNormals;
#if UF_DEFERRED_SAMPLING
layout (location = 2) out vec2 outUvs;
#else
layout (location = 2) out vec4 outAlbedo;
#endif
vec2 encodeNormals( vec3 n ) {
float p = sqrt(n.z*8+8);
return n.xy/p + 0.5;
}
float wrap( float i ) {
return fract(i);
}
vec2 wrap( vec2 uv ) {
return vec2( wrap( uv.x ), wrap( uv.y ) );
}
float mipLevel( in vec2 uv ) {
vec2 dx_vtc = dFdx(uv);
vec2 dy_vtc = dFdy(uv);
return 0.5 * log2(max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc)));
}
bool validTextureIndex( int textureIndex ) {
return 0 <= textureIndex && textureIndex < TEXTURES;
}
void main() {
float mip = mipLevel(inUv.xy);
vec2 uv = wrap(inUv.xy);
vec4 C = vec4(0, 0, 0, 0);
vec3 P = inPosition;
vec3 N = inNormal;
#if UF_DEFERRED_SAMPLING
outUvs = wrap(inUv.xy);
vec4 outAlbedo = vec4(0,0,0,0);
#endif
#if !UF_DEFERRED_SAMPLING || UF_CAN_DISCARD
int materialId = int(inId.y);
Material material = materials[materialId];
float M = material.factorMetallic;
float R = material.factorRoughness;
float AO = material.factorOcclusion;
// sample albedo
if ( !validTextureIndex( material.indexAlbedo ) ) discard; {
Texture t = textures[material.indexAlbedo + 1];
C = textureLod( samplerTextures[0], mix( t.lerp.xy, t.lerp.zw, uv ), mip );
// alpha mode OPAQUE
if ( material.modeAlpha == 0 ) {
C.a = 1;
// alpha mode BLEND
} else if ( material.modeAlpha == 1 ) {
// alpha mode MASK
} else if ( material.modeAlpha == 2 ) {
if ( C.a < abs(material.factorAlphaCutoff) ) discard;
C.a = 1;
}
}
#endif
#if !UF_DEFERRED_SAMPLING
// sample normal
if ( validTextureIndex( material.indexNormal ) ) {
Texture t = textures[material.indexNormal + 1];
N = inTBN * normalize( textureLod( samplerTextures[0], mix( t.lerp.xy, t.lerp.zw, uv ), mip ).xyz * 2.0 - vec3(1.0));
}
#if 0
// sample metallic/roughness
if ( validTextureIndex( material.indexMetallicRoughness ) ) {
Texture t = textures[material.indexMetallicRoughness + 1];
vec4 sampled = texture( samplerTextures[0], mix( t.lerp.xy, t.lerp.zw, uv ), mip );
M = sampled.b;
R = sampled.g;
}
// sample ao
AO = material.factorOcclusion;
if ( validTextureIndex( material.indexOcclusion ) ) {
Texture t = textures[material.indexMetallicRoughness + 1];
AO = texture( samplerTextures[0], mix( t.lerp.xy, t.lerp.zw, uv ) ).r;
}
#endif
outAlbedo = C * inColor;
#endif
outNormals = encodeNormals( N );
outId = ivec2(inId.w+1, inId.y+1);
}

View File

@ -1,62 +0,0 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec4 inTangent;
layout (location = 4) in ivec2 inId;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
layout (binding = 3) uniform UBO {
mat4 view[PASSES];
mat4 projection[PASSES];
} ubo;
layout (std140, binding = 4) readonly buffer Models {
mat4 models[];
};
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec4 outColor;
layout (location = 2) out vec3 outNormal;
layout (location = 3) out mat3 outTBN;
layout (location = 6) out vec3 outPosition;
layout (location = 7) out ivec4 outId;
out gl_PerVertex {
vec4 gl_Position;
};
vec4 snap(vec4 vertex, vec2 resolution) {
vec4 snappedPos = vertex;
snappedPos.xyz = vertex.xyz / vertex.w;
snappedPos.xy = floor(resolution * snappedPos.xy) / resolution;
snappedPos.xyz *= vertex.w;
return snappedPos;
}
void main() {
outUv = inUv;
outColor = vec4(1.0);
outId = ivec4(inId, PushConstant.pass, PushConstant.draw);
mat4 model = models.length() <= 0 ? mat4(1.0) : models[int(inId.x)];
outPosition = vec3(ubo.view[PushConstant.pass] * model * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.view[PushConstant.pass] * model * vec4(inNormal.xyz, 0.0));
outNormal = normalize(outNormal);
{
vec3 T = vec3(ubo.view[PushConstant.pass] * model * vec4(inTangent.xyz, 0.0));
vec3 N = outNormal;
vec3 B = cross(N, T) * inTangent.w;
outTBN = mat3( T, B, N );
}
gl_Position = ubo.projection[PushConstant.pass] * ubo.view[PushConstant.pass] * model * vec4(inPos.xyz, 1.0);
// gl_Position = snap( gl_Position, vec2(256.0, 224.0) );
}

View File

@ -1,74 +0,0 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec4 inTangent;
layout (location = 4) in ivec2 inId;
layout (location = 5) in vec4 inJoints;
layout (location = 6) in vec4 inWeights;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
layout (binding = 3) uniform UBO {
mat4 view[PASSES];
mat4 projection[PASSES];
} ubo;
layout (std140, binding = 4) readonly buffer Models {
mat4 models[];
};
layout (std140, binding = 5) readonly buffer Joints {
mat4 joints[];
};
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec4 outColor;
layout (location = 2) out vec3 outNormal;
layout (location = 3) out mat3 outTBN;
layout (location = 6) out vec3 outPosition;
layout (location = 7) out ivec4 outId;
out gl_PerVertex {
vec4 gl_Position;
};
vec4 snap(vec4 vertex, vec2 resolution) {
vec4 snappedPos = vertex;
snappedPos.xyz = vertex.xyz / vertex.w;
snappedPos.xy = floor(resolution * snappedPos.xy) / resolution;
snappedPos.xyz *= vertex.w;
return snappedPos;
}
void main() {
outUv = inUv;
outColor = vec4(1.0);
outId = ivec4(inId, PushConstant.pass, PushConstant.draw);
mat4 model = models.length() <= 0 ? mat4(1.0) : models[int(inId.x)];
mat4 skinnedMatrix = joints.length() <= 0 ? mat4(1.0) :
inWeights.x * joints[int(inJoints.x)] +
inWeights.y * joints[int(inJoints.y)] +
inWeights.z * joints[int(inJoints.z)] +
inWeights.w * joints[int(inJoints.w)];
outPosition = vec3(ubo.view[PushConstant.pass] * model * skinnedMatrix * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.view[PushConstant.pass] * model * vec4(inNormal.xyz, 0.0));
outNormal = normalize(outNormal);
{
vec3 T = vec3(ubo.view[PushConstant.pass] * model * vec4(inTangent.xyz, 0.0));
vec3 N = outNormal;
vec3 B = cross(N, T) * inTangent.w;
outTBN = mat3( T, B, N );
}
gl_Position = ubo.projection[PushConstant.pass] * ubo.view[PushConstant.pass] * model * skinnedMatrix * vec4(inPos.xyz, 1.0);
}

View File

@ -1,78 +0,0 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec4 inTangent;
layout (location = 4) in ivec2 inId;
layout (location = 5) in vec4 inJoints;
layout (location = 6) in vec4 inWeights;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[PASSES];
mat4 projection[PASSES];
};
layout (binding = 3) uniform UBO {
Matrices matrices;
vec4 color;
} ubo;
layout (std140, binding = 4) readonly buffer Joints {
mat4 joints[];
};
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec4 outColor;
layout (location = 2) out vec3 outNormal;
layout (location = 3) out mat3 outTBN;
layout (location = 6) out vec3 outPosition;
layout (location = 7) out ivec4 outId;
out gl_PerVertex {
vec4 gl_Position;
};
vec4 snap(vec4 vertex, vec2 resolution) {
vec4 snappedPos = vertex;
snappedPos.xyz = vertex.xyz / vertex.w;
snappedPos.xy = floor(resolution * snappedPos.xy) / resolution;
snappedPos.xyz *= vertex.w;
return snappedPos;
}
void main() {
outUv = inUv;
outColor = ubo.color;
outId = ivec4(inId, PushConstant.pass, PushConstant.draw);
mat4 skinnedMatrix = joints.length() <= 0 ? mat4(1.0) :
inWeights.x * joints[int(inJoints.x)] +
inWeights.y * joints[int(inJoints.y)] +
inWeights.z * joints[int(inJoints.z)] +
inWeights.w * joints[int(inJoints.w)];
outPosition = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * skinnedMatrix * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outNormal = normalize(outNormal);
{
vec3 T = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inTangent.xyz, 0.0));
vec3 N = outNormal;
vec3 B = cross(N, T) * inTangent.w;
outTBN = mat3( T, B, N );
}
gl_Position = ubo.matrices.projection[PushConstant.pass] * ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * skinnedMatrix * vec4(inPos.xyz, 1.0);
// gl_Position = snap( gl_Position, vec2(320.0, 240.0) );
// gl_Position = snap( gl_Position, vec2(480.0, 270.0) );
// gl_Position = snap( gl_Position, vec2(640.0, 480.0) );
}

View File

@ -1,64 +0,0 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec4 inTangent;
layout (location = 4) in ivec2 inId;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[PASSES];
mat4 projection[PASSES];
};
layout (binding = 3) uniform UBO {
Matrices matrices;
vec4 color;
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec4 outColor;
layout (location = 2) out vec3 outNormal;
layout (location = 3) out mat3 outTBN;
layout (location = 6) out vec3 outPosition;
layout (location = 7) out ivec4 outId;
out gl_PerVertex {
vec4 gl_Position;
};
vec4 snap(vec4 vertex, vec2 resolution) {
vec4 snappedPos = vertex;
snappedPos.xyz = vertex.xyz / vertex.w;
snappedPos.xy = floor(resolution * snappedPos.xy) / resolution;
snappedPos.xyz *= vertex.w;
return snappedPos;
}
void main() {
outUv = inUv;
outColor = ubo.color;
outId = ivec4(inId, PushConstant.pass, PushConstant.draw);
outPosition = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outNormal = normalize(outNormal);
{
vec3 T = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inTangent.xyz, 0.0));
vec3 N = outNormal;
vec3 B = cross(N, T) * inTangent.w;
outTBN = mat3( T, B, N );
}
gl_Position = ubo.matrices.projection[PushConstant.pass] * ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0);
// gl_Position = snap( gl_Position, vec2(320.0, 240.0) );
}

View File

@ -0,0 +1,178 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out vec4 outFragColor;
const int indexMatrix16x16[256] = int[](0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255,
128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127,
32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223,
160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95,
8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247,
136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119,
40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215,
168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87,
2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253,
130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125,
34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221,
162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93,
10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245,
138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117,
42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213,
170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85);
float indexValue16x16() {
int x = int(mod(gl_FragCoord.x, 16));
int y = int(mod(gl_FragCoord.y, 16));
return indexMatrix16x16[(x + y * 16)] / 256.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue16x16();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue16x16();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
if ( inUv.x < inGui.offset.x ) discard;
if ( inUv.y < inGui.offset.y ) discard;
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
outFragColor = texture(samplerColor, inUv);// vec4(inUv.s, inUv.t, 1.0, 1.0);
if ( outFragColor.a < 0.001 ) discard;
if ( inGui.mode == 1 ) {
outFragColor = inGui.color;
} else {
outFragColor *= inGui.color;
}
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -0,0 +1,166 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out vec4 outFragColor;
const int indexMatrix4x4[16] = int[](0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5);
float indexValue4x4() {
int x = int(mod(gl_FragCoord.x, 4));
int y = int(mod(gl_FragCoord.y, 4));
return indexMatrix4x4[(x + y * 4)] / 16.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue4x4();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue4x4();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
if ( inUv.x < inGui.offset.x ) discard;
if ( inUv.y < inGui.offset.y ) discard;
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
outFragColor = texture(samplerColor, inUv);// vec4(inUv.s, inUv.t, 1.0, 1.0);
if ( outFragColor.a < 0.001 ) discard;
if ( inGui.mode == 1 ) {
outFragColor = inGui.color;
} else {
outFragColor *= inGui.color;
}
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -0,0 +1,170 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out vec4 outFragColor;
const int indexMatrix8x8[64] = int[](0, 32, 8, 40, 2, 34, 10, 42,
48, 16, 56, 24, 50, 18, 58, 26,
12, 44, 4, 36, 14, 46, 6, 38,
60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41,
51, 19, 59, 27, 49, 17, 57, 25,
15, 47, 7, 39, 13, 45, 5, 37,
63, 31, 55, 23, 61, 29, 53, 21);
float indexValue8x8() {
int x = int(mod(gl_FragCoord.x, 8));
int y = int(mod(gl_FragCoord.y, 8));
return indexMatrix8x8[(x + y * 8)] / 64.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue8x8();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue8x8();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
if ( inUv.x < inGui.offset.x ) discard;
if ( inUv.y < inGui.offset.y ) discard;
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
outFragColor = texture(samplerColor, inUv);// vec4(inUv.s, inUv.t, 1.0, 1.0);
if ( outFragColor.a < 0.001 ) discard;
if ( inGui.mode == 1 ) {
outFragColor = inGui.color;
} else {
outFragColor *= inGui.color;
}
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -1,38 +1,17 @@
#version 450
#define UF_DEFERRED_SAMPLING 0
#define UF_CAN_DISCARD 1
layout (binding = 1) uniform sampler2D samplerTexture;
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
vec2 padding;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out uvec2 outId;
layout (location = 1) out vec2 outNormals;
#if UF_DEFERRED_SAMPLING
layout (location = 2) out vec2 outUvs;
#else
layout (location = 2) out vec4 outAlbedo;
#endif
vec2 encodeNormals( vec3 n ) {
float p = sqrt(n.z*8+8);
return n.xy/p + 0.5;
}
float mipLevel( in vec2 uv ) {
vec2 dx_vtc = dFdx(uv);
vec2 dy_vtc = dFdy(uv);
return 0.5 * log2(max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc)));
}
layout (location = 0) out vec4 outFragColor;
void main() {
if ( inUv.x < inGui.offset.x ) discard;
@ -40,27 +19,11 @@ void main() {
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
float mip = mipLevel(inUv.xy);
vec2 uv = inUv.xy;
vec4 C = vec4(1, 1, 1, 1);
//vec3 N = inNormal;
#if UF_DEFERRED_SAMPLING
outUvs = wrap(inUv.xy);
vec4 outAlbedo = vec4(0,0,0,0);
#endif
#if !UF_DEFERRED_SAMPLING || UF_CAN_DISCARD
C = textureLod( samplerTexture, uv, mip );
#endif
#if !UF_DEFERRED_SAMPLING
outFragColor = texture(samplerColor, inUv);// vec4(inUv.s, inUv.t, 1.0, 1.0);
if ( outFragColor.a < 0.001 ) discard;
if ( inGui.mode == 1 ) {
C = inGui.color;
outFragColor = inGui.color;
} else {
C *= inGui.color;
outFragColor *= inGui.color;
}
outAlbedo = C;
#endif
/*
outNormals = encodeNormals( N );
outId = ivec2(0, 0);
*/
}

View File

@ -0,0 +1,38 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out vec4 outFragColor;
void main() {
if ( inUv.x < inGui.offset.x ) discard;
if ( inUv.y < inGui.offset.y ) discard;
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
outFragColor = texture(samplerColor, inUv);// vec4(inUv.s, inUv.t, 1.0, 1.0);
if ( outFragColor.a < 0.001 ) discard;
if ( inGui.mode == 1 ) {
outFragColor = inGui.color;
} else {
outFragColor *= inGui.color;
}
float end = 0.25;
if ( inUv.x < end ) {
outFragColor.a = inUv.x / end;
} else if ( inUv.x + end >= 1 ) {
float offset = (1 - inUv.x);
outFragColor.a = offset / end;
}
}

View File

@ -3,39 +3,36 @@
layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUv;
struct Cursor {
vec2 position;
vec2 radius;
vec4 color;
};
layout (location = 0) out vec2 outUv;
layout (location = 1) out float outAlpha;
layout (location = 2) out flat Cursor outCursor;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model[2];
};
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
};
layout (binding = 0) uniform UBO {
Matrices matrices;
Gui gui;
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out flat Gui outGui;
out gl_PerVertex {
vec4 gl_Position;
};
struct Matrices {
mat4 model[2];
};
layout (binding = 0) uniform UBO {
Matrices matrices;
Cursor cursor;
// float alpha;
// float padding;
} ubo;
void main() {
outUv = inUv;
outCursor = ubo.cursor;
outAlpha = 1;
outGui = ubo.gui;
gl_Position = ubo.matrices.model[PushConstant.pass] * vec4(inPos.xy, 0.0, 1.0);
gl_Position = ubo.matrices.model[PushConstant.pass] * vec4(inPos.xy, ubo.gui.depth, 1.0);
}

View File

@ -0,0 +1,196 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
int sdf;
int shadowbox;
vec4 stroke;
float weight;
int spread;
float scale;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out vec4 outFragColor;
const int indexMatrix16x16[256] = int[](0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255,
128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127,
32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223,
160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95,
8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247,
136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119,
40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215,
168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87,
2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253,
130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125,
34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221,
162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93,
10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245,
138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117,
42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213,
170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85);
float indexValue16x16() {
int x = int(mod(gl_FragCoord.x, 16));
int y = int(mod(gl_FragCoord.y, 16));
return indexMatrix16x16[(x + y * 16)] / 256.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue16x16();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue16x16();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
if ( inUv.x < inGui.offset.x ) discard;
if ( inUv.y < inGui.offset.y ) discard;
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
if ( inGui.shadowbox == 1 ) {
outFragColor = inGui.color;
return;
}
float dist = texture(samplerColor, inUv).r;
if ( inGui.sdf == 1 ) {
float smoothing = ( inGui.spread > 0 && inGui.scale > 0 ) ? 0.25 / (inGui.spread * inGui.scale) : 0.25 / (4 * 1.5);
float outlining = smoothstep(0.5 - smoothing, 0.5 + smoothing, dist);
float alpha = smoothstep(inGui.weight - smoothing, inGui.weight + smoothing, dist);
vec4 c = inGui.color;
outFragColor = mix(inGui.stroke, c, outlining);
outFragColor.a = inGui.color.a * alpha;
if ( alpha < 0.001 ) discard;
if ( alpha > 1 ) discard;
} else {
outFragColor = vec4(inGui.color) * dist;
if ( dist < 0.001 ) discard;
if ( dist > 1 ) discard;
}
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -0,0 +1,185 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
int sdf;
int shadowbox;
vec4 stroke;
float weight;
int spread;
float scale;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out vec4 outFragColor;
const int indexMatrix4x4[16] = int[](0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5);
float indexValue4x4() {
int x = int(mod(gl_FragCoord.x, 4));
int y = int(mod(gl_FragCoord.y, 4));
return indexMatrix4x4[(x + y * 4)] / 16.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue4x4();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue4x4();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
if ( inUv.x < inGui.offset.x ) discard;
if ( inUv.y < inGui.offset.y ) discard;
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
if ( inGui.shadowbox == 1 ) {
outFragColor = inGui.color;
return;
}
float dist = texture(samplerColor, inUv).r;
if ( inGui.sdf == 1 ) {
float smoothing = ( inGui.spread > 0 && inGui.scale > 0 ) ? 0.25 / (inGui.spread * inGui.scale) : 0.25 / (4 * 1.5);
float outlining = smoothstep(0.5 - smoothing, 0.5 + smoothing, dist);
float alpha = smoothstep(inGui.weight - smoothing, inGui.weight + smoothing, dist);
vec4 c = inGui.color;
outFragColor = mix(inGui.stroke, c, outlining);
outFragColor.a = inGui.color.a * alpha;
if ( alpha < 0.001 ) discard;
if ( alpha > 1 ) discard;
} else {
outFragColor = vec4(inGui.color) * dist;
if ( dist < 0.001 ) discard;
if ( dist > 1 ) discard;
}
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -0,0 +1,187 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
int sdf;
int shadowbox;
vec4 stroke;
float weight;
int spread;
float scale;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out vec4 outFragColor;
const int indexMatrix8x8[64] = int[](0, 32, 8, 40, 2, 34, 10, 42,
48, 16, 56, 24, 50, 18, 58, 26,
12, 44, 4, 36, 14, 46, 6, 38,
60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41,
51, 19, 59, 27, 49, 17, 57, 25,
15, 47, 7, 39, 13, 45, 5, 37,
63, 31, 55, 23, 61, 29, 53, 21);
float indexValue8x8() {
int x = int(mod(gl_FragCoord.x, 8));
int y = int(mod(gl_FragCoord.y, 8));
return indexMatrix8x8[(x + y * 8)] / 64.0;
}
const int paletteSize = 28;
const vec3 palette[28] = vec3[](
vec3(0, 0, 0),
vec3(0, 0, 1),
vec3(0, 0, 0.502),
vec3(0, 0, 0.753),
vec3(0, 1, 0.251),
vec3(0, 1, 0.50),
vec3(60.0/360.0, 1, 0.251),
vec3(60.0/360.0, 1, 0.5),
vec3(120.0/360.0, 1, 0.251),
vec3(120.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.251),
vec3(180.0/360.0, 1, 0.5),
vec3(240.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.5),
vec3(300.0/360.0, 1, 0.251),
vec3(300.0/360.0, 1, 0.5),
vec3(60.0/360.0, 0.333, 0.376),
vec3(60.0/360.0, 1, 0.751),
vec3(180.0/360.0, 1, 0.125),
vec3(150.0/360.0, 1, 0.5),
vec3(210.0/360.0, 1, 0.5),
vec3(180.0/360.0, 1, 0.751),
vec3(210.0/360.0, 1, 0.251),
vec3(240.0/360.0, 1, 0.751),
vec3(270.0/360.0, 1, 0.5),
vec3(330.0/360.0, 1, 0.5),
vec3(30.0/360.0, 1, 0.251),
vec3(24.0/360.0, 1, 0.625)
);
vec3 hslToRgb(vec3 HSL) {
vec3 RGB; {
float H = HSL.x;
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
RGB = clamp(vec3(R,G,B), 0, 1);
}
float C = (1 - abs(2 * HSL.z - 1)) * HSL.y;
return (RGB - 0.5) * C + HSL.z;
}
vec3 rgbToHsl(vec3 RGB) {
float Epsilon = 1e-10;
vec3 HCV; {
vec4 P = (RGB.g < RGB.b) ? vec4(RGB.bg, -1.0, 2.0/3.0) : vec4(RGB.gb, 0.0, -1.0/3.0);
vec4 Q = (RGB.r < P.x) ? vec4(P.xyw, RGB.r) : vec4(RGB.r, P.yzx);
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);
HCV = vec3(H, C, Q.x);
}
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2 - 1) + Epsilon);
return vec3(HCV.x, S, L);
}
float hueDistance(float h1, float h2) {
float diff = abs((h1 - h2));
return min(abs((1.0 - diff)), diff);
}
vec3[2] closestColors(float hue) {
vec3 ret[2];
vec3 closest = vec3(-2, 0, 0);
vec3 secondClosest = vec3(-2, 0, 0);
vec3 temp;
for (int i = 0; i < paletteSize; ++i) {
temp = palette[i];
float tempDistance = hueDistance(temp.x, hue);
if (tempDistance < hueDistance(closest.x, hue)) {
secondClosest = closest;
closest = temp;
} else {
if (tempDistance < hueDistance(secondClosest.x, hue)) {
secondClosest = temp;
}
}
}
ret[0] = closest;
ret[1] = secondClosest;
return ret;
}
const float lightnessSteps = 4.0;
float lightnessStep(float l) {
/* Quantize the lightness to one of `lightnessSteps` values */
return floor((0.5 + l * lightnessSteps)) / lightnessSteps;
}
vec3 dither1(vec3 color) {
vec3 hsl = rgbToHsl(color);
vec3 cs[2] = closestColors(hsl.x);
vec3 c1 = cs[0];
vec3 c2 = cs[1];
float d = indexValue8x8();
float hueDiff = hueDistance(hsl.x, c1.x) / hueDistance(c2.x, c1.x);
float l1 = lightnessStep(max((hsl.z - 0.125), 0.0));
float l2 = lightnessStep(min((hsl.z + 0.124), 1.0));
float lightnessDiff = (hsl.z - l1) / (l2 - l1);
vec3 resultColor = (hueDiff < d) ? c1 : c2;
//resultColor.z = (lightnessDiff < d) ? l1 : l2;
return hslToRgb(resultColor);
}
float dither(float color) {
float closestColor = (color < 0.5) ? 0 : 1;
float secondClosestColor = 1 - closestColor;
float d = indexValue8x8();
float distance = abs(closestColor - color);
return (distance < d) ? closestColor : secondClosestColor;
}
vec3 dither(vec3 color) {
vec3 hsl = rgbToHsl(color);
hsl.y = dither(hsl.y);
return hslToRgb(hsl);
}
void main() {
if ( inUv.x < inGui.offset.x ) discard;
if ( inUv.y < inGui.offset.y ) discard;
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
if ( inGui.shadowbox == 1 ) {
outFragColor = inGui.color;
return;
}
float dist = texture(samplerColor, inUv).r;
if ( inGui.sdf == 1 ) {
float smoothing = ( inGui.spread > 0 && inGui.scale > 0 ) ? 0.25 / (inGui.spread * inGui.scale) : 0.25 / (4 * 1.5);
float outlining = smoothstep(0.5 - smoothing, 0.5 + smoothing, dist);
float alpha = smoothstep(inGui.weight - smoothing, inGui.weight + smoothing, dist);
vec4 c = inGui.color;
outFragColor = mix(inGui.stroke, c, outlining);
outFragColor.a = inGui.color.a * alpha;
if ( alpha < 0.001 ) discard;
if ( alpha > 1 ) discard;
} else {
outFragColor = vec4(inGui.color) * dist;
if ( dist < 0.001 ) discard;
if ( dist > 1 ) discard;
}
outFragColor.rgb = dither(outFragColor.rgb);
}

View File

@ -1,9 +1,6 @@
#version 450
#define UF_DEFERRED_SAMPLING 0
#define UF_CAN_DISCARD 1
layout (binding = 1) uniform sampler2D samplerTexture;
layout (binding = 1) uniform sampler2D samplerColor;
struct Gui {
vec4 offset;
@ -16,19 +13,11 @@ struct Gui {
float weight;
int spread;
float scale;
float padding;
};
layout (location = 0) in vec2 inUv;
layout (location = 1) in flat Gui inGui;
layout (location = 0) out uvec2 outId;
layout (location = 1) out vec2 outNormals;
#if UF_DEFERRED_SAMPLING
layout (location = 2) out vec2 outUvs;
#else
layout (location = 2) out vec4 outAlbedo;
#endif
layout (location = 0) out vec4 outFragColor;
void main() {
if ( inUv.x < inGui.offset.x ) discard;
@ -36,26 +25,22 @@ void main() {
if ( inUv.x > inGui.offset.z ) discard;
if ( inUv.y > inGui.offset.w ) discard;
#if UF_DEFERRED_SAMPLING
vec4 outAlbedo = vec4(0,0,0,0);
#endif
if ( inGui.shadowbox == 1 ) {
outAlbedo = inGui.color;
outFragColor = inGui.color;
return;
}
float dist = texture(samplerTexture, inUv).r;
float dist = texture(samplerColor, inUv).r;
if ( inGui.sdf == 1 ) {
float smoothing = ( inGui.spread > 0 && inGui.scale > 0 ) ? 0.25 / (inGui.spread * inGui.scale) : 0.25 / (4 * 1.5);
float outlining = smoothstep(0.5 - smoothing, 0.5 + smoothing, dist);
float alpha = smoothstep(inGui.weight - smoothing, inGui.weight + smoothing, dist);
vec4 c = inGui.color;
outAlbedo = mix(inGui.stroke, c, outlining);
outAlbedo.a = inGui.color.a * alpha;
outFragColor = mix(inGui.stroke, c, outlining);
outFragColor.a = inGui.color.a * alpha;
if ( alpha < 0.001 ) discard;
if ( alpha > 1 ) discard;
} else {
outAlbedo = vec4(inGui.color) * dist;
outFragColor = vec4(inGui.color) * dist;
if ( dist < 0.001 ) discard;
if ( dist > 1 ) discard;
}

View File

@ -0,0 +1,44 @@
#version 450
layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUv;
layout( push_constant ) uniform PushBlock {
uint pass;
} PushConstant;
struct Matrices {
mat4 model[2];
};
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
int sdf;
int shadowbox;
vec4 stroke;
float weight;
int spread;
float scale;
};
layout (binding = 0) uniform UBO {
Matrices matrices;
Gui gui;
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out flat Gui outGui;
out gl_PerVertex {
vec4 gl_Position;
};
void main() {
outUv = inUv;
outGui = ubo.gui;
gl_Position = ubo.matrices.model[PushConstant.pass] * vec4(inPos.xy, ubo.gui.depth, 1.0);
}

View File

@ -1,16 +1,10 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUv;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model[PASSES];
mat4 model;
};
struct Gui {
vec4 offset;
@ -23,7 +17,6 @@ struct Gui {
float weight;
int spread;
float scale;
float padding;
};
layout (binding = 0) uniform UBO {
@ -43,5 +36,5 @@ void main() {
outUv = inUv;
outGui = ubo.gui;
gl_Position = ubo.matrices.model[PushConstant.pass] * vec4(inPos.xy, ubo.gui.depth, 1.0);
gl_Position = ubo.matrices.model * vec4(inPos.xy, ubo.gui.depth, 1.0);
}

View File

@ -1,23 +1,16 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUv;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model[PASSES];
mat4 model;
};
struct Gui {
vec4 offset;
vec4 color;
int mode;
float depth;
vec2 padding;
};
layout (binding = 0) uniform UBO {
@ -37,5 +30,5 @@ void main() {
outUv = inUv;
outGui = ubo.gui;
gl_Position = ubo.matrices.model[PushConstant.pass] * vec4(inPos.xy, ubo.gui.depth, 1.0);
gl_Position = ubo.matrices.model * vec4(inPos.xy, ubo.gui.depth, 1.0);
}

View File

@ -1,19 +0,0 @@
#version 450
layout (binding = 1) uniform sampler2D samplerColor;
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec3 inNormal;
layout (location = 2) in vec4 inColor;
layout (location = 0) out vec4 outAlbedoSpecular;
layout (location = 1) out vec4 outNormal;
void main() {
outAlbedoSpecular = texture(samplerColor, inUv);
outAlbedoSpecular = vec4(1,1,1,1);
outAlbedoSpecular.rgb *= inColor.rgb;
outAlbedoSpecular.a = 1;
// outPosition = vec4(inPosition, 1.0);
outNormal = vec4(normalize(inNormal), 1.0);
}

View File

@ -1,10 +0,0 @@
#version 450
layout (location = 0) in vec3 inColor;
layout (location = 0) out vec4 outAlbedoSpecular;
void main() {
outAlbedoSpecular.rgb *= inColor.rgb;
outAlbedoSpecular.a = 1;
}

View File

@ -1,35 +0,0 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[PASSES];
mat4 projection[PASSES];
};
layout (binding = 0) uniform UBO {
Matrices matrices;
vec4 color;
} ubo;
layout (location = 0) out vec4 outColor;
out gl_PerVertex {
vec4 gl_Position;
};
void main() {
outColor = ubo.color;
// outPosition = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
gl_Position = ubo.matrices.projection[PushConstant.pass] * ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0);
}

View File

@ -1,23 +0,0 @@
#version 450
layout (binding = 1) uniform sampler3D samplerColor;
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec4 inColor;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec3 inPosition;
layout (location = 0) out vec4 outAlbedoSpecular;
layout (location = 1) out vec4 outNormal;
layout (location = 2) out vec4 outPosition;
layout (binding = 2) uniform UBO {
float slice;
} ubo;
void main() {
outAlbedoSpecular.rgb = vec3(texture(samplerColor, vec3(inUv,ubo.slice)).r);
outAlbedoSpecular.a = 1;
outNormal = vec4(inNormal,1);
outPosition = vec4(inPosition,1);
}

View File

@ -1,295 +1,408 @@
#version 450
layout (local_size_x = 32, local_size_y = 32) in;
layout (binding = 0, rgba8) uniform writeonly image2D resultImage;
layout (constant_id = 0) const uint LIGHTS = 16;
layout (constant_id = 1) const uint EYES = 2;
layout (binding = 0, rgba8) uniform writeonly image2D resultImage[EYES];
#define EPSILON 0.0001
#define EPSILON 0.00001
#define MAXLEN 1000.0
#define SHADOW 0.5
#define RAYBOUNCES 4
#define REFLECTIONS true
#define REFLECTIONSTRENGTH 0.4
#define REFLECTIONFALLOFF 0.5
layout( push_constant ) uniform PushBlock {
uint marchingSteps;
uint rayBounces;
float shadowFactor;
float reflectionStrength;
float reflectionFalloff;
} PushConstant;
#define UINT32_MAX 0xFFFFFFFF
struct Ray {
vec3 origin;
vec3 direction;
#define TREE_SIZE 8
#define TREE_STACK 32
#define PRIMITIVE_TYPE_EMPTY UINT32_MAX
#define PRIMITIVE_TYPE_CUBE 1
#define PRIMITIVE_TYPE_LEAF 2
#define PRIMITIVE_TYPE_TREE 3
#define PRIMITIVE_TYPE_ROOT 4
struct Camera {
vec3 position;
mat4 view;
float aspectRatio;
};
struct Result {
vec3 color;
float t;
int id;
struct StartEnd {
uint start;
uint end;
};
struct Cube {
vec4 position;
uint type;
// uint _padding[3];
};
struct Tree {
vec4 position;
uint type;
uint children[TREE_SIZE];
// uint _padding[3];
};
struct Light {
vec3 position;
float radius;
vec3 color;
float power;
vec2 type;
vec2 padding;
mat4 view;
mat4 projection;
};
struct State {
vec3 viewPosition;
Ray ray;
Result result;
} state;
struct Fog {
vec2 range;
vec2 padding;
vec4 color;
};
layout (binding = 1) uniform UBO {
mat4 matrices[2];
vec4 ambient;
Fog fog;
Light lights[LIGHTS];
layout (binding = 1) uniform UBO {
Camera camera;
StartEnd cubes;
StartEnd lights;
uint root;
} ubo;
struct Shape {
vec4 values;
vec4 albedoSpecular;
int type;
layout (std140, binding = 2) buffer Cubes {
Cube cubes[ ];
};
layout (std140, binding = 2) buffer Shapes {
Shape shapes[];
layout (std430, binding = 3) buffer Trees {
Tree trees[ ];
};
layout (std140, binding = 4) buffer Lights {
Light lights[ ];
};
layout (binding = 5) uniform sampler2D samplerTexture;
void reflectRay(inout vec3 rayD, in vec3 normal) {
rayD = rayD + 2.0 * -dot(normal, rayD) * normal;
}
// Lighting =========================================================
void reflectRay(inout vec3 rayD, in vec3 mormal) {
rayD = rayD + 2.0 * -dot(mormal, rayD) * mormal;
}
float lightDiffuse(vec3 normal, vec3 lightDir) {
return clamp(dot(normal, lightDir), 0.1, 1.0);
}
float lightSpecular(vec3 normal, vec3 lightDir, float specularFactor) {
vec3 viewVec = normalize(state.viewPosition);
vec3 viewVec = normalize(ubo.camera.position);
vec3 halfVec = normalize(lightDir + viewVec);
return pow(clamp(dot(normal, halfVec), 0.0, 1.0), specularFactor);
}
// Cube ===========================================================
float cubeIntersect(vec3 rayO, vec3 rayD, vec3 rayDRecip, Cube cube) {
float t[10];
t[1] = ( cube.position.x - cube.position.w - rayO.x) * rayDRecip.x;
t[2] = ( cube.position.x + cube.position.w - rayO.x) * rayDRecip.x;
t[3] = ( cube.position.y - cube.position.w - rayO.y) * rayDRecip.y;
t[4] = ( cube.position.y + cube.position.w - rayO.y) * rayDRecip.y;
t[5] = ( cube.position.z - cube.position.w - rayO.z) * rayDRecip.z;
t[6] = ( cube.position.z + cube.position.w - rayO.z) * rayDRecip.z;
t[7] = max(max(min(t[1], t[2]), min(t[3], t[4])), min(t[5], t[6]));
t[8] = min(min(max(t[1], t[2]), max(t[3], t[4])), max(t[5], t[6]));
t[9] = (t[8] < 0 || t[7] > t[8]) ? 0.0 : t[7];
return t[9];
}
uint intersect(in vec3 rayO, in vec3 rayD, inout float resT, uint start, uint end) {
uint id = UINT32_MAX;
vec3 rayDRecip = 1.0f / rayD;
for (uint i = start; i < end && i < ubo.cubes.end && i < cubes.length(); i++) {
Cube cube = cubes[i];
if ( cube.type == PRIMITIVE_TYPE_EMPTY ) continue;
float tcube = cubeIntersect(rayO, rayD, rayDRecip, cube);
if ((tcube > EPSILON) && (tcube < resT)) {
id = i;
resT = tcube;
}
}
// Sphere ===========================================================
float sphereIntersect(in vec3 rayO, in vec3 rayD, in Shape shape ) {
vec3 oc = rayO - shape.values.xyz;
float b = 2.0 * dot(oc, rayD);
float c = dot(oc, oc) - shape.values.w * shape.values.w;
float h = b*b - 4.0*c;
if (h < 0.0) return -1.0;
float t = (-b - sqrt(h)) / 2.0;
return id;
}
// Tree ===========================================================
float treeIntersect( in vec3 rayO, in vec3 rayD, in vec3 rayDRecip, Tree tree ) {
Cube treecube;
treecube.type = tree.type;
treecube.position = tree.position;
float t = cubeIntersect( rayO, rayD, rayDRecip, treecube );
return t;
}
vec3 sphereNormal(in vec3 position, in Shape shape) {
return (position - shape.values.xyz) / shape.values.w;
struct StackIterator {
uint tree;
uint child;
};
struct Stack {
int pointer;
StackIterator container[TREE_STACK];
};
Stack stack;
StackIterator popStack( ) {
StackIterator top = stack.container[stack.pointer];
stack.container[stack.pointer--] = StackIterator( UINT32_MAX, UINT32_MAX );
return top;
}
float sphereSDF( vec3 position, in Shape shape ) {
return length(position - shape.values.xyz) - shape.values.w;
void pushStack( StackIterator item ) {
stack.container[++stack.pointer] = item;
}
// Plane ===========================================================
float planeIntersect(in vec3 rayO, in vec3 rayD, in Shape shape) {
float d = dot(rayD, shape.values.xyz);
if (d == 0.0) return 0.0;
float t = -(shape.values.w + dot(rayO, shape.values.xyz)) / d;
return t < 0.0 ? 0.0 : t;
}
vec3 planeNormal(in vec3 position, in Shape shape) {
return shape.values.xyz;
}
float planeSDF( vec3 position, in Shape shape ) {
return dot( position, shape.values.xyz ) + shape.values.w;
}
// Generic =========================================================
float shapeIntersect(in vec3 rayO, in vec3 rayD, in Shape shape) {
if ( shape.type == 1 ) return sphereIntersect( rayO, rayD, shape );
if ( shape.type == 2 ) return planeIntersect( rayO, rayD, shape );
return 0.0;
}
vec3 shapeNormal( vec3 position, in Shape shape ) {
if ( shape.type == 1 ) return sphereNormal(position, shape);
if ( shape.type == 2 ) return planeNormal(position, shape);
return vec3(0.0);
}
float shapeSDF( vec3 position, in Shape shape ) {
if ( shape.type == 1 ) return sphereSDF(position, shape);
if ( shape.type == 2 ) return planeSDF(position, shape);
return MAXLEN;
}
// Intersect =======================================================
int intersect(in vec3 rayO, in vec3 rayD, inout float resT) {
int id = -1;
for (int i = 0; i < shapes.length(); i++) {
Shape shape = shapes[i];
float tShape = shapeIntersect(rayO, rayD, shape);
if ((tShape > EPSILON) && (tShape < resT)) {
id = i;
resT = tShape;
}
uint intersectTreecursive( in vec3 rayO, in vec3 rayD, in vec3 rayDRecip, inout float resT, uint root ) {
uint id = UINT32_MAX;
if ( root == UINT32_MAX ) return id;
// set up stack
stack.pointer = -1;
for ( uint i = 0; i < TREE_STACK; ++i ) stack.container[i] = StackIterator( UINT32_MAX, UINT32_MAX );
pushStack(StackIterator( root, UINT32_MAX ));
while ( true ) {
StackIterator it = popStack();
// end of stack
if ( it.tree == UINT32_MAX ) break;
Tree tree = trees[it.tree];
// invalid tree
if ( tree.type == PRIMITIVE_TYPE_EMPTY ) break;
// new tree, parse collision
if ( it.child == UINT32_MAX ) {
float t = treeIntersect( rayO, rayD, rayDRecip, tree );
// bad intersection with this tree, continue with next iteration
if ( t <= EPSILON || t >= resT ) continue;
// push back with new stack
it.child = 0;
pushStack( it );
// continue with next iteration
continue;
} else if ( it.child >= TREE_SIZE ) {
// no new children, continue with next iteration
continue;
} else {
// is leaf
if ( tree.type == PRIMITIVE_TYPE_LEAF ) {
// check children for a match
for ( uint i = 0; i < TREE_SIZE; ++i ) {
uint branchId = tree.children[i];
// unallocated, skip
if ( branchId == UINT32_MAX ) continue;
Cube primitive = cubes[branchId];
if ( primitive.type == PRIMITIVE_TYPE_EMPTY ) continue;
float t = cubeIntersect( rayO, rayD, rayDRecip, primitive );
// branch intersects with ray, set as new parent
if ( (t <= EPSILON) || (t >= resT) ) continue;
id = branchId;
resT = t;
}
// continue with next iteration
continue;
}
// parse children
uint branchId = tree.children[it.child++];
// add new iterator to the stack
pushStack( it );
// unused child, continue with next iteration
if ( branchId == UINT32_MAX ) continue;
// tree branch, push to stack
// the first if block will check its collision
it.tree = branchId;
it.child = UINT32_MAX;
pushStack( it );
continue;
}
}
return id;
}
float calcShadow(in vec3 rayO, in vec3 rayD, in int objectID, inout float resT) {
for (int i = 0; i < shapes.length(); i++) {
if ( i == objectID ) continue;
Shape shape = shapes[i];
float tShape = shapeIntersect(rayO, rayD, shape);
if ((tShape > EPSILON) && (tShape < resT)) {
resT = tShape;
return PushConstant.shadowFactor;
uint intersectTree( in vec3 rayO, in vec3 rayD, in vec3 rayDRecip, inout float resT ) {
uint id = UINT32_MAX;
// traverse the tree branches to the leaf
uint index = 0;
while ( true ) {
Tree tree = trees[index++];
if ( tree.type == PRIMITIVE_TYPE_EMPTY ) break;
if ( tree.type != PRIMITIVE_TYPE_LEAF ) continue;
float tcube = treeIntersect( rayO, rayD, rayDRecip, tree );
// ray fails collision with parent tree
if ( (tcube <= EPSILON) || (tcube >= resT) ) continue;
// ray intersects with parent tree, check children branches
for ( uint i = 0; i < TREE_SIZE; ++i ) {
uint branchId = tree.children[i];
// unallocated, skip
if ( branchId == UINT32_MAX ) continue;
Cube primitive = cubes[branchId];
if ( primitive.type == PRIMITIVE_TYPE_EMPTY ) continue;
tcube = cubeIntersect( rayO, rayD, rayDRecip, primitive );
// branch intersects with ray, set as new parent
if ( (tcube <= EPSILON) || (tcube >= resT) ) continue;
id = branchId;
resT = tcube;
}
}
return id;
}
float calcShadow(in vec3 rayO, in vec3 rayD, in uint objectId, inout float t, uint start, uint end) {
vec3 rayDRecip = 1.0f / rayD;
for (uint i = ubo.cubes.start; i < ubo.cubes.end && i < cubes.length(); i++) {
if (i == objectId) continue;
float tCube = cubeIntersect(rayO, rayD, rayDRecip, cubes[i]);
if ((tCube > EPSILON) && (tCube < t)) {
t = tCube;
return SHADOW;
}
}
return 1.0;
}
float calcShadowTree(in vec3 rayO, in vec3 rayD, in vec3 rayDRecip, in uint objectId, inout float t){
// traverse the tree branches to the leaf
uint index = 0;
while ( true ) {
Tree tree = trees[index++];
if ( tree.type == PRIMITIVE_TYPE_EMPTY ) break;
if ( tree.type != PRIMITIVE_TYPE_LEAF ) continue;
float tcube = treeIntersect( rayO, rayD, rayDRecip, tree );
// ray fails collision with parent tree
if ( (tcube <= EPSILON) || (tcube >= t) ) continue;
// ray intersects with parent tree, check children branches
for ( uint i = 0; i < TREE_SIZE; ++i ) {
uint branchId = tree.children[i];
// unallocated, skip
if ( branchId == UINT32_MAX ) continue;
Cube primitive = cubes[branchId];
if ( primitive.type == PRIMITIVE_TYPE_EMPTY ) continue;
if ( branchId == objectId ) continue;
tcube = cubeIntersect( rayO, rayD, rayDRecip, primitive );
// branch intersects with ray, set as new parent
if ( (tcube <= EPSILON) || (tcube >= t) ) continue;
t = tcube;
return SHADOW;
}
}
return 1.0;
}
// Marching ========================================
int intersectMarch( in vec3 rayO, in vec3 rayD, inout float resT ) {
resT = 0;
for (int i = 0; i < PushConstant.marchingSteps; ++i) {
vec3 position = resT * rayD + rayO;
float tNearest = MAXLEN;
int objectID = -1;
for ( int j = 0; j < shapes.length(); ++j ) {
Shape shape = shapes[j];
float tShape = shapeSDF(position, shape);
// if ((tShape > EPSILON) && (tShape < tNearest)) {
if ( tShape < tNearest ) {
objectID = j;
tNearest = tShape;
}
}
if (tNearest < EPSILON) {
return objectID;
}
if (resT > MAXLEN) break;
resT += tNearest;
}
resT = MAXLEN;
return -1;
}
float calcShadowMarch( in vec3 rayO, in vec3 rayD, in int objectID, inout float resT ) {
float distance = resT;
resT = 0;
for (int i = 0; i < PushConstant.marchingSteps; ++i) {
vec3 position = resT * rayD + rayO;
float tNearest = distance;
int objectID = -1;
for ( int j = 0; j < shapes.length(); ++j ) {
if ( j == objectID ) continue;
Shape shape = shapes[j];
float tShape = shapeSDF(position, shape);
// if ((tShape > EPSILON) && (tShape < tNearest)) {
if ( tShape < tNearest ) {
objectID = j;
tNearest = tShape;
}
}
if (tNearest < EPSILON) {
return PushConstant.shadowFactor;
}
if (resT > distance) break;
resT += tNearest;
}
resT = distance;
return 1.0;
vec3 fog(in float t, in vec3 color) {
return mix(color, vec3(0, 0, 0), clamp(sqrt(t*t)/20.0, 0.0, 1.0));
}
void fog(inout vec3 i, in float t ) {
/*
vec3 fogColor = ubo.ambient.rgb;
i = mix(i, fogColor.rgb, clamp(sqrt(t*t)/20.0, 0.0, 1.0));
*/
if ( ubo.fog.range.x == 0 || ubo.fog.range.y == 0 ) return;
vec3 renderScene(inout vec3 rayO, inout vec3 rayD, inout uint id) {
float t = MAXLEN;
vec3 rayDRecip = 1.0f / rayD;
vec3 color = ubo.fog.color.rgb;
float inner = ubo.fog.range.x, outer = ubo.fog.range.y;
float factor = (t - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
// Get intersected object ID
uint objectID = intersect(rayO, rayD, t, ubo.cubes.start, ubo.cubes.end );
// uint objectID = intersectTree( rayO, rayD, rayDRecip, t );
// uint objectID = intersectTreecursive( rayO, rayD, rayDRecip, t, ubo.root );
i = mix(i.rgb, color, factor);
}
Result renderScene(inout vec3 rayO, inout vec3 rayD ) {
Result result;
result.color = vec3(0.0);
result.t = MAXLEN;
result.id = PushConstant.marchingSteps > 0 ? intersectMarch(rayO, rayD, result.t) : intersect(rayO, rayD, result.t);
if (result.id == -1) return result;
vec3 color = vec3(0.0);
if ( objectID == UINT32_MAX ) return color;
Shape shape = shapes[result.id];
vec3 position = rayO + result.t * rayD;
vec3 normal = shapeNormal( position, shape );
vec3 pos = rayO + t * rayD;
vec3 normal;
for ( uint i = 0; i < LIGHTS; ++i ) {
Light light = ubo.lights[i];
if ( light.radius <= EPSILON ) continue;
if ( light.power <= EPSILON ) continue;
// Cubes
if ( id == UINT32_MAX ) return color;
id = objectID;
// Hit Data
{
Cube cube = cubes[objectID];
vec2 mappedUv = vec2(0, 0); {
float min_distance = MAXLEN;
vec3 point = cube.position.xyz - pos;
float distance = abs(cube.position.w - abs(point.x));
if (distance < min_distance) {
min_distance = distance;
normal = vec3(-1, 0, 0);
if ( cube.position.w + point.x <= EPSILON ) normal *= -1;
vec3 L = light.position - position;
float dist = length(L);
vec3 D = normalize(L);
float attenuation = light.radius / (pow(dist, 2.0) + 1.0);;
attenuation = 1;
// if ( dist > light.radius ) continue;
vec4 albedoSpecular = shape.albedoSpecular;
mappedUv.x = point.y - cube.position.y;
mappedUv.y = point.z - cube.position.z;
}
distance = abs(cube.position.w - abs(point.y));
if (distance < min_distance) {
min_distance = distance;
normal = vec3(0, -1, 0);
if ( cube.position.w + point.y <= EPSILON ) normal *= -1;
float d_dot = lightDiffuse(normal, D);
float s_factor = lightSpecular(normal, D, albedoSpecular.a);
vec3 color = (light.color * albedoSpecular.rgb) * d_dot + s_factor;
mappedUv.x = point.x - cube.position.x;
mappedUv.y = point.z - cube.position.z;
}
distance = abs(cube.position.w - abs(point.z));
if (distance < min_distance) {
min_distance = distance;
normal = vec3(0, 0, -1);
if ( cube.position.w + point.z <= EPSILON ) normal *= -1;
// Shadows
float tShadow = dist;
float shadowed = 1;
if ( PushConstant.shadowFactor < 1.0 )
shadowed = PushConstant.marchingSteps > 0 ? calcShadowMarch(position, D, result.id, tShadow) : calcShadow(position, D, result.id, tShadow);
result.color += color * light.power * attenuation * shadowed;
mappedUv.x = point.x - cube.position.x;
mappedUv.y = point.y - cube.position.y;
}
mappedUv -= 2.0f / 4.0f;
mappedUv *= 1.0f / 4.0f;
mappedUv.x = mod(mappedUv.x, 1.0f / 4.0f);
mappedUv.y = mod(mappedUv.y, 1.0f / 4.0f);
}
vec3 textureMapped = texture(samplerTexture, mappedUv).rgb;
color = textureMapped;
}
// Lighting
{
int di = 0;
vec4 diffuses[256];
for ( int j = 0; j < lights.length(); ++j ) {
Light light = lights[j];
if ( light.color.r <= EPSILON && light.color.g <= EPSILON && light.color.b <= EPSILON ) continue;
vec3 lightVec = normalize(light.position - pos);
float diffuse = lightDiffuse(normal, lightVec);
float specular = lightSpecular(normal, lightVec, 2000.0f);
diffuses[di].x = length(light.position - pos);
diffuses[di].gba = diffuse * light.color + specular;
++di;
}
vec4 a = vec4(MAXLEN, vec3(1.0));
vec4 b = vec4(MAXLEN, vec3(1.0));
vec4 c = vec4(MAXLEN, vec3(1.0));
for ( int j = 0; j < lights.length(); ++j ) {
vec4 current = diffuses[j];
if ( current.y <= EPSILON ) continue;
// use slot a
if ( current.x < a.x ) {
c = b;
b = a;
a = current;
} else if ( current.x < b.x ) {
c = b;
b = current;
} else if ( current.x < c.x ) {
c = current;
}
}
vec3 avg = (a.gba * 0.5 + b.gba * 0.3 + c.gba * 0.2);
color *= avg;
}
// Shadows
{
vec3 lightVec = vec3(0, 4, 0) - pos;
t = length(lightVec);
color *= calcShadow(pos, lightVec, id, t, ubo.cubes.start, ubo.cubes.end);
// color *= calcShadowTree(pos, lightVec, rayDRecip, id, t);
}
// Fog
// fog(t, result.color);
// color = fog(t, color);
// Reflect ray for next render pass
reflectRay(rayD, normal);
rayO = position;
rayO = pos;
return result;
return color;
}
void main() {
for ( int pass = 0; pass < EYES; ++pass ) {
{
vec2 uv = vec2(gl_GlobalInvocationID.xy) / imageSize(resultImage[pass]);
vec4 near4 = ubo.matrices[pass] * (vec4(2.0 * uv - 1.0, -1.0, 1.0));
vec4 far4 = ubo.matrices[pass] * (vec4(2.0 * uv - 1.0, 1.0, 1.0));
vec3 near3 = near4.xyz / near4.w;
vec3 far3 = far4.xyz / far4.w;
ivec2 dim = imageSize(resultImage);
vec2 uv = vec2(gl_GlobalInvocationID.xy) / dim;
state.viewPosition = near3;
state.ray.origin = near3;
state.ray.direction = normalize( far3 - near3 );
}
// Basic color path
state.result = renderScene(state.ray.origin, state.ray.direction);
vec3 finalColor = state.result.color;
vec3 rayO = ubo.camera.position; // * vec3(1,1,-1);
vec3 rayD = normalize(vec3((-1.0 + 2.0 * uv) * vec2(ubo.camera.aspectRatio, 1.0), -1.0));
rayD = (ubo.camera.view * vec4( rayD, 0.0 )).xyz;
// Reflection
float reflectionStrength = PushConstant.reflectionStrength;
for (int i = 0; i < PushConstant.rayBounces; i++) {
Result result = renderScene(state.ray.origin, state.ray.direction);
vec3 reflectionColor = result.color;
finalColor = (1.0 - reflectionStrength) * finalColor + reflectionStrength * mix(reflectionColor, finalColor, 1.0 - reflectionStrength);
reflectionStrength *= PushConstant.reflectionFalloff;
// Basic color path
uint id = 0;
vec3 finalColor = renderScene(rayO, rayD, id);
// Reflection
if ( REFLECTIONS ) {
float reflectionStrength = REFLECTIONSTRENGTH;
for (int i = 0; i < RAYBOUNCES; i++) {
vec3 reflectionColor = renderScene(rayO, rayD, id);
finalColor = (1.0 - reflectionStrength) * finalColor + reflectionStrength * mix(reflectionColor, finalColor, 1.0 - reflectionStrength);
reflectionStrength *= REFLECTIONFALLOFF;
}
imageStore(resultImage[pass], ivec2(gl_GlobalInvocationID.xy), vec4(finalColor, 1.0));
}
imageStore(resultImage, ivec2(gl_GlobalInvocationID.xy), vec4(finalColor, 0.0));
}

View File

@ -3,18 +3,53 @@
layout (binding = 1) uniform sampler2D samplerColor;
layout (location = 0) in vec2 inUv;
layout (location = 1) in vec4 inColor;
layout (location = 2) in vec3 inNormal;
layout (location = 3) in vec3 inPosition;
layout (location = 1) in vec3 inPositionEye;
layout (location = 2) in vec3 inNormalEye;
layout (location = 3) in vec4 inColor;
layout (location = 0) out vec4 outFragColor;
layout (location = 0) out vec4 outAlbedoSpecular;
layout (location = 1) out vec4 outNormal;
layout (location = 2) out vec4 outPosition;
void fog( inout vec3 i ) {
vec3 color = vec3( 0, 0, 0 );
float inner = 8, outer = 64;
float distance = length(-inPositionEye);
float factor = (distance - inner) / (outer - inner);
factor = clamp( factor, 0.0, 1.0 );
i = mix(i.rgb, color, factor);
}
void phong( inout vec3 i ) {
vec3 Ls = vec3(1.0, 1.0, 1.0); // light specular
vec3 Ld = vec3(0.4, 0.4, 1.0); // light color
vec3 La = vec3(0.1, 0.1, 0.1);
vec3 Ks = vec3(0.6, 0.6, 0.9); // material specular
vec3 Kd = i; // material diffuse
vec3 Ka = vec3(0.7, 0.7, 0.7);
float Kexp = 1000.0;
vec3 dist_light_eye = vec3(0, 0, 0) - inPositionEye;
vec3 dir_light_eye = normalize(dist_light_eye);
float d_dot = max(dot( dir_light_eye, inNormalEye ), 0.0);
vec3 reflection_eye = reflect( -dir_light_eye, inNormalEye );
vec3 surface_eye = normalize(-inPositionEye);
float s_dot = max(dot( reflection_eye, surface_eye ), 0.0);
float s_factor = pow( s_dot, Kexp );
vec3 Ia = La * Ka;
vec3 Id = Ld * Kd * d_dot;
vec3 Is = Ls * Ks * s_factor;
i = Is + Id + Ia;
}
void main() {
outAlbedoSpecular = texture(samplerColor, inUv);
// outAlbedoSpecular.rgb *= inColor.rgb;
outAlbedoSpecular.a = 1;
outNormal = vec4(inNormal,1);
outPosition = vec4(inPosition,1);
outFragColor = texture(samplerColor, inUv);
// phong(outFragColor.rgb);
fog(outFragColor.rgb);
// outFragColor.rgb = mix( outFragColor.rgb, inColor.rgb, inColor.a );
outFragColor.rgb = outFragColor.rgb * inColor.rgb;
// outFragColor.rgb = inColor.rgb;
if ( outFragColor.a < 0.001 ) discard;
}

View File

@ -1,6 +1,5 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
@ -8,13 +7,12 @@ layout (location = 3) in uint inColor;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[PASSES];
mat4 projection[PASSES];
mat4 view[2];
mat4 projection[2];
};
layout (binding = 0) uniform UBO {
@ -23,8 +21,9 @@ layout (binding = 0) uniform UBO {
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec3 outNormal;
layout (location = 2) out vec4 outColor;
layout (location = 1) out vec3 outPositionEye;
layout (location = 2) out vec3 outNormalEye;
layout (location = 3) out vec4 outColor;
out gl_PerVertex {
vec4 gl_Position;
@ -33,14 +32,10 @@ out gl_PerVertex {
void main() {
outUv = inUv;
outPositionEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormalEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
// outColor = ubo.color;
// outPosition = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
// outPosition = vec3(ubo.matrices.model * vec4(inPos.xyz, 1.0));
// outNormal = vec3(ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outColor.a = (inColor >> 24u) & 0xFF;
outColor.b = (inColor >> 16u) & 0xFF;
outColor.g = (inColor >> 8u) & 0xFF;

View File

@ -1,6 +1,5 @@
#version 450
layout (constant_id = 0) const uint PASSES = 6;
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec2 inUv;
layout (location = 2) in vec3 inNormal;
@ -8,13 +7,12 @@ layout (location = 3) in uint inColor;
layout( push_constant ) uniform PushBlock {
uint pass;
uint draw;
} PushConstant;
struct Matrices {
mat4 model;
mat4 view[PASSES];
mat4 projection[PASSES];
mat4 view[2];
mat4 projection[2];
};
layout (binding = 0) uniform UBO {
@ -23,9 +21,9 @@ layout (binding = 0) uniform UBO {
} ubo;
layout (location = 0) out vec2 outUv;
layout (location = 1) out vec4 outColor;
layout (location = 2) out vec3 outNormal;
layout (location = 3) out vec3 outPosition;
layout (location = 1) out vec3 outPositionEye;
layout (location = 2) out vec3 outNormalEye;
layout (location = 3) out vec4 outColor;
out gl_PerVertex {
vec4 gl_Position;
@ -34,12 +32,10 @@ out gl_PerVertex {
void main() {
outUv = inUv;
outPositionEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormalEye = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
// outColor = ubo.color;
outPosition = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inPos.xyz, 1.0));
outNormal = vec3(ubo.matrices.view[PushConstant.pass] * ubo.matrices.model * vec4(inNormal.xyz, 0.0));
outNormal = normalize(outNormal);
outColor.a = (inColor >> 24u) & 0xFF;
outColor.b = (inColor >> 16u) & 0xFF;
outColor.g = (inColor >> 8u) & 0xFF;

View File

@ -5,7 +5,7 @@ layout (location = 0) in vec2 inUV;
layout (location = 0) out vec4 outFragColor;
void main() {
vec4 sampledColor = texture(samplerColor, inUV);
vec4 sampledColor = texture(samplerColor, vec2(inUV.s, 1.0 - inUV.t));
if ( sampledColor.r <= 0.000001 && sampledColor.g <= 0.000001 && sampledColor.b <= 0.000001 ) discard;
outFragColor = sampledColor;
}

View File

@ -6,8 +6,8 @@
#include <uf/utils/audio/audio.h>
#include <uf/spec/terminal/terminal.h>
#include <uf/utils/hook/hook.h>
#include <uf/utils/thread/thread.h>
#include <uf/utils/renderer/renderer.h>
#include <uf/ext/vulkan/vulkan.h>
bool client::ready = false;
bool client::terminated = false;
@ -15,18 +15,39 @@ uf::Window client::window;
uf::Serializer client::config;
void client::initialize() {
// spec::Context::globalInit();
uf::IoStream::ncurses = true;
uf::renderer::device.window = &client::window;
ext::load();
ext::vulkan::device.window = &client::window;
/* Initialize config */ {
struct {
uf::Serializer ext;
uf::Serializer fallback;
} config;
/* Get configuration */ {
config.ext = ext::config.serialize();
config.ext = ext::getConfig();
}
/* Initialize default configuration */ {
config.fallback["terminal"]["visible"] = true;
config.fallback["terminal"]["ncurses"] = true;
config.fallback["window"]["title"] = "[uf] Grimgram";
config.fallback["window"]["icon"] = "./cfg/icon.png";
config.fallback["window"]["size"]["x"] = 640;
config.fallback["window"]["size"]["y"] = 480;
config.fallback["window"]["visible"] = true;
config.fallback["window"]["fullscreen"] = false;
config.fallback["cursor"]["visible"] = true;
config.fallback["keyboard"]["repeat"] = true;
config.fallback["hook"]["mode"] = "Readable";
config.fallback["light"]["ambient"]["g"] = 0.0f;
config.fallback["light"]["ambient"]["b"] = 0.0f;
config.fallback["light"]["ambient"]["a"] = 1.0f;
config.fallback["context"]["depthBits"] = 24;
config.fallback["context"]["stencilBits"] = 4;
config.fallback["context"]["bitsPerPixel"] = 8;
config.fallback["context"]["antialiasingLevel"] = 0;
config.fallback["context"]["majorVersion"] = 3;
config.fallback["context"]["minorVersion"] = 0;
}
/* Merge */ {
client::config = config.ext;
@ -36,43 +57,42 @@ void client::initialize() {
/* Initialize window */ {
// Window size
pod::Vector2i size; {
size.x = client::config["window"]["size"]["x"].as<size_t>();
size.y = client::config["window"]["size"]["y"].as<size_t>();
// request system size
if ( size.x <= 0 && size.y <= 0 ) {
auto resolution = client::window.getResolution();
client::config["window"]["size"]["x"] = (size.x = resolution.x);
client::config["window"]["size"]["y"] = (size.y = resolution.y);
}
size.x = client::config["window"]["size"]["x"].asUInt();
size.y = client::config["window"]["size"]["y"].asUInt();
}
// Window title
uf::String title; {
title = client::config["window"]["title"].as<std::string>();
title = client::config["window"]["title"].asString();
}
// Terminal window;
spec::terminal.setVisible( client::config["window"]["terminal"]["visible"].as<bool>() );
spec::terminal.setVisible( client::config["terminal"]["visible"].asBool() );
// Ncurses
uf::IoStream::ncurses = client::config["window"]["terminal"]["ncurses"].as<bool>();
uf::IoStream::ncurses = client::config["terminal"]["ncurses"].asBool();
// Window's context settings
uf::renderer::settings::width = size.x;
uf::renderer::settings::height = size.y;
client::window.create( size, title );
// Set refresh rate
ext::config["window"]["refresh rate"] = client::window.getRefreshRate();
spec::Context::Settings settings; {
settings.depthBits = client::config["context"]["depthBits"].asUInt();
settings.stencilBits = client::config["context"]["stencilBits"].asUInt();
settings.bitsPerPixel = client::config["context"]["bitsPerPixel"].asUInt();
settings.antialiasingLevel = client::config["context"]["antialiasingLevel"].asUInt();
settings.majorVersion = client::config["context"]["majorVersion"].asUInt();
settings.minorVersion = client::config["context"]["minorVersion"].asUInt();
}
ext::vulkan::width = size.x;
ext::vulkan::height = size.y;
client::window.create( size, title, settings );
// Miscellaneous
client::window.setVisible(client::config["window"]["visible"].as<bool>());
client::window.setCursorVisible(client::config["window"]["cursor"]["visible"].as<bool>());
client::window.setKeyRepeatEnabled(client::config["window"]["keyboard"]["repeat"].as<bool>());
client::window.setVisible(client::config["window"]["visible"].asBool());
client::window.setCursorVisible(client::config["cursor"]["visible"].asBool());
client::window.setKeyRepeatEnabled(client::config["keyboard"]["repeat"].asBool());
// client::window.centerWindow();
// client::window.setPosition({0, 0});
// client::window.setMouseGrabbed(true);
/* Set Icon */ if ( client::config["window"]["icon"].is<std::string>() ) {
/* Set Icon */ {
uf::Image icon;
icon.open(client::config["window"]["icon"].as<std::string>());
icon.open(client::config["window"]["icon"].asString());
client::window.setIcon({(int) icon.getDimensions().x, (int) icon.getDimensions().y}, ((uint8_t*)icon.getPixelsPtr()));
}
client::window.setTitle(title); {
@ -83,15 +103,26 @@ void client::initialize() {
json["window"]["title"] = std::string(title);
uf::hooks.call( hook, json );
}
/*
uf::hooks.shouldPreferReadable();
if ( client::config["engine"]["hook"]["mode"] == "Readable" ) {
if ( client::config["hook"]["mode"] == "Readable" ) {}
}
/* Initialize OpenGL */ {
/*
if ( !ext::gl.initialize() ) {
std::cerr << "[ERROR] GL failed to initialize!" << std::endl;
std::exit(EXIT_SUCCESS);
return;
}
pod::Vector4f ambient;
ambient.x = client::config["light"]["ambient"]["r"].asDouble();
ambient.y = client::config["light"]["ambient"]["g"].asDouble();
ambient.z = client::config["light"]["ambient"]["b"].asDouble();
ambient.w = client::config["light"]["ambient"]["a"].asDouble();
glClearColor(ambient.x, ambient.y, ambient.z, ambient.w);
*/
}
#if UF_USE_OPENAL
/* Initialize OpenAL */ {
if ( !ext::oal.initialize() ) {
std::cerr << "[ERROR] AL failed to initialize!" << std::endl;
@ -99,52 +130,57 @@ void client::initialize() {
return;
}
}
#endif
/* Initialize hooks */ {
// if ( client::config["engine"]["hook"]["mode"] == "Both" || client::config["engine"]["hook"]["mode"] == "Readable" ) {
uf::hooks.addHook( "window:Mouse.CursorVisibility", [&](const ext::json::Value& json){
client::window.setCursorVisible(json["state"].as<bool>());
client::window.setMouseGrabbed(!json["state"].as<bool>());
client::config["mouse"]["visible"] = json["state"].as<bool>();
client::config["window"]["mouse"]["center"] = !json["state"].as<bool>();
if ( client::config["hook"]["mode"] == "Both" || client::config["hook"]["mode"] == "Readable" ) {
uf::hooks.addHook( "window:Mouse.CursorVisibility", [&](const std::string& event)->std::string{
uf::Serializer json = event;
client::window.setCursorVisible(json["state"].asBool());
client::window.setMouseGrabbed(!json["state"].asBool());
client::config["mouse"]["visible"] = json["state"].asBool();
return "true";
});
uf::hooks.addHook( "window:Mouse.Lock", [&](const ext::json::Value& json){
uf::hooks.addHook( "window:Mouse.Lock", [&](const std::string& event)->std::string{
if ( client::window.hasFocus() ) {
client::window.setMousePosition(client::window.getSize()/2);
}
return "true";
});
uf::hooks.addHook( "window:Closed", [&](const ext::json::Value& json){
uf::hooks.addHook( "window:Closed", [&](const std::string& event)->std::string{
client::ready = false;
// std::exit(EXIT_SUCCESS);
return "true";
} );
uf::hooks.addHook( "window:Title.Changed", [&](const ext::json::Value& json){
uf::hooks.addHook( "window:Title.Changed", [&](const std::string& event)->std::string{
uf::Serializer json = event;
if ( json["invoker"] != "os" ) {
if ( !ext::json::isObject( json["window"] ) ) return;
uf::String title = json["window"]["title"].as<std::string>();
if ( !json["window"].isObject() ) return "false";
uf::String title = json["window"]["title"].asString();
client::window.setTitle(title);
}
return "true";
} );
uf::hooks.addHook( "window:Resized", [&](const ext::json::Value& json){
uf::hooks.addHook( "window:Resized", [&](const std::string& event)->std::string{
uf::Serializer json = event;
pod::Vector2i size; {
size.x = json["window"]["size"]["x"].as<size_t>();
size.y = json["window"]["size"]["y"].as<size_t>();
size.x = json["window"]["size"]["x"].asUInt64();
size.y = json["window"]["size"]["y"].asUInt64();
}
if ( json["invoker"] != "os" ) {
client::window.setSize(size);
}
// Update viewport
if ( !ext::json::isArray( client::config["engine"]["ext"]["vulkan"]["framebuffer"]["size"] ) ) {
float scale = client::config["engine"]["ext"]["vulkan"]["framebuffer"]["size"].is<double>() ? client::config["engine"]["ext"]["vulkan"]["framebuffer"]["size"].as<float>() : 1;
uf::renderer::settings::width = size.x * scale;
uf::renderer::settings::height = size.y * scale;
}
// glViewport( 0, 0, size.x, size.y );
// client::window.centerWindow();
uf::renderer::states::resized = true;
ext::vulkan::width = size.x;
ext::vulkan::height = size.y;
ext::vulkan::swapchain.rebuild = true;
return "true";
} );
/*
}
else if ( client::config["engine"]["hook"]["mode"] == "Both" || client::config["engine"]["hook"]["mode"] == "Optimal" ) {
} else if ( client::config["hook"]["mode"] == "Both" || client::config["hook"]["mode"] == "Optimal" ) {
uf::hooks.addHook( "window:Closed", [&](const uf::OptimalHook::argument_t& userdata)->uf::OptimalHook::return_t{
client::ready = false;
std::exit(EXIT_SUCCESS);
@ -182,13 +218,12 @@ void client::initialize() {
client::window.setSize(hook.window.size);
}
// Update viewport
// glViewport( 0, 0, hook.window.size.x, hook.window.size.y );
return NULL;
} );
}
*/
}
if ( client::config["window"]["mode"].as<std::string>() == "fullscreen" ) client::window.switchToFullscreen();
if ( client::config["window"]["mode"].as<std::string>() == "borderless" ) client::window.switchToFullscreen( true );
if ( client::config["window"]["fullscreen"].asBool() ) client::window.switchToFullscreen();
client::ready = true;
}
void client::tick() {
@ -196,11 +231,11 @@ void client::tick() {
client::window.pollEvents();
// call mouse move
// query lock
if ( client::window.hasFocus() && client::config["window"]["mouse"]["center"].as<bool>() ) {
if ( client::window.hasFocus() && !client::config["mouse"]["visible"].asBool() ) {
auto previous = client::window.getMousePosition();
client::window.setMousePosition(client::window.getSize()/2);
auto current = client::window.getMousePosition();
// std::cout << "Delta: (" << current.x - previous.x << ", " << current.y - previous.y << ")" << std::endl;
auto size = client::window.getSize();
uf::Serializer payload;
payload["invoker"] = "client";
@ -245,18 +280,22 @@ void client::render() {
client::window.display();
}
#include <uf/utils/thread/thread.h>
void client::terminate() {
/* Close Threads */ {
uf::thread::terminate();
}
client::window.terminate();
/* Close vulkan */ {
ext::vulkan::destroy();
}
client::window.terminate();
// spec::Context::globalCleanup();
#if UF_USE_BULLET
if ( !ext::oal.terminate() ) {
std::cerr << "[ERROR] AL failed to terminate!" << std::endl;
std::exit(EXIT_SUCCESS);
return;
}
#endif
}

View File

@ -1,8 +0,0 @@
/*
#include <iostream>
int main(int argc, char** argv){
std::cout << "nggge" << std::endl;
return 0;
}
*/

View File

@ -3,17 +3,12 @@
#include <uf/utils/io/iostream.h>
#include <uf/utils/time/time.h>
#include <uf/utils/mempool/mempool.h>
#include <uf/utils/math/quaternion.h>
// #include <uf/utils/math/glm.h>
#define HANDLE_EXCEPTIONS 0
#include <uf/engine/entity/entity.h>
int main(int argc, char** argv){
for ( size_t i = 0; i < argc; ++i ) {
char* c_str = argv[i];
std::string string(argv[i]);
ext::arguments.emplace_back(string);
}
std::atexit([]{
uf::iostream << "Termination via std::atexit()!" << "\n";
client::terminated = !(client::ready = ext::ready = false);
@ -34,42 +29,34 @@ int main(int argc, char** argv){
}
}
while ( client::ready && ext::ready ) {
#if HANDLE_EXCEPTIONS
try {
#endif
client::tick();
ext::tick();
static bool first = false; if ( !first ) { first = true;
uf::Serializer json;
std::string hook = "window:Resized";
json["type"] = hook;
json["invoker"] = "ext";
json["window"]["size"]["x"] = client::config["window"]["size"]["x"];
json["window"]["size"]["y"] = client::config["window"]["size"]["y"];
uf::hooks.call(hook, json);
}
client::tick();
ext::tick();
client::render();
ext::render();
#if HANDLE_EXCEPTIONS
} catch ( std::runtime_error& e ) {
uf::iostream << "RUNTIME ERROR: " << e.what() << "\n";
break;
} catch ( std::exception& e ) {
uf::iostream << "EXCEPTION ERROR: " << e.what() << "\n";
uf::iostream << "ERROR: " << e.what() << "\n";
throw e;
} catch ( bool handled ) {
if (!handled) uf::iostream << "UNHANDLED ERROR: " << "???" << "\n";
if (!handled) uf::iostream << "ERROR: " << "???" << "\n";
} catch ( ... ) {
uf::iostream << "UNKNOWN ERROR: " << "???" << "\n";
uf::iostream << "ERROR: " << "???" << "\n";
}
#endif
client::render();
ext::render();
}
if ( !client::terminated ) {
uf::iostream << "Natural termination!" << "\n";
ext::terminate();
client::terminate();
}
ext::terminate();
client::terminate();
return 0;
}

View File

@ -1,8 +1,6 @@
#!/bin/bash
cd bin
PREFIX=$(cat ./exe/default.config)
cp ./exe/lib/win64/*.dll .
cp ./exe/lib/win64/$PREFIX/*.dll .
gdb ./exe/program.$PREFIX.exe
cp lib/win64/*.dll .
gdb program.exe
rm *.dll

View File

@ -1,92 +0,0 @@
/*---------------------------------------------------------------------------*/
/* */
/* ActiveSocket.h - Active Socket Decleration */
/* */
/* Author : Mark Carrier (mark@carrierlabs.com) */
/* */
/*---------------------------------------------------------------------------*/
/* Copyright (c) 2007-2009 CarrierLabs, LLC. 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.
*
* 4. The name "CarrierLabs" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* mark@carrierlabs.com.
*
* THIS SOFTWARE IS PROVIDED BY MARK CARRIER ``AS IS'' AND ANY
* EXPRESSED 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 MARK CARRIER OR
* ITS CONTRIBUTORS 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.
*----------------------------------------------------------------------------*/
#ifndef __ACTIVESOCKET_H__
#define __ACTIVESOCKET_H__
#include "SimpleSocket.h"
class CPassiveSocket;
/// Provides a platform independent class to create an active socket.
/// An active socket is used to create a socket which connects to a server.
/// This type of object would be used when an application needs to send/receive
/// data from a server.
class CActiveSocket : public CSimpleSocket
{
public:
friend class CPassiveSocket;
CActiveSocket(CSocketType type = SocketTypeTcp);
virtual ~CActiveSocket()
{
Close();
};
/// Established a connection to the address specified by pAddr.
/// Connection-based protocol sockets (CSocket::SocketTypeTcp) may
/// successfully call Open() only once, however; connectionless protocol
/// sockets (CSocket::SocketTypeUdp) may use Open() multiple times to
/// change their association.
/// @param pAddr specifies the destination address to connect.
/// @param nPort specifies the destination port.
/// @return true if successful connection made, otherwise false.
virtual bool Open(const char *pAddr, uint16 nPort);
private:
/// Utility function used to create a TCP connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectTCP(const char *pAddr, uint16 nPort);
/// Utility function used to create a UDP connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectUDP(const char *pAddr, uint16 nPort);
/// Utility function used to create a RAW connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectRAW(const char *pAddr, uint16 nPort);
private:
struct hostent *m_pHE;
};
#endif /* __ACTIVESOCKET_H__ */

View File

@ -1,182 +0,0 @@
///
/// @file App.h
///
/// @brief The header for the App class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Defines.h"
#include <Ultralight/RefPtr.h>
#include <Ultralight/Renderer.h>
#include <Ultralight/platform/Config.h>
namespace ultralight {
class Monitor;
class Window;
///
/// Interface for all App-related events. @see App::set_listener
///
class AExport AppListener {
public:
virtual ~AppListener() {}
///
/// Called whenever the App updates. You should update all app logic here.
///
/// @note This event is fired right before the run loop calls
/// Renderer::Update and Renderer::Render.
///
virtual void OnUpdate() {}
};
///
/// App-specific settings.
///
struct AExport Settings {
///
/// The name of the developer of this app.
///
/// This is used to generate a unique path to store local application data
/// on the user's machine.
///
String developer_name = "MyCompany";
///
/// The name of this app.
///
/// This is used to generate a unique path to store local application data
/// on the user's machine.
///
String app_name = "MyApp";
///
/// The root file path for our file system. You should set this to the
/// relative path where all of your app data is.
///
/// This will be used to resolve all file URLs, eg file:///page.html
///
/// @note This relative path is resolved using the following logic:
/// - Windows: relative to the executable path
/// - Linux: relative to the executable path
/// - macOS: relative to YourApp.app/Contents/Resources/
///
String file_system_path = "./assets/";
///
/// Whether or not we should load and compile shaders from the file system
/// (eg, from the /shaders/ path, relative to file_system_path).
///
/// If this is false (the default), we will instead load pre-compiled shaders
/// from memory which speeds up application startup time.
///
bool load_shaders_from_file_system = false;
///
/// We try to use the GPU renderer when a compatible GPU is detected.
///
/// Set this to true to force the engine to always use the CPU renderer.
///
bool force_cpu_renderer = false;
};
///
/// Main application class.
///
class AExport App : public RefCounted {
public:
///
/// Create the App singleton.
///
/// @param settings Settings to customize App runtime behavior.
///
/// @param config Config options for the Ultralight renderer.
///
/// @return Returns a ref-pointer to the created App instance.
///
/// @note You should only create one of these per application lifetime.
///
/// @note Certain Config options may be overridden during App creation,
/// most commonly Config::face_winding and Config::device_scale_hint.
///
static Ref<App> Create(Settings settings = Settings(), Config config = Config());
///
/// Get the App singleton.
///
static App* instance();
///
/// Get the settings this App was created with.
///
virtual const Settings& settings() const = 0;
///
/// Set the main window. You must set this before calling Run.
///
/// @param window The window to use for all rendering.
///
/// @note We currently only support one Window per App, this will change
/// later once we add support for multiple driver instances.
///
virtual void set_window(Ref<Window> window) = 0;
///
/// Get the main window.
///
virtual RefPtr<Window> window() = 0;
///
/// Set an AppListener to receive callbacks for app-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_listener(AppListener* listener) = 0;
///
/// Get the AppListener, if any.
///
virtual AppListener* listener() = 0;
///
/// Whether or not the App is running.
///
virtual bool is_running() const = 0;
///
/// Get the main monitor (this is never NULL).
///
/// @note We'll add monitor enumeration later.
///
virtual Monitor* main_monitor() = 0;
///
/// Get the underlying Renderer instance.
///
virtual Ref<Renderer> renderer() = 0;
///
/// Run the main loop.
///
/// @note Make sure to call set_window before calling this.
///
virtual void Run() = 0;
///
/// Quit the application.
///
virtual void Quit() = 0;
protected:
virtual ~App();
};
} // namespace ultralight

View File

@ -1,6 +0,0 @@
#include <AppCore/App.h>
#include <AppCore/Monitor.h>
#include <AppCore/Window.h>
#include <AppCore/Overlay.h>
#include <AppCore/JSHelpers.h>
#include <AppCore/Platform.h>

View File

@ -1,448 +0,0 @@
///
/// @file CAPI.h
///
/// @brief The C-language API for AppCore
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#ifndef APPCORE_CAPI_H
#define APPCORE_CAPI_H
#include <Ultralight/CAPI.h>
#if defined(__WIN32__) || defined(_WIN32)
# if defined(APPCORE_IMPLEMENTATION)
# define ACExport __declspec(dllexport)
# else
# define ACExport __declspec(dllimport)
# endif
#else
# define ACExport __attribute__((visibility("default")))
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct C_Settings* ULSettings;
typedef struct C_App* ULApp;
typedef struct C_Window* ULWindow;
typedef struct C_Monitor* ULMonitor;
typedef struct C_Overlay* ULOverlay;
///
/// Window creation flags. @see Window::Create
///
typedef enum {
kWindowFlags_Borderless = 1 << 0,
kWindowFlags_Titled = 1 << 1,
kWindowFlags_Resizable = 1 << 2,
kWindowFlags_Maximizable = 1 << 3,
} ULWindowFlags;
///
/// Create settings with default values (see <AppCore/App.h>).
///
ACExport ULSettings ulCreateSettings();
///
/// Destroy settings.
///
ACExport void ulDestroySettings(ULSettings settings);
///
/// Set the name of the developer of this app.
///
/// This is used to generate a unique path to store local application data
/// on the user's machine.
///
/// Default is "MyCompany"
///
ACExport void ulSettingsSetDeveloperName(ULSettings settings, ULString name);
///
/// Set the name of this app.
///
/// This is used to generate a unique path to store local application data
/// on the user's machine.
///
/// Default is "MyApp"
///
ACExport void ulSettingsSetAppName(ULSettings settings, ULString name);
///
/// Set the root file path for our file system, you should set this to the
/// relative path where all of your app data is.
///
/// This will be used to resolve all file URLs, eg file:///page.html
///
/// @note The default path is "./assets/"
///
/// This relative path is resolved using the following logic:
/// - Windows: relative to the executable path
/// - Linux: relative to the executable path
/// - macOS: relative to YourApp.app/Contents/Resources/
///
ACExport void ulSettingsSetFileSystemPath(ULSettings settings, ULString path);
///
/// Set whether or not we should load and compile shaders from the file system
/// (eg, from the /shaders/ path, relative to file_system_path).
///
/// If this is false (the default), we will instead load pre-compiled shaders
/// from memory which speeds up application startup time.
///
ACExport void ulSettingsSetLoadShadersFromFileSystem(ULSettings settings,
bool enabled);
///
/// We try to use the GPU renderer when a compatible GPU is detected.
///
/// Set this to true to force the engine to always use the CPU renderer.
///
ACExport void ulSettingsSetForceCPURenderer(ULSettings settings,
bool force_cpu);
///
/// Create the App singleton.
///
/// @param settings Settings to customize App runtime behavior. You can pass
/// NULL for this parameter to use default settings.
///
/// @param config Config options for the Ultralight renderer. You can pass
/// NULL for this parameter to use default config.
///
/// @note You should only create one of these per application lifetime.
///
/// @note Certain Config options may be overridden during App creation,
/// most commonly Config::face_winding and Config::device_scale_hint.
///
ACExport ULApp ulCreateApp(ULSettings settings, ULConfig config);
///
/// Destroy the App instance.
///
ACExport void ulDestroyApp(ULApp app);
///
/// Set the main window, you must set this before calling ulAppRun.
///
/// @param window The window to use for all rendering.
///
/// @note We currently only support one Window per App, this will change
/// later once we add support for multiple driver instances.
///
ACExport void ulAppSetWindow(ULApp app, ULWindow window);
///
/// Get the main window.
///
ACExport ULWindow ulAppGetWindow(ULApp app);
typedef void
(*ULUpdateCallback) (void* user_data);
///
/// Set a callback for whenever the App updates. You should update all app
/// logic here.
///
/// @note This event is fired right before the run loop calls
/// Renderer::Update and Renderer::Render.
///
ACExport void ulAppSetUpdateCallback(ULApp app, ULUpdateCallback callback,
void* user_data);
///
/// Whether or not the App is running.
///
ACExport bool ulAppIsRunning(ULApp app);
///
/// Get the main monitor (this is never NULL).
///
/// @note We'll add monitor enumeration later.
///
ACExport ULMonitor ulAppGetMainMonitor(ULApp app);
///
/// Get the underlying Renderer instance.
///
ACExport ULRenderer ulAppGetRenderer(ULApp app);
///
/// Run the main loop, make sure to call ulAppSetWindow before calling this.
///
ACExport void ulAppRun(ULApp app);
///
/// Quit the application.
///
ACExport void ulAppQuit(ULApp app);
///
/// Get the monitor's DPI scale (1.0 = 100%).
///
ACExport double ulMonitorGetScale(ULMonitor monitor);
///
/// Get the width of the monitor (in pixels).
///
ACExport unsigned int ulMonitorGetWidth(ULMonitor monitor);
///
/// Get the height of the monitor (in pixels).
///
ACExport unsigned int ulMonitorGetHeight(ULMonitor monitor);
///
/// Create a new Window.
///
/// @param monitor The monitor to create the Window on.
///
/// @param width The width (in device coordinates).
///
/// @param height The height (in device coordinates).
///
/// @param fullscreen Whether or not the window is fullscreen.
///
/// @param window_flags Various window flags.
///
ACExport ULWindow ulCreateWindow(ULMonitor monitor, unsigned int width,
unsigned int height, bool fullscreen,
unsigned int window_flags);
///
/// Destroy a Window.
///
ACExport void ulDestroyWindow(ULWindow window);
typedef void
(*ULCloseCallback) (void* user_data);
///
/// Set a callback to be notified when a window closes.
///
ACExport void ulWindowSetCloseCallback(ULWindow window,
ULCloseCallback callback,
void* user_data);
typedef void
(*ULResizeCallback) (void* user_data, unsigned int width, unsigned int height);
///
/// Set a callback to be notified when a window resizes
/// (parameters are passed back in pixels).
///
ACExport void ulWindowSetResizeCallback(ULWindow window,
ULResizeCallback callback,
void* user_data);
///
/// Get window width (in pixels).
///
ACExport unsigned int ulWindowGetWidth(ULWindow window);
///
/// Get window height (in pixels).
///
ACExport unsigned int ulWindowGetHeight(ULWindow window);
///
/// Get whether or not a window is fullscreen.
///
ACExport bool ulWindowIsFullscreen(ULWindow window);
///
/// Get the DPI scale of a window.
///
ACExport double ulWindowGetScale(ULWindow window);
///
/// Set the window title.
///
ACExport void ulWindowSetTitle(ULWindow window, const char* title);
///
/// Set the cursor for a window.
///
ACExport void ulWindowSetCursor(ULWindow window, ULCursor cursor);
///
/// Close a window.
///
ACExport void ulWindowClose(ULWindow window);
///
/// Convert device coordinates to pixels using the current DPI scale.
///
ACExport int ulWindowDeviceToPixel(ULWindow window, int val);
///
/// Convert pixels to device coordinates using the current DPI scale.
///
ACExport int ulWindowPixelsToDevice(ULWindow window, int val);
///
/// Get the underlying native window handle.
///
/// @note This is: - HWND on Windows
/// - NSWindow* on macOS
/// - GLFWwindow* on Linux
///
ACExport void* ulWindowGetNativeHandle(ULWindow window);
///
/// Create a new Overlay.
///
/// @param window The window to create the Overlay in. (we currently only
/// support one window per application)
///
/// @param width The width in device coordinates.
///
/// @param height The height in device coordinates.
///
/// @param x The x-position (offset from the left of the Window), in
/// pixels.
///
/// @param y The y-position (offset from the top of the Window), in
/// pixels.
///
/// @note Each Overlay is essentially a View and an on-screen quad. You should
/// create the Overlay then load content into the underlying View.
///
ACExport ULOverlay ulCreateOverlay(ULWindow window, unsigned int width,
unsigned int height, int x, int y);
///
/// Create a new Overlay, wrapping an existing View.
///
/// @param window The window to create the Overlay in. (we currently only
/// support one window per application)
///
/// @param view The View to wrap (will use its width and height).
///
/// @param x The x-position (offset from the left of the Window), in
/// pixels.
///
/// @param y The y-position (offset from the top of the Window), in
/// pixels.
///
/// @note Each Overlay is essentially a View and an on-screen quad. You should
/// create the Overlay then load content into the underlying View.
///
ACExport ULOverlay ulCreateOverlayWithView(ULWindow window, ULView view,
int x, int y);
///
/// Destroy an overlay.
///
ACExport void ulDestroyOverlay(ULOverlay overlay);
///
/// Get the underlying View.
///
ACExport ULView ulOverlayGetView(ULOverlay overlay);
///
/// Get the width (in pixels).
///
ACExport unsigned int ulOverlayGetWidth(ULOverlay overlay);
///
/// Get the height (in pixels).
///
ACExport unsigned int ulOverlayGetHeight(ULOverlay overlay);
///
/// Get the x-position (offset from the left of the Window), in pixels.
///
ACExport int ulOverlayGetX(ULOverlay overlay);
///
/// Get the y-position (offset from the top of the Window), in pixels.
///
ACExport int ulOverlayGetY(ULOverlay overlay);
///
/// Move the overlay to a new position (in pixels).
///
ACExport void ulOverlayMoveTo(ULOverlay overlay, int x, int y);
///
/// Resize the overlay (and underlying View), dimensions should be
/// specified in pixels.
///
ACExport void ulOverlayResize(ULOverlay overlay, unsigned int width,
unsigned int height);
///
/// Whether or not the overlay is hidden (not drawn).
///
ACExport bool ulOverlayIsHidden(ULOverlay overlay);
///
/// Hide the overlay (will no longer be drawn).
///
ACExport void ulOverlayHide(ULOverlay overlay);
///
/// Show the overlay.
///
ACExport void ulOverlayShow(ULOverlay overlay);
///
/// Whether or not an overlay has keyboard focus.
///
ACExport bool ulOverlayHasFocus(ULOverlay overlay);
///
/// Grant this overlay exclusive keyboard focus.
///
ACExport void ulOverlayFocus(ULOverlay overlay);
///
/// Remove keyboard focus.
///
ACExport void ulOverlayUnfocus(ULOverlay overlay);
/******************************************************************************
* Platform
*****************************************************************************/
///
/// This is only needed if you are not calling ulCreateApp().
///
/// Initializes the platform font loader and sets it as the current FontLoader.
///
ACExport void ulEnablePlatformFontLoader();
///
/// This is only needed if you are not calling ulCreateApp().
///
/// Initializes the platform file system (needed for loading file:/// URLs) and
/// sets it as the current FileSystem.
///
/// You can specify a base directory path to resolve relative paths against.
///
ACExport void ulEnablePlatformFileSystem(ULString base_dir);
///
/// This is only needed if you are not calling ulCreateApp().
///
/// Initializes the default logger (writes the log to a file).
///
/// You should specify a writable log path to write the log to
/// for example "./ultralight.log".
///
ACExport void ulEnableDefaultLogger(ULString log_path);
#ifdef __cplusplus
}
#endif
#endif // APPCORE_CAPI_H

View File

@ -1,42 +0,0 @@
// Copyright 2018 Ultralight, Inc. All rights reserved.
#pragma once
// Needed for limit defines, like INTMAX_MAX, which is used by the std C++ library
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstdint>
#include <cstddef>
#include <limits.h>
#ifdef SWIG
#define AExport
#else
// Require C++11 Support
#if defined(_MSC_VER)
# if _MSC_VER < 1800
# error This project needs at least Visual Studio 2013 to build
# endif
#elif __cplusplus <= 199711L
# error This project can only be compiled with a compiler that supports C++11
#endif
#if defined(__WIN32__) || defined(_WIN32)
# if defined(APPCORE_IMPLEMENTATION)
# define AExport __declspec(dllexport)
# else
# define AExport __declspec(dllimport)
# endif
#define _thread_local __declspec(thread)
#ifndef _NATIVE_WCHAR_T_DEFINED
#define DISABLE_NATIVE_WCHAR_T
#endif
#else
# define AExport __attribute__((visibility("default")))
#define _thread_local __thread
#endif
#endif

View File

@ -1,554 +0,0 @@
#pragma once
#include <AppCore/Defines.h>
#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/JSStringRef.h>
#include <Ultralight/String.h>
#include <functional>
#include <memory>
namespace ultralight {
///
/// Set the current JSContext.
///
/// Most JavaScriptCore C API calls require an active JavaScript execution
/// context (JSContextRef). You can get the JSContextRef for a page via
/// `View::LockJSContext()`. This context changes with each page navigation.
///
/// **Note**:
/// You MUST set a JSContext before using most of the C++ API below.
///
void AExport SetJSContext(JSContextRef ctx);
///
/// Get the current JSContext.
///
JSContextRef AExport GetJSContext();
///
/// JavaScript String wrapper that automatically manages JSStringRef lifetime
/// and provides helpful conversions.
///
class AExport JSString {
public:
/// Create empty string
JSString();
/// Create from C-string
JSString(const char* str);
/// Create from Ultralight String
JSString(const String& str);
/// Take ownership of existing JSStringRef (will not increase ref-count)
JSString(JSStringRef str);
/// Copy constructor (will increase ref-count)
JSString(const JSString& other);
/// Destructor
~JSString();
/// Assignment operator (will increase ref-count)
JSString& operator=(const JSString& other);
/// Cast to String
operator String();
/// Cast to underlying JSStringRef
operator JSStringRef() const { return instance_; }
protected:
JSStringRef instance_;
};
class JSArray;
class JSObject;
class JSFunction;
/// Tag type used with the JSValue constructor to create "Null" types
struct AExport JSValueNullTag {};
/// Tag type used with the JSValue constructor to create "Undefined" types
struct AExport JSValueUndefinedTag {};
///
/// JavaScript variant value wrapper that automatically manages JSValueRef
/// lifetime and provides helpful conversions.
///
class AExport JSValue {
public:
/// Create null (empty) JSValue
JSValue();
/// Create null JSValue explicitly
JSValue(JSValueNullTag);
/// Create undefined JSValue
JSValue(JSValueUndefinedTag);
/// Create boolean JSValue
JSValue(bool val);
/// Create unsigned integer JSValue (aka, Number) [will be cast to double]
JSValue(uint32_t val);
/// Create integer JSValue (aka, Number) [will be cast to double]
JSValue(int32_t val);
/// Create unsigned integer JSValue (aka, Number) [will be cast to double]
JSValue(uint64_t val);
/// Create integer JSValue (aka, Number) [will be cast to double]
JSValue(int64_t val);
/// Create double JSValue (aka, Number)
JSValue(double val);
/// Create string JSValue
JSValue(const char* val);
/// Create string JSValue
JSValue(const String& val);
/// Create string JSValue
JSValue(JSString val);
/// Create from existing JSValueRef
JSValue(JSValueRef val);
/// Create object JSValue
JSValue(JSObjectRef obj);
/// Copy constructor, a shallow copy is made, the constructed JSValue will
/// point to the same JSValueRef.
JSValue(const JSValue& other);
/// Destructor
virtual ~JSValue();
/// A shallow copy is made, this JSValue will point to the same JSValueRef
virtual JSValue& operator=(const JSValue& other);
/// Whether or not the value is a JavaScript Null type.
bool IsNull() const;
/// Whether or not the value is a JavaScript Undefined type.
bool IsUndefined() const;
/// Whether or not the value is a JavaScript Boolean type.
bool IsBoolean() const;
/// Whether or not the value is a JavaScript Number type.
bool IsNumber() const;
/// Whether or not the value is a JavaScript String type.
bool IsString() const;
/// Whether or not the value is a JavaScript Object type.
bool IsObject() const;
/// Whether or not the value is a JavaScript Array type.
bool IsArray() const;
/// Whether or not the value is a JavaScript Function type.
bool IsFunction() const;
/// Get the value as a Boolean
bool ToBoolean() const;
/// Get the value as a Number (Double)
double ToNumber() const;
/// Get the value as a Number (Integer)
int64_t ToInteger() const { return static_cast<int64_t>(ToNumber()); }
/// Get the value as a String
JSString ToString() const;
/// Get the value as an Object (will debug assert if not an Object)
JSObject ToObject() const;
/// Get the value as an Array (will debug asset if not an Array)
JSArray ToArray() const;
/// Get the value as a Function (will debug asset if not a Function)
JSFunction ToFunction() const;
operator bool() const { return ToBoolean(); }
operator double() const { return ToNumber(); }
operator uint32_t() const { return static_cast<uint32_t>(ToNumber()); }
operator int32_t() const { return static_cast<uint32_t>(ToNumber()); }
operator uint64_t() const { return static_cast<uint64_t>(ToNumber()); }
operator int64_t() const { return ToInteger(); }
operator String() const { return ToString(); }
operator JSString() const { return ToString(); }
operator JSObject() const;
operator JSObjectRef() const;
operator JSArray() const;
operator JSFunction() const;
/// Get the underlying JSValueRef
operator JSValueRef() const { return instance(); }
///
/// Get the bound context for this JSValue (it is cached at creation).
///
JSContextRef context() const { return ctx_; }
///
/// Set the JSContext for this JSValue.
///
/// **Note**:
/// JSValues created from within a JSCallback have a temporary JSContext
/// that is destroyed when the callback returns. You will need to "move"
/// any JSValues created within these callbacks to the View's main context
/// (call set_context() with the main context) before using them outside
/// the callback.
///
void set_context(JSContextRef context) { ctx_ = context; }
protected:
JSValue(JSContextRef ctx);
JSValue(JSContextRef ctx, JSValueRef val);
virtual JSValueRef instance() const;
JSContextRef ctx_;
JSValueRef instance_ = nullptr;
friend class JSFunction;
};
///
/// A vector of JSValues, used for passing around arguments in JSCallback.
///
class AExport JSArgs {
public:
/// Create an empty list of JavaScript arguments
JSArgs();
/// Create a list of JavaScript arguments using a C++ initializer list
JSArgs(const std::initializer_list<JSValue>& values);
/// Copy-constructor
JSArgs(const JSArgs& other);
/// Destructor
~JSArgs();
/// Assignment operator
JSArgs& operator=(const JSArgs& other);
///
/// Access an element of the argument list by index.
///
/// **Note**:
/// All JSValues are actually wrappers of JSValueRef instances so even
/// though this function doesn't return a JSValue& you are still operating
/// directly on the underlying JavaScript value instance.
///
JSValue operator[](size_t pos);
///
/// Access an element of the argument list by index. (const overload)
///
/// **Note**:
/// All JSValues are actually wrappers of JSValueRef instances so even
/// though this function doesn't return a JSValue& you are still operating
/// directly on the underlying JavaScript value instance.
///
const JSValue operator[](size_t pos) const;
/// Whether or not the argument list is empty.
bool empty() const;
/// The number of elements in the argument list.
size_t size() const;
/// Clear the argument list.
void clear();
/// Add a new argument to the end of the list.
void push_back(const JSValue& val);
/// Remove the last item from the end of the list.
void pop_back();
/// Get the argument list as a C-array of JSValues
JSValue* data();
/// Get the argument list as a C-array of JSValues (const overload)
const JSValue* data() const;
protected:
void* instance_;
};
///
/// JSCallback typedef used for binding C++ callbacks to JavaScript functions.
///
/// Takes two arguments (const JSObject& thisObj, const JSArgs& args) and
/// returns nothing (void).
///
typedef std::function<void(const JSObject&, const JSArgs&)> JSCallback;
///
/// JSCallbackWithRetval typedef used for binding C++ callbacks to JavaScript
/// functions with an optional return value.
///
/// Takes two arguments (const JSObject& thisObj, const JSArgs& args) and
/// returns a JSValue back to JavaScript.
///
typedef std::function<JSValue(const JSObject&, const JSArgs&)> JSCallbackWithRetval;
///
/// Macro to help bind C++ member functions to a JSCallback
///
/// Usage: JSCallback callback = BindJSCallback(&MyClass::MyMemberFunction);
///
/// **Note**: Expected to run from within an instance of 'MyClass', note the
/// 'this' keyword in the macro.
///
#define BindJSCallback(fn) (JSCallback)std::bind(fn, this, std::placeholders::_1, std::placeholders::_2)
///
/// Macro to help bind C++ member functions to a JSCallbackWithRetval
///
/// Usage: JSCallback callback = BindJSCallback(&MyClass::MyMemberFunction);
///
/// **Note**: Expected to run from within an instance of 'MyClass', note the
/// 'this' keyword in the macro.
///
#define BindJSCallbackWithRetval(fn) (JSCallbackWithRetval)std::bind(fn, this, std::placeholders::_1, std::placeholders::_2)
///
/// Wrapper for JSObject property value (JSValue subclass). Allows new value assignment
/// to object property, binding C++ callbacks to object properties via function objects,
/// as well as value query via the JSValue interface.
///
class AExport JSPropertyValue : public JSValue {
public:
virtual ~JSPropertyValue();
/// Assign a new value to the property (internally calls JSObjectSetProperty)
virtual JSPropertyValue& operator=(const JSValue& value);
/// Bind to native C++ callback (creates a Function object that can be called from JS)
JSPropertyValue& operator=(const JSCallback& callback);
/// Bind to native C++ callback with return value (creates a Function object that can be called from JS)
JSPropertyValue& operator=(const JSCallbackWithRetval& callback);
protected:
virtual JSValueRef instance() const;
JSPropertyValue(JSContextRef ctx, JSObjectRef proxy_obj, unsigned idx);
JSPropertyValue(JSContextRef ctx, JSObjectRef proxy_obj, JSString idx);
JSPropertyValue(const JSPropertyValue&) = default;
JSPropertyValue& operator=(const JSPropertyValue&) = delete;
JSObject* proxyObj_;
bool using_numeric_idx_;
unsigned numeric_idx_;
JSString string_idx_;
friend class JSArray;
friend class JSObject;
};
///
/// JSArray wrapper that automatically manages lifetime and provides
/// convenient access to indices and Array functions.
///
class AExport JSArray {
public:
/// Create empty Array
JSArray();
/// Create Array from list of JSValues
JSArray(const std::initializer_list<JSValue>& values);
/// Create Array from existing JSObjectRef (JavaScriptCore C API)
JSArray(JSObjectRef array_obj);
/// Copy constructor (shallow copy, will point to same instance)
JSArray(const JSArray& other);
~JSArray();
/// Assignment (shallow assignment, will point to same instance)
JSArray& operator=(const JSArray& other);
/// Get number of elements in the Array
unsigned length();
/// Push an element to back of Array
void push(const JSValue& val);
/// Find the index (location) of a certain value, will return -1 if not found
int indexOf(const JSValue& val, int start = 0) const;
/// Get a property by array index (numbering starts at 0)
JSPropertyValue operator[](unsigned idx) const;
/// Get the underlying JSObjectRef (JavaScriptCore C API)
operator JSObjectRef() const { return instance_; }
///
/// Get the bound context for this JSArray (it is cached at creation).
///
JSContextRef context() const { return ctx_; }
///
/// Set the JSContext for this JSArray.
///
/// **Note**:
/// JSArrays created from within a JSCallback have a temporary JSContext
/// that is destroyed when the callback returns. You will need to "move"
/// any JSArrays created within these callbacks to the View's main context
/// (call set_context() with the main context) before using them outside
/// the callback.
///
void set_context(JSContextRef context) { ctx_ = context; }
protected:
JSArray(JSContextRef ctx, JSValueRef val);
JSContextRef ctx_;
JSObjectRef instance_;
friend class JSValue;
};
///
/// JSObject wrapper that automatically manages lifetime and provides
/// convenient access to properties.
///
class AExport JSObject {
public:
/// Create empty Object
JSObject();
/// Create from existing JSObjectRef from JavaScriptCore C API
JSObject(JSObjectRef obj);
/// Copy constructor (shallow copy, will point to same instance)
JSObject(const JSObject& other);
~JSObject();
/// Assignment (shallow assignment, will point to same instance)
JSObject& operator=(const JSObject& other);
/// Get a property by name
JSPropertyValue operator[](JSString propertyName) const;
/// Check if a property exists
bool HasProperty(JSString propertyName) const;
/// Remove a property
bool DeleteProperty(JSString propertyName);
/// Get the underlying JSObjectRef (JavaScriptCore C API)
operator JSObjectRef() const { return instance_; }
///
/// Get the bound context for this JSObject (it is cached at creation).
///
JSContextRef context() const { return ctx_; }
///
/// Set the JSContext for this JSObject.
///
/// **Note**:
/// JSObjects created from within a JSCallback have a temporary JSContext
/// that is destroyed when the callback returns. You will need to "move"
/// any JSObjects created within these callbacks to the View's main context
/// (call set_context() with the main context) before using them outside
/// the callback.
///
void set_context(JSContextRef context) { ctx_ = context; }
protected:
JSObject(JSContextRef ctx, JSValueRef val);
JSObject(JSContextRef ctx, JSObjectRef obj);
JSContextRef ctx_;
JSObjectRef instance_;
friend class JSValue;
friend class JSPropertyValue;
};
///
/// JSFunction wrapper that automatically manages lifetime and provides
/// convenient function invocation operators.
///
class AExport JSFunction {
public:
/// Create an empty Function.
/// NOTE: It is OKAY to create this without calling SetJSContext() first.
JSFunction();
/// Copy constructor (shallow copy, will point to same instance)
JSFunction(const JSFunction& other);
~JSFunction();
/// Assignment (shallow assignment, will point to same instance)
JSFunction& operator=(const JSFunction& other);
/// Whether or not this is a valid, callable Function object.
bool IsValid() const;
/// Call function (using Global Object for 'this') and return the result.
JSValue operator()(const JSArgs& args);
/// Call function (with explicit object for 'this') and return the result
JSValue operator()(const JSObject& thisObject, const JSArgs& args);
/// Get the underlying JSObjectRef (JavaScriptCore C API)
operator JSObjectRef() const { return instance_; }
///
/// Get the bound context for this JSFunction (it is cached at creation).
///
JSContextRef context() const { return ctx_; }
///
/// Set the JSContext for this JSFunction.
///
/// **Note**:
/// JSFunctions created from within a JSCallback have a temporary JSContext
/// that is destroyed when the callback returns. You will need to "move"
/// any JSFunctions created within these callbacks to the View's main context
/// (call set_context() with the main context) before using them outside
/// the callback.
///
void set_context(JSContextRef context) { ctx_ = context; }
protected:
JSFunction(JSContextRef ctx, JSValueRef val);
JSContextRef ctx_;
JSObjectRef instance_;
friend class JSValue;
};
///
/// Get the Global Object for the current JSContext.
/// In JavaScript, this would be equivalent to the "window" object.
///
JSObject AExport JSGlobalObject();
///
/// Evaluate a string of JavaScript and return a result.
///
JSValue AExport JSEval(const JSString& str);
} // namespace ultralight

View File

@ -1,41 +0,0 @@
///
/// @file Monitor.h
///
/// @brief The header for the Monitor class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Defines.h"
namespace ultralight {
///
/// Monitor class, represents a platform monitor.
///
class AExport Monitor {
public:
virtual ~Monitor() {}
///
/// Get the DPI scale (1.0 = 100%)
///
virtual double scale() const = 0;
///
/// Get the width of the monitor.
///
virtual uint32_t width() const = 0;
/// Get the height of the monitor.
///
virtual uint32_t height() const = 0;
};
} // namespace ultralight

View File

@ -1,141 +0,0 @@
///
/// @file Overlay.h
///
/// @brief The header for the Overlay class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Window.h"
#include <Ultralight/View.h>
namespace ultralight {
///
/// Web-content overlay. Displays a web-page within an area of the main window.
///
/// @note Each Overlay is essentially a View and an on-screen quad. You should
/// create the Overlay then load content into the underlying View.
///
class AExport Overlay : public RefCounted {
public:
///
/// Create a new Overlay.
///
/// @param window The window to create the Overlay in. (we currently only
/// support one window per application)
///
/// @param width The width in pixels.
///
/// @param height The height in pixels.
///
/// @param x The x-position (offset from the left of the Window), in
/// pixels.
///
/// @param y The y-position (offset from the top of the Window), in
/// pixels.
///
static Ref<Overlay> Create(Ref<Window> window, uint32_t width,
uint32_t height, int x, int y);
///
/// Create a new Overlay, wrapping an existing View.
///
/// @param window The window to create the Overlay in. (we currently only
/// support one window per application)
///
/// @param view The View to wrap (will use its width and height).
///
/// @param x The x-position (offset from the left of the Window), in
/// pixels.
///
/// @param y The y-position (offset from the top of the Window), in
/// pixels.
///
static Ref<Overlay> Create(Ref<Window> window, Ref<View> view, int x, int y);
///
/// Get the underlying View.
///
virtual ultralight::Ref<ultralight::View> view() = 0;
///
/// Get the width (in pixels).
///
virtual uint32_t width() const = 0;
///
/// Get the height (in pixels).
///
virtual uint32_t height() const = 0;
///
/// Get the x-position (offset from the left of the Window), in pixels.
///
virtual int x() const = 0;
///
/// Get the y-position (offset from the top of the Window), in pixels.
///
virtual int y() const = 0;
///
/// Whether or not the overlay is hidden (not drawn).
///
virtual bool is_hidden() const = 0;
///
/// Hide the overlay (will no longer be drawn)
///
virtual void Hide() = 0;
///
/// Show the overlay.
///
virtual void Show() = 0;
///
/// Whether or not this overlay has keyboard focus.
///
virtual bool has_focus() const = 0;
///
/// Grant this overlay exclusive keyboard focus.
///
virtual void Focus() = 0;
///
/// Remove keyboard focus.
///
virtual void Unfocus() = 0;
///
/// Move the overlay to a new position (in pixels).
///
virtual void MoveTo(int x, int y) = 0;
///
/// Resize the overlay (and underlying View), dimensions should be
/// specified in pixels.
///
virtual void Resize(uint32_t width, uint32_t height) = 0;
///
/// Whether or not this Overlay needs repaint (either it has moved, resized,
/// or the internal View needs repaint).
///
virtual bool NeedsRepaint() = 0;
protected:
virtual ~Overlay();
virtual void Draw() = 0;
friend class OverlayManager;
};
} // namespace framework

View File

@ -1,53 +0,0 @@
///
/// @file Platform.h
///
/// @brief The header for the Platform helpers.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Defines.h"
#include <Ultralight/String.h>
#include <Ultralight/platform/FontLoader.h>
#include <Ultralight/platform/FileSystem.h>
#include <Ultralight/platform/Logger.h>
namespace ultralight {
///
/// Get the native font loader for the current platform.
///
/// @note This singleton is owned by the library, do not destroy it.
///
AExport FontLoader* GetPlatformFontLoader();
///
/// Get the native file system for the current platform, creating it if it
/// doesn't exist using the base directory provided.
///
/// This is used to load data for file:/// URLs.
///
/// @param baseDir An base file path that will be used to resolve relative
/// file paths. You can optionally specify "@resource_path"
/// on macOS to use the app bundle's resource path.
///
/// @note This singleton is owned by the library, do not destroy it.
///
AExport FileSystem* GetPlatformFileSystem(const String& baseDir);
///
/// Get the default logger (writes the log to a file on disk).
///
/// @param logPath A file path to write the log to.
///
/// @note This singleton is owned by the library, do not destroy it.
///
AExport Logger* GetDefaultLogger(const String& logPath);
} // namespace ultralight

View File

@ -1,157 +0,0 @@
///
/// @file Window.h
///
/// @brief The header for the Window class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Defines.h"
#include <Ultralight/RefPtr.h>
#include <Ultralight/Listener.h>
#include <Ultralight/Bitmap.h>
namespace ultralight {
class Monitor;
class OverlayManager;
class Surface;
///
/// Interface for all Window-related events. @see Window::set_listener
///
class WindowListener {
public:
virtual ~WindowListener() {}
///
/// Called when the Window is closed.
///
virtual void OnClose() = 0;
///
/// Called when the Window is resized.
///
/// @param width The new width (in pixels).
///
/// @param height The new height (in pixels).
///
virtual void OnResize(uint32_t width, uint32_t height) = 0;
};
///
/// Window creation flags. @see Window::Create
///
enum WindowFlags : uint8_t {
kWindowFlags_Borderless = 1 << 0,
kWindowFlags_Titled = 1 << 1,
kWindowFlags_Resizable = 1 << 2,
kWindowFlags_Maximizable = 1 << 3,
};
///
/// Window class, represents a platform window.
///
class AExport Window : public RefCounted {
public:
///
/// Create a new Window.
///
/// @param monitor The monitor to create the Window on.
///
/// @param width The width (in device coordinates).
///
/// @param height The height (in device coordinates).
///
/// @param fullscreen Whether or not the window is fullscreen.
///
/// @param window_flags Various window flags.
///
static Ref<Window> Create(Monitor* monitor, uint32_t width, uint32_t height,
bool fullscreen, unsigned int window_flags);
///
/// Set a WindowListener to receive callbacks for window-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_listener(WindowListener* listener) = 0;
///
/// Get the WindowListener, if any.
///
virtual WindowListener* listener() = 0;
///
/// Get the window width (in pixels).
///
virtual uint32_t width() const = 0;
///
/// Get the window height (in pixels).
///
virtual uint32_t height() const = 0;
///
/// Whether or not the window is fullscreen.
///
virtual bool is_fullscreen() const = 0;
///
/// The DPI scale of the window.
///
virtual double scale() const = 0;
///
/// Set the window title.
///
virtual void SetTitle(const char* title) = 0;
///
/// Set the cursor.
///
virtual void SetCursor(ultralight::Cursor cursor) = 0;
///
/// Close the window.
///
virtual void Close() = 0;
///
/// Convert device coordinates to pixels using the current DPI scale.
///
virtual int DeviceToPixels(int val) const = 0;
///
/// Convert pixels to device coordinates using the current DPI scale.
///
virtual int PixelsToDevice(int val) const = 0;
///
/// Draw a surface directly to window, used only by CPU renderer
///
virtual void DrawSurface(int x, int y, Surface* surface) {}
///
/// Get the underlying native window handle.
///
/// @note This is: - HWND on Windows
/// - NSWindow* on macOS
/// - GLFWwindow* on Linux
///
virtual void* native_handle() const = 0;
protected:
virtual ~Window();
virtual OverlayManager* overlay_manager() const = 0;
friend class OverlayImpl;
};
} // namespace ultralight

File diff suppressed because it is too large Load Diff

View File

@ -1,901 +0,0 @@
#ifndef __wglext_h_
#define __wglext_h_
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright (c) 2007-2010 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Function declaration macros - to move into glplatform.h */
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#endif
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifndef GLAPI
#define GLAPI extern
#endif
/*************************************************************/
/* Header file version number */
/* wglext.h last updated 2010/08/06 */
/* Current version at http://www.opengl.org/registry/ */
#define WGL_WGLEXT_VERSION 22
#ifndef WGL_ARB_buffer_region
#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001
#define WGL_BACK_COLOR_BUFFER_BIT_ARB 0x00000002
#define WGL_DEPTH_BUFFER_BIT_ARB 0x00000004
#define WGL_STENCIL_BUFFER_BIT_ARB 0x00000008
#endif
#ifndef WGL_ARB_multisample
#define WGL_SAMPLE_BUFFERS_ARB 0x2041
#define WGL_SAMPLES_ARB 0x2042
#endif
#ifndef WGL_ARB_extensions_string
#endif
#ifndef WGL_ARB_pixel_format
#define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
#define WGL_DRAW_TO_WINDOW_ARB 0x2001
#define WGL_DRAW_TO_BITMAP_ARB 0x2002
#define WGL_ACCELERATION_ARB 0x2003
#define WGL_NEED_PALETTE_ARB 0x2004
#define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
#define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
#define WGL_SWAP_METHOD_ARB 0x2007
#define WGL_NUMBER_OVERLAYS_ARB 0x2008
#define WGL_NUMBER_UNDERLAYS_ARB 0x2009
#define WGL_TRANSPARENT_ARB 0x200A
#define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
#define WGL_SHARE_DEPTH_ARB 0x200C
#define WGL_SHARE_STENCIL_ARB 0x200D
#define WGL_SHARE_ACCUM_ARB 0x200E
#define WGL_SUPPORT_GDI_ARB 0x200F
#define WGL_SUPPORT_OPENGL_ARB 0x2010
#define WGL_DOUBLE_BUFFER_ARB 0x2011
#define WGL_STEREO_ARB 0x2012
#define WGL_PIXEL_TYPE_ARB 0x2013
#define WGL_COLOR_BITS_ARB 0x2014
#define WGL_RED_BITS_ARB 0x2015
#define WGL_RED_SHIFT_ARB 0x2016
#define WGL_GREEN_BITS_ARB 0x2017
#define WGL_GREEN_SHIFT_ARB 0x2018
#define WGL_BLUE_BITS_ARB 0x2019
#define WGL_BLUE_SHIFT_ARB 0x201A
#define WGL_ALPHA_BITS_ARB 0x201B
#define WGL_ALPHA_SHIFT_ARB 0x201C
#define WGL_ACCUM_BITS_ARB 0x201D
#define WGL_ACCUM_RED_BITS_ARB 0x201E
#define WGL_ACCUM_GREEN_BITS_ARB 0x201F
#define WGL_ACCUM_BLUE_BITS_ARB 0x2020
#define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
#define WGL_DEPTH_BITS_ARB 0x2022
#define WGL_STENCIL_BITS_ARB 0x2023
#define WGL_AUX_BUFFERS_ARB 0x2024
#define WGL_NO_ACCELERATION_ARB 0x2025
#define WGL_GENERIC_ACCELERATION_ARB 0x2026
#define WGL_FULL_ACCELERATION_ARB 0x2027
#define WGL_SWAP_EXCHANGE_ARB 0x2028
#define WGL_SWAP_COPY_ARB 0x2029
#define WGL_SWAP_UNDEFINED_ARB 0x202A
#define WGL_TYPE_RGBA_ARB 0x202B
#define WGL_TYPE_COLORINDEX_ARB 0x202C
#endif
#ifndef WGL_ARB_make_current_read
#define ERROR_INVALID_PIXEL_TYPE_ARB 0x2043
#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
#endif
#ifndef WGL_ARB_pbuffer
#define WGL_DRAW_TO_PBUFFER_ARB 0x202D
#define WGL_MAX_PBUFFER_PIXELS_ARB 0x202E
#define WGL_MAX_PBUFFER_WIDTH_ARB 0x202F
#define WGL_MAX_PBUFFER_HEIGHT_ARB 0x2030
#define WGL_PBUFFER_LARGEST_ARB 0x2033
#define WGL_PBUFFER_WIDTH_ARB 0x2034
#define WGL_PBUFFER_HEIGHT_ARB 0x2035
#define WGL_PBUFFER_LOST_ARB 0x2036
#endif
#ifndef WGL_ARB_render_texture
#define WGL_BIND_TO_TEXTURE_RGB_ARB 0x2070
#define WGL_BIND_TO_TEXTURE_RGBA_ARB 0x2071
#define WGL_TEXTURE_FORMAT_ARB 0x2072
#define WGL_TEXTURE_TARGET_ARB 0x2073
#define WGL_MIPMAP_TEXTURE_ARB 0x2074
#define WGL_TEXTURE_RGB_ARB 0x2075
#define WGL_TEXTURE_RGBA_ARB 0x2076
#define WGL_NO_TEXTURE_ARB 0x2077
#define WGL_TEXTURE_CUBE_MAP_ARB 0x2078
#define WGL_TEXTURE_1D_ARB 0x2079
#define WGL_TEXTURE_2D_ARB 0x207A
#define WGL_MIPMAP_LEVEL_ARB 0x207B
#define WGL_CUBE_MAP_FACE_ARB 0x207C
#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D
#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E
#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F
#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080
#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081
#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082
#define WGL_FRONT_LEFT_ARB 0x2083
#define WGL_FRONT_RIGHT_ARB 0x2084
#define WGL_BACK_LEFT_ARB 0x2085
#define WGL_BACK_RIGHT_ARB 0x2086
#define WGL_AUX0_ARB 0x2087
#define WGL_AUX1_ARB 0x2088
#define WGL_AUX2_ARB 0x2089
#define WGL_AUX3_ARB 0x208A
#define WGL_AUX4_ARB 0x208B
#define WGL_AUX5_ARB 0x208C
#define WGL_AUX6_ARB 0x208D
#define WGL_AUX7_ARB 0x208E
#define WGL_AUX8_ARB 0x208F
#define WGL_AUX9_ARB 0x2090
#endif
#ifndef WGL_ARB_pixel_format_float
#define WGL_TYPE_RGBA_FLOAT_ARB 0x21A0
#endif
#ifndef WGL_ARB_framebuffer_sRGB
#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
#endif
#ifndef WGL_ARB_create_context
#define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001
#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
#define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093
#define WGL_CONTEXT_FLAGS_ARB 0x2094
#define ERROR_INVALID_VERSION_ARB 0x2095
#endif
#ifndef WGL_ARB_create_context_profile
#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#define ERROR_INVALID_PROFILE_ARB 0x2096
#endif
#ifndef WGL_ARB_create_context_robustness
#define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
#define WGL_LOSE_CONTEXT_ON_RESET_ARB 0x8252
#define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
#define WGL_NO_RESET_NOTIFICATION_ARB 0x8261
#endif
#ifndef WGL_EXT_make_current_read
#define ERROR_INVALID_PIXEL_TYPE_EXT 0x2043
#endif
#ifndef WGL_EXT_pixel_format
#define WGL_NUMBER_PIXEL_FORMATS_EXT 0x2000
#define WGL_DRAW_TO_WINDOW_EXT 0x2001
#define WGL_DRAW_TO_BITMAP_EXT 0x2002
#define WGL_ACCELERATION_EXT 0x2003
#define WGL_NEED_PALETTE_EXT 0x2004
#define WGL_NEED_SYSTEM_PALETTE_EXT 0x2005
#define WGL_SWAP_LAYER_BUFFERS_EXT 0x2006
#define WGL_SWAP_METHOD_EXT 0x2007
#define WGL_NUMBER_OVERLAYS_EXT 0x2008
#define WGL_NUMBER_UNDERLAYS_EXT 0x2009
#define WGL_TRANSPARENT_EXT 0x200A
#define WGL_TRANSPARENT_VALUE_EXT 0x200B
#define WGL_SHARE_DEPTH_EXT 0x200C
#define WGL_SHARE_STENCIL_EXT 0x200D
#define WGL_SHARE_ACCUM_EXT 0x200E
#define WGL_SUPPORT_GDI_EXT 0x200F
#define WGL_SUPPORT_OPENGL_EXT 0x2010
#define WGL_DOUBLE_BUFFER_EXT 0x2011
#define WGL_STEREO_EXT 0x2012
#define WGL_PIXEL_TYPE_EXT 0x2013
#define WGL_COLOR_BITS_EXT 0x2014
#define WGL_RED_BITS_EXT 0x2015
#define WGL_RED_SHIFT_EXT 0x2016
#define WGL_GREEN_BITS_EXT 0x2017
#define WGL_GREEN_SHIFT_EXT 0x2018
#define WGL_BLUE_BITS_EXT 0x2019
#define WGL_BLUE_SHIFT_EXT 0x201A
#define WGL_ALPHA_BITS_EXT 0x201B
#define WGL_ALPHA_SHIFT_EXT 0x201C
#define WGL_ACCUM_BITS_EXT 0x201D
#define WGL_ACCUM_RED_BITS_EXT 0x201E
#define WGL_ACCUM_GREEN_BITS_EXT 0x201F
#define WGL_ACCUM_BLUE_BITS_EXT 0x2020
#define WGL_ACCUM_ALPHA_BITS_EXT 0x2021
#define WGL_DEPTH_BITS_EXT 0x2022
#define WGL_STENCIL_BITS_EXT 0x2023
#define WGL_AUX_BUFFERS_EXT 0x2024
#define WGL_NO_ACCELERATION_EXT 0x2025
#define WGL_GENERIC_ACCELERATION_EXT 0x2026
#define WGL_FULL_ACCELERATION_EXT 0x2027
#define WGL_SWAP_EXCHANGE_EXT 0x2028
#define WGL_SWAP_COPY_EXT 0x2029
#define WGL_SWAP_UNDEFINED_EXT 0x202A
#define WGL_TYPE_RGBA_EXT 0x202B
#define WGL_TYPE_COLORINDEX_EXT 0x202C
#endif
#ifndef WGL_EXT_pbuffer
#define WGL_DRAW_TO_PBUFFER_EXT 0x202D
#define WGL_MAX_PBUFFER_PIXELS_EXT 0x202E
#define WGL_MAX_PBUFFER_WIDTH_EXT 0x202F
#define WGL_MAX_PBUFFER_HEIGHT_EXT 0x2030
#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT 0x2031
#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032
#define WGL_PBUFFER_LARGEST_EXT 0x2033
#define WGL_PBUFFER_WIDTH_EXT 0x2034
#define WGL_PBUFFER_HEIGHT_EXT 0x2035
#endif
#ifndef WGL_EXT_depth_float
#define WGL_DEPTH_FLOAT_EXT 0x2040
#endif
#ifndef WGL_3DFX_multisample
#define WGL_SAMPLE_BUFFERS_3DFX 0x2060
#define WGL_SAMPLES_3DFX 0x2061
#endif
#ifndef WGL_EXT_multisample
#define WGL_SAMPLE_BUFFERS_EXT 0x2041
#define WGL_SAMPLES_EXT 0x2042
#endif
#ifndef WGL_I3D_digital_video_control
#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050
#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051
#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052
#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053
#endif
#ifndef WGL_I3D_gamma
#define WGL_GAMMA_TABLE_SIZE_I3D 0x204E
#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D 0x204F
#endif
#ifndef WGL_I3D_genlock
#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044
#define WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D 0x2045
#define WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D 0x2046
#define WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D 0x2047
#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048
#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049
#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A
#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B
#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C
#endif
#ifndef WGL_I3D_image_buffer
#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001
#define WGL_IMAGE_BUFFER_LOCK_I3D 0x00000002
#endif
#ifndef WGL_I3D_swap_frame_lock
#endif
#ifndef WGL_NV_render_depth_texture
#define WGL_BIND_TO_TEXTURE_DEPTH_NV 0x20A3
#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4
#define WGL_DEPTH_TEXTURE_FORMAT_NV 0x20A5
#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6
#define WGL_DEPTH_COMPONENT_NV 0x20A7
#endif
#ifndef WGL_NV_render_texture_rectangle
#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0
#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1
#define WGL_TEXTURE_RECTANGLE_NV 0x20A2
#endif
#ifndef WGL_ATI_pixel_format_float
#define WGL_TYPE_RGBA_FLOAT_ATI 0x21A0
#endif
#ifndef WGL_NV_float_buffer
#define WGL_FLOAT_COMPONENTS_NV 0x20B0
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4
#define WGL_TEXTURE_FLOAT_R_NV 0x20B5
#define WGL_TEXTURE_FLOAT_RG_NV 0x20B6
#define WGL_TEXTURE_FLOAT_RGB_NV 0x20B7
#define WGL_TEXTURE_FLOAT_RGBA_NV 0x20B8
#endif
#ifndef WGL_3DL_stereo_control
#define WGL_STEREO_EMITTER_ENABLE_3DL 0x2055
#define WGL_STEREO_EMITTER_DISABLE_3DL 0x2056
#define WGL_STEREO_POLARITY_NORMAL_3DL 0x2057
#define WGL_STEREO_POLARITY_INVERT_3DL 0x2058
#endif
#ifndef WGL_EXT_pixel_format_packed_float
#define WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT 0x20A8
#endif
#ifndef WGL_EXT_framebuffer_sRGB
#define WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20A9
#endif
#ifndef WGL_NV_present_video
#define WGL_NUM_VIDEO_SLOTS_NV 0x20F0
#endif
#ifndef WGL_NV_video_out
#define WGL_BIND_TO_VIDEO_RGB_NV 0x20C0
#define WGL_BIND_TO_VIDEO_RGBA_NV 0x20C1
#define WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV 0x20C2
#define WGL_VIDEO_OUT_COLOR_NV 0x20C3
#define WGL_VIDEO_OUT_ALPHA_NV 0x20C4
#define WGL_VIDEO_OUT_DEPTH_NV 0x20C5
#define WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV 0x20C6
#define WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV 0x20C7
#define WGL_VIDEO_OUT_FRAME 0x20C8
#define WGL_VIDEO_OUT_FIELD_1 0x20C9
#define WGL_VIDEO_OUT_FIELD_2 0x20CA
#define WGL_VIDEO_OUT_STACKED_FIELDS_1_2 0x20CB
#define WGL_VIDEO_OUT_STACKED_FIELDS_2_1 0x20CC
#endif
#ifndef WGL_NV_swap_group
#endif
#ifndef WGL_NV_gpu_affinity
#define WGL_ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV 0x20D0
#define WGL_ERROR_MISSING_AFFINITY_MASK_NV 0x20D1
#endif
#ifndef WGL_AMD_gpu_association
#define WGL_GPU_VENDOR_AMD 0x1F00
#define WGL_GPU_RENDERER_STRING_AMD 0x1F01
#define WGL_GPU_OPENGL_VERSION_STRING_AMD 0x1F02
#define WGL_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2
#define WGL_GPU_RAM_AMD 0x21A3
#define WGL_GPU_CLOCK_AMD 0x21A4
#define WGL_GPU_NUM_PIPES_AMD 0x21A5
#define WGL_GPU_NUM_SIMD_AMD 0x21A6
#define WGL_GPU_NUM_RB_AMD 0x21A7
#define WGL_GPU_NUM_SPI_AMD 0x21A8
#endif
#ifndef WGL_NV_video_capture
#define WGL_UNIQUE_ID_NV 0x20CE
#define WGL_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF
#endif
#ifndef WGL_NV_copy_image
#endif
#ifndef WGL_NV_multisample_coverage
#define WGL_COVERAGE_SAMPLES_NV 0x2042
#define WGL_COLOR_SAMPLES_NV 0x20B9
#endif
#ifndef WGL_EXT_create_context_es2_profile
#define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
#endif
/*************************************************************/
#ifndef WGL_ARB_pbuffer
DECLARE_HANDLE(HPBUFFERARB);
#endif
#ifndef WGL_EXT_pbuffer
DECLARE_HANDLE(HPBUFFEREXT);
#endif
#ifndef WGL_NV_present_video
DECLARE_HANDLE(HVIDEOOUTPUTDEVICENV);
#endif
#ifndef WGL_NV_video_output
DECLARE_HANDLE(HPVIDEODEV);
#endif
#ifndef WGL_NV_gpu_affinity
DECLARE_HANDLE(HPGPUNV);
DECLARE_HANDLE(HGPUNV);
typedef struct _GPU_DEVICE {
DWORD cb;
CHAR DeviceName[32];
CHAR DeviceString[128];
DWORD Flags;
RECT rcVirtualScreen;
} GPU_DEVICE, *PGPU_DEVICE;
#endif
#ifndef WGL_NV_video_capture
DECLARE_HANDLE(HVIDEOINPUTDEVICENV);
#endif
#ifndef WGL_ARB_buffer_region
#define WGL_ARB_buffer_region 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern HANDLE WINAPI wglCreateBufferRegionARB (HDC hDC, int iLayerPlane, UINT uType);
extern VOID WINAPI wglDeleteBufferRegionARB (HANDLE hRegion);
extern BOOL WINAPI wglSaveBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height);
extern BOOL WINAPI wglRestoreBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType);
typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion);
typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height);
typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
#endif
#ifndef WGL_ARB_multisample
#define WGL_ARB_multisample 1
#endif
#ifndef WGL_ARB_extensions_string
#define WGL_ARB_extensions_string 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern const char * WINAPI wglGetExtensionsStringARB (HDC hdc);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
#endif
#ifndef WGL_ARB_pixel_format
#define WGL_ARB_pixel_format 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglGetPixelFormatAttribivARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
extern BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
extern BOOL WINAPI wglChoosePixelFormatARB (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
#endif
#ifndef WGL_ARB_make_current_read
#define WGL_ARB_make_current_read 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglMakeContextCurrentARB (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
extern HDC WINAPI wglGetCurrentReadDCARB (void);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void);
#endif
#ifndef WGL_ARB_pbuffer
#define WGL_ARB_pbuffer 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern HPBUFFERARB WINAPI wglCreatePbufferARB (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
extern HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB hPbuffer);
extern int WINAPI wglReleasePbufferDCARB (HPBUFFERARB hPbuffer, HDC hDC);
extern BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB hPbuffer);
extern BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
#endif
#ifndef WGL_ARB_render_texture
#define WGL_ARB_render_texture 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglBindTexImageARB (HPBUFFERARB hPbuffer, int iBuffer);
extern BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB hPbuffer, int iBuffer);
extern BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB hPbuffer, const int *piAttribList);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList);
#endif
#ifndef WGL_ARB_pixel_format_float
#define WGL_ARB_pixel_format_float 1
#endif
#ifndef WGL_ARB_framebuffer_sRGB
#define WGL_ARB_framebuffer_sRGB 1
#endif
#ifndef WGL_ARB_create_context
#define WGL_ARB_create_context 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern HGLRC WINAPI wglCreateContextAttribsARB (HDC hDC, HGLRC hShareContext, const int *attribList);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
#endif
#ifndef WGL_ARB_create_context_profile
#define WGL_ARB_create_context_profile 1
#endif
#ifndef WGL_ARB_create_context_robustness
#define WGL_ARB_create_context_robustness 1
#endif
#ifndef WGL_EXT_display_color_table
#define WGL_EXT_display_color_table 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort id);
extern GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *table, GLuint length);
extern GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort id);
extern VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort id);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id);
typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length);
typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id);
typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id);
#endif
#ifndef WGL_EXT_extensions_string
#define WGL_EXT_extensions_string 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern const char * WINAPI wglGetExtensionsStringEXT (void);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void);
#endif
#ifndef WGL_EXT_make_current_read
#define WGL_EXT_make_current_read 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglMakeContextCurrentEXT (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
extern HDC WINAPI wglGetCurrentReadDCEXT (void);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void);
#endif
#ifndef WGL_EXT_pbuffer
#define WGL_EXT_pbuffer 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
extern HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT hPbuffer);
extern int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT hPbuffer, HDC hDC);
extern BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT hPbuffer);
extern BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer);
typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC);
typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer);
typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
#endif
#ifndef WGL_EXT_pixel_format
#define WGL_EXT_pixel_format 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
extern BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
extern BOOL WINAPI wglChoosePixelFormatEXT (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
#endif
#ifndef WGL_EXT_swap_control
#define WGL_EXT_swap_control 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglSwapIntervalEXT (int interval);
extern int WINAPI wglGetSwapIntervalEXT (void);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
#endif
#ifndef WGL_EXT_depth_float
#define WGL_EXT_depth_float 1
#endif
#ifndef WGL_NV_vertex_array_range
#define WGL_NV_vertex_array_range 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern void* WINAPI wglAllocateMemoryNV (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
extern void WINAPI wglFreeMemoryNV (void *pointer);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef void* (WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer);
#endif
#ifndef WGL_3DFX_multisample
#define WGL_3DFX_multisample 1
#endif
#ifndef WGL_EXT_multisample
#define WGL_EXT_multisample 1
#endif
#ifndef WGL_OML_sync_control
#define WGL_OML_sync_control 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglGetSyncValuesOML (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
extern BOOL WINAPI wglGetMscRateOML (HDC hdc, INT32 *numerator, INT32 *denominator);
extern INT64 WINAPI wglSwapBuffersMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
extern INT64 WINAPI wglSwapLayerBuffersMscOML (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
extern BOOL WINAPI wglWaitForMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
extern BOOL WINAPI wglWaitForSbcOML (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator);
typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
#endif
#ifndef WGL_I3D_digital_video_control
#define WGL_I3D_digital_video_control 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC hDC, int iAttribute, int *piValue);
extern BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC hDC, int iAttribute, const int *piValue);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
#endif
#ifndef WGL_I3D_gamma
#define WGL_I3D_gamma 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglGetGammaTableParametersI3D (HDC hDC, int iAttribute, int *piValue);
extern BOOL WINAPI wglSetGammaTableParametersI3D (HDC hDC, int iAttribute, const int *piValue);
extern BOOL WINAPI wglGetGammaTableI3D (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
extern BOOL WINAPI wglSetGammaTableI3D (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
#endif
#ifndef WGL_I3D_genlock
#define WGL_I3D_genlock 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglEnableGenlockI3D (HDC hDC);
extern BOOL WINAPI wglDisableGenlockI3D (HDC hDC);
extern BOOL WINAPI wglIsEnabledGenlockI3D (HDC hDC, BOOL *pFlag);
extern BOOL WINAPI wglGenlockSourceI3D (HDC hDC, UINT uSource);
extern BOOL WINAPI wglGetGenlockSourceI3D (HDC hDC, UINT *uSource);
extern BOOL WINAPI wglGenlockSourceEdgeI3D (HDC hDC, UINT uEdge);
extern BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC hDC, UINT *uEdge);
extern BOOL WINAPI wglGenlockSampleRateI3D (HDC hDC, UINT uRate);
extern BOOL WINAPI wglGetGenlockSampleRateI3D (HDC hDC, UINT *uRate);
extern BOOL WINAPI wglGenlockSourceDelayI3D (HDC hDC, UINT uDelay);
extern BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC hDC, UINT *uDelay);
extern BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC);
typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC);
typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag);
typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource);
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource);
typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge);
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge);
typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate);
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate);
typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay);
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay);
typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
#endif
#ifndef WGL_I3D_image_buffer
#define WGL_I3D_image_buffer 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern LPVOID WINAPI wglCreateImageBufferI3D (HDC hDC, DWORD dwSize, UINT uFlags);
extern BOOL WINAPI wglDestroyImageBufferI3D (HDC hDC, LPVOID pAddress);
extern BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
extern BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC hDC, const LPVOID *pAddress, UINT count);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags);
typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress);
typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count);
#endif
#ifndef WGL_I3D_swap_frame_lock
#define WGL_I3D_swap_frame_lock 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglEnableFrameLockI3D (void);
extern BOOL WINAPI wglDisableFrameLockI3D (void);
extern BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *pFlag);
extern BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *pFlag);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void);
typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void);
typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag);
typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag);
#endif
#ifndef WGL_I3D_swap_frame_usage
#define WGL_I3D_swap_frame_usage 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglGetFrameUsageI3D (float *pUsage);
extern BOOL WINAPI wglBeginFrameTrackingI3D (void);
extern BOOL WINAPI wglEndFrameTrackingI3D (void);
extern BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage);
typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void);
typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void);
typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
#endif
#ifndef WGL_ATI_pixel_format_float
#define WGL_ATI_pixel_format_float 1
#endif
#ifndef WGL_NV_float_buffer
#define WGL_NV_float_buffer 1
#endif
#ifndef WGL_3DL_stereo_control
#define WGL_3DL_stereo_control 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglSetStereoEmitterState3DL (HDC hDC, UINT uState);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLSETSTEREOEMITTERSTATE3DLPROC) (HDC hDC, UINT uState);
#endif
#ifndef WGL_EXT_pixel_format_packed_float
#define WGL_EXT_pixel_format_packed_float 1
#endif
#ifndef WGL_EXT_framebuffer_sRGB
#define WGL_EXT_framebuffer_sRGB 1
#endif
#ifndef WGL_NV_present_video
#define WGL_NV_present_video 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern int WINAPI wglEnumerateVideoDevicesNV (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList);
extern BOOL WINAPI wglBindVideoDeviceNV (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList);
extern BOOL WINAPI wglQueryCurrentContextNV (int iAttribute, int *piValue);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef int (WINAPI * PFNWGLENUMERATEVIDEODEVICESNVPROC) (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList);
typedef BOOL (WINAPI * PFNWGLBINDVIDEODEVICENVPROC) (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList);
typedef BOOL (WINAPI * PFNWGLQUERYCURRENTCONTEXTNVPROC) (int iAttribute, int *piValue);
#endif
#ifndef WGL_NV_video_output
#define WGL_NV_video_output 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglGetVideoDeviceNV (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice);
extern BOOL WINAPI wglReleaseVideoDeviceNV (HPVIDEODEV hVideoDevice);
extern BOOL WINAPI wglBindVideoImageNV (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer);
extern BOOL WINAPI wglReleaseVideoImageNV (HPBUFFERARB hPbuffer, int iVideoBuffer);
extern BOOL WINAPI wglSendPbufferToVideoNV (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock);
extern BOOL WINAPI wglGetVideoInfoNV (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLGETVIDEODEVICENVPROC) (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice);
typedef BOOL (WINAPI * PFNWGLRELEASEVIDEODEVICENVPROC) (HPVIDEODEV hVideoDevice);
typedef BOOL (WINAPI * PFNWGLBINDVIDEOIMAGENVPROC) (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer);
typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOIMAGENVPROC) (HPBUFFERARB hPbuffer, int iVideoBuffer);
typedef BOOL (WINAPI * PFNWGLSENDPBUFFERTOVIDEONVPROC) (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock);
typedef BOOL (WINAPI * PFNWGLGETVIDEOINFONVPROC) (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
#endif
#ifndef WGL_NV_swap_group
#define WGL_NV_swap_group 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglJoinSwapGroupNV (HDC hDC, GLuint group);
extern BOOL WINAPI wglBindSwapBarrierNV (GLuint group, GLuint barrier);
extern BOOL WINAPI wglQuerySwapGroupNV (HDC hDC, GLuint *group, GLuint *barrier);
extern BOOL WINAPI wglQueryMaxSwapGroupsNV (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
extern BOOL WINAPI wglQueryFrameCountNV (HDC hDC, GLuint *count);
extern BOOL WINAPI wglResetFrameCountNV (HDC hDC);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group);
typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier);
typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier);
typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count);
typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC);
#endif
#ifndef WGL_NV_gpu_affinity
#define WGL_NV_gpu_affinity 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglEnumGpusNV (UINT iGpuIndex, HGPUNV *phGpu);
extern BOOL WINAPI wglEnumGpuDevicesNV (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
extern HDC WINAPI wglCreateAffinityDCNV (const HGPUNV *phGpuList);
extern BOOL WINAPI wglEnumGpusFromAffinityDCNV (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
extern BOOL WINAPI wglDeleteDCNV (HDC hdc);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLENUMGPUSNVPROC) (UINT iGpuIndex, HGPUNV *phGpu);
typedef BOOL (WINAPI * PFNWGLENUMGPUDEVICESNVPROC) (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
typedef HDC (WINAPI * PFNWGLCREATEAFFINITYDCNVPROC) (const HGPUNV *phGpuList);
typedef BOOL (WINAPI * PFNWGLENUMGPUSFROMAFFINITYDCNVPROC) (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
typedef BOOL (WINAPI * PFNWGLDELETEDCNVPROC) (HDC hdc);
#endif
#ifndef WGL_AMD_gpu_association
#define WGL_AMD_gpu_association 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern UINT WINAPI wglGetGPUIDsAMD (UINT maxCount, UINT *ids);
extern INT WINAPI wglGetGPUInfoAMD (UINT id, int property, GLenum dataType, UINT size, void *data);
extern UINT WINAPI wglGetContextGPUIDAMD (HGLRC hglrc);
extern HGLRC WINAPI wglCreateAssociatedContextAMD (UINT id);
extern HGLRC WINAPI wglCreateAssociatedContextAttribsAMD (UINT id, HGLRC hShareContext, const int *attribList);
extern BOOL WINAPI wglDeleteAssociatedContextAMD (HGLRC hglrc);
extern BOOL WINAPI wglMakeAssociatedContextCurrentAMD (HGLRC hglrc);
extern HGLRC WINAPI wglGetCurrentAssociatedContextAMD (void);
extern VOID WINAPI wglBlitContextFramebufferAMD (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef UINT (WINAPI * PFNWGLGETGPUIDSAMDPROC) (UINT maxCount, UINT *ids);
typedef INT (WINAPI * PFNWGLGETGPUINFOAMDPROC) (UINT id, int property, GLenum dataType, UINT size, void *data);
typedef UINT (WINAPI * PFNWGLGETCONTEXTGPUIDAMDPROC) (HGLRC hglrc);
typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC) (UINT id);
typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (UINT id, HGLRC hShareContext, const int *attribList);
typedef BOOL (WINAPI * PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC) (HGLRC hglrc);
typedef BOOL (WINAPI * PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (HGLRC hglrc);
typedef HGLRC (WINAPI * PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void);
typedef VOID (WINAPI * PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC) (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
#endif
#ifndef WGL_NV_video_capture
#define WGL_NV_video_capture 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglBindVideoCaptureDeviceNV (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice);
extern UINT WINAPI wglEnumerateVideoCaptureDevicesNV (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList);
extern BOOL WINAPI wglLockVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
extern BOOL WINAPI wglQueryVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue);
extern BOOL WINAPI wglReleaseVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLBINDVIDEOCAPTUREDEVICENVPROC) (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice);
typedef UINT (WINAPI * PFNWGLENUMERATEVIDEOCAPTUREDEVICESNVPROC) (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList);
typedef BOOL (WINAPI * PFNWGLLOCKVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
typedef BOOL (WINAPI * PFNWGLQUERYVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue);
typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
#endif
#ifndef WGL_NV_copy_image
#define WGL_NV_copy_image 1
#ifdef WGL_WGLEXT_PROTOTYPES
extern BOOL WINAPI wglCopyImageSubDataNV (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
#endif /* WGL_WGLEXT_PROTOTYPES */
typedef BOOL (WINAPI * PFNWGLCOPYIMAGESUBDATANVPROC) (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
#endif
#ifndef WGL_NV_multisample_coverage
#define WGL_NV_multisample_coverage 1
#endif
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,254 +0,0 @@
/*---------------------------------------------------------------------------*/
/* */
/* Host.h - Basic header file to provide cross-platform solutions via */
/* macros, conditional compilation, etc. */
/* */
/* Author : Mark Carrier (mark@carrierlabs.com) */
/* */
/*---------------------------------------------------------------------------*/
/* Copyright (c) 2007 CarrierLabs, LLC. 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.
*
* 4. The name "CarrierLabs" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* mark@carrierlabs.com.
*
* THIS SOFTWARE IS PROVIDED BY MARK CARRIER ``AS IS'' AND ANY
* EXPRESSED 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 MARK CARRIER OR
* ITS CONTRIBUTORS 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.
*----------------------------------------------------------------------------*/
#ifndef __HOST_H__
#define __HOST_H__
#include <limits.h>
#ifdef __cplusplus
extern "C"
{
#endif
/*---------------------------------------------------------------------------*/
/* */
/* Type Definition Macros */
/* */
/*---------------------------------------------------------------------------*/
#ifndef __WORDSIZE
/* Assume 32 */
#define __WORDSIZE 32
#endif
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
typedef int SOCKET;
#endif
#ifdef WIN32
struct iovec
{
void *iov_base;
size_t iov_len;
};
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
#endif
#ifdef WIN32
typedef int socklen_t;
#endif
#if defined(WIN32)
typedef unsigned long long int uint64;
typedef long long int int64;
#elif (__WORDSIZE == 32)
__extension__ typedef long long int int64;
__extension__ typedef unsigned long long int uint64;
#elif (__WORDSIZE == 64)
typedef unsigned long int uint64;
typedef long int int64;
#endif
#ifdef WIN32
#ifndef UINT8_MAX
#define UINT8_MAX (UCHAR_MAX)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (USHRT_MAX)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (ULONG_MAX)
#endif
#if __WORDSIZE == 64
#define SIZE_MAX (18446744073709551615UL)
#else
#ifndef SIZE_MAX
#define SIZE_MAX (4294967295U)
#endif
#endif
#endif
#if defined(WIN32)
#define ssize_t size_t
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef htonll
#ifdef _BIG_ENDIAN
#define htonll(x) (x)
#define ntohll(x) (x)
#else
#define htonll(x) ((((uint64)htonl(x)) << 32) + htonl(x >> 32))
#define ntohll(x) ((((uint64)ntohl(x)) << 32) + ntohl(x >> 32))
#endif
#endif
/*---------------------------------------------------------------------------*/
/* */
/* Socket Macros */
/* */
/*---------------------------------------------------------------------------*/
#ifdef WIN32
#define SHUT_RD 0
#define SHUT_WR 1
#define SHUT_RDWR 2
#define ACCEPT(a, b, c) accept(a, b, c)
#define CONNECT(a, b, c) connect(a, b, c)
#define CLOSE(a) closesocket(a)
#define READ(a, b, c) read(a, b, c)
#define RECV(a, b, c, d) recv(a, (char *)b, c, d)
#define RECVFROM(a, b, c, d, e, f) recvfrom(a, (char *)b, c, d, (sockaddr *)e, (int *)f)
#define RECV_FLAGS MSG_WAITALL
#define SELECT(a, b, c, d, e) select((int32)a, b, c, d, e)
#define SEND(a, b, c, d) send(a, (const char *)b, (int)c, d)
#define SENDTO(a, b, c, d, e, f) sendto(a, (const char *)b, (int)c, d, e, f)
#define SEND_FLAGS 0
#define SENDFILE(a, b, c, d) sendfile(a, b, c, d)
#define SET_SOCKET_ERROR(x, y) errno = y
#define SOCKET_ERROR_INTERUPT EINTR
#define SOCKET_ERROR_TIMEDOUT EAGAIN
#define WRITE(a, b, c) write(a, b, c)
#define WRITEV(a, b, c) Writev(b, c)
#define GETSOCKOPT(a, b, c, d, e) getsockopt(a, b, c, (char *)d, (int *)e)
#define SETSOCKOPT(a, b, c, d, e) setsockopt(a, b, c, (char *)d, (int)e)
#define GETHOSTBYNAME(a) gethostbyname(a)
#endif
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
#define ACCEPT(a, b, c) accept(a, b, c)
#define CONNECT(a, b, c) connect(a, b, c)
#define CLOSE(a) close(a)
#define READ(a, b, c) read(a, b, c)
#define RECV(a, b, c, d) recv(a, (void *)b, c, d)
#define RECVFROM(a, b, c, d, e, f) recvfrom(a, (char *)b, c, d, (sockaddr *)e, f)
#define RECV_FLAGS MSG_WAITALL
#define SELECT(a, b, c, d, e) select(a, b, c, d, e)
#define SEND(a, b, c, d) send(a, (const int8 *)b, c, d)
#define SENDTO(a, b, c, d, e, f) sendto(a, (const int8 *)b, c, d, e, f)
#define SEND_FLAGS 0
#define SENDFILE(a, b, c, d) sendfile(a, b, c, d)
#define SET_SOCKET_ERROR(x, y) errno = y
#define SOCKET_ERROR_INTERUPT EINTR
#define SOCKET_ERROR_TIMEDOUT EAGAIN
#define WRITE(a, b, c) write(a, b, c)
#define WRITEV(a, b, c) writev(a, b, c)
#define GETSOCKOPT(a, b, c, d, e) getsockopt((int)a, (int)b, (int)c, (void *)d, (socklen_t *)e)
#define SETSOCKOPT(a, b, c, d, e) setsockopt((int)a, (int)b, (int)c, (const void *)d, (int)e)
#define GETHOSTBYNAME(a) gethostbyname(a)
#endif
/*---------------------------------------------------------------------------*/
/* */
/* File Macros */
/* */
/*---------------------------------------------------------------------------*/
#define STRUCT_STAT struct stat
#define LSTAT(x, y) lstat(x, y)
#define FILE_HANDLE FILE *
#define CLEARERR(x) clearerr(x)
#define FCLOSE(x) fclose(x)
#define FEOF(x) feof(x)
#define FERROR(x) ferror(x)
#define FFLUSH(x) fflush(x)
#define FILENO(s) fileno(s)
#define FOPEN(x, y) fopen(x, y)
//#define FREAD(a,b,c,d) fread(a, b, c, d)
#define FSTAT(s, st) fstat(FILENO(s), st)
//#define FWRITE(a,b,c,d) fwrite(a, b, c, d)
#define STAT_BLK_SIZE(x) ((x).st_blksize)
/*---------------------------------------------------------------------------*/
/* */
/* Misc Macros */
/* */
/*---------------------------------------------------------------------------*/
#if defined(WIN32)
#define GET_CLOCK_COUNT(x) QueryPerformanceCounter((LARGE_INTEGER *)x)
#else
#define GET_CLOCK_COUNT(x) gettimeofday(x, NULL)
#endif
#if defined(WIN32)
#define STRTOULL(x) _atoi64(x)
#else
#define STRTOULL(x) strtoull(x, NULL, 10)
#endif
#if defined(WIN32)
#define SNPRINTF _snprintf
#define PRINTF printf
#define VPRINTF vprintf
#define FPRINTF fprintf
#else
#define SNPRINTF snprintf
#define PRINTF printf
#define VPRINTF vprintf
#define FPRINTF fprintf
#endif
#ifdef __cplusplus
}
#endif
#endif /* __HOST_H__ */

View File

@ -1,155 +0,0 @@
/*
* Copyright (C) 2006 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS 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.
*/
#ifndef JSBase_h
#define JSBase_h
#ifndef __cplusplus
#include <stdbool.h>
#endif
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#endif
/* JavaScript engine interface */
/*! @typedef JSContextGroupRef A group that associates JavaScript contexts with one another. Contexts in the same group may share and exchange JavaScript objects. */
typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
/*! @typedef JSContextRef A JavaScript execution context. Holds the global object and other execution state. */
typedef const struct OpaqueJSContext* JSContextRef;
/*! @typedef JSGlobalContextRef A global JavaScript execution context. A JSGlobalContext is a JSContext. */
typedef struct OpaqueJSContext* JSGlobalContextRef;
/*! @typedef JSStringRef A UTF16 character buffer. The fundamental string representation in JavaScript. */
typedef struct OpaqueJSString* JSStringRef;
/*! @typedef JSClassRef A JavaScript class. Used with JSObjectMake to construct objects with custom behavior. */
typedef struct OpaqueJSClass* JSClassRef;
/*! @typedef JSPropertyNameArrayRef An array of JavaScript property names. */
typedef struct OpaqueJSPropertyNameArray* JSPropertyNameArrayRef;
/*! @typedef JSPropertyNameAccumulatorRef An ordered set used to collect the names of a JavaScript object's properties. */
typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
/*! @typedef JSTypedArrayBytesDeallocator A function used to deallocate bytes passed to a Typed Array constructor. The function should take two arguments. The first is a pointer to the bytes that were originally passed to the Typed Array constructor. The second is a pointer to additional information desired at the time the bytes are to be freed. */
typedef void (*JSTypedArrayBytesDeallocator)(void* bytes, void* deallocatorContext);
/* JavaScript data types */
/*! @typedef JSValueRef A JavaScript value. The base type for all JavaScript values, and polymorphic functions on them. */
typedef const struct OpaqueJSValue* JSValueRef;
/*! @typedef JSObjectRef A JavaScript object. A JSObject is a JSValue. */
typedef struct OpaqueJSValue* JSObjectRef;
/* Clang's __has_declspec_attribute emulation */
/* https://clang.llvm.org/docs/LanguageExtensions.html#has-declspec-attribute */
#ifndef __has_declspec_attribute
#define __has_declspec_attribute(x) 0
#endif
/* JavaScript symbol exports */
/* These rules should stay the same as in WebKit/Shared/API/c/WKDeclarationSpecifiers.h */
#undef JS_EXPORT
#if defined(JS_NO_EXPORT)
#define JS_EXPORT
#elif defined(WIN32) || defined(_WIN32) || defined(__CC_ARM) || defined(__ARMCC__) || (__has_declspec_attribute(dllimport) && __has_declspec_attribute(dllexport))
#if defined(BUILDING_JavaScriptCore) || defined(STATICALLY_LINKED_WITH_JavaScriptCore)
#define JS_EXPORT __declspec(dllexport)
#else
#define JS_EXPORT __declspec(dllimport)
#endif
#elif defined(__GNUC__)
#define JS_EXPORT __attribute__((visibility("default")))
#else /* !defined(JS_NO_EXPORT) */
#define JS_EXPORT
#endif /* defined(JS_NO_EXPORT) */
#ifdef __cplusplus
extern "C" {
#endif
/* Script Evaluation */
/*!
@function JSEvaluateScript
@abstract Evaluates a string of JavaScript.
@param ctx The execution context to use.
@param script A JSString containing the script to evaluate.
@param thisObject The object to use as "this," or NULL to use the global object as "this."
@param sourceURL A JSString containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information.
@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSValue that results from evaluating script, or NULL if an exception is thrown.
*/
JS_EXPORT JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
/*!
@function JSCheckScriptSyntax
@abstract Checks for syntax errors in a string of JavaScript.
@param ctx The execution context to use.
@param script A JSString containing the script to check for syntax errors.
@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions.
@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception.
@result true if the script is syntactically correct, otherwise false.
*/
JS_EXPORT bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
/*!
@function JSGarbageCollect
@abstract Performs a JavaScript garbage collection.
@param ctx The execution context to use.
@discussion JavaScript values that are on the machine stack, in a register,
protected by JSValueProtect, set as the global object of an execution context,
or reachable from any such value will not be collected.
During JavaScript execution, you are not required to call this function; the
JavaScript engine will garbage collect as needed. JavaScript values created
within a context group are automatically destroyed when the last reference
to the context group is released.
*/
JS_EXPORT void JSGarbageCollect(JSContextRef ctx);
#ifdef __cplusplus
}
#endif
/* Enable the Objective-C API for platforms with a modern runtime. NOTE: This is duplicated in VM.h. */
#if !defined(JSC_OBJC_API_ENABLED)
#if (defined(__clang__) && defined(__APPLE__) && ((defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)))
#define JSC_OBJC_API_ENABLED 1
#else
#define JSC_OBJC_API_ENABLED 0
#endif
#endif
#endif /* JSBase_h */

View File

@ -1,163 +0,0 @@
/*
* Copyright (C) 2006 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS 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.
*/
#ifndef JSContextRef_h
#define JSContextRef_h
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSValueRef.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Creates a JavaScript context group.
@discussion A JSContextGroup associates JavaScript contexts with one another.
Contexts in the same group may share and exchange JavaScript objects. Sharing and/or exchanging
JavaScript objects between contexts in different groups will produce undefined behavior.
When objects from the same context group are used in multiple threads, explicit
synchronization is required.
A JSContextGroup may need to run deferred tasks on a run loop, such as garbage collection
or resolving WebAssembly compilations. By default, calling JSContextGroupCreate will use
the run loop of the thread it was called on. Currently, there is no API to change a
JSContextGroup's run loop once it has been created.
@result The created JSContextGroup.
*/
JS_EXPORT JSContextGroupRef JSContextGroupCreate(void) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Retains a JavaScript context group.
@param group The JSContextGroup to retain.
@result A JSContextGroup that is the same as group.
*/
JS_EXPORT JSContextGroupRef JSContextGroupRetain(JSContextGroupRef group) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Releases a JavaScript context group.
@param group The JSContextGroup to release.
*/
JS_EXPORT void JSContextGroupRelease(JSContextGroupRef group) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Creates a global JavaScript execution context.
@discussion JSGlobalContextCreate allocates a global object and populates it with all the
built-in JavaScript objects, such as Object, Function, String, and Array.
In WebKit version 4.0 and later, the context is created in a unique context group.
Therefore, scripts may execute in it concurrently with scripts executing in other contexts.
However, you may not use values created in the context in other contexts.
@param globalObjectClass The class to use when creating the global object. Pass
NULL to use the default object class.
@result A JSGlobalContext with a global object of class globalObjectClass.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextCreate(JSClassRef globalObjectClass) JSC_API_AVAILABLE(macos(10.5), ios(7.0));
/*!
@function
@abstract Creates a global JavaScript execution context in the context group provided.
@discussion JSGlobalContextCreateInGroup allocates a global object and populates it with
all the built-in JavaScript objects, such as Object, Function, String, and Array.
@param globalObjectClass The class to use when creating the global object. Pass
NULL to use the default object class.
@param group The context group to use. The created global context retains the group.
Pass NULL to create a unique group for the context.
@result A JSGlobalContext with a global object of class globalObjectClass and a context
group equal to group.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextCreateInGroup(JSContextGroupRef group, JSClassRef globalObjectClass) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Retains a global JavaScript execution context.
@param ctx The JSGlobalContext to retain.
@result A JSGlobalContext that is the same as ctx.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextRetain(JSGlobalContextRef ctx);
/*!
@function
@abstract Releases a global JavaScript execution context.
@param ctx The JSGlobalContext to release.
*/
JS_EXPORT void JSGlobalContextRelease(JSGlobalContextRef ctx);
/*!
@function
@abstract Gets the global object of a JavaScript execution context.
@param ctx The JSContext whose global object you want to get.
@result ctx's global object.
*/
JS_EXPORT JSObjectRef JSContextGetGlobalObject(JSContextRef ctx);
/*!
@function
@abstract Gets the context group to which a JavaScript execution context belongs.
@param ctx The JSContext whose group you want to get.
@result ctx's group.
*/
JS_EXPORT JSContextGroupRef JSContextGetGroup(JSContextRef ctx) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Gets the global context of a JavaScript execution context.
@param ctx The JSContext whose global context you want to get.
@result ctx's global context.
*/
JS_EXPORT JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx) JSC_API_AVAILABLE(macos(10.7), ios(7.0));
/*!
@function
@abstract Gets a copy of the name of a context.
@param ctx The JSGlobalContext whose name you want to get.
@result The name for ctx.
@discussion A JSGlobalContext's name is exposed for remote debugging to make it
easier to identify the context you would like to attach to.
*/
JS_EXPORT JSStringRef JSGlobalContextCopyName(JSGlobalContextRef ctx) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@function
@abstract Sets the remote debugging name for a context.
@param ctx The JSGlobalContext that you want to name.
@param name The remote debugging name to set on ctx.
*/
JS_EXPORT void JSGlobalContextSetName(JSGlobalContextRef ctx, JSStringRef name) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
#ifdef __cplusplus
}
#endif
#endif /* JSContextRef_h */

View File

@ -1,856 +0,0 @@
/*
* Copyright (C) 2006-2019 Apple Inc. All rights reserved.
* Copyright (C) 2008 Kelvin W Sherlock (ksherlock@gmail.com)
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS 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.
*/
#ifndef JSObjectRef_h
#define JSObjectRef_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSValueRef.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
/*!
@enum JSPropertyAttribute
@constant kJSPropertyAttributeNone Specifies that a property has no special attributes.
@constant kJSPropertyAttributeReadOnly Specifies that a property is read-only.
@constant kJSPropertyAttributeDontEnum Specifies that a property should not be enumerated by JSPropertyEnumerators and JavaScript for...in loops.
@constant kJSPropertyAttributeDontDelete Specifies that the delete operation should fail on a property.
*/
enum {
kJSPropertyAttributeNone = 0,
kJSPropertyAttributeReadOnly = 1 << 1,
kJSPropertyAttributeDontEnum = 1 << 2,
kJSPropertyAttributeDontDelete = 1 << 3
};
/*!
@typedef JSPropertyAttributes
@abstract A set of JSPropertyAttributes. Combine multiple attributes by logically ORing them together.
*/
typedef unsigned JSPropertyAttributes;
/*!
@enum JSClassAttribute
@constant kJSClassAttributeNone Specifies that a class has no special attributes.
@constant kJSClassAttributeNoAutomaticPrototype Specifies that a class should not automatically generate a shared prototype for its instance objects. Use kJSClassAttributeNoAutomaticPrototype in combination with JSObjectSetPrototype to manage prototypes manually.
*/
enum {
kJSClassAttributeNone = 0,
kJSClassAttributeNoAutomaticPrototype = 1 << 1
};
/*!
@typedef JSClassAttributes
@abstract A set of JSClassAttributes. Combine multiple attributes by logically ORing them together.
*/
typedef unsigned JSClassAttributes;
/*!
@typedef JSObjectInitializeCallback
@abstract The callback invoked when an object is first created.
@param ctx The execution context to use.
@param object The JSObject being created.
@discussion If you named your function Initialize, you would declare it like this:
void Initialize(JSContextRef ctx, JSObjectRef object);
Unlike the other object callbacks, the initialize callback is called on the least
derived class (the parent class) first, and the most derived class last.
*/
typedef void
(*JSObjectInitializeCallback) (JSContextRef ctx, JSObjectRef object);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef void
(*JSObjectInitializeCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef object);
/*!
@typedef JSObjectFinalizeCallback
@abstract The callback invoked when an object is finalized (prepared for garbage collection). An object may be finalized on any thread.
@param object The JSObject being finalized.
@discussion If you named your function Finalize, you would declare it like this:
void Finalize(JSObjectRef object);
The finalize callback is called on the most derived class first, and the least
derived class (the parent class) last.
You must not call any function that may cause a garbage collection or an allocation
of a garbage collected object from within a JSObjectFinalizeCallback. This includes
all functions that have a JSContextRef parameter.
*/
typedef void
(*JSObjectFinalizeCallback) (JSObjectRef object);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef void
(*JSObjectFinalizeCallbackEx) (JSClassRef jsClass, JSObjectRef object);
/*!
@typedef JSObjectHasPropertyCallback
@abstract The callback invoked when determining whether an object has a property.
@param ctx The execution context to use.
@param object The JSObject to search for the property.
@param propertyName A JSString containing the name of the property look up.
@result true if object has the property, otherwise false.
@discussion If you named your function HasProperty, you would declare it like this:
bool HasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
If this function returns false, the hasProperty request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
This callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value would be expensive.
If this callback is NULL, the getProperty callback will be used to service hasProperty requests.
*/
typedef bool
(*JSObjectHasPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef bool
(*JSObjectHasPropertyCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef object, JSStringRef propertyName);
/*!
@typedef JSObjectGetPropertyCallback
@abstract The callback invoked when getting a property's value.
@param ctx The execution context to use.
@param object The JSObject to search for the property.
@param propertyName A JSString containing the name of the property to get.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result The property's value if object has the property, otherwise NULL.
@discussion If you named your function GetProperty, you would declare it like this:
JSValueRef GetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
If this function returns NULL, the get request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
*/
typedef JSValueRef
(*JSObjectGetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef JSValueRef
(*JSObjectGetPropertyCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@typedef JSObjectSetPropertyCallback
@abstract The callback invoked when setting a property's value.
@param ctx The execution context to use.
@param object The JSObject on which to set the property's value.
@param propertyName A JSString containing the name of the property to set.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if the property was set, otherwise false.
@discussion If you named your function SetProperty, you would declare it like this:
bool SetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
If this function returns false, the set request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
*/
typedef bool
(*JSObjectSetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef bool
(*JSObjectSetPropertyCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
/*!
@typedef JSObjectDeletePropertyCallback
@abstract The callback invoked when deleting a property.
@param ctx The execution context to use.
@param object The JSObject in which to delete the property.
@param propertyName A JSString containing the name of the property to delete.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if propertyName was successfully deleted, otherwise false.
@discussion If you named your function DeleteProperty, you would declare it like this:
bool DeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
If this function returns false, the delete request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
*/
typedef bool
(*JSObjectDeletePropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef bool
(*JSObjectDeletePropertyCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@typedef JSObjectGetPropertyNamesCallback
@abstract The callback invoked when collecting the names of an object's properties.
@param ctx The execution context to use.
@param object The JSObject whose property names are being collected.
@param propertyNames A JavaScript property name accumulator in which to accumulate the names of object's properties.
@discussion If you named your function GetPropertyNames, you would declare it like this:
void GetPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
Property name accumulators are used by JSObjectCopyPropertyNames and JavaScript for...in loops.
Use JSPropertyNameAccumulatorAddName to add property names to accumulator. A class's getPropertyNames callback only needs to provide the names of properties that the class vends through a custom getProperty or setProperty callback. Other properties, including statically declared properties, properties vended by other classes, and properties belonging to object's prototype, are added independently.
*/
typedef void
(*JSObjectGetPropertyNamesCallback) (JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef void
(*JSObjectGetPropertyNamesCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
/*!
@typedef JSObjectCallAsFunctionCallback
@abstract The callback invoked when an object is called as a function.
@param ctx The execution context to use.
@param function A JSObject that is the function being called.
@param thisObject A JSObject that is the 'this' variable in the function's scope.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of the arguments passed to the function.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result A JSValue that is the function's return value.
@discussion If you named your function CallAsFunction, you would declare it like this:
JSValueRef CallAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'myObject.myFunction()', function would be set to myFunction, and thisObject would be set to myObject.
If this callback is NULL, calling your object as a function will throw an exception.
*/
typedef JSValueRef
(*JSObjectCallAsFunctionCallback) (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/* Extension of the above callback with the class and class name of the object being called as a function.
@discussion If this is a JSStaticFunctionEx, className will actually be the name of the function.
*/
typedef JSValueRef
(*JSObjectCallAsFunctionCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSStringRef className, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@typedef JSObjectCallAsConstructorCallback
@abstract The callback invoked when an object is used as a constructor in a 'new' expression.
@param ctx The execution context to use.
@param constructor A JSObject that is the constructor being called.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of the arguments passed to the function.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result A JSObject that is the constructor's return value.
@discussion If you named your function CallAsConstructor, you would declare it like this:
JSObjectRef CallAsConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'new myConstructor()', constructor would be set to myConstructor.
If this callback is NULL, using your object as a constructor in a 'new' expression will throw an exception.
*/
typedef JSObjectRef
(*JSObjectCallAsConstructorCallback) (JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef JSObjectRef
(*JSObjectCallAsConstructorCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@typedef JSObjectHasInstanceCallback
@abstract hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
@param ctx The execution context to use.
@param constructor The JSObject that is the target of the 'instanceof' expression.
@param possibleInstance The JSValue being tested to determine if it is an instance of constructor.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if possibleInstance is an instance of constructor, otherwise false.
@discussion If you named your function HasInstance, you would declare it like this:
bool HasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'someValue instanceof myObject', constructor would be set to myObject and possibleInstance would be set to someValue.
If this callback is NULL, 'instanceof' expressions that target your object will return false.
Standard JavaScript practice calls for objects that implement the callAsConstructor callback to implement the hasInstance callback as well.
*/
typedef bool
(*JSObjectHasInstanceCallback) (JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef bool
(*JSObjectHasInstanceCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
/*!
@typedef JSObjectConvertToTypeCallback
@abstract The callback invoked when converting an object to a particular JavaScript type.
@param ctx The execution context to use.
@param object The JSObject to convert.
@param type A JSType specifying the JavaScript type to convert to.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result The objects's converted value, or NULL if the object was not converted.
@discussion If you named your function ConvertToType, you would declare it like this:
JSValueRef ConvertToType(JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
If this function returns false, the conversion request forwards to object's parent class chain (which includes the default object class).
This function is only invoked when converting an object to number or string. An object converted to boolean is 'true.' An object converted to object is itself.
*/
typedef JSValueRef
(*JSObjectConvertToTypeCallback) (JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
/* Extension of the above callback with the class that the method is being invoked for. */
typedef JSValueRef
(*JSObjectConvertToTypeCallbackEx) (JSContextRef ctx, JSClassRef jsClass, JSObjectRef object, JSType type, JSValueRef* exception);
/*!
@struct JSStaticValue
@abstract This structure describes a statically declared value property.
@field name A null-terminated UTF8 string containing the property's name.
@field getProperty A JSObjectGetPropertyCallback to invoke when getting the property's value.
@field setProperty A JSObjectSetPropertyCallback to invoke when setting the property's value. May be NULL if the ReadOnly attribute is set.
@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
typedef struct {
const char* name;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSPropertyAttributes attributes;
} JSStaticValue;
/* Extension of the above structure for use with class version 1000 */
typedef struct {
const char* name;
JSObjectGetPropertyCallbackEx getPropertyEx;
JSObjectSetPropertyCallbackEx setPropertyEx;
JSPropertyAttributes attributes;
} JSStaticValueEx;
/*!
@struct JSStaticFunction
@abstract This structure describes a statically declared function property.
@field name A null-terminated UTF8 string containing the property's name.
@field callAsFunction A JSObjectCallAsFunctionCallback to invoke when the property is called as a function.
@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
typedef struct {
const char* name;
JSObjectCallAsFunctionCallback callAsFunction;
JSPropertyAttributes attributes;
} JSStaticFunction;
/* Extension of the above structure for use with class version 1000 */
typedef struct {
const char* name;
JSObjectCallAsFunctionCallbackEx callAsFunctionEx;
JSPropertyAttributes attributes;
} JSStaticFunctionEx;
/*!
@struct JSClassDefinition
@abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL.
@field version The version number of this structure. The current version is 0.
@field attributes A logically ORed set of JSClassAttributes to give to the class.
@field className A null-terminated UTF8 string containing the class's name.
@field parentClass A JSClass to set as the class's parent class. Pass NULL use the default object class.
@field staticValues A JSStaticValue array containing the class's statically declared value properties. Pass NULL to specify no statically declared value properties. The array must be terminated by a JSStaticValue whose name field is NULL.
@field staticFunctions A JSStaticFunction array containing the class's statically declared function properties. Pass NULL to specify no statically declared function properties. The array must be terminated by a JSStaticFunction whose name field is NULL.
@field initialize The callback invoked when an object is first created. Use this callback to initialize the object.
@field finalize The callback invoked when an object is finalized (prepared for garbage collection). Use this callback to release resources allocated for the object, and perform other cleanup.
@field hasProperty The callback invoked when determining whether an object has a property. If this field is NULL, getProperty is called instead. The hasProperty callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value is expensive.
@field getProperty The callback invoked when getting a property's value.
@field setProperty The callback invoked when setting a property's value.
@field deleteProperty The callback invoked when deleting a property.
@field getPropertyNames The callback invoked when collecting the names of an object's properties.
@field callAsFunction The callback invoked when an object is called as a function.
@field hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
@field callAsConstructor The callback invoked when an object is used as a constructor in a 'new' expression.
@field convertToType The callback invoked when converting an object to a particular JavaScript type.
@discussion The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties. Statically declared properties autmatically service requests like getProperty, setProperty, and getPropertyNames. Property access callbacks are required only to implement unusual properties, like array indexes, whose names are not known at compile-time.
If you named your getter function "GetX" and your setter function "SetX", you would declare a JSStaticValue array containing "X" like this:
JSStaticValue StaticValueArray[] = {
{ "X", GetX, SetX, kJSPropertyAttributeNone },
{ 0, 0, 0, 0 }
};
Standard JavaScript practice calls for storing function objects in prototypes, so they can be shared. The default JSClass created by JSClassCreate follows this idiom, instantiating objects with a shared, automatically generating prototype containing the class's function objects. The kJSClassAttributeNoAutomaticPrototype attribute specifies that a JSClass should not automatically generate such a prototype. The resulting JSClass instantiates objects with the default object prototype, and gives each instance object its own copy of the class's function objects.
A NULL callback specifies that the default object callback should substitute, except in the case of hasProperty, where it specifies that getProperty should substitute.
*/
typedef struct {
int version; /* default version is 0, use version 1000 for callbacks with extended class information */
JSClassAttributes attributes;
const char* className;
JSClassRef parentClass;
union {
/* version 0 */
struct {
const JSStaticValue* staticValues;
const JSStaticFunction* staticFunctions;
JSObjectInitializeCallback initialize;
JSObjectFinalizeCallback finalize;
JSObjectHasPropertyCallback hasProperty;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSObjectDeletePropertyCallback deleteProperty;
JSObjectGetPropertyNamesCallback getPropertyNames;
JSObjectCallAsFunctionCallback callAsFunction;
JSObjectCallAsConstructorCallback callAsConstructor;
JSObjectHasInstanceCallback hasInstance;
JSObjectConvertToTypeCallback convertToType;
};
/* version 1000 */
struct {
const JSStaticValueEx* staticValuesEx;
const JSStaticFunctionEx* staticFunctionsEx;
JSObjectInitializeCallbackEx initializeEx;
JSObjectFinalizeCallbackEx finalizeEx;
JSObjectHasPropertyCallbackEx hasPropertyEx;
JSObjectGetPropertyCallbackEx getPropertyEx;
JSObjectSetPropertyCallbackEx setPropertyEx;
JSObjectDeletePropertyCallbackEx deletePropertyEx;
JSObjectGetPropertyNamesCallbackEx getPropertyNamesEx;
JSObjectCallAsFunctionCallbackEx callAsFunctionEx;
JSObjectCallAsConstructorCallbackEx callAsConstructorEx;
JSObjectHasInstanceCallbackEx hasInstanceEx;
JSObjectConvertToTypeCallbackEx convertToTypeEx;
};
};
void* privateData; /* version 1000 only */
} JSClassDefinition;
/*!
@const kJSClassDefinitionEmpty
@abstract A JSClassDefinition structure of the current version, filled with NULL pointers and having no attributes.
@discussion Use this constant as a convenience when creating class definitions. For example, to create a class definition with only a finalize method:
JSClassDefinition definition = kJSClassDefinitionEmpty;
definition.finalize = Finalize;
*/
JS_EXPORT extern const JSClassDefinition kJSClassDefinitionEmpty;
/*!
@function
@abstract Creates a JavaScript class suitable for use with JSObjectMake.
@param definition A JSClassDefinition that defines the class.
@result A JSClass with the given definition. Ownership follows the Create Rule.
*/
JS_EXPORT JSClassRef JSClassCreate(const JSClassDefinition* definition);
/*!
@function
@abstract Retains a JavaScript class.
@param jsClass The JSClass to retain.
@result A JSClass that is the same as jsClass.
*/
JS_EXPORT JSClassRef JSClassRetain(JSClassRef jsClass);
/*!
@function
@abstract Releases a JavaScript class.
@param jsClass The JSClass to release.
*/
JS_EXPORT void JSClassRelease(JSClassRef jsClass);
/*!
@function
@abstract Retrieves the private data from a class reference, only possible with classes created with version 1000 (extended callbacks).
@param jsClass The class to get the data from
@result The private data on the class, or NULL, if not set
@discussion Only classes with version 1000 (extended callbacks) can store private data, for other classes always NULL will always be returned.
*/
JS_EXPORT void* JSClassGetPrivate(JSClassRef jsClass);
/*!
@function
@abstract Sets the private data on a class, only possible with classes created with version 1000 (extended callbacks).
@param jsClass The class to set the data on
@param data A void* to set as the private data for the class
@result true if the data has been set on the class, false if the class has not been created with version 1000 (extended callbacks)
@discussion Only classes with version 1000 (extended callbacks) can store private data, for other classes the function always fails. The set pointer is not touched by the engine.
*/
JS_EXPORT bool JSClassSetPrivate(JSClassRef jsClass, void* data);
/*!
@function
@abstract Creates a JavaScript object.
@param ctx The execution context to use.
@param jsClass The JSClass to assign to the object. Pass NULL to use the default object class.
@param data A void* to set as the object's private data. Pass NULL to specify no private data.
@result A JSObject with the given class and private data.
@discussion The default object class does not allocate storage for private data, so you must provide a non-NULL jsClass to JSObjectMake if you want your object to be able to store private data.
data is set on the created object before the intialize methods in its class chain are called. This enables the initialize methods to retrieve and manipulate data through JSObjectGetPrivate.
*/
JS_EXPORT JSObjectRef JSObjectMake(JSContextRef ctx, JSClassRef jsClass, void* data);
/*!
@function
@abstract Convenience method for creating a JavaScript function with a given callback as its implementation.
@param ctx The execution context to use.
@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
@param callAsFunction The JSObjectCallAsFunctionCallback to invoke when the function is called.
@result A JSObject that is a function. The object's prototype will be the default function prototype.
*/
JS_EXPORT JSObjectRef JSObjectMakeFunctionWithCallback(JSContextRef ctx, JSStringRef name, JSObjectCallAsFunctionCallback callAsFunction);
/*!
@function
@abstract Convenience method for creating a JavaScript constructor.
@param ctx The execution context to use.
@param jsClass A JSClass that is the class your constructor will assign to the objects its constructs. jsClass will be used to set the constructor's .prototype property, and to evaluate 'instanceof' expressions. Pass NULL to use the default object class.
@param callAsConstructor A JSObjectCallAsConstructorCallback to invoke when your constructor is used in a 'new' expression. Pass NULL to use the default object constructor.
@result A JSObject that is a constructor. The object's prototype will be the default object prototype.
@discussion The default object constructor takes no arguments and constructs an object of class jsClass with no private data.
*/
JS_EXPORT JSObjectRef JSObjectMakeConstructor(JSContextRef ctx, JSClassRef jsClass, JSObjectCallAsConstructorCallback callAsConstructor);
/*!
@function
@abstract Creates a JavaScript Array object.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of data to populate the Array with. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is an Array.
@discussion The behavior of this function does not exactly match the behavior of the built-in Array constructor. Specifically, if one argument
is supplied, this function returns an array with one element.
*/
JS_EXPORT JSObjectRef JSObjectMakeArray(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Creates a JavaScript Date object, as if by invoking the built-in Date constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the Date Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a Date.
*/
JS_EXPORT JSObjectRef JSObjectMakeDate(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Creates a JavaScript Error object, as if by invoking the built-in Error constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the Error Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a Error.
*/
JS_EXPORT JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Creates a JavaScript RegExp object, as if by invoking the built-in RegExp constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the RegExp Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a RegExp.
*/
JS_EXPORT JSObjectRef JSObjectMakeRegExp(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Creates a JavaScript promise object by invoking the provided executor.
@param ctx The execution context to use.
@param resolve A pointer to a JSObjectRef in which to store the resolve function for the new promise. Pass NULL if you do not care to store the resolve callback.
@param reject A pointer to a JSObjectRef in which to store the reject function for the new promise. Pass NULL if you do not care to store the reject callback.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a promise or NULL if an exception occurred.
*/
JS_EXPORT JSObjectRef JSObjectMakeDeferredPromise(JSContextRef ctx, JSObjectRef* resolve, JSObjectRef* reject, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Creates a function with a given script as its body.
@param ctx The execution context to use.
@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
@param parameterCount An integer count of the number of parameter names in parameterNames.
@param parameterNames A JSString array containing the names of the function's parameters. Pass NULL if parameterCount is 0.
@param body A JSString containing the script to use as the function's body.
@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions.
@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception.
@result A JSObject that is a function, or NULL if either body or parameterNames contains a syntax error. The object's prototype will be the default function prototype.
@discussion Use this method when you want to execute a script repeatedly, to avoid the cost of re-parsing the script before each execution.
*/
JS_EXPORT JSObjectRef JSObjectMakeFunction(JSContextRef ctx, JSStringRef name, unsigned parameterCount, const JSStringRef parameterNames[], JSStringRef body, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
/*!
@function
@abstract Gets an object's prototype.
@param ctx The execution context to use.
@param object A JSObject whose prototype you want to get.
@result A JSValue that is the object's prototype.
*/
JS_EXPORT JSValueRef JSObjectGetPrototype(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Sets an object's prototype.
@param ctx The execution context to use.
@param object The JSObject whose prototype you want to set.
@param value A JSValue to set as the object's prototype.
*/
JS_EXPORT void JSObjectSetPrototype(JSContextRef ctx, JSObjectRef object, JSValueRef value);
/*!
@function
@abstract Tests whether an object has a given property.
@param object The JSObject to test.
@param propertyName A JSString containing the property's name.
@result true if the object has a property whose name matches propertyName, otherwise false.
*/
JS_EXPORT bool JSObjectHasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@function
@abstract Gets a property from an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyName A JSString containing the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The property's value if object has the property, otherwise the undefined value.
*/
JS_EXPORT JSValueRef JSObjectGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@function
@abstract Sets a property on an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyName A JSString containing the property's name.
@param value A JSValueRef to use as the property's value.
@param attributes A logically ORed set of JSPropertyAttributes to give to the property.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
*/
JS_EXPORT void JSObjectSetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception);
/*!
@function
@abstract Deletes a property from an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to delete.
@param propertyName A JSString containing the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the delete operation succeeds, otherwise false (for example, if the property has the kJSPropertyAttributeDontDelete attribute set).
*/
JS_EXPORT bool JSObjectDeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@function
@abstract Tests whether an object has a given property using a JSValueRef as the property key.
@param object The JSObject to test.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the object has a property whose name matches propertyKey, otherwise false.
@discussion This function is the same as performing "propertyKey in object" from JavaScript.
*/
JS_EXPORT bool JSObjectHasPropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Gets a property from an object using a JSValueRef as the property key.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The property's value if object has the property key, otherwise the undefined value.
@discussion This function is the same as performing "object[propertyKey]" from JavaScript.
*/
JS_EXPORT JSValueRef JSObjectGetPropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Sets a property on an object using a JSValueRef as the property key.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@param value A JSValueRef to use as the property's value.
@param attributes A logically ORed set of JSPropertyAttributes to give to the property.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@discussion This function is the same as performing "object[propertyKey] = value" from JavaScript.
*/
JS_EXPORT void JSObjectSetPropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Deletes a property from an object using a JSValueRef as the property key.
@param ctx The execution context to use.
@param object The JSObject whose property you want to delete.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the delete operation succeeds, otherwise false (for example, if the property has the kJSPropertyAttributeDontDelete attribute set).
@discussion This function is the same as performing "delete object[propertyKey]" from JavaScript.
*/
JS_EXPORT bool JSObjectDeletePropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Gets a property from an object by numeric index.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyIndex An integer value that is the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The property's value if object has the property, otherwise the undefined value.
@discussion Calling JSObjectGetPropertyAtIndex is equivalent to calling JSObjectGetProperty with a string containing propertyIndex, but JSObjectGetPropertyAtIndex provides optimized access to numeric properties.
*/
JS_EXPORT JSValueRef JSObjectGetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef* exception);
/*!
@function
@abstract Sets a property on an object by numeric index.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyIndex The property's name as a number.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@discussion Calling JSObjectSetPropertyAtIndex is equivalent to calling JSObjectSetProperty with a string containing propertyIndex, but JSObjectSetPropertyAtIndex provides optimized access to numeric properties.
*/
JS_EXPORT void JSObjectSetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Gets an object's private data.
@param object A JSObject whose private data you want to get.
@result A void* that is the object's private data, if the object has private data, otherwise NULL.
*/
JS_EXPORT void* JSObjectGetPrivate(JSObjectRef object);
/*!
@function
@abstract Sets a pointer to private data on an object.
@param object The JSObject whose private data you want to set.
@param data A void* to set as the object's private data.
@result true if object can store private data, otherwise false.
@discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data.
*/
JS_EXPORT bool JSObjectSetPrivate(JSObjectRef object, void* data);
/*!
@function
@abstract Tests whether an object can be called as a function.
@param ctx The execution context to use.
@param object The JSObject to test.
@result true if the object can be called as a function, otherwise false.
*/
JS_EXPORT bool JSObjectIsFunction(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Calls an object as a function.
@param ctx The execution context to use.
@param object The JSObject to call as a function.
@param thisObject The object to use as "this," or NULL to use the global object as "this."
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the function. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSValue that results from calling object as a function, or NULL if an exception is thrown or object is not a function.
*/
JS_EXPORT JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Tests whether an object can be called as a constructor.
@param ctx The execution context to use.
@param object The JSObject to test.
@result true if the object can be called as a constructor, otherwise false.
*/
JS_EXPORT bool JSObjectIsConstructor(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Calls an object as a constructor.
@param ctx The execution context to use.
@param object The JSObject to call as a constructor.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSObject that results from calling object as a constructor, or NULL if an exception is thrown or object is not a constructor.
*/
JS_EXPORT JSObjectRef JSObjectCallAsConstructor(JSContextRef ctx, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Gets the names of an object's enumerable properties.
@param ctx The execution context to use.
@param object The object whose property names you want to get.
@result A JSPropertyNameArray containing the names object's enumerable properties. Ownership follows the Create Rule.
*/
JS_EXPORT JSPropertyNameArrayRef JSObjectCopyPropertyNames(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Retains a JavaScript property name array.
@param array The JSPropertyNameArray to retain.
@result A JSPropertyNameArray that is the same as array.
*/
JS_EXPORT JSPropertyNameArrayRef JSPropertyNameArrayRetain(JSPropertyNameArrayRef array);
/*!
@function
@abstract Releases a JavaScript property name array.
@param array The JSPropetyNameArray to release.
*/
JS_EXPORT void JSPropertyNameArrayRelease(JSPropertyNameArrayRef array);
/*!
@function
@abstract Gets a count of the number of items in a JavaScript property name array.
@param array The array from which to retrieve the count.
@result An integer count of the number of names in array.
*/
JS_EXPORT size_t JSPropertyNameArrayGetCount(JSPropertyNameArrayRef array);
/*!
@function
@abstract Gets a property name at a given index in a JavaScript property name array.
@param array The array from which to retrieve the property name.
@param index The index of the property name to retrieve.
@result A JSStringRef containing the property name.
*/
JS_EXPORT JSStringRef JSPropertyNameArrayGetNameAtIndex(JSPropertyNameArrayRef array, size_t index);
/*!
@function
@abstract Adds a property name to a JavaScript property name accumulator.
@param accumulator The accumulator object to which to add the property name.
@param propertyName The property name to add.
*/
JS_EXPORT void JSPropertyNameAccumulatorAddName(JSPropertyNameAccumulatorRef accumulator, JSStringRef propertyName);
#ifdef __cplusplus
}
#endif
#endif /* JSObjectRef_h */

View File

@ -1,78 +0,0 @@
/*
* Copyright (C) 2010-2019 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS CONTRIBUTORS
* 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.
*/
#ifndef JSObjectRefPrivate_h
#define JSObjectRefPrivate_h
#include <JavaScriptCore/JSObjectRef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Sets a private property on an object. This private property cannot be accessed from within JavaScript.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to set.
@param propertyName A JSString containing the property's name.
@param value A JSValue to use as the property's value. This may be NULL.
@result true if object can store private data, otherwise false.
@discussion This API allows you to store JS values directly an object in a way that will be ensure that they are kept alive without exposing them to JavaScript code and without introducing the reference cycles that may occur when using JSValueProtect.
The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private properties.
*/
JS_EXPORT bool JSObjectSetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value);
/*!
@function
@abstract Gets a private property from an object.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to get.
@param propertyName A JSString containing the property's name.
@result The property's value if object has the property, otherwise NULL.
*/
JS_EXPORT JSValueRef JSObjectGetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@function
@abstract Deletes a private property from an object.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to delete.
@param propertyName A JSString containing the property's name.
@result true if object can store private data, otherwise false.
@discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data.
*/
JS_EXPORT bool JSObjectDeletePrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
JS_EXPORT JSObjectRef JSObjectGetProxyTarget(JSObjectRef);
JS_EXPORT JSGlobalContextRef JSObjectGetGlobalContext(JSObjectRef object);
#ifdef __cplusplus
}
#endif
#endif // JSObjectRefPrivate_h

View File

@ -1,187 +0,0 @@
/*
* Copyright (C) 2005-2018 Apple Inc. 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. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS CONTRIBUTORS 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.
*/
#pragma once
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <algorithm>
#if !defined(WARN_UNUSED_RETURN)
#define WARN_UNUSED_RETURN
#endif
inline void JSRetain(JSStringRef string) { JSStringRetain(string); }
inline void JSRelease(JSStringRef string) { JSStringRelease(string); }
inline void JSRetain(JSGlobalContextRef context) { JSGlobalContextRetain(context); }
inline void JSRelease(JSGlobalContextRef context) { JSGlobalContextRelease(context); }
enum AdoptTag { Adopt };
template<typename T> class JSRetainPtr {
public:
JSRetainPtr() = default;
JSRetainPtr(T ptr) : m_ptr(ptr) { if (ptr) JSRetain(ptr); }
JSRetainPtr(const JSRetainPtr&);
JSRetainPtr(JSRetainPtr&&);
~JSRetainPtr();
T get() const { return m_ptr; }
void clear();
T leakRef() WARN_UNUSED_RETURN;
T operator->() const { return m_ptr; }
bool operator!() const { return !m_ptr; }
explicit operator bool() const { return m_ptr; }
JSRetainPtr& operator=(const JSRetainPtr&);
JSRetainPtr& operator=(JSRetainPtr&&);
JSRetainPtr& operator=(T);
void swap(JSRetainPtr&);
friend JSRetainPtr<JSStringRef> adopt(JSStringRef);
friend JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef);
// FIXME: Make this private once Apple's internal code is updated to not rely on it.
// https://bugs.webkit.org/show_bug.cgi?id=189644
JSRetainPtr(AdoptTag, T);
private:
T m_ptr { nullptr };
};
JSRetainPtr<JSStringRef> adopt(JSStringRef);
JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef);
template<typename T> inline JSRetainPtr<T>::JSRetainPtr(AdoptTag, T ptr)
: m_ptr(ptr)
{
}
inline JSRetainPtr<JSStringRef> adopt(JSStringRef o)
{
return JSRetainPtr<JSStringRef>(Adopt, o);
}
inline JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef o)
{
return JSRetainPtr<JSGlobalContextRef>(Adopt, o);
}
template<typename T> inline JSRetainPtr<T>::JSRetainPtr(const JSRetainPtr& o)
: m_ptr(o.m_ptr)
{
if (m_ptr)
JSRetain(m_ptr);
}
template<typename T> inline JSRetainPtr<T>::JSRetainPtr(JSRetainPtr&& o)
: m_ptr(o.leakRef())
{
}
template<typename T> inline JSRetainPtr<T>::~JSRetainPtr()
{
if (m_ptr)
JSRelease(m_ptr);
}
template<typename T> inline void JSRetainPtr<T>::clear()
{
if (T ptr = leakRef())
JSRelease(ptr);
}
template<typename T> inline T JSRetainPtr<T>::leakRef()
{
return std::exchange(m_ptr, nullptr);
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<T>& o)
{
return operator=(o.get());
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(JSRetainPtr&& o)
{
if (T ptr = std::exchange(m_ptr, o.leakRef()))
JSRelease(ptr);
return *this;
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(T optr)
{
if (optr)
JSRetain(optr);
if (T ptr = std::exchange(m_ptr, optr))
JSRelease(ptr);
return *this;
}
template<typename T> inline void JSRetainPtr<T>::swap(JSRetainPtr<T>& o)
{
std::swap(m_ptr, o.m_ptr);
}
template<typename T> inline void swap(JSRetainPtr<T>& a, JSRetainPtr<T>& b)
{
a.swap(b);
}
template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() == b.get();
}
template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, U* b)
{
return a.get() == b;
}
template<typename T, typename U> inline bool operator==(T* a, const JSRetainPtr<U>& b)
{
return a == b.get();
}
template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() != b.get();
}
template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, U* b)
{
return a.get() != b;
}
template<typename T, typename U> inline bool operator!=(T* a, const JSRetainPtr<U>& b)
{
return a != b.get();
}

View File

@ -1,148 +0,0 @@
/*
* Copyright (C) 2006 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS 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.
*/
#ifndef JSStringRef_h
#define JSStringRef_h
#include <JavaScriptCore/JSValueRef.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(_NATIVE_WCHAR_T_DEFINED) /* MSVC */ \
&& (!defined(__WCHAR_MAX__) || (__WCHAR_MAX__ > 0xffffU)) /* ISO C/C++ */ \
&& (!defined(WCHAR_MAX) || (WCHAR_MAX > 0xffffU)) /* RVCT */
/*!
@typedef JSChar
@abstract A UTF-16 code unit. One, or a sequence of two, can encode any Unicode
character. As with all scalar types, endianness depends on the underlying
architecture.
*/
typedef unsigned short JSChar;
#else
typedef wchar_t JSChar;
#endif
/*!
@function
@abstract Creates a JavaScript string from a buffer of Unicode characters.
@param chars The buffer of Unicode characters to copy into the new JSString.
@param numChars The number of characters to copy from the buffer pointed to by chars.
@result A JSString containing chars. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSStringCreateWithCharacters(const JSChar* chars, size_t numChars);
/*!
@function
@abstract Creates a JavaScript string from a null-terminated UTF8 string.
@param string The null-terminated UTF8 string to copy into the new JSString.
@result A JSString containing string. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSStringCreateWithUTF8CString(const char* string);
/*!
@function
@abstract Retains a JavaScript string.
@param string The JSString to retain.
@result A JSString that is the same as string.
*/
JS_EXPORT JSStringRef JSStringRetain(JSStringRef string);
/*!
@function
@abstract Releases a JavaScript string.
@param string The JSString to release.
*/
JS_EXPORT void JSStringRelease(JSStringRef string);
/*!
@function
@abstract Returns the number of Unicode characters in a JavaScript string.
@param string The JSString whose length (in Unicode characters) you want to know.
@result The number of Unicode characters stored in string.
*/
JS_EXPORT size_t JSStringGetLength(JSStringRef string);
/*!
@function
@abstract Returns a pointer to the Unicode character buffer that
serves as the backing store for a JavaScript string.
@param string The JSString whose backing store you want to access.
@result A pointer to the Unicode character buffer that serves as string's
backing store, which will be deallocated when string is deallocated.
*/
JS_EXPORT const JSChar* JSStringGetCharactersPtr(JSStringRef string);
/*!
@function
@abstract Returns the maximum number of bytes a JavaScript string will
take up if converted into a null-terminated UTF8 string.
@param string The JSString whose maximum converted size (in bytes) you
want to know.
@result The maximum number of bytes that could be required to convert string into a
null-terminated UTF8 string. The number of bytes that the conversion actually ends
up requiring could be less than this, but never more.
*/
JS_EXPORT size_t JSStringGetMaximumUTF8CStringSize(JSStringRef string);
/*!
@function
@abstract Converts a JavaScript string into a null-terminated UTF8 string,
and copies the result into an external byte buffer.
@param string The source JSString.
@param buffer The destination byte buffer into which to copy a null-terminated
UTF8 representation of string. On return, buffer contains a UTF8 string
representation of string. If bufferSize is too small, buffer will contain only
partial results. If buffer is not at least bufferSize bytes in size,
behavior is undefined.
@param bufferSize The size of the external buffer in bytes.
@result The number of bytes written into buffer (including the null-terminator byte).
*/
JS_EXPORT size_t JSStringGetUTF8CString(JSStringRef string, char* buffer, size_t bufferSize);
/*!
@function
@abstract Tests whether two JavaScript strings match.
@param a The first JSString to test.
@param b The second JSString to test.
@result true if the two strings match, otherwise false.
*/
JS_EXPORT bool JSStringIsEqual(JSStringRef a, JSStringRef b);
/*!
@function
@abstract Tests whether a JavaScript string matches a null-terminated UTF8 string.
@param a The JSString to test.
@param b The null-terminated UTF8 string to test.
@result true if the two strings match, otherwise false.
*/
JS_EXPORT bool JSStringIsEqualToUTF8CString(JSStringRef a, const char* b);
#ifdef __cplusplus
}
#endif
#endif /* JSStringRef_h */

View File

@ -1,180 +0,0 @@
/*
* Copyright (C) 2015 Dominic Szablewski (dominic@phoboslab.org)
* Copyright (C) 2015-2016 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS 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.
*/
#ifndef JSTypedArray_h
#define JSTypedArray_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSValueRef.h>
#ifdef __cplusplus
extern "C" {
#endif
// ------------- Typed Array functions --------------
/*!
@function
@abstract Creates a JavaScript Typed Array object with the given number of elements.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param length The number of elements to be in the new Typed Array.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef that is a Typed Array with all elements set to zero or NULL if there was an error.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArray(JSContextRef ctx, JSTypedArrayType arrayType, size_t length, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing pointer.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the JSTypedArrayData object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef Typed Array whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithBytesNoCopy(JSContextRef ctx, JSTypedArrayType arrayType, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBuffer(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object with the given offset and length.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@param byteOffset The byte offset for the created Typed Array. byteOffset should aligned with the element size of arrayType.
@param length The number of elements to include in the Typed Array.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBufferAndOffset(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, size_t byteOffset, size_t length, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns a temporary pointer to the backing store of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose backing store pointer to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A pointer to the raw data buffer that serves as object's backing store or NULL if object is not a Typed Array object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetTypedArrayBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose length to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the byte length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte length to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The byte length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the byte offset of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte offset to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The byte offset of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteOffset(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the JavaScript Array Buffer object that is used as the backing of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The JSObjectRef whose Typed Array type data pointer to obtain.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef with a JSTypedArrayType of kJSTypedArrayTypeArrayBuffer or NULL if object is not a Typed Array.
*/
JS_EXPORT JSObjectRef JSObjectGetTypedArrayBuffer(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
// ------------- Array Buffer functions -------------
/*!
@function
@abstract Creates a JavaScript Array Buffer object from an existing pointer.
@param ctx The execution context to use.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the Typed Array data object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef Array Buffer whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeArrayBufferWithBytesNoCopy(JSContextRef ctx, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns a pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object.
@param object The Array Buffer object whose internal backing store pointer to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A pointer to the raw data buffer that serves as object's backing store or NULL if object is not an Array Buffer object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetArrayBufferBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the number of bytes in a JavaScript data object.
@param ctx The execution context to use.
@param object The JS Arary Buffer object whose length in bytes to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The number of bytes stored in the data object.
*/
JS_EXPORT size_t JSObjectGetArrayBufferByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
#ifdef __cplusplus
}
#endif
#endif /* JSTypedArray_h */

View File

@ -1,380 +0,0 @@
/*
* Copyright (C) 2006-2019 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS 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.
*/
#ifndef JSValueRef_h
#define JSValueRef_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
/*!
@enum JSType
@abstract A constant identifying the type of a JSValue.
@constant kJSTypeUndefined The unique undefined value.
@constant kJSTypeNull The unique null value.
@constant kJSTypeBoolean A primitive boolean value, one of true or false.
@constant kJSTypeNumber A primitive number value.
@constant kJSTypeString A primitive string value.
@constant kJSTypeObject An object value (meaning that this JSValueRef is a JSObjectRef).
@constant kJSTypeSymbol A primitive symbol value.
*/
typedef enum {
kJSTypeUndefined,
kJSTypeNull,
kJSTypeBoolean,
kJSTypeNumber,
kJSTypeString,
kJSTypeObject,
kJSTypeSymbol JSC_API_AVAILABLE(macos(10.15), ios(13.0))
} JSType;
/*!
@enum JSTypedArrayType
@abstract A constant identifying the Typed Array type of a JSObjectRef.
@constant kJSTypedArrayTypeInt8Array Int8Array
@constant kJSTypedArrayTypeInt16Array Int16Array
@constant kJSTypedArrayTypeInt32Array Int32Array
@constant kJSTypedArrayTypeUint8Array Uint8Array
@constant kJSTypedArrayTypeUint8ClampedArray Uint8ClampedArray
@constant kJSTypedArrayTypeUint16Array Uint16Array
@constant kJSTypedArrayTypeUint32Array Uint32Array
@constant kJSTypedArrayTypeFloat32Array Float32Array
@constant kJSTypedArrayTypeFloat64Array Float64Array
@constant kJSTypedArrayTypeArrayBuffer ArrayBuffer
@constant kJSTypedArrayTypeNone Not a Typed Array
*/
typedef enum {
kJSTypedArrayTypeInt8Array,
kJSTypedArrayTypeInt16Array,
kJSTypedArrayTypeInt32Array,
kJSTypedArrayTypeUint8Array,
kJSTypedArrayTypeUint8ClampedArray,
kJSTypedArrayTypeUint16Array,
kJSTypedArrayTypeUint32Array,
kJSTypedArrayTypeFloat32Array,
kJSTypedArrayTypeFloat64Array,
kJSTypedArrayTypeArrayBuffer,
kJSTypedArrayTypeNone,
} JSTypedArrayType JSC_API_AVAILABLE(macos(10.12), ios(10.0));
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Returns a JavaScript value's type.
@param ctx The execution context to use.
@param value The JSValue whose type you want to obtain.
@result A value of type JSType that identifies value's type.
*/
JS_EXPORT JSType JSValueGetType(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the undefined type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the undefined type, otherwise false.
*/
JS_EXPORT bool JSValueIsUndefined(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the null type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the null type, otherwise false.
*/
JS_EXPORT bool JSValueIsNull(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the boolean type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the boolean type, otherwise false.
*/
JS_EXPORT bool JSValueIsBoolean(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the number type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the number type, otherwise false.
*/
JS_EXPORT bool JSValueIsNumber(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the string type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the string type, otherwise false.
*/
JS_EXPORT bool JSValueIsString(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the symbol type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the symbol type, otherwise false.
*/
JS_EXPORT bool JSValueIsSymbol(JSContextRef ctx, JSValueRef value) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Tests whether a JavaScript value's type is the object type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the object type, otherwise false.
*/
JS_EXPORT bool JSValueIsObject(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value is an object with a given class in its class chain.
@param ctx The execution context to use.
@param value The JSValue to test.
@param jsClass The JSClass to test against.
@result true if value is an object and has jsClass in its class chain, otherwise false.
*/
JS_EXPORT bool JSValueIsObjectOfClass(JSContextRef ctx, JSValueRef value, JSClassRef jsClass);
/*!
@function
@abstract Tests whether a JavaScript value is an array.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value is an array, otherwise false.
*/
JS_EXPORT bool JSValueIsArray(JSContextRef ctx, JSValueRef value) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
/*!
@function
@abstract Tests whether a JavaScript value is a date.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value is a date, otherwise false.
*/
JS_EXPORT bool JSValueIsDate(JSContextRef ctx, JSValueRef value) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
/*!
@function
@abstract Returns a JavaScript value's Typed Array type.
@param ctx The execution context to use.
@param value The JSValue whose Typed Array type to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A value of type JSTypedArrayType that identifies value's Typed Array type, or kJSTypedArrayTypeNone if the value is not a Typed Array object.
*/
JS_EXPORT JSTypedArrayType JSValueGetTypedArrayType(JSContextRef ctx, JSValueRef value, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/* Comparing values */
/*!
@function
@abstract Tests whether two JavaScript values are equal, as compared by the JS == operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the two values are equal, false if they are not equal or an exception is thrown.
*/
JS_EXPORT bool JSValueIsEqual(JSContextRef ctx, JSValueRef a, JSValueRef b, JSValueRef* exception);
/*!
@function
@abstract Tests whether two JavaScript values are strict equal, as compared by the JS === operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@result true if the two values are strict equal, otherwise false.
*/
JS_EXPORT bool JSValueIsStrictEqual(JSContextRef ctx, JSValueRef a, JSValueRef b);
/*!
@function
@abstract Tests whether a JavaScript value is an object constructed by a given constructor, as compared by the JS instanceof operator.
@param ctx The execution context to use.
@param value The JSValue to test.
@param constructor The constructor to test against.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if value is an object constructed by constructor, as compared by the JS instanceof operator, otherwise false.
*/
JS_EXPORT bool JSValueIsInstanceOfConstructor(JSContextRef ctx, JSValueRef value, JSObjectRef constructor, JSValueRef* exception);
/* Creating values */
/*!
@function
@abstract Creates a JavaScript value of the undefined type.
@param ctx The execution context to use.
@result The unique undefined value.
*/
JS_EXPORT JSValueRef JSValueMakeUndefined(JSContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the null type.
@param ctx The execution context to use.
@result The unique null value.
*/
JS_EXPORT JSValueRef JSValueMakeNull(JSContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the boolean type.
@param ctx The execution context to use.
@param boolean The bool to assign to the newly created JSValue.
@result A JSValue of the boolean type, representing the value of boolean.
*/
JS_EXPORT JSValueRef JSValueMakeBoolean(JSContextRef ctx, bool boolean);
/*!
@function
@abstract Creates a JavaScript value of the number type.
@param ctx The execution context to use.
@param number The double to assign to the newly created JSValue.
@result A JSValue of the number type, representing the value of number.
*/
JS_EXPORT JSValueRef JSValueMakeNumber(JSContextRef ctx, double number);
/*!
@function
@abstract Creates a JavaScript value of the string type.
@param ctx The execution context to use.
@param string The JSString to assign to the newly created JSValue. The
newly created JSValue retains string, and releases it upon garbage collection.
@result A JSValue of the string type, representing the value of string.
*/
JS_EXPORT JSValueRef JSValueMakeString(JSContextRef ctx, JSStringRef string);
/*!
@function
@abstract Creates a JavaScript value of the symbol type.
@param ctx The execution context to use.
@param description A description of the newly created symbol value.
@result A unique JSValue of the symbol type, whose description matches the one provided.
*/
JS_EXPORT JSValueRef JSValueMakeSymbol(JSContextRef ctx, JSStringRef description) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/* Converting to and from JSON formatted strings */
/*!
@function
@abstract Creates a JavaScript value from a JSON formatted string.
@param ctx The execution context to use.
@param string The JSString containing the JSON string to be parsed.
@result A JSValue containing the parsed value, or NULL if the input is invalid.
*/
JS_EXPORT JSValueRef JSValueMakeFromJSONString(JSContextRef ctx, JSStringRef string) JSC_API_AVAILABLE(macos(10.7), ios(7.0));
/*!
@function
@abstract Creates a JavaScript string containing the JSON serialized representation of a JS value.
@param ctx The execution context to use.
@param value The value to serialize.
@param indent The number of spaces to indent when nesting. If 0, the resulting JSON will not contains newlines. The size of the indent is clamped to 10 spaces.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSString with the result of serialization, or NULL if an exception is thrown.
*/
JS_EXPORT JSStringRef JSValueCreateJSONString(JSContextRef ctx, JSValueRef value, unsigned indent, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.7), ios(7.0));
/* Converting to primitive values */
/*!
@function
@abstract Converts a JavaScript value to boolean and returns the resulting boolean.
@param ctx The execution context to use.
@param value The JSValue to convert.
@result The boolean result of conversion.
*/
JS_EXPORT bool JSValueToBoolean(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Converts a JavaScript value to number and returns the resulting number.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The numeric result of conversion, or NaN if an exception is thrown.
*/
JS_EXPORT double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to string and copies the result into a JavaScript string.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSString with the result of conversion, or NULL if an exception is thrown. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSValueToStringCopy(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to object and returns the resulting object.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSObject result of conversion, or NULL if an exception is thrown.
*/
JS_EXPORT JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/* Garbage collection */
/*!
@function
@abstract Protects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The JSValue to protect.
@discussion Use this method when you want to store a JSValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void JSValueProtect(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Unprotects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The JSValue to unprotect.
@discussion A value may be protected multiple times and must be unprotected an
equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void JSValueUnprotect(JSContextRef ctx, JSValueRef value);
#ifdef __cplusplus
}
#endif
#endif /* JSValueRef_h */

View File

@ -1,37 +0,0 @@
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
* Copyright (C) 2008 Alp Toker <alp@atoker.com>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS 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.
*/
#ifndef JavaScript_h
#define JavaScript_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSTypedArray.h>
#include <JavaScriptCore/JSValueRef.h>
#endif /* JavaScript_h */

View File

@ -1,80 +0,0 @@
/*
* Copyright (C) 2008, 2009, 2010, 2014 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS 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.
*/
#ifndef __WebKitAvailability__
#define __WebKitAvailability__
#if defined(__APPLE__) && defined(DEFINE_AVAILABILITY_MACROS)
#include <AvailabilityMacros.h>
#include <CoreFoundation/CoreFoundation.h>
#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED < 101100
/* To support availability macros that mention newer OS X versions when building on older OS X versions,
we provide our own definitions of the underlying macros that the availability macros expand to. We're
free to expand the macros as no-ops since frameworks built on older OS X versions only ship bundled with
an application rather than as part of the system.
*/
#ifndef __NSi_10_10 // Building from trunk rather than SDK.
#define __NSi_10_10 introduced=10.0 // Use 10.0 to indicate that everything is available.
#endif
#ifndef __NSi_10_11 // Building from trunk rather than SDK.
#define __NSi_10_11 introduced=10.0 // Use 10.0 to indicate that everything is available.
#endif
#ifndef __NSi_10_12 // Building from trunk rather than SDK.
#define __NSi_10_12 introduced=10.0 // Use 10.0 to indicate that everything is available.
#endif
#ifndef __AVAILABILITY_INTERNAL__MAC_10_9
#define __AVAILABILITY_INTERNAL__MAC_10_9
#endif
#ifndef __AVAILABILITY_INTERNAL__MAC_10_10
#define __AVAILABILITY_INTERNAL__MAC_10_10
#endif
#ifndef AVAILABLE_MAC_OS_X_VERSION_10_9_AND_LATER
#define AVAILABLE_MAC_OS_X_VERSION_10_9_AND_LATER
#endif
#ifndef AVAILABLE_MAC_OS_X_VERSION_10_10_AND_LATER
#define AVAILABLE_MAC_OS_X_VERSION_10_10_AND_LATER
#endif
#endif /* !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED < 101100 */
#if defined(BUILDING_GTK__)
#undef JSC_API_AVAILABLE
#define JSC_API_AVAILABLE(...)
#endif
#else
#define JSC_API_AVAILABLE(...)
#endif
#endif /* __WebKitAvailability__ */

View File

@ -1,120 +0,0 @@
/*---------------------------------------------------------------------------*/
/* */
/* Socket.h - Passive Socket Decleration. */
/* */
/* Author : Mark Carrier (mark@carrierlabs.com) */
/* */
/*---------------------------------------------------------------------------*/
/* Copyright (c) 2007-2009 CarrierLabs, LLC. 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.
*
* 4. The name "CarrierLabs" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* mark@carrierlabs.com.
*
* THIS SOFTWARE IS PROVIDED BY MARK CARRIER ``AS IS'' AND ANY
* EXPRESSED 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 MARK CARRIER OR
* ITS CONTRIBUTORS 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.
*----------------------------------------------------------------------------*/
#ifndef __PASSIVESOCKET_H__
#define __PASSIVESOCKET_H__
#include "ActiveSocket.h"
/// Provides a platform independent class to create a passive socket.
/// A passive socket is used to create a "listening" socket. This type
/// of object would be used when an application needs to wait for
/// inbound connections. Support for CSimpleSocket::SocketTypeTcp,
/// CSimpleSocket::SocketTypeUdp, and CSimpleSocket::SocketTypeRaw is handled
/// in a similar fashion. The big difference is that the method
/// CPassiveSocket::Accept should not be called on the latter two socket
/// types.
class CPassiveSocket : public CSimpleSocket
{
public:
CPassiveSocket(CSocketType type = SocketTypeTcp);
virtual ~CPassiveSocket()
{
Close();
};
/// Extracts the first connection request on the queue of pending
/// connections and creates a newly connected socket. Used with
/// CSocketType CSimpleSocket::SocketTypeTcp. It is the responsibility of
/// the caller to delete the returned object when finished.
/// @return if successful a pointer to a newly created CActiveSocket object
/// will be returned and the internal error condition of the CPassiveSocket
/// object will be CPassiveSocket::SocketSuccess. If an error condition was encountered
/// the NULL will be returned and one of the following error conditions will be set:
/// CPassiveSocket::SocketEwouldblock, CPassiveSocket::SocketInvalidSocket,
/// CPassiveSocket::SocketConnectionAborted, CPassiveSocket::SocketInterrupted
/// CPassiveSocket::SocketProtocolError, CPassiveSocket::SocketFirewallError
virtual CActiveSocket *Accept(void);
/// Bind to a multicast group on a specified interface, multicast group, and port
///
/// @param pInterface - interface on which to bind.
/// @param pGroup - multicast group address to bind.
/// @param nPort - port on which multicast
/// @return true if able to bind to interface and multicast group.
/// If not successful, the false is returned and one of the following error
/// condiitions will be set: CPassiveSocket::SocketAddressInUse, CPassiveSocket::SocketProtocolError,
/// CPassiveSocket::SocketInvalidSocket. The following socket errors are for Linux/Unix
/// derived systems only: CPassiveSocket::SocketInvalidSocketBuffer
bool BindMulticast(const char *pInterface, const char *pGroup, uint16 nPort);
/// Create a listening socket at local ip address 'x.x.x.x' or 'localhost'
/// if pAddr is NULL on port nPort.
///
/// @param pAddr specifies the IP address on which to listen.
/// @param nPort specifies the port on which to listen.
/// @param nConnectionBacklog specifies connection queue backlog (default 30,000)
/// @return true if a listening socket was created.
/// If not successful, the false is returned and one of the following error
/// conditions will be set: CPassiveSocket::SocketAddressInUse, CPassiveSocket::SocketProtocolError,
/// CPassiveSocket::SocketInvalidSocket. The following socket errors are for Linux/Unix
/// derived systems only: CPassiveSocket::SocketInvalidSocketBuffer
virtual bool Listen(const char *pAddr, uint16 nPort, int32 nConnectionBacklog = 30000);
/// Attempts to send a block of data on an established connection.
/// @param pBuf block of data to be sent.
/// @param bytesToSend size of data block to be sent.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred. If an error was signaled then one
/// of the following error codes will be set: CPassiveSocket::SocketInvalidSocket,
/// CPassiveSocket::SocketEwouldblock, SimpleSocket::SocketConnectionReset,
/// CPassiveSocket::SocketInvalidSocketBuffer, CPassiveSocket::SocketInterrupted,
/// CPassiveSocket::SocketProtocolError, CPassiveSocket::SocketNotconnected
/// <br>\b Note: This function is used only for a socket of type
/// CSimpleSocket::SocketTypeUdp
virtual int32 Send(const uint8 *pBuf, size_t bytesToSend);
private:
struct ip_mreq m_stMulticastRequest; /// group address for multicast
};
#endif // __PASSIVESOCKET_H__

View File

@ -1,617 +0,0 @@
/*---------------------------------------------------------------------------*/
/* */
/* SimpleSocket.h - Simple Socket base class decleration. */
/* */
/* Author : Mark Carrier (mark@carrierlabs.com) */
/* */
/*---------------------------------------------------------------------------*/
/* Copyright (c) 2007-2009 CarrierLabs, LLC. 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.
*
* 4. The name "CarrierLabs" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* mark@carrierlabs.com.
*
* THIS SOFTWARE IS PROVIDED BY MARK CARRIER ``AS IS'' AND ANY
* EXPRESSED 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 MARK CARRIER OR
* ITS CONTRIBUTORS 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.
*----------------------------------------------------------------------------*/
#ifndef __SOCKET_H__
#define __SOCKET_H__
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/ip.h>
#include <netdb.h>
#endif
#ifdef _LINUX
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/if.h>
#include <sys/sendfile.h>
#endif
#ifdef _DARWIN
#include <net/if.h>
#endif
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
#include <sys/time.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
#endif
#ifdef _WIN32
#include <io.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define IPTOS_LOWDELAY 0x10
#endif
#include "Host.h"
#include "StatTimer.h"
//-----------------------------------------------------------------------------
// General class macro definitions and typedefs
//-----------------------------------------------------------------------------
#ifndef INVALID_SOCKET
#define INVALID_SOCKET ~(0)
#endif
#define SOCKET_SENDFILE_BLOCKSIZE 8192
/// Provides a platform independent class to for socket development.
/// This class is designed to abstract socket communication development in a
/// platform independent manner.
/// - Socket types
/// -# CActiveSocket Class
/// -# CPassiveSocket Class
class CSimpleSocket
{
public:
/// Defines the three possible states for shuting down a socket.
typedef enum
{
Receives = SHUT_RD, ///< Shutdown passive socket.
Sends = SHUT_WR, ///< Shutdown active socket.
Both = SHUT_RDWR ///< Shutdown both active and passive sockets.
} CShutdownMode;
/// Defines the socket types defined by CSimpleSocket class.
typedef enum
{
SocketTypeInvalid, ///< Invalid socket type.
SocketTypeTcp, ///< Defines socket as TCP socket.
SocketTypeUdp, ///< Defines socket as UDP socket.
SocketTypeTcp6, ///< Defines socket as IPv6 TCP socket.
SocketTypeUdp6, ///< Defines socket as IPv6 UDP socket.
SocketTypeRaw ///< Provides raw network protocol access.
} CSocketType;
/// Defines all error codes handled by the CSimpleSocket class.
typedef enum
{
SocketError = -1, ///< Generic socket error translates to error below.
SocketSuccess = 0, ///< No socket error.
SocketInvalidSocket, ///< Invalid socket handle.
SocketInvalidAddress, ///< Invalid destination address specified.
SocketInvalidPort, ///< Invalid destination port specified.
SocketConnectionRefused, ///< No server is listening at remote address.
SocketTimedout, ///< Timed out while attempting operation.
SocketEwouldblock, ///< Operation would block if socket were blocking.
SocketNotconnected, ///< Currently not connected.
SocketEinprogress, ///< Socket is non-blocking and the connection cannot be completed immediately
SocketInterrupted, ///< Call was interrupted by a signal that was caught before a valid connection arrived.
SocketConnectionAborted, ///< The connection has been aborted.
SocketProtocolError, ///< Invalid protocol for operation.
SocketFirewallError, ///< Firewall rules forbid connection.
SocketInvalidSocketBuffer, ///< The receive buffer point outside the process's address space.
SocketConnectionReset, ///< Connection was forcibly closed by the remote host.
SocketAddressInUse, ///< Address already in use.
SocketInvalidPointer, ///< Pointer type supplied as argument is invalid.
SocketEunknown ///< Unknown error please report to mark@carrierlabs.com
} CSocketError;
public:
CSimpleSocket(CSocketType type = SocketTypeTcp);
CSimpleSocket(CSimpleSocket &socket);
virtual ~CSimpleSocket()
{
if (m_pBuffer != NULL)
{
delete[] m_pBuffer;
m_pBuffer = NULL;
}
};
/// Initialize instance of CSocket. This method MUST be called before an
/// object can be used. Errors : CSocket::SocketProtocolError,
/// CSocket::SocketInvalidSocket,
/// @return true if properly initialized.
virtual bool Initialize(void);
/// Close socket
/// @return true if successfully closed otherwise returns false.
virtual bool Close(void);
/// Shutdown shut down socket send and receive operations
/// CShutdownMode::Receives - Disables further receive operations.
/// CShutdownMode::Sends - Disables further send operations.
/// CShutdownBoth:: - Disables further send and receive operations.
/// @param nShutdown specifies the type of shutdown.
/// @return true if successfully shutdown otherwise returns false.
virtual bool Shutdown(CShutdownMode nShutdown);
/// Examine the socket descriptor sets currently owned by the instance of
/// the socket class (the readfds, writefds, and errorfds parameters) to
/// see whether some of their descriptors are ready for reading, are ready
/// for writing, or have an exceptional condition pending, respectively.
/// Block until an event happens on the specified file descriptors.
/// @return true if socket has data ready, or false if not ready or timed out.
virtual bool Select(void)
{
return Select(0, 0);
};
/// Examine the socket descriptor sets currently owned by the instance of
/// the socket class (the readfds, writefds, and errorfds parameters) to
/// see whether some of their descriptors are ready for reading, are ready
/// for writing, or have an exceptional condition pending, respectively.
/// @param nTimeoutSec timeout in seconds for select.
/// @param nTimeoutUSec timeout in micro seconds for select.
/// @return true if socket has data ready, or false if not ready or timed out.
virtual bool Select(int32 nTimeoutSec, int32 nTimeoutUSec);
/// Does the current instance of the socket object contain a valid socket
/// descriptor.
/// @return true if the socket object contains a valid socket descriptor.
virtual bool IsSocketValid(void)
{
return (m_socket != SocketError);
};
/// Provides a standard error code for cross platform development by
/// mapping the operating system error to an error defined by the CSocket
/// class.
void TranslateSocketError(void);
/// Returns a human-readable description of the given error code
/// or the last error code of a socket
static const char *DescribeError(CSocketError err);
inline const char *DescribeError()
{
return DescribeError(m_socketErrno);
};
/// Attempts to receive a block of data on an established connection.
/// @param nMaxBytes maximum number of bytes to receive.
/// @param pBuffer, memory where to receive the data,
/// NULL receives to internal buffer returned with GetData()
/// Non-NULL receives directly there, but GetData() will return WRONG ptr!
/// @return number of bytes actually received.
/// @return of zero means the connection has been shutdown on the other side.
/// @return of -1 means that an error has occurred.
virtual int32 Receive(int32 nMaxBytes = 1, uint8 *pBuffer = 0);
/// Attempts to send a block of data on an established connection.
/// @param pBuf block of data to be sent.
/// @param bytesToSend size of data block to be sent.
/// @return number of bytes actually sent.
/// @return of zero means the connection has been shutdown on the other side.
/// @return of -1 means that an error has occurred.
virtual int32 Send(const uint8 *pBuf, size_t bytesToSend);
/// Attempts to send at most nNumItem blocks described by sendVector
/// to the socket descriptor associated with the socket object.
/// @param sendVector pointer to an array of iovec structures
/// @param nNumItems number of items in the vector to process
/// <br>\b NOTE: Buffers are processed in the order specified.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred.
virtual int32 Send(const struct iovec *sendVector, int32 nNumItems);
/// Copies data between one file descriptor and another.
/// On some systems this copying is done within the kernel, and thus is
/// more efficient than the combination of CSimpleSocket::Send and
/// CSimpleSocket::Receive, which would require transferring data to and
/// from user space.
/// <br>\b Note: This is available on all implementations, but the kernel
/// implementation is only available on Unix type systems.
/// @param nOutFd descriptor opened for writing.
/// @param nInFd descriptor opened for reading.
/// @param pOffset from which to start reading data from input file.
/// @param nCount number of bytes to copy between file descriptors.
/// @return number of bytes written to the out socket descriptor.
virtual int32 SendFile(int32 nOutFd, int32 nInFd, off_t *pOffset, int32 nCount);
/// Returns blocking/non-blocking state of socket.
/// @return true if the socket is non-blocking, else return false.
bool IsNonblocking(void)
{
return (m_bIsBlocking == false);
};
/// Set the socket to blocking.
/// @return true if successful set to blocking, else return false;
bool SetBlocking(void);
/// Set the socket as non-blocking.
/// @return true if successful set to non-blocking, else return false;
bool SetNonblocking(void);
/// Get a pointer to internal receive buffer. The user MUST not free this
/// pointer when finished. This memory is managed internally by the CSocket
/// class.
/// @return pointer to data if valid, else returns NULL.
uint8 *GetData(void)
{
return m_pBuffer;
};
/// Returns the number of bytes received on the last call to
/// CSocket::Receive().
/// @return number of bytes received.
int32 GetBytesReceived(void)
{
return m_nBytesReceived;
};
/// Returns the number of bytes sent on the last call to
/// CSocket::Send().
/// @return number of bytes sent.
int32 GetBytesSent(void)
{
return m_nBytesSent;
};
/// Controls the actions taken when CSimpleSocket::Close is executed on a
/// socket object that has unsent data. The default value for this option
/// is \b off.
/// - Following are the three possible scenarios.
/// -# \b bEnable is false, CSimpleSocket::Close returns immediately, but
/// any unset data is transmitted (after CSimpleSocket::Close returns)
/// -# \b bEnable is true and \b nTime is zero, CSimpleSocket::Close return
/// immediately and any unsent data is discarded.
/// -# \b bEnable is true and \b nTime is nonzero, CSimpleSocket::Close does
/// not return until all unsent data is transmitted (or the connection is
/// Closed by the remote system).
/// <br><p>
/// @param bEnable true to enable option false to disable option.
/// @param nTime time in seconds to linger.
/// @return true if option successfully set
bool SetOptionLinger(bool bEnable, uint16 nTime);
/// Tells the kernel that even if this port is busy (in the TIME_WAIT state),
/// go ahead and reuse it anyway. If it is busy, but with another state,
/// you will still get an address already in use error.
/// @return true if option successfully set
bool SetOptionReuseAddr();
/// Gets the timeout value that specifies the maximum number of seconds a
/// call to CSimpleSocket::Open waits until it completes.
/// @return the length of time in seconds
int32 GetConnectTimeoutSec(void)
{
return m_stConnectTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Open waits until it completes.
/// @return the length of time in microseconds
int32 GetConnectTimeoutUSec(void)
{
return m_stConnectTimeout.tv_usec;
};
/// Sets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Receive waits until it completes. Use the method
/// CSimpleSocket::SetReceiveTimeout to specify the number of seconds to wait.
/// If a call to CSimpleSocket::Receive has blocked for the specified length of
/// time without receiving additional data, it returns with a partial count
/// or CSimpleSocket::GetSocketError set to CSimpleSocket::SocketEwouldblock if no data
/// were received.
/// @param nConnectTimeoutSec of timeout in seconds.
/// @param nConnectTimeoutUsec of timeout in microseconds.
/// @return true if socket connection timeout was successfully set.
void SetConnectTimeout(int32 nConnectTimeoutSec, int32 nConnectTimeoutUsec = 0)
{
m_stConnectTimeout.tv_sec = nConnectTimeoutSec;
m_stConnectTimeout.tv_usec = nConnectTimeoutUsec;
};
/// Gets the timeout value that specifies the maximum number of seconds a
/// a call to CSimpleSocket::Receive waits until it completes.
/// @return the length of time in seconds
int32 GetReceiveTimeoutSec(void)
{
return m_stRecvTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Receive waits until it completes.
/// @return the length of time in microseconds
int32 GetReceiveTimeoutUSec(void)
{
return m_stRecvTimeout.tv_usec;
};
/// Sets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Receive waits until it completes. Use the method
/// CSimpleSocket::SetReceiveTimeout to specify the number of seconds to wait.
/// If a call to CSimpleSocket::Receive has blocked for the specified length of
/// time without receiving additional data, it returns with a partial count
/// or CSimpleSocket::GetSocketError set to CSimpleSocket::SocketEwouldblock if no data
/// were received.
/// @param nRecvTimeoutSec of timeout in seconds.
/// @param nRecvTimeoutUsec of timeout in microseconds.
/// @return true if socket timeout was successfully set.
bool SetReceiveTimeout(int32 nRecvTimeoutSec, int32 nRecvTimeoutUsec = 0);
/// Enable/disable multicast for a socket. This options is only valid for
/// socket descriptors of type CSimpleSocket::SocketTypeUdp.
/// @return true if multicast was enabled or false if socket type is not
/// CSimpleSocket::SocketTypeUdp and the error will be set to
/// CSimpleSocket::SocketProtocolError
bool SetMulticast(bool bEnable, uint8 multicastTTL = 1);
/// Return true if socket is multicast or false is socket is unicast
/// @return true if multicast is enabled
bool GetMulticast()
{
return m_bIsMulticast;
};
/// Bind socket to a specific interface when using multicast.
/// @return true if successfully bound to interface
bool BindInterface(const char *pInterface);
/// Gets the timeout value that specifies the maximum number of seconds a
/// a call to CSimpleSocket::Send waits until it completes.
/// @return the length of time in seconds
int32 GetSendTimeoutSec(void)
{
return m_stSendTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Send waits until it completes.
/// @return the length of time in microseconds
int32 GetSendTimeoutUSec(void)
{
return m_stSendTimeout.tv_usec;
};
/// Gets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Send waits until it completes.
/// @return the length of time in seconds
bool SetSendTimeout(int32 nSendTimeoutSec, int32 nSendTimeoutUsec = 0);
/// Returns the last error that occured for the instace of the CSimpleSocket
/// instance. This method should be called immediately to retrieve the
/// error code for the failing mehtod call.
/// @return last error that occured.
CSocketError GetSocketError(void)
{
return m_socketErrno;
};
/*
CSocketError GetSocketError(void) {
CSocketError err = m_socketErrno;
m_socketErrno = SocketSuccess;
return err;
};
*/
/// Get the total time the of the last operation in milliseconds.
/// @return number of milliseconds of last operation.
uint32 GetTotalTimeMs()
{
return m_timer.GetMilliSeconds();
};
/// Get the total time the of the last operation in microseconds.
/// @return number of microseconds or last operation.
uint32 GetTotalTimeUsec()
{
return m_timer.GetMicroSeconds();
};
/// Return Differentiated Services Code Point (DSCP) value currently set on the socket object.
/// @return DSCP for current socket object.
/// <br><br> \b NOTE: Windows special notes http://support.microsoft.com/kb/248611.
int GetSocketDscp(void);
/// Set Differentiated Services Code Point (DSCP) for socket object.
/// @param nDscp value of TOS setting which will be converted to DSCP
/// @return true if DSCP value was properly set
/// <br><br> \b NOTE: Windows special notes http://support.microsoft.com/kb/248611.
bool SetSocketDscp(int nDscp);
/// Return socket descriptor
/// @return socket descriptor which is a signed 32 bit integer.
SOCKET GetSocketDescriptor()
{
return m_socket;
};
/// Return socket descriptor
/// @return socket descriptor which is a signed 32 bit integer.
CSocketType GetSocketType()
{
return m_nSocketType;
};
/// Returns clients Internet host address as a string in standard numbers-and-dots notation.
/// @return NULL if invalid
const char *GetClientAddr()
{
return inet_ntoa(m_stClientSockaddr.sin_addr);
};
/// Returns the port number on which the client is connected.
/// @return client port number.
uint16 GetClientPort()
{
return m_stClientSockaddr.sin_port;
};
/// Returns server Internet host address as a string in standard numbers-and-dots notation.
/// @return NULL if invalid
const char *GetServerAddr()
{
return inet_ntoa(m_stServerSockaddr.sin_addr);
};
/// Returns the port number on which the server is connected.
/// @return server port number.
uint16 GetServerPort()
{
return ntohs(m_stServerSockaddr.sin_port);
};
/// Get the TCP receive buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the receive buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP receive buffer window size if successful.
uint32 GetReceiveWindowSize()
{
return GetWindowSize(SO_RCVBUF);
};
/// Get the TCP send buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the send buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP receive buffer window size if successful.
uint32 GetSendWindowSize()
{
return GetWindowSize(SO_SNDBUF);
};
/// Set the TCP receive buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the receive buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP send buffer window size if successful.
uint32 SetReceiveWindowSize(uint32 nWindowSize)
{
return SetWindowSize(SO_RCVBUF, nWindowSize);
};
/// Set the TCP send buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the send buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP send buffer window size if successful.
uint32 SetSendWindowSize(uint32 nWindowSize)
{
return SetWindowSize(SO_SNDBUF, nWindowSize);
};
/// Disable the Nagle algorithm (Set TCP_NODELAY to true)
/// @return false if failed to set socket option otherwise return true;
bool DisableNagleAlgoritm();
/// Enable the Nagle algorithm (Set TCP_NODELAY to false)
/// @return false if failed to set socket option otherwise return true;
bool EnableNagleAlgoritm();
protected:
/// Set internal socket error to that specified error
/// @param error type of error
void SetSocketError(CSimpleSocket::CSocketError error)
{
m_socketErrno = error;
};
/// Set object socket handle to that specified as parameter
/// @param socket value of socket descriptor
void SetSocketHandle(SOCKET socket)
{
m_socket = socket;
};
private:
/// Generic function used to get the send/receive window size
/// @return zero on failure else the number of bytes of the TCP window size if successful.
uint32 GetWindowSize(uint32 nOptionName);
/// Generic function used to set the send/receive window size
/// @return zero on failure else the number of bytes of the TCP window size if successful.
uint32 SetWindowSize(uint32 nOptionName, uint32 nWindowSize);
/// Attempts to send at most nNumItem blocks described by sendVector
/// to the socket descriptor associated with the socket object.
/// @param sendVector pointer to an array of iovec structures
/// @param nNumItems number of items in the vector to process
/// <br>\b Note: This implementation is for systems that don't natively
/// support this functionality.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred.
int32 Writev(const struct iovec *pVector, size_t nCount);
/// Flush the socket descriptor owned by the object.
/// @return true data was successfully sent, else return false;
bool Flush();
CSimpleSocket *operator=(CSimpleSocket &socket);
protected:
SOCKET m_socket; /// socket handle
CSocketError m_socketErrno; /// number of last error
uint8 *m_pBuffer; /// internal send/receive buffer
int32 m_nBufferSize; /// size of internal send/receive buffer
int32 m_nSocketDomain; /// socket type PF_INET, PF_INET6
CSocketType m_nSocketType; /// socket type - UDP, TCP or RAW
int32 m_nBytesReceived; /// number of bytes received
int32 m_nBytesSent; /// number of bytes sent
uint32 m_nFlags; /// socket flags
bool m_bIsBlocking; /// is socket blocking
bool m_bIsMulticast; /// is the UDP socket multicast;
struct timeval m_stConnectTimeout; /// connection timeout
struct timeval m_stRecvTimeout; /// receive timeout
struct timeval m_stSendTimeout; /// send timeout
struct sockaddr_in m_stServerSockaddr; /// server address
struct sockaddr_in m_stClientSockaddr; /// client address
struct sockaddr_in m_stMulticastGroup; /// multicast group to bind to
struct linger m_stLinger; /// linger flag
CStatTimer m_timer; /// internal statistics.
#ifdef WIN32
WSADATA m_hWSAData; /// Windows
#endif
fd_set m_writeFds; /// write file descriptor set
fd_set m_readFds; /// read file descriptor set
fd_set m_errorFds; /// error file descriptor set
};
#endif /* __SOCKET_H__ */

View File

@ -1,110 +0,0 @@
/*----------------------------------------------------------------------------*/
/* */
/* StatTimer.h: interface for the CStatTimer class. */
/* */
/* Author: Mark Carrier (mark@carrierlabs.com) */
/* */
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2006 CarrierLabs, LLC. 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.
*
* 4. The name "CarrierLabs" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* mark@carrierlabs.com.
*
* THIS SOFTWARE IS PROVIDED BY MARK CARRIER ``AS IS'' AND ANY
* EXPRESSED 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 MARK CARRIER OR
* ITS CONTRIBUTORS 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.
*----------------------------------------------------------------------------*/
#ifndef __CSTATTIMER_H__
#define __CSTATTIMER_H__
#include <string.h>
#ifdef WIN32
#include <winsock2.h>
#include <time.h>
#endif
#ifdef _LINUX
#include <stdio.h>
#include <sys/time.h>
#endif
#include "Host.h"
#if defined(WIN32)
#define GET_CLOCK_COUNT(x) QueryPerformanceCounter((LARGE_INTEGER *)x)
#else
#define GET_CLOCK_COUNT(x) gettimeofday(x, NULL)
#endif
#define MILLISECONDS_CONVERSION 1000
#define MICROSECONDS_CONVERSION 1000000
/// Class to abstract socket communications in a cross platform manner.
/// This class is designed
class CStatTimer
{
public:
CStatTimer(){};
~CStatTimer(){};
void Initialize()
{
memset(&m_startTime, 0, sizeof(struct timeval));
memset(&m_endTime, 0, sizeof(struct timeval));
};
struct timeval GetStartTime() { return m_startTime; };
void SetStartTime() { GET_CLOCK_COUNT(&m_startTime); };
struct timeval GetEndTime() { return m_endTime; };
void SetEndTime() { GET_CLOCK_COUNT(&m_endTime); };
uint32 GetMilliSeconds() { return (CalcTotalUSec() / MILLISECONDS_CONVERSION); };
uint32 GetMicroSeconds() { return (CalcTotalUSec()); };
uint32 GetSeconds() { return (CalcTotalUSec() / MICROSECONDS_CONVERSION); };
uint32 GetCurrentTime()
{
struct timeval tmpTime;
GET_CLOCK_COUNT(&tmpTime);
return ((tmpTime.tv_sec * MICROSECONDS_CONVERSION) + tmpTime.tv_usec);
};
private:
uint32 CalcTotalUSec() { return (((m_endTime.tv_sec - m_startTime.tv_sec) * MICROSECONDS_CONVERSION) +
(m_endTime.tv_usec - m_startTime.tv_usec)); };
private:
struct timeval m_startTime;
struct timeval m_endTime;
};
#endif // __CSTATTIMER_H__

View File

@ -1,279 +0,0 @@
///
/// @file Bitmap.h
///
/// @brief The header for the Bitmap class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/Geometry.h>
namespace ultralight {
#pragma pack(push, 1)
///
/// The various Bitmap formats.
///
enum UExport BitmapFormat {
/**
* Alpha channel only, 8-bits per pixel.
*
* Encoding: 8-bits per channel, unsigned normalized.
*
* Color-space: Linear (no gamma), alpha-coverage only.
*/
kBitmapFormat_A8_UNORM,
/**
* Blue Green Red Alpha channels, 32-bits per pixel.
*
* Encoding: 8-bits per channel, unsigned normalized.
*
* Color-space: sRGB gamma with premultiplied linear alpha channel.
*
* NOTE: Alpha is premultiplied with BGR channels _before_ sRGB gamma is
* applied so we can use sRGB conversion hardware and perform all
* blending in linear space on GPU.
*/
kBitmapFormat_BGRA8_UNORM_SRGB,
};
///
/// Macro to get the bytes per pixel from a BitmapFormat
///
#define GetBytesPerPixel(x) (x == kBitmapFormat_A8_UNORM? 1 : 4)
///
/// @brief Bitmap container with basic blitting and conversion routines.
///
class UExport Bitmap : public RefCounted {
public:
///
/// Create an empty Bitmap. No pixels will be allocated.
///
static Ref<Bitmap> Create();
///
/// Create a Bitmap with a certain configuration. Pixels will be allocated
/// but not initialized.
///
/// @param width The width in pixels.
///
/// @param height The height in pixels.
///
/// @param format The pixel format to use.
///
/// @return A ref-pointer to a new Bitmap instance.
///
static Ref<Bitmap> Create(uint32_t width, uint32_t height,
BitmapFormat format);
///
/// Create a Bitmap with existing pixels and configuration.
///
/// @param width The width in pixels.
///
/// @param height The height in pixels.
///
/// @param format The pixel format to use.
///
/// @param row_bytes The number of bytes between each row (note that this
/// value should be >= width * bytes_per_pixel).
///
/// @param pixels Pointer to raw pixel buffer.
///
/// @param size Size of the raw pixel buffer.
///
/// @param should_copy Whether or not a copy should be made of the pixels.
/// If this is false, the returned Bitmap will use the
/// raw pixels passed in as its own, but you are still
/// responsible for destroying your buffer afterwards.
///
/// @param fixup_gamma Whether or not we should reinterpret the source
/// as an sRGB bitmap with premultiplied alpha applied
/// after the gamma function (typical of PNGs). We
/// expect all premultiplication to be applied before
/// the gamma function so we can blend properly in
/// linear space. Only valid for
/// kBitmapFormat_BGRA8_UNORM_SRGB.
///
/// @return A ref-pointer to a new Bitmap instance.
///
static Ref<Bitmap> Create(uint32_t width, uint32_t height,
BitmapFormat format, uint32_t row_bytes,
const void* pixels, size_t size,
bool should_copy = true, bool fixup_gamma = false);
///
/// Create a bitmap from a deep copy of another Bitmap.
///
static Ref<Bitmap> Create(const Bitmap& bitmap);
///
/// Get the width in pixels.
///
virtual uint32_t width() const = 0;
///
/// Get the height in pixels.
///
virtual uint32_t height() const = 0;
///
/// Get the bounds as an IntRect
///
virtual IntRect bounds() const = 0;
///
/// Get the pixel format.
///
virtual BitmapFormat format() const = 0;
///
/// Get the number of bytes per pixel.
///
virtual uint32_t bpp() const = 0;
///
/// Get the number of bytes between each row of pixels.
///
/// @note This value is usually calculated as width * bytes_per_pixel (bpp)
/// but it may be larger due to alignment rules in the allocator.
///
virtual uint32_t row_bytes() const = 0;
///
/// Get the size in bytes of the pixel buffer.
///
/// @note Size is calculated as row_bytes() * height().
///
virtual size_t size() const = 0;
///
/// Whether or not this Bitmap owns the pixel buffer and will destroy it
/// at the end of its lifetime.
///
virtual bool owns_pixels() const = 0;
///
/// Lock the pixel buffer for reading/writing.
///
/// @return A pointer to the pixel buffer.
///
virtual void* LockPixels() = 0;
///
/// Unlock the pixel buffer.
///
virtual void UnlockPixels() = 0;
///
/// Lock the pixel buffer for reading/writing. (const)
///
/// @return A const pointer to the pixel buffer.
///
virtual const void* LockPixels() const = 0;
///
/// Unlock the pixel buffer. (const)
///
virtual void UnlockPixels() const = 0;
///
/// Get the raw pixel buffer.
///
/// @note You should only call this if pixels are already locked.
///
virtual void* raw_pixels() = 0;
///
/// Whether or not this Bitmap is empty (no pixels allocated).
///
virtual bool IsEmpty() const = 0;
///
/// Erase the Bitmap (set all pixels to 0).
///
virtual void Erase() = 0;
///
/// Assign another bitmap to this one.
///
/// @param bitmap The bitmap to copy from.
///
virtual void Set(Ref<Bitmap> bitmap) = 0;
///
/// Draw another bitmap to this bitmap.
///
/// @note Formats do not need to match. Bitmap formats will be converted
/// to one another automatically. Note that when converting from
/// BGRA8 to A8, only the Blue channel will be used.
///
/// @param src_rect The source rectangle, relative to src bitmap.
///
/// @param dest_rect The destination rectangle, relative to this bitmap.
///
/// @param src The source bitmap.
///
/// @param pad_repeat Whether or not we should pad the drawn bitmap by one
/// pixel of repeated edge pixels from the source bitmap.
///
/// @return Whether or not the operation succeeded (this can fail if the
/// src_rect and/or dest_rect are invalid, or if their total
/// dimensions do not match).
///
virtual bool DrawBitmap(IntRect src_rect, IntRect dest_rect,
Ref<Bitmap> src, bool pad_repeat) = 0;
///
/// Write this Bitmap out to a PNG image. (mainly used for Debug)
///
/// @param path The filepath to write to (opened with fopen())
///
/// @return Whether or not the operation succeeded.
///
virtual bool WritePNG(const char* path) = 0;
///
/// Make a resized copy of this bitmap by writing to a pre-allocated
/// destination bitmap.
///
/// @param destination The bitmap to store the result in, the width and
/// height of the destination will be used.
///
/// @param high_quality Whether or not a high quality resampling will be
/// used during the resize. (Otherwise, just uses fast
/// nearest-neighbor sampling)
///
/// @return Whether or not the operation succeeded. This operation is only
/// valid if both formats are kBitmapFormat_BGRA8_UNORM_SRGB and
/// both the source and destination are non-empty.
///
virtual bool Resample(Ref<Bitmap> destination, bool high_quality) = 0;
///
/// This converts a BGRA bitmap to RGBA bitmap and vice-versa by swapping
/// the red and blue channels.
///
virtual void SwapRedBlueChannels() = 0;
protected:
Bitmap();
virtual ~Bitmap();
Bitmap(const Bitmap&);
void operator=(const Bitmap&);
};
#pragma pack(pop)
} // namespace ultralight

View File

@ -1,47 +0,0 @@
///
/// @file Buffer.h
///
/// @brief The header for the Buffer class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
namespace ultralight {
///
/// A fixed-size byte container for passing data around.
///
class UExport Buffer : public RefCounted {
public:
///
/// Create a Buffer, a copy of data is made.
///
static Ref<Buffer> Create(const void* data, size_t size);
///
/// Get a pointer to raw byte data.
///
virtual void* data() = 0;
///
/// Get the size in bytes.
///
virtual size_t size() const = 0;
protected:
Buffer();
virtual ~Buffer();
Buffer(const Buffer&);
void operator=(const Buffer&);
};
} // namespace ultralight

File diff suppressed because it is too large Load Diff

View File

@ -1,95 +0,0 @@
///
/// @file Defines.h
///
/// @brief Common platform definitions
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
// Needed for limit defines, like INTMAX_MAX, which is used by the std C++ library
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstdint>
#include <cstddef>
#include <limits.h>
#ifdef SWIG
#define UExport
#else
// Require C++11 Support
#if defined(_MSC_VER)
# if _MSC_VER < 1800
# error This project needs at least Visual Studio 2013 to build
# endif
#elif __cplusplus <= 199711L
# error This project can only be compiled with a compiler that supports C++11
#endif
#if defined(__WIN32__) || defined(_WIN32)
# if defined(ULTRALIGHT_IMPLEMENTATION)
# define UExport __declspec(dllexport)
# else
# define UExport __declspec(dllimport)
# endif
#define _thread_local __declspec(thread)
#ifndef _NATIVE_WCHAR_T_DEFINED
#define DISABLE_NATIVE_WCHAR_T
#endif
#else
# define UExport __attribute__((visibility("default")))
#define _thread_local __thread
#endif
#endif
#define ULTRALIGHT_VERSION "1.2.0"
#define ULTRALIGHT_VERSION_MAJOR 1
#define ULTRALIGHT_VERSION_MINOR 2
#define ULTRALIGHT_VERSION_PATCH 0
#ifdef __cplusplus
extern "C" {
#endif
UExport const char* UltralightVersionString();
UExport uint32_t UltralightVersionMajor();
UExport uint32_t UltralightVersionMinor();
UExport uint32_t UltralightVersionPatch();
#ifdef __cplusplus
}
#endif
///
/// @mainpage Ultralight C++ API Reference
///
/// @section intro_sec Introduction
///
/// Hi there, welcome to the C++ API Reference for Ultralight!
///
/// Ultralight is a fast, lightweight HTML UI engine for desktop apps and games.
///
/// If this is your first time exploring the API, we recommend
/// starting with ultralight::Renderer and ultralight::View.
///
///
/// @section usefullinks_sec Useful Links
/// - Home: <https://ultralig.ht> -- Get the latest binaries
/// - Docs: <https://docs.ultralig.ht> -- API overview, code snippets, tutorials and more!
/// - Discord: <http://chat.ultralig.ht/> -- Stuck? Have questions? Come chat with us!
/// - GitHub: <https://github.com/ultralight-ux/ultralight> -- Report issues and browse code
///
/// @section copyright_sec Copyright
/// Documentation is Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///

View File

@ -1,677 +0,0 @@
///
/// @file Geometry.h
///
/// @brief The header for various geometry definitions and helpers
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <memory.h>
#include <cmath>
#include <cstring>
#include <algorithm>
namespace ultralight {
///
/// 2D Vector Helper
///
struct UExport vec2 {
union {
float value[2];
struct { float x, y; };
};
inline vec2() {}
inline vec2(float x, float y) : x(x), y(y) {}
inline vec2(float x) : x(x), y(x) {}
inline vec2 yx() const { return { y, x }; }
inline vec2 xx() const { return { x, x }; }
inline vec2 yy() const { return { y, y }; }
inline friend vec2 operator+(vec2 lhs, const vec2& rhs) { lhs += rhs; return lhs; }
inline friend vec2 operator-(vec2 lhs, const vec2& rhs) { lhs -= rhs; return lhs; }
inline friend vec2 operator*(vec2 lhs, const vec2& rhs) { lhs *= rhs; return lhs; }
inline friend vec2 operator/(vec2 lhs, const vec2& rhs) { lhs /= rhs; return lhs; }
inline friend vec2 operator+(vec2 lhs, float rhs) { lhs += rhs; return lhs; }
inline friend vec2 operator-(vec2 lhs, float rhs) { lhs -= rhs; return lhs; }
inline friend vec2 operator*(vec2 lhs, float rhs) { lhs *= rhs; return lhs; }
inline friend vec2 operator/(vec2 lhs, float rhs) { lhs /= rhs; return lhs; }
inline vec2& operator+=(const vec2& rhs) {
value[0] += rhs.value[0];
value[1] += rhs.value[1];
return *this;
}
inline vec2& operator-=(const vec2& rhs) {
value[0] -= rhs.value[0];
value[1] -= rhs.value[1];
return *this;
}
inline vec2& operator*=(const vec2& rhs) {
value[0] *= rhs.value[0];
value[1] *= rhs.value[1];
return *this;
}
inline vec2& operator/=(const vec2& rhs) {
value[0] /= rhs.value[0];
value[1] /= rhs.value[1];
return *this;
}
inline vec2& operator+=(float rhs) {
value[0] += rhs;
value[1] += rhs;
return *this;
}
inline vec2& operator-=(float rhs) {
value[0] -= rhs;
value[1] -= rhs;
return *this;
}
inline vec2& operator*=(float rhs) {
value[0] *= rhs;
value[1] *= rhs;
return *this;
}
inline vec2& operator/=(float rhs) {
value[0] /= rhs;
value[1] /= rhs;
return *this;
}
inline friend bool operator==(const vec2& a, const vec2& b) {
return !memcmp(&a, &b, sizeof(a));
}
inline friend bool operator!=(const vec2& a, const vec2& b) {
return !(a == b);
}
inline friend vec2 min_(const vec2& a, const vec2& b) {
return{ (b.x < a.x) ? b.x : a.x,
(b.y < a.y) ? b.y : a.y };
}
inline friend vec2 max_(const vec2& a, const vec2& b) {
return{ (a.x < b.x) ? b.x : a.x,
(a.y < b.y) ? b.y : a.y };
}
inline friend vec2 clamp(const vec2& x, const vec2& minVal, const vec2& maxVal) {
return min_(max_(x, minVal), maxVal);
}
inline friend vec2 mix(const vec2& a, const vec2& b, float t) {
return a * (1.0f - t) + b * t;
}
inline friend float length(const vec2& a) {
return sqrtf(a.x * a.x + a.y * a.y);
}
// squared length
inline friend float length2(const vec2& a) {
return dot(a, a);
}
inline friend float distance(const vec2& a, const vec2& b) {
return length(a - b);
}
// squared distance
inline friend float distance2(const vec2& a, const vec2& b) {
return length2(a - b);
}
inline friend vec2 normalize(const vec2& a) {
return a / length(a);
}
inline friend float dot(const vec2& a, const vec2& b) {
return a.x * b.x + a.y * b.y;
}
};
///
/// 3D Vector Helper
///
struct UExport vec3 {
union {
float value[3];
struct { float x, y, z; };
};
inline vec3() {}
inline vec3(float x, float y, float z) : x(x), y(y), z(z) {}
inline vec3(float x) : x(x), y(x), z(x) {}
inline friend vec3 operator+(vec3 lhs, const vec3& rhs) { lhs += rhs; return lhs; }
inline friend vec3 operator-(vec3 lhs, const vec3& rhs) { lhs -= rhs; return lhs; }
inline friend vec3 operator*(vec3 lhs, const vec3& rhs) { lhs *= rhs; return lhs; }
inline friend vec3 operator/(vec3 lhs, const vec3& rhs) { lhs /= rhs; return lhs; }
inline friend vec3 operator+(vec3 lhs, float rhs) { lhs += rhs; return lhs; }
inline friend vec3 operator-(vec3 lhs, float rhs) { lhs -= rhs; return lhs; }
inline friend vec3 operator*(vec3 lhs, float rhs) { lhs *= rhs; return lhs; }
inline friend vec3 operator/(vec3 lhs, float rhs) { lhs /= rhs; return lhs; }
inline vec3& operator+=(const vec3& rhs) {
value[0] += rhs.value[0];
value[1] += rhs.value[1];
value[2] += rhs.value[2];
return *this;
}
inline vec3& operator-=(const vec3& rhs) {
value[0] -= rhs.value[0];
value[1] -= rhs.value[1];
value[2] -= rhs.value[2];
return *this;
}
inline vec3& operator*=(const vec3& rhs) {
value[0] *= rhs.value[0];
value[1] *= rhs.value[1];
value[2] *= rhs.value[2];
return *this;
}
inline vec3& operator/=(const vec3& rhs) {
value[0] /= rhs.value[0];
value[1] /= rhs.value[1];
value[2] /= rhs.value[2];
return *this;
}
inline vec3& operator+=(float rhs) {
value[0] += rhs;
value[1] += rhs;
value[2] += rhs;
return *this;
}
inline vec3& operator-=(float rhs) {
value[0] -= rhs;
value[1] -= rhs;
value[2] -= rhs;
return *this;
}
inline vec3& operator*=(float rhs) {
value[0] *= rhs;
value[1] *= rhs;
value[2] *= rhs;
return *this;
}
inline vec3& operator/=(float rhs) {
value[0] /= rhs;
value[1] /= rhs;
value[2] /= rhs;
return *this;
}
inline friend bool operator==(const vec3& a, const vec3& b) {
return !memcmp(&a, &b, sizeof(a));
}
inline friend bool operator!=(const vec3& a, const vec3& b) {
return !(a == b);
}
inline friend vec3 min_(const vec3& a, const vec3& b) {
return{ (b.x < a.x) ? b.x : a.x,
(b.y < a.y) ? b.y : a.y,
(b.z < a.z) ? b.z : a.z };
}
inline friend vec3 max_(const vec3& a, const vec3& b) {
return{ (a.x < b.x) ? b.x : a.x,
(a.y < b.y) ? b.y : a.y,
(a.z < b.z) ? b.z : a.z };
}
inline friend vec3 clamp(const vec3& x, const vec3& minVal, const vec3& maxVal) {
return min_(max_(x, minVal), maxVal);
}
inline friend vec3 mix(const vec3& a, const vec3& b, float t) {
return a * (1.0f - t) + b * t;
}
inline friend float length(const vec3& a) {
return sqrtf(a.x * a.x + a.y * a.y + a.z * a.z);
}
inline friend float distance(const vec3& a, const vec3& b) {
return length(a - b);
}
inline friend vec3 normalize(const vec3& a) {
return a / length(a);
}
inline friend float dot(const vec3& a, const vec3& b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
};
///
/// 4D Vector Helper
///
struct UExport vec4 {
union {
float value[4];
struct { float x, y, z, w; };
};
inline vec4() {}
inline vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
inline vec4(float x) : x(x), y(x), z(x), w(x) {}
inline vec4(const float x[4]) { memcpy(value, x, sizeof(value)); }
inline friend bool operator==(const vec4& a, const vec4& b) {
return !memcmp(&a, &b, sizeof(a));
}
inline friend bool operator!=(const vec4& a, const vec4& b) {
return !(a == b);
}
inline friend vec4 operator+(vec4 lhs, const vec4& rhs) { lhs += rhs; return lhs; }
inline friend vec4 operator-(vec4 lhs, const vec4& rhs) { lhs -= rhs; return lhs; }
inline friend vec4 operator*(vec4 lhs, const vec4& rhs) { lhs *= rhs; return lhs; }
inline friend vec4 operator/(vec4 lhs, const vec4& rhs) { lhs /= rhs; return lhs; }
inline friend vec4 operator+(vec4 lhs, float rhs) { lhs += rhs; return lhs; }
inline friend vec4 operator-(vec4 lhs, float rhs) { lhs -= rhs; return lhs; }
inline friend vec4 operator*(vec4 lhs, float rhs) { lhs *= rhs; return lhs; }
inline friend vec4 operator/(vec4 lhs, float rhs) { lhs /= rhs; return lhs; }
inline vec4& operator+=(const vec4& rhs) {
value[0] += rhs.value[0];
value[1] += rhs.value[1];
value[2] += rhs.value[2];
value[3] += rhs.value[3];
return *this;
}
inline vec4& operator-=(const vec4& rhs) {
value[0] -= rhs.value[0];
value[1] -= rhs.value[1];
value[2] -= rhs.value[2];
value[3] -= rhs.value[3];
return *this;
}
inline vec4& operator*=(const vec4& rhs) {
value[0] *= rhs.value[0];
value[1] *= rhs.value[1];
value[2] *= rhs.value[2];
value[3] *= rhs.value[3];
return *this;
}
inline vec4& operator/=(const vec4& rhs) {
value[0] /= rhs.value[0];
value[1] /= rhs.value[1];
value[2] /= rhs.value[2];
value[3] /= rhs.value[3];
return *this;
}
inline vec4& operator+=(float rhs) {
value[0] += rhs;
value[1] += rhs;
value[2] += rhs;
value[3] += rhs;
return *this;
}
inline vec4& operator-=(float rhs) {
value[0] -= rhs;
value[1] -= rhs;
value[2] -= rhs;
value[3] -= rhs;
return *this;
}
inline vec4& operator*=(float rhs) {
value[0] *= rhs;
value[1] *= rhs;
value[2] *= rhs;
value[3] *= rhs;
return *this;
}
inline vec4& operator/=(float rhs) {
value[0] /= rhs;
value[1] /= rhs;
value[2] /= rhs;
value[3] /= rhs;
return *this;
}
inline friend vec4 min_(const vec4& a, const vec4& b) {
return{ (b.x < a.x) ? b.x : a.x,
(b.y < a.y) ? b.y : a.y,
(b.z < a.z) ? b.z : a.z,
(b.w < a.w) ? b.w : a.w };
}
inline friend vec4 max_(const vec4& a, const vec4& b) {
return{ (a.x < b.x) ? b.x : a.x,
(a.y < b.y) ? b.y : a.y,
(a.z < b.z) ? b.z : a.z,
(a.w < b.w) ? b.w : a.w };
}
};
///
/// Point is typedef'd to a 2D vector
///
typedef vec2 Point;
///
/// Float Rectangle Helper
///
struct UExport Rect {
union {
float value[4];
struct { float left, top, right, bottom; };
};
static inline Rect MakeEmpty() {
Rect result;
result.SetEmpty();
return result;
}
inline float width() const { return right - left; }
inline float height() const { return bottom - top; }
inline float x() const { return left; }
inline float y() const { return top; }
inline float center_x() const { return (left + right) * 0.5f; }
inline float center_y() const { return (top + bottom) * 0.5f; }
inline Point origin() const { return { left, top }; }
inline void SetEmpty() {
memset(this, 0, sizeof(*this));
}
inline bool IsEmpty() const {
return *this == MakeEmpty();
}
inline bool IsValid() const {
return width() > 0 && height() > 0;
}
inline void Inset(float dx, float dy) {
value[0] += dx;
value[1] += dy;
value[2] -= dx;
value[3] -= dy;
}
inline void Outset(float dx, float dy) {
Inset(-dx, -dy);
}
inline void Move(float dx, float dy) {
value[0] += dx;
value[1] += dy;
value[2] += dx;
value[3] += dy;
}
inline float area() const {
return width() * height();
}
inline void Join(const Rect& rhs) {
// if we are empty, just assign
if (IsEmpty()) {
*this = rhs;
}
else {
if (rhs.value[0] < value[0]) value[0] = rhs.value[0];
if (rhs.value[1] < value[1]) value[1] = rhs.value[1];
if (rhs.value[2] > value[2]) value[2] = rhs.value[2];
if (rhs.value[3] > value[3]) value[3] = rhs.value[3];
}
}
inline void Join(const Point& p) {
// if we are empty, just assign
if (IsEmpty()) {
*this = { p.x, p.y, p.x, p.y };
}
else {
if (p.x < value[0]) value[0] = p.x;
if (p.y < value[1]) value[1] = p.y;
if (p.x > value[2]) value[2] = p.x;
if (p.y > value[3]) value[3] = p.y;
}
}
inline bool Contains(const Point& p) const {
return p.x >= left && p.x <= right &&
p.y >= top && p.y <= bottom;
}
inline bool Contains(const Rect& r) const {
return left <= r.left && top <= r.top &&
right >= r.right && bottom >= r.bottom;
}
inline bool Intersects(const Rect& rhs) const {
return !(rhs.left > right ||
rhs.right < left ||
rhs.top > bottom ||
rhs.bottom < top);
}
inline Rect Intersect(const Rect& other) const {
return{ (left < other.left) ? other.left : left,
(top < other.top) ? other.top : top,
(other.right < right) ? other.right : right,
(other.bottom < bottom) ? other.bottom : bottom };
}
friend inline bool operator==(const Rect& a, const Rect& b) {
return !memcmp(&a, &b, sizeof(a));
}
friend inline bool operator!=(const Rect& a, const Rect& b) {
return !(a == b);
}
};
///
/// Integer Rectangle Helper
///
struct UExport IntRect {
union {
int value[4];
struct { int left, top, right, bottom; };
};
static inline IntRect MakeEmpty() {
IntRect result;
result.SetEmpty();
return result;
}
inline int width() const { return right - left; }
inline int height() const { return bottom - top; }
inline int x() const { return left; }
inline int y() const { return top; }
inline int center_x() const { return (int)std::round((left + right) * 0.5f); }
inline int center_y() const { return (int)std::round((top + bottom) * 0.5f); }
inline Point origin() const { return{ (float)left, (float)top }; }
inline void SetEmpty() {
memset(this, 0, sizeof(*this));
}
inline bool IsEmpty() const {
return *this == MakeEmpty();
}
inline bool IsValid() const {
return width() > 0 && height() > 0;
}
inline void Inset(int dx, int dy) {
value[0] += dx;
value[1] += dy;
value[2] -= dx;
value[3] -= dy;
}
inline void Outset(int dx, int dy) {
Inset(-dx, -dy);
}
inline void Move(int dx, int dy) {
value[0] += dx;
value[1] += dy;
value[2] += dx;
value[3] += dy;
}
inline int area() const {
return width() * height();
}
inline void Join(const IntRect& rhs) {
// if we are empty, just assign
if (IsEmpty()) {
*this = rhs;
}
else {
if (rhs.value[0] < value[0]) value[0] = rhs.value[0];
if (rhs.value[1] < value[1]) value[1] = rhs.value[1];
if (rhs.value[2] > value[2]) value[2] = rhs.value[2];
if (rhs.value[3] > value[3]) value[3] = rhs.value[3];
}
}
inline void Join(const Point& p) {
// if we are empty, just assign
if (IsEmpty()) {
*this = { (int)std::floor(p.x), (int)std::floor(p.y), (int)std::ceil(p.x), (int)std::ceil(p.y) };
}
else {
if ((int)std::floor(p.x) < value[0]) value[0] = (int)std::floor(p.x);
if ((int)std::floor(p.y) < value[1]) value[1] = (int)std::floor(p.y);
if ((int)std::ceil(p.x) > value[2]) value[2] = (int)std::ceil(p.x);
if ((int)std::ceil(p.y) > value[3]) value[3] = (int)std::ceil(p.y);
}
}
inline bool Contains(const Point& p) const {
return p.x >= left && p.x <= right &&
p.y >= top && p.y <= bottom;
}
inline bool Contains(const IntRect& r) const {
return left <= r.left && top <= r.top &&
right >= r.right && bottom >= r.bottom;
}
inline bool Intersects(const IntRect& rhs) const {
// Since this is mostly used for pixel operations, we only count
// intersections that have width and height >= 1.
return !(rhs.left > right - 1 ||
rhs.right < left ||
rhs.top > bottom - 1 ||
rhs.bottom < top);
}
inline IntRect Intersect(const IntRect& other) const {
return{ (left < other.left) ? other.left : left,
(top < other.top) ? other.top : top,
(other.right < right) ? other.right : right,
(other.bottom < bottom) ? other.bottom : bottom };
}
friend inline bool operator==(const IntRect& a, const IntRect& b) {
return !memcmp(&a, &b, sizeof(a));
}
friend inline bool operator!=(const IntRect& a, const IntRect& b) {
return !(a == b);
}
};
///
/// Rounded Rectangle Helper
///
struct UExport RoundedRect {
Rect rect;
float radii_x[4];
float radii_y[4];
void SetEmpty();
bool IsRounded() const;
// Negative is inside, positive is outside.
float GetSignedDistance(const Point& p) const;
// Returns whether or not intersection is found. Can fail if the resulting
// geometry is not a rounded rectangle.
bool Intersect(const RoundedRect& other, RoundedRect& result) const;
void SnapToPixels();
Rect CalculateInterior() const;
};
} // namespace ultralight

View File

@ -1,39 +0,0 @@
///
/// @file View.h
///
/// @brief The header for the View class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <JavaScriptCore/JavaScript.h>
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/String.h>
namespace ultralight {
///
/// This class wraps a JSContextRef (a JavaScript execution context for use
/// with JavaScriptCore) and locks the context on the current thread for the
/// duration of its lifetime.
///
class UExport JSContext : public RefCounted {
public:
/// Get the underlying JSContextRef for use with JavaScriptCore C API
virtual JSContextRef ctx() = 0;
/// Typecast to a JSContextRef for use with JavaScriptCore C API
operator JSContextRef();
protected:
virtual ~JSContext();
};
} // namespace ultralight

View File

@ -1,527 +0,0 @@
///
/// @file KeyCodes.h
///
/// @brief The header for the KeyCodes definitions.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
namespace ultralight {
///
/// Namespace containing all the key-code definitions for KeyboardEvent.
/// Most of these correspond directly to the key-code values on Windows.
///
namespace KeyCodes {
// GK_BACK (08) BACKSPACE key
const int GK_BACK = 0x08;
// GK_TAB (09) TAB key
const int GK_TAB = 0x09;
// GK_CLEAR (0C) CLEAR key
const int GK_CLEAR = 0x0C;
// GK_RETURN (0D)
const int GK_RETURN = 0x0D;
// GK_SHIFT (10) SHIFT key
const int GK_SHIFT = 0x10;
// GK_CONTROL (11) CTRL key
const int GK_CONTROL = 0x11;
// GK_MENU (12) ALT key
const int GK_MENU = 0x12;
// GK_PAUSE (13) PAUSE key
const int GK_PAUSE = 0x13;
// GK_CAPITAL (14) CAPS LOCK key
const int GK_CAPITAL = 0x14;
// GK_KANA (15) Input Method Editor (IME) Kana mode
const int GK_KANA = 0x15;
// GK_HANGUEL (15) IME Hanguel mode (maintained for compatibility; use GK_HANGUL)
// GK_HANGUL (15) IME Hangul mode
const int GK_HANGUL = 0x15;
// GK_JUNJA (17) IME Junja mode
const int GK_JUNJA = 0x17;
// GK_FINAL (18) IME final mode
const int GK_FINAL = 0x18;
// GK_HANJA (19) IME Hanja mode
const int GK_HANJA = 0x19;
// GK_KANJI (19) IME Kanji mode
const int GK_KANJI = 0x19;
// GK_ESCAPE (1B) ESC key
const int GK_ESCAPE = 0x1B;
// GK_CONVERT (1C) IME convert
const int GK_CONVERT = 0x1C;
// GK_NONCONVERT (1D) IME nonconvert
const int GK_NONCONVERT = 0x1D;
// GK_ACCEPT (1E) IME accept
const int GK_ACCEPT = 0x1E;
// GK_MODECHANGE (1F) IME mode change request
const int GK_MODECHANGE = 0x1F;
// GK_SPACE (20) SPACEBAR
const int GK_SPACE = 0x20;
// GK_PRIOR (21) PAGE UP key
const int GK_PRIOR = 0x21;
// GK_NEXT (22) PAGE DOWN key
const int GK_NEXT = 0x22;
// GK_END (23) END key
const int GK_END = 0x23;
// GK_HOME (24) HOME key
const int GK_HOME = 0x24;
// GK_LEFT (25) LEFT ARROW key
const int GK_LEFT = 0x25;
// GK_UP (26) UP ARROW key
const int GK_UP = 0x26;
// GK_RIGHT (27) RIGHT ARROW key
const int GK_RIGHT = 0x27;
// GK_DOWN (28) DOWN ARROW key
const int GK_DOWN = 0x28;
// GK_SELECT (29) SELECT key
const int GK_SELECT = 0x29;
// GK_PRINT (2A) PRINT key
const int GK_PRINT = 0x2A;
// GK_EXECUTE (2B) EXECUTE key
const int GK_EXECUTE = 0x2B;
// GK_SNAPSHOT (2C) PRINT SCREEN key
const int GK_SNAPSHOT = 0x2C;
// GK_INSERT (2D) INS key
const int GK_INSERT = 0x2D;
// GK_DELETE (2E) DEL key
const int GK_DELETE = 0x2E;
// GK_HELP (2F) HELP key
const int GK_HELP = 0x2F;
// (30) 0 key
const int GK_0 = 0x30;
// (31) 1 key
const int GK_1 = 0x31;
// (32) 2 key
const int GK_2 = 0x32;
// (33) 3 key
const int GK_3 = 0x33;
// (34) 4 key
const int GK_4 = 0x34;
// (35) 5 key;
const int GK_5 = 0x35;
// (36) 6 key
const int GK_6 = 0x36;
// (37) 7 key
const int GK_7 = 0x37;
// (38) 8 key
const int GK_8 = 0x38;
// (39) 9 key
const int GK_9 = 0x39;
// (41) A key
const int GK_A = 0x41;
// (42) B key
const int GK_B = 0x42;
// (43) C key
const int GK_C = 0x43;
// (44) D key
const int GK_D = 0x44;
// (45) E key
const int GK_E = 0x45;
// (46) F key
const int GK_F = 0x46;
// (47) G key
const int GK_G = 0x47;
// (48) H key
const int GK_H = 0x48;
// (49) I key
const int GK_I = 0x49;
// (4A) J key
const int GK_J = 0x4A;
// (4B) K key
const int GK_K = 0x4B;
// (4C) L key
const int GK_L = 0x4C;
// (4D) M key
const int GK_M = 0x4D;
// (4E) N key
const int GK_N = 0x4E;
// (4F) O key
const int GK_O = 0x4F;
// (50) P key
const int GK_P = 0x50;
// (51) Q key
const int GK_Q = 0x51;
// (52) R key
const int GK_R = 0x52;
// (53) S key
const int GK_S = 0x53;
// (54) T key
const int GK_T = 0x54;
// (55) U key
const int GK_U = 0x55;
// (56) V key
const int GK_V = 0x56;
// (57) W key
const int GK_W = 0x57;
// (58) X key
const int GK_X = 0x58;
// (59) Y key
const int GK_Y = 0x59;
// (5A) Z key
const int GK_Z = 0x5A;
// GK_LWIN (5B) Left Windows key (Microsoft Natural keyboard)
const int GK_LWIN = 0x5B;
// GK_RWIN (5C) Right Windows key (Natural keyboard)
const int GK_RWIN = 0x5C;
// GK_APPS (5D) Applications key (Natural keyboard)
const int GK_APPS = 0x5D;
// GK_SLEEP (5F) Computer Sleep key
const int GK_SLEEP = 0x5F;
// GK_NUMPAD0 (60) Numeric keypad 0 key
const int GK_NUMPAD0 = 0x60;
// GK_NUMPAD1 (61) Numeric keypad 1 key
const int GK_NUMPAD1 = 0x61;
// GK_NUMPAD2 (62) Numeric keypad 2 key
const int GK_NUMPAD2 = 0x62;
// GK_NUMPAD3 (63) Numeric keypad 3 key
const int GK_NUMPAD3 = 0x63;
// GK_NUMPAD4 (64) Numeric keypad 4 key
const int GK_NUMPAD4 = 0x64;
// GK_NUMPAD5 (65) Numeric keypad 5 key
const int GK_NUMPAD5 = 0x65;
// GK_NUMPAD6 (66) Numeric keypad 6 key
const int GK_NUMPAD6 = 0x66;
// GK_NUMPAD7 (67) Numeric keypad 7 key
const int GK_NUMPAD7 = 0x67;
// GK_NUMPAD8 (68) Numeric keypad 8 key
const int GK_NUMPAD8 = 0x68;
// GK_NUMPAD9 (69) Numeric keypad 9 key
const int GK_NUMPAD9 = 0x69;
// GK_MULTIPLY (6A) Multiply key
const int GK_MULTIPLY = 0x6A;
// GK_ADD (6B) Add key
const int GK_ADD = 0x6B;
// GK_SEPARATOR (6C) Separator key
const int GK_SEPARATOR = 0x6C;
// GK_SUBTRACT (6D) Subtract key
const int GK_SUBTRACT = 0x6D;
// GK_DECIMAL (6E) Decimal key
const int GK_DECIMAL = 0x6E;
// GK_DIVIDE (6F) Divide key
const int GK_DIVIDE = 0x6F;
// GK_F1 (70) F1 key
const int GK_F1 = 0x70;
// GK_F2 (71) F2 key
const int GK_F2 = 0x71;
// GK_F3 (72) F3 key
const int GK_F3 = 0x72;
// GK_F4 (73) F4 key
const int GK_F4 = 0x73;
// GK_F5 (74) F5 key
const int GK_F5 = 0x74;
// GK_F6 (75) F6 key
const int GK_F6 = 0x75;
// GK_F7 (76) F7 key
const int GK_F7 = 0x76;
// GK_F8 (77) F8 key
const int GK_F8 = 0x77;
// GK_F9 (78) F9 key
const int GK_F9 = 0x78;
// GK_F10 (79) F10 key
const int GK_F10 = 0x79;
// GK_F11 (7A) F11 key
const int GK_F11 = 0x7A;
// GK_F12 (7B) F12 key
const int GK_F12 = 0x7B;
// GK_F13 (7C) F13 key
const int GK_F13 = 0x7C;
// GK_F14 (7D) F14 key
const int GK_F14 = 0x7D;
// GK_F15 (7E) F15 key
const int GK_F15 = 0x7E;
// GK_F16 (7F) F16 key
const int GK_F16 = 0x7F;
// GK_F17 (80H) F17 key
const int GK_F17 = 0x80;
// GK_F18 (81H) F18 key
const int GK_F18 = 0x81;
// GK_F19 (82H) F19 key
const int GK_F19 = 0x82;
// GK_F20 (83H) F20 key
const int GK_F20 = 0x83;
// GK_F21 (84H) F21 key
const int GK_F21 = 0x84;
// GK_F22 (85H) F22 key
const int GK_F22 = 0x85;
// GK_F23 (86H) F23 key
const int GK_F23 = 0x86;
// GK_F24 (87H) F24 key
const int GK_F24 = 0x87;
// GK_NUMLOCK (90) NUM LOCK key
const int GK_NUMLOCK = 0x90;
// GK_SCROLL (91) SCROLL LOCK key
const int GK_SCROLL = 0x91;
// GK_LSHIFT (A0) Left SHIFT key
const int GK_LSHIFT = 0xA0;
// GK_RSHIFT (A1) Right SHIFT key
const int GK_RSHIFT = 0xA1;
// GK_LCONTROL (A2) Left CONTROL key
const int GK_LCONTROL = 0xA2;
// GK_RCONTROL (A3) Right CONTROL key
const int GK_RCONTROL = 0xA3;
// GK_LMENU (A4) Left MENU key
const int GK_LMENU = 0xA4;
// GK_RMENU (A5) Right MENU key
const int GK_RMENU = 0xA5;
// GK_BROWSER_BACK (A6) Windows 2000/XP: Browser Back key
const int GK_BROWSER_BACK = 0xA6;
// GK_BROWSER_FORWARD (A7) Windows 2000/XP: Browser Forward key
const int GK_BROWSER_FORWARD = 0xA7;
// GK_BROWSER_REFRESH (A8) Windows 2000/XP: Browser Refresh key
const int GK_BROWSER_REFRESH = 0xA8;
// GK_BROWSER_STOP (A9) Windows 2000/XP: Browser Stop key
const int GK_BROWSER_STOP = 0xA9;
// GK_BROWSER_SEARCH (AA) Windows 2000/XP: Browser Search key
const int GK_BROWSER_SEARCH = 0xAA;
// GK_BROWSER_FAVORITES (AB) Windows 2000/XP: Browser Favorites key
const int GK_BROWSER_FAVORITES = 0xAB;
// GK_BROWSER_HOME (AC) Windows 2000/XP: Browser Start and Home key
const int GK_BROWSER_HOME = 0xAC;
// GK_VOLUME_MUTE (AD) Windows 2000/XP: Volume Mute key
const int GK_VOLUME_MUTE = 0xAD;
// GK_VOLUME_DOWN (AE) Windows 2000/XP: Volume Down key
const int GK_VOLUME_DOWN = 0xAE;
// GK_VOLUME_UP (AF) Windows 2000/XP: Volume Up key
const int GK_VOLUME_UP = 0xAF;
// GK_MEDIA_NEXT_TRACK (B0) Windows 2000/XP: Next Track key
const int GK_MEDIA_NEXT_TRACK = 0xB0;
// GK_MEDIA_PREV_TRACK (B1) Windows 2000/XP: Previous Track key
const int GK_MEDIA_PREV_TRACK = 0xB1;
// GK_MEDIA_STOP (B2) Windows 2000/XP: Stop Media key
const int GK_MEDIA_STOP = 0xB2;
// GK_MEDIA_PLAY_PAUSE (B3) Windows 2000/XP: Play/Pause Media key
const int GK_MEDIA_PLAY_PAUSE = 0xB3;
// GK_LAUNCH_MAIL (B4) Windows 2000/XP: Start Mail key
const int GK_MEDIA_LAUNCH_MAIL = 0xB4;
// GK_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key
const int GK_MEDIA_LAUNCH_MEDIA_SELECT = 0xB5;
// GK_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key
const int GK_MEDIA_LAUNCH_APP1 = 0xB6;
// GK_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key
const int GK_MEDIA_LAUNCH_APP2 = 0xB7;
// GK_OEM_1 (BA) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key
const int GK_OEM_1 = 0xBA;
// GK_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key
const int GK_OEM_PLUS = 0xBB;
// GK_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key
const int GK_OEM_COMMA = 0xBC;
// GK_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key
const int GK_OEM_MINUS = 0xBD;
// GK_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key
const int GK_OEM_PERIOD = 0xBE;
// GK_OEM_2 (BF) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
const int GK_OEM_2 = 0xBF;
// GK_OEM_3 (C0) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
const int GK_OEM_3 = 0xC0;
// GK_OEM_4 (DB) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
const int GK_OEM_4 = 0xDB;
// GK_OEM_5 (DC) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
const int GK_OEM_5 = 0xDC;
// GK_OEM_6 (DD) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
const int GK_OEM_6 = 0xDD;
// GK_OEM_7 (DE) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
const int GK_OEM_7 = 0xDE;
// GK_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard.
const int GK_OEM_8 = 0xDF;
// GK_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
const int GK_OEM_102 = 0xE2;
// GK_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
const int GK_PROCESSKEY = 0xE5;
// GK_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The GK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP
const int GK_PACKET = 0xE7;
// GK_ATTN (F6) Attn key
const int GK_ATTN = 0xF6;
// GK_CRSEL (F7) CrSel key
const int GK_CRSEL = 0xF7;
// GK_EXSEL (F8) ExSel key
const int GK_EXSEL = 0xF8;
// GK_EREOF (F9) Erase EOF key
const int GK_EREOF = 0xF9;
// GK_PLAY (FA) Play key
const int GK_PLAY = 0xFA;
// GK_ZOOM (FB) Zoom key
const int GK_ZOOM = 0xFB;
// GK_NONAME (FC) Reserved for future use
const int GK_NONAME = 0xFC;
// GK_PA1 (FD) PA1 key
const int GK_PA1 = 0xFD;
// GK_OEM_CLEAR (FE) Clear key
const int GK_OEM_CLEAR = 0xFE;
const int GK_UNKNOWN = 0;
} // namespace KeyCodes
} // namespace ultralight

View File

@ -1,180 +0,0 @@
///
/// @file KeyEvent.h
///
/// @brief The header for the KeyEvent class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/KeyCodes.h>
#include <Ultralight/String.h>
#ifdef __OBJC__
#import <AppKit/NSEvent.h>
#endif
namespace ultralight {
///
/// @brief A generic keyboard event that can be created from a platform event
/// or synthesized from scratch.
///
/// @see View::FireKeyEvent
///
class UExport KeyEvent {
public:
///
/// The various KeyEvent types.
///
enum Type {
///
/// Key-Down event type. (Does not trigger accelerator commands in WebCore)
///
/// @NOTE: You should probably use RawKeyDown instead when a physical key
/// is pressed. This member is only here for historic compatibility
/// with WebCore's key event types.
///
kType_KeyDown,
///
/// Key-Up event type. Use this when a physical key is released.
///
kType_KeyUp,
///
/// Raw Key-Down type. Use this when a physical key is pressed.
///
/// @NOTE: You should use RawKeyDown for physical key presses since it
/// allows WebCore to do additional command translation.
///
kType_RawKeyDown,
///
/// Character input event type. Use this when the OS generates text from
/// a physical key being pressed (eg, WM_CHAR on Windows).
///
kType_Char,
};
///
/// Creates an empty KeyEvent, you will need to initialize its members
/// yourself. This is useful for synthesizing your own keyboard events.
///
KeyEvent();
#ifdef _WIN32
///
/// Create a KeyEvent directly from a Windows keyboard event.
///
KeyEvent(Type type, uintptr_t wparam, intptr_t lparam, bool is_system_key);
#endif
#ifdef __OBJC__
///
/// Create a KeyEvent directly from a macOS NSEvent.
///
KeyEvent(NSEvent* evt);
#endif
///
/// An enumeration of the different keyboard modifiers.
///
enum Modifiers : uint8_t {
/// Whether or not an ALT key is down
kMod_AltKey = 1 << 0,
/// Whether or not a Control key is down
kMod_CtrlKey = 1 << 1,
/// Whether or not a meta key (Command-key on Mac, Windows-key on Win) is down
kMod_MetaKey = 1 << 2,
/// Whether or not a Shift key is down
kMod_ShiftKey = 1 << 3,
};
///
// The type of this KeyEvent
///
Type type;
///
/// The current state of the keyboard. Modifiers may be OR'd together to
/// represent multiple values.
///
unsigned modifiers;
///
// The virtual key-code associated with this keyboard event. This is either
// directly from the event (ie, WPARAM on Windows) or via a mapping function.
// You can see a full list of the possible virtual key-codes in
// KeyboardCodes.h
///
int virtual_key_code;
///
/// The actual key-code generated by the platform. The DOM spec primarily
/// uses Windows-equivalent codes (hence virtualKeyCode above) but it helps to
/// also specify the platform-specific key-code as well.
///
int native_key_code;
///
/// This is a string identifying the key that was pressed. This can be
/// generated from the virtual_key_code via the GetKeyIdentifierFromVirtualKeyCode()
/// utility function. You can find the full list of key identifiers at:
/// <https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/keyset.html>
///
String key_identifier;
///
/// The actual text generated by this keyboard event. This is usually only a
/// single character.
///
String text;
///
/// The text generated by this keyboard event before all modifiers except
/// shift are applied. This is used internally for working out shortcut keys.
/// This is usually only a single character.
///
String unmodified_text;
///
/// Whether or not this is a keypad event.
///
bool is_keypad;
///
/// Whether or not this was generated as the result of an auto-repeat
/// (eg, holding down a key).
///
bool is_auto_repeat;
///
/// Whether or not the pressed key is a "system key". This is a Windows-only
/// concept and should be "false" for all non-Windows platforms. For more
/// information, see the following link:
/// <http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx>
bool is_system_key;
};
///
/// Utility function for generating a key identifier string from a virtual
/// key-code.
///
/// @param virtual_key_code The virtual key-code to generate the key
/// identifier from.
///
/// @param key_identifier_result The string to store the result in.
///
void UExport GetKeyIdentifierFromVirtualKeyCode(int virtual_key_code,
String& key_identifier_result);
} // namespace ultralight

View File

@ -1,287 +0,0 @@
///
/// @file Listener.h
///
/// @brief The header for View listener interfaces.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/Geometry.h>
namespace ultralight {
class View;
///
/// MessageSource types, @see ViewListener::OnAddConsoleMessage
///
enum MessageSource {
kMessageSource_XML = 0,
kMessageSource_JS,
kMessageSource_Network,
kMessageSource_ConsoleAPI,
kMessageSource_Storage,
kMessageSource_AppCache,
kMessageSource_Rendering,
kMessageSource_CSS,
kMessageSource_Security,
kMessageSource_ContentBlocker,
kMessageSource_Other,
};
///
/// MessageLevel types, @see ViewListener::OnAddConsoleMessage
///
enum MessageLevel {
kMessageLevel_Log = 1,
kMessageLevel_Warning = 2,
kMessageLevel_Error = 3,
kMessageLevel_Debug = 4,
kMessageLevel_Info = 5,
};
///
/// Cursor types, @see ViewListener::OnChangeCursor
///
enum Cursor {
kCursor_Pointer = 0,
kCursor_Cross,
kCursor_Hand,
kCursor_IBeam,
kCursor_Wait,
kCursor_Help,
kCursor_EastResize,
kCursor_NorthResize,
kCursor_NorthEastResize,
kCursor_NorthWestResize,
kCursor_SouthResize,
kCursor_SouthEastResize,
kCursor_SouthWestResize,
kCursor_WestResize,
kCursor_NorthSouthResize,
kCursor_EastWestResize,
kCursor_NorthEastSouthWestResize,
kCursor_NorthWestSouthEastResize,
kCursor_ColumnResize,
kCursor_RowResize,
kCursor_MiddlePanning,
kCursor_EastPanning,
kCursor_NorthPanning,
kCursor_NorthEastPanning,
kCursor_NorthWestPanning,
kCursor_SouthPanning,
kCursor_SouthEastPanning,
kCursor_SouthWestPanning,
kCursor_WestPanning,
kCursor_Move,
kCursor_VerticalText,
kCursor_Cell,
kCursor_ContextMenu,
kCursor_Alias,
kCursor_Progress,
kCursor_NoDrop,
kCursor_Copy,
kCursor_None,
kCursor_NotAllowed,
kCursor_ZoomIn,
kCursor_ZoomOut,
kCursor_Grab,
kCursor_Grabbing,
kCursor_Custom
};
///
/// @brief Interface for View-related events
///
/// @note For more info @see View::set_view_listener
///
class UExport ViewListener {
public:
virtual ~ViewListener() {}
///
/// Called when the page title changes
///
virtual void OnChangeTitle(ultralight::View* caller,
const String& title) {}
///
/// Called when the page URL changes
///
virtual void OnChangeURL(ultralight::View* caller,
const String& url) {}
///
/// Called when the tooltip changes (usually as result of a mouse hover)
///
virtual void OnChangeTooltip(ultralight::View* caller,
const String& tooltip) {}
///
/// Called when the mouse cursor changes
///
virtual void OnChangeCursor(ultralight::View* caller,
Cursor cursor) {}
///
/// Called when a message is added to the console (useful for errors / debug)
///
virtual void OnAddConsoleMessage(ultralight::View* caller,
MessageSource source,
MessageLevel level,
const String& message,
uint32_t line_number,
uint32_t column_number,
const String& source_id) {}
///
/// Called when the page wants to create a new View.
///
/// This is usually the result of a user clicking a link with target="_blank"
/// or by JavaScript calling window.open(url).
///
/// To allow creation of these new Views, you should create a new View in
/// this callback (eg, Renderer::CreateView()), resize it to your container,
/// and return it. You are responsible for displaying the returned View.
///
/// @param caller The View that called this event.
///
/// @param opener_url The URL of the page that initiated this request.
///
/// @param target_url The URL that the new View will navigate to.
///
/// @param is_popup Whether or not this was triggered by window.open().
///
/// @param popup_rect Popups can optionally request certain dimensions and
/// coordinates via window.open(). You can choose to
/// respect these or not by resizing/moving the View to
/// this rect.
///
/// @return Returns a RefPtr<> to a created View to use to satisfy the
/// the request (or return nullptr if you want to block the action).
///
virtual RefPtr<View> OnCreateChildView(ultralight::View* caller,
const String& opener_url,
const String& target_url,
bool is_popup,
const IntRect& popup_rect);
};
///
/// @brief Interface for Load-related events
///
/// @note For more info @see View::set_load_listener
///
class UExport LoadListener {
public:
virtual ~LoadListener() {}
///
/// Called when the page begins loading a new URL into a frame.
///
/// @param frame_id A unique ID for the frame.
///
/// @param is_main_frame Whether or not this is the main frame.
///
/// @param url The URL for the load.
///
virtual void OnBeginLoading(ultralight::View* caller,
uint64_t frame_id,
bool is_main_frame,
const String& url) {}
///
/// Called when the page finishes loading a URL into a frame.
///
/// @param frame_id A unique ID for the frame.
///
/// @param is_main_frame Whether or not this is the main frame.
///
/// @param url The URL for the load.
///
virtual void OnFinishLoading(ultralight::View* caller,
uint64_t frame_id,
bool is_main_frame,
const String& url) {}
///
/// Called when an error occurs while loading a URL into a frame.
///
/// @param frame_id A unique ID for the frame.
///
/// @param is_main_frame Whether or not this is the main frame.
///
/// @param url The URL for the load.
///
/// @param description A human-readable description of the error.
///
/// @param error_domain The name of the module that triggered the error.
///
/// @param error_code Internal error code generated by the module.
///
virtual void OnFailLoading(ultralight::View* caller,
uint64_t frame_id,
bool is_main_frame,
const String& url,
const String& description,
const String& error_domain,
int error_code) {}
///
/// Called when the JavaScript window object is reset for a new page load.
///
/// This is called before any scripts are executed on the page and is the
/// earliest time to setup any initial JavaScript state or bindings.
///
/// The document is not guaranteed to be loaded/parsed at this point. If
/// you need to make any JavaScript calls that are dependent on DOM elements
/// or scripts on the page, use OnDOMReady instead.
///
/// The window object is lazily initialized (this will not be called on pages
/// with no scripts).
///
/// @param frame_id A unique ID for the frame.
///
/// @param is_main_frame Whether or not this is the main frame.
///
/// @param url The URL for the load.
///
virtual void OnWindowObjectReady(ultralight::View* caller,
uint64_t frame_id,
bool is_main_frame,
const String& url) {}
///
/// Called when all JavaScript has been parsed and the document is ready.
///
/// This is the best time to make any JavaScript calls that are dependent on
/// DOM elements or scripts on the page.
///
/// @param frame_id A unique ID for the frame.
///
/// @param is_main_frame Whether or not this is the main frame.
///
/// @param url The URL for the load.
///
virtual void OnDOMReady(ultralight::View* caller,
uint64_t frame_id,
bool is_main_frame,
const String& url) {}
///
/// Called when the session history (back/forward state) is modified.
///
virtual void OnUpdateHistory(ultralight::View* caller) {}
};
} // namespace ultralight

View File

@ -1,190 +0,0 @@
///
/// @file Matrix.h
///
/// @brief The header for Matrix helpers
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/Geometry.h>
namespace ultralight {
///
/// 4x4 Matrix Helper
///
struct UExport Matrix4x4 {
///
/// Raw 4x4 matrix as an array
///
float data[16];
///
/// Set to identity matrix.
///
void SetIdentity();
};
///
/// Transformation Matrix helper
///
struct UExport Matrix {
#if defined(__x86_64__) || defined(_M_X64)
#if defined(_MSC_VER)
__declspec(align(16)) typedef double Aligned4x4[4][4];
#else
typedef double Aligned4x4[4][4] __attribute__((aligned(16)));
#endif
#else
typedef double Aligned4x4[4][4];
#endif
Aligned4x4 data;
///
/// Set to identity matrix.
///
void SetIdentity();
///
/// Set to an orthographic projection matrix suitable for use with our
/// vertex shaders. Optionally flip the y-coordinate space (eg, for OpenGL).
///
void SetOrthographicProjection(double screen_width, double screen_height,
bool flip_y);
///
/// Set to another matrix.
///
void Set(const Matrix& other);
///
/// Set to another matrix.
///
void Set(const Matrix4x4& other);
///
/// Set from raw affine members.
///
void Set(double a, double b, double c, double d, double e, double f);
///
/// Set from raw 4x4 components.
///
void Set(double m11, double m12, double m13, double m14,
double m21, double m22, double m23, double m24,
double m31, double m32, double m33, double m34,
double m41, double m42, double m43, double m44);
inline double m11() const { return data[0][0]; }
inline double m12() const { return data[0][1]; }
inline double m13() const { return data[0][2]; }
inline double m14() const { return data[0][3]; }
inline double m21() const { return data[1][0]; }
inline double m22() const { return data[1][1]; }
inline double m23() const { return data[1][2]; }
inline double m24() const { return data[1][3]; }
inline double m31() const { return data[2][0]; }
inline double m32() const { return data[2][1]; }
inline double m33() const { return data[2][2]; }
inline double m34() const { return data[2][3]; }
inline double m41() const { return data[3][0]; }
inline double m42() const { return data[3][1]; }
inline double m43() const { return data[3][2]; }
inline double m44() const { return data[3][3]; }
inline double a() const { return data[0][0]; }
inline double b() const { return data[0][1]; }
inline double c() const { return data[1][0]; }
inline double d() const { return data[1][1]; }
inline double e() const { return data[3][0]; }
inline double f() const { return data[3][1]; }
///
/// Whether or not this is an identity matrix.
///
bool IsIdentity() const;
///
/// Whether or not this is an identity matrix or translation.
///
bool IsIdentityOrTranslation() const;
///
/// Whether or not this matrix uses only affine transformations.
///
bool IsAffine() const;
///
/// Whether or not this is an identity, translation, or non-negative
/// uniform scale.
///
bool IsSimple() const;
///
/// Translate by x and y.
///
void Translate(double x, double y);
///
/// Scale by x and y.
///
void Scale(double x, double y);
///
/// Rotate matrix by theta (in degrees)
///
void Rotate(double theta);
///
/// Rotate matrix by x and y
///
void Rotate(double x, double y);
///
/// Transform (multiply) by another Matrix
///
void Transform(const Matrix& other);
///
/// Get the inverse of this matrix. May return false if not invertible.
///
bool GetInverse(Matrix& result) const;
///
/// Transform point by this matrix and get the result.
///
Point Apply(const Point& p) const;
///
/// Transform rect by this matrix and get the result as an axis-aligned rect.
///
Rect Apply(const Rect& r) const;
///
/// Get an integer hash of this matrix's members.
///
uint32_t Hash() const;
///
/// Get this matrix as unaligned 4x4 float components (for use passing to
/// GPU driver APIs).
///
Matrix4x4 GetMatrix4x4() const;
};
bool UExport operator==(const Matrix& a, const Matrix& b);
bool UExport operator!=(const Matrix& a, const Matrix& b);
bool UExport operator==(const Matrix4x4& a, const Matrix4x4& b);
bool UExport operator!=(const Matrix4x4& a, const Matrix4x4& b);
} // namespace ultralight

View File

@ -1,77 +0,0 @@
///
/// @file MouseEvent.h
///
/// @brief The header for the MouseEvent class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
namespace ultralight {
///
/// @brief A generic mouse event.
///
/// @note @see View::FireMouseEvent
///
class MouseEvent {
public:
///
/// The various MouseEvent types.
///
enum Type {
///
/// Mouse moved type
///
kType_MouseMoved,
///
/// Mouse button pressed type
///
kType_MouseDown,
///
/// Mouse button released type
///
kType_MouseUp,
};
///
/// The various mouse button types.
///
enum Button {
kButton_None = 0,
kButton_Left,
kButton_Middle,
kButton_Right,
};
///
/// The type of this MouseEvent
///
Type type;
///
/// The current x-position of the mouse, relative to the View
///
int x;
///
/// The current y-position of the mouse, relative to the View
///
int y;
///
/// The mouse button that was pressed/released, if any.
///
Button button;
};
} // namespace ultralight

View File

@ -1,538 +0,0 @@
///
/// @file RefPtr.h
///
/// @brief The header for all ref-counting utilities.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
/*
* Portions of the below code are derived from 'RefPtr.h' from Apple's WTF,
* with the following license header:
*
* Copyright (C) 2013-2014 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS CONTRIBUTORS
* 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.
*/
#pragma once
#include <Ultralight/Defines.h>
#include <assert.h>
#include <utility>
namespace ultralight {
///
/// @brief Interface for all ref-counted objects that will be managed using
/// the Ref<> and RefPtr<> smart pointers.
///
class UExport RefCounted {
public:
virtual void AddRef() const = 0;
virtual void Release() const = 0;
virtual int ref_count() const = 0;
protected:
virtual ~RefCounted();
};
inline void adopted(const void*) { }
template<typename T> class Ref;
template<typename T> class RefPtr;
///
/// @brief Helper for wrapping new objects with the Ref smart pointer.
///
/// All ref-counted object are created with an initial ref-count of '1'.
/// The AdoptRef() helper returns a Ref<T> without calling AddRef().
/// This is used for creating new objects, like so:
///
/// Ref<Object> ref = AdoptRef(*new ObjectImpl());
///
template<typename T> Ref<T> AdoptRef(T&);
///
/// @brief A non-nullable smart pointer.
///
/// This smart pointer automatically manages the lifetime of a RefCounted
/// object. Also guarantees that the managed instance is not NULL.
///
template<typename T> class Ref {
public:
///
/// Destroy Ref (wll decrement ref-count by one)
///
~Ref()
{
if (instance_)
instance_->Release();
}
///
/// Construct Ref from a reference. (Will increment ref-count by one)
///
Ref(T& object)
: instance_(&object)
{
instance_->AddRef();
}
///
/// Copy constructor.
///
Ref(const Ref& other)
: instance_(other.instance_)
{
instance_->AddRef();
}
///
/// Copy constructor with internal type conversion.
///
template<typename U>
Ref(Ref<U>& other)
: instance_(other.ptr())
{
instance_->AddRef();
}
///
/// Copy constructor with internal type conversion.
///
template<typename U>
Ref(const Ref<U>& other)
: instance_(other.ptr())
{
instance_->AddRef();
}
///
/// Move constructor.
///
Ref(Ref&& other)
: instance_(&other.LeakRef())
{
assert(instance_);
}
///
/// Move constructor.
///
template<typename U>
Ref(Ref<U>&& other)
: instance_(&other.LeakRef())
{
assert(instance_);
}
Ref& operator=(T& object)
{
assert(instance_);
object.AddRef();
instance_->Release();
instance_ = &object;
assert(instance_);
return *this;
}
Ref& operator=(const Ref& other)
{
assert(instance_);
other.instance_->AddRef();
instance_->Release();
instance_ = other.instance_;
assert(instance_);
return *this;
}
template<typename U>
Ref& operator=(const Ref<U>& other)
{
assert(instance_);
other.instance_->AddRef();
instance_->Release();
instance_ = other.instance_;
assert(instance_);
return *this;
}
Ref& operator=(Ref&& reference)
{
assert(instance_);
instance_->Release();
instance_ = &reference.LeakRef();
assert(instance_);
return *this;
}
template<typename U> Ref& operator=(Ref<U>&& reference)
{
assert(instance_);
instance_->Release();
instance_ = &reference.LeakRef();
assert(instance_);
return *this;
}
const T* operator->() const { assert(instance_); return instance_; }
T* operator->() { assert(instance_); return instance_; }
///
/// Get a pointer to wrapped object.
///
const T* ptr() const { assert(instance_); return instance_; }
///
/// Get a pointer to wrapped object.
///
T* ptr() { assert(instance_); return instance_; }
///
/// Get a reference to wrapped object.
///
const T& get() const { assert(instance_); return *instance_; }
///
/// Get a reference to wrapped object.
///
T& get() { assert(instance_); return *instance_; }
operator T&() { assert(instance_); return *instance_; }
operator const T&() const { assert(instance_); return *instance_; }
template<typename U> Ref<T> Replace(Ref<U>&&);
T& LeakRef() {
assert(instance_);
T* result = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
return *result;
}
friend inline bool operator==(const Ref& a, const Ref& b) {
return a.instance_ == b.instance_;
}
friend inline bool operator!=(const Ref& a, const Ref& b) {
return a.instance_ != b.instance_;
}
friend inline bool operator<(const Ref& a, const Ref& b) {
return a.instance_ < b.instance_;
}
protected:
friend Ref AdoptRef<T>(T&);
template<typename U> friend class RefPtr;
enum AdoptTag { Adopt };
Ref(T& object, AdoptTag)
: instance_(&object)
{
}
T* instance_;
};
template<typename T> template<typename U> Ref<T> Ref<T>::Replace(Ref<U>&& reference)
{
auto oldReference = AdoptRef(*instance_);
instance_ = &reference.LeakRef();
return oldReference;
}
template<typename T>
Ref<T> AdoptRef(T& reference)
{
adopted(&reference);
return Ref<T>(reference, Ref<T>::Adopt);
}
///
/// @brief A nullable smart pointer.
///
/// This smart pointer automatically manages the lifetime of a RefCounted
/// object. The managed instance may be NULL.
///
template<typename T> class RefPtr {
public:
///
/// Construct a NULL ref-pointer.
///
RefPtr()
: instance_(nullptr)
{
}
///
/// Construct a NULL ref-pointer.
///
RefPtr(std::nullptr_t)
: instance_(nullptr)
{
}
///
/// Construct from a pointer. (Will increment ref-count by one)
///
RefPtr(T* other)
: instance_(other)
{
if (instance_)
instance_->AddRef();
}
///
/// Copy constructor.
///
RefPtr(const RefPtr& other)
: instance_(other.instance_)
{
if (instance_)
instance_->AddRef();
}
///
/// Copy constructor with internal type conversion.
///
template<typename U>
RefPtr(const RefPtr<U>& other)
: instance_(other.instance_)
{
if (instance_)
instance_->AddRef();
}
///
/// Move constructor.
///
RefPtr(RefPtr&& other)
: instance_(other.LeakRef())
{
}
///
/// Move constructor.
///
template<typename U>
RefPtr(RefPtr<U>&& other)
: instance_(other.LeakRef())
{
}
///
/// Construct from a Ref
///
template<typename U>
RefPtr(const Ref<U>& other)
: instance_(other.instance_)
{
if (instance_)
instance_->AddRef();
}
///
/// Construct by moving from a Ref
///
template<typename U>
RefPtr(Ref<U>&& other);
///
/// Destroy RefPtr (wll decrement ref-count by one)
///
~RefPtr()
{
T* old_value = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
if (old_value)
old_value->Release();
}
///
/// Get a pointer to wrapped object.
///
T* get() const { return instance_; }
T* LeakRef() {
T* result = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
return result;
}
T& operator*() const { assert(instance_); return *instance_; }
T* operator->() const { return instance_; }
bool operator!() const { return !instance_; }
// This conversion operator allows implicit conversion to bool but not to other integer types.
typedef T* (RefPtr::*UnspecifiedBoolType);
operator UnspecifiedBoolType() const { return instance_ ? &RefPtr::instance_ : nullptr; }
RefPtr& operator=(const RefPtr&);
RefPtr& operator=(T*);
RefPtr& operator=(std::nullptr_t);
template<typename U> RefPtr& operator=(const RefPtr<U>&);
RefPtr& operator=(RefPtr&&);
template<typename U> RefPtr& operator=(RefPtr<U>&&);
template<typename U> RefPtr& operator=(Ref<U>&&);
friend inline bool operator==(const RefPtr& a, const RefPtr& b) {
return a.instance_ == b.instance_;
}
friend inline bool operator!=(const RefPtr& a, const RefPtr& b) {
return a.instance_ != b.instance_;
}
friend inline bool operator<(const RefPtr& a, const RefPtr& b) {
return a.instance_ < b.instance_;
}
void Swap(RefPtr&);
private:
T* instance_;
};
template<typename T>
template<typename U>
RefPtr<T>::RefPtr(Ref<U>&& reference)
: instance_(&reference.LeakRef())
{
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(const RefPtr& other)
{
RefPtr ptr = other;
Swap(ptr);
return *this;
}
template<typename T>
template<typename U>
RefPtr<T>& RefPtr<T>::operator=(const RefPtr<U>& other)
{
RefPtr ptr = other;
Swap(ptr);
return *this;
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(T* object)
{
RefPtr ptr = object;
Swap(ptr);
return *this;
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(std::nullptr_t)
{
T* old_instance = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
if (old_instance)
old_instance->Release();
return *this;
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(RefPtr&& other)
{
RefPtr ptr = std::move(other);
Swap(ptr);
return *this;
}
template<typename T>
template<typename U>
RefPtr<T>& RefPtr<T>::operator=(RefPtr<U>&& other)
{
RefPtr ptr = std::move(other);
Swap(ptr);
return *this;
}
template<typename T>
template<typename U>
RefPtr<T>& RefPtr<T>::operator=(Ref<U>&& other)
{
RefPtr ptr = std::move(other);
Swap(ptr);
return *this;
}
template<typename T>
void RefPtr<T>::Swap(RefPtr& other)
{
std::swap(instance_, other.instance_);
}
template<class T>
void Swap(RefPtr<T>& a, RefPtr<T>& b)
{
a.Swap(b);
}
template<typename T, typename U>
bool operator==(const RefPtr<T>& a, const RefPtr<U>& b)
{
return a.get() == b.get();
}
template<typename T, typename U>
bool operator==(const RefPtr<T>& a, U* b)
{
return a.get() == b;
}
template<typename T, typename U>
bool operator==(T* a, const RefPtr<U>& b)
{
return a == b.get();
}
template<typename T, typename U>
bool operator!=(const RefPtr<T>& a, const RefPtr<U>& b)
{
return a.get() != b.get();
}
template<typename T, typename U>
bool operator!=(const RefPtr<T>& a, U* b)
{
return a.get() != b;
}
template<typename T, typename U>
bool operator!=(T* a, const RefPtr<U>& b)
{
return a != b.get();
}
} // namespace ultralight

View File

@ -1,84 +0,0 @@
///
/// @file RenderTarget.h
///
/// @brief The header for the RenderTarget struct.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/Bitmap.h>
#include <Ultralight/Geometry.h>
namespace ultralight {
#pragma pack(push, 1)
///
/// @brief Rendering details for a View, to be used with your own GPUDriver
///
/// When using your own GPUDriver, each View is rendered to an offscreen
/// texture that you can display on a 3D quad in your application. This struct
/// provides all the details you need to display the corresponding texture in
/// your application.
///
struct UExport RenderTarget {
///
/// Whether this target is empty (null texture)
///
bool is_empty;
///
/// The viewport width (in device coordinates).
///
uint32_t width;
///
/// The viewport height (in device coordinates).
///
uint32_t height;
///
/// The GPUDriver-specific texture ID (you should bind the texture using
/// your implementation of GPUDriver::BindTexture before drawing a quad).
///
uint32_t texture_id;
///
/// The texture width (in pixels). This may be padded.
///
uint32_t texture_width;
///
/// The texture height (in pixels). This may be padded.
///
uint32_t texture_height;
///
/// The pixel format of the texture.
///
BitmapFormat texture_format;
///
/// UV coordinates of the texture (this is needed because the texture may
/// be padded).
///
Rect uv_coords;
///
/// The GPUDriver-specific render buffer ID.
///
uint32_t render_buffer_id;
RenderTarget();
};
#pragma pack(pop)
} // namespace ultralight

View File

@ -1,137 +0,0 @@
///
/// @file Renderer.h
///
/// @brief The header for the Renderer class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/Session.h>
#include <Ultralight/View.h>
namespace ultralight {
///
/// @brief This singleton manages the lifetime of all Views (@see View) and
/// coordinates painting, network requests, and event dispatch.
///
/// @note You don't have to create this instance directly if you use the
/// AppCore API. The App class will automatically create a Renderer and
/// perform all rendering within its run loop. @see App::Create
///
class UExport Renderer : public RefCounted {
public:
///
/// Create the Ultralight Renderer directly.
///
/// Unlike App::Create(), this does not use any native windows for drawing
/// and allows you to manage your own runloop and painting. This method is
/// recommended for those wishing to integrate the library into a game.
///
/// You should set up your Platform config, file-system, font loader,
/// and surface-factories/gpu-drivers before calling this function.
/// (@see <Ultralight/Platform.h>)
///
/// At a minimum, you will need to define a FontLoader ahead of time or this
/// call will fail. You can use the platform's native FontLoader by calling:
/// <pre>
/// /// This function is defined in <AppCore/Platform.h>
/// Platform::instance().set_font_loader(GetPlatformFontLoader());
/// </pre>
///
/// @note You should only create one Renderer per application lifetime.
///
/// @note: You should not call this if you are using App::Create(), it
/// creates its own renderer and provides default implementations for
/// various platform handlers automatically.
///
/// @return Renderer is ref-counted. This method returns a ref-pointer
/// to a new instance, you should store it in a RefPtr<> to keep
/// the instance alive.
///
static Ref<Renderer> Create();
///
/// Create a Session to store local data in (such as cookies, local storage,
/// application cache, indexed db, etc).
///
/// @note A default, persistent Session is already created for you. You
/// only need to call this if you want to create private, in-memory
/// session or use a separate session for each View.
///
/// @param is_persistent Whether or not to store the session on disk.
/// Persistent sessions will be written to the path
/// set in Config::cache_path
///
/// @param name A unique name for this session, this will be used to
/// generate a unique disk path for persistent sessions.
///
virtual Ref<Session> CreateSession(bool is_persistent, const String& name) = 0;
///
/// Get the default Session. This session is persistent (backed to disk) and
/// has the name "default".
///
virtual Ref<Session> default_session() = 0;
///
/// Create a new View.
///
/// @param width The initial width, in pixels.
///
/// @param height The initial height, in pixels.
///
/// @param transparent Whether or not the view background is transparent.
///
/// @param session The session to store local data in. Pass a nullptr to
/// use the default session.
///
/// @return Returns a ref-pointer to a new View instance. You should assign
/// it to either a Ref<View> (non-nullable) or RefPtr<View>
/// (nullable).
///
virtual Ref<View> CreateView(uint32_t width, uint32_t height,
bool transparent, RefPtr<Session> session,
bool force_cpu_renderer = false) = 0;
///
/// Update timers and dispatch internal callbacks. You should call this often
/// from your main application loop.
///
virtual void Update() = 0;
///
/// Render all active views to their respective render-targets/surfaces.
///
/// You should call this once per frame (usually in synchrony with the
/// monitor's refresh rate).
///
/// @note Views are only repainted if they actually need painting.
///
virtual void Render() = 0;
///
/// Attempt to release as much memory as possible. Don't call this from any
/// callbacks or driver code.
///
virtual void PurgeMemory() = 0;
///
/// Print detailed memory usage statistics to the log.
/// (@see Platform::set_logger())
///
virtual void LogMemoryUsage() = 0;
protected:
virtual ~Renderer();
};
} // namespace ultralight

View File

@ -1,53 +0,0 @@
///
/// @file ScrollEvent.h
///
/// @brief The header for the ScrollEvent class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
namespace ultralight {
///
/// @brief A generic scroll event.
///
/// @note @see View::FireScrollEvent
///
class ScrollEvent {
public:
///
/// The scroll event granularity type
///
enum Type {
/// The delta value is interpreted as number of pixels
kType_ScrollByPixel,
/// The delta value is interpreted as number of pages
kType_ScrollByPage,
};
///
/// Scroll granularity type
///
Type type;
///
/// Horizontal scroll amount
///
int delta_x;
///
/// Vertical scroll amount
///
int delta_y;
};
} // namespace ultralight

View File

@ -1,53 +0,0 @@
///
/// @file Session.h
///
/// @brief The header for the Session class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/String.h>
namespace ultralight {
///
/// @brief A Session stores local data such as cookies, local storage,
/// and application cache for one or more Views.
///
/// @see Renderer::CreateSession
///
class UExport Session : public RefCounted {
public:
///
/// Whether or not this session is written to disk.
///
virtual bool is_persistent() const = 0;
///
/// A unique name identifying this session.
///
virtual String name() const = 0;
///
/// A unique numeric ID identifying this session.
///
virtual uint64_t id() const = 0;
///
/// The disk path of this session (only valid for persistent sessions).
///
virtual String disk_path() const = 0;
protected:
virtual ~Session();
};
} // namespace ultralight

View File

@ -1,120 +0,0 @@
///
/// @file String.h
///
/// @brief The header for the String class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String8.h>
#include <Ultralight/String16.h>
#include <Ultralight/String32.h>
namespace ultralight {
///
/// @brief UTF-16 String container with conversions for UTF-8 and UTF-32.
///
/// @note Internally, all strings are represented as UTF-16.
///
class UExport String {
public:
///
/// Create empty string
///
String();
///
/// Create from null-terminated, ASCII C-string
///
String(const char* str);
///
/// Create from raw, UTF-8 string with certain length
///
String(const char* str, size_t len);
///
/// Create from existing String8 (UTF-8).
///
String(const String8& str);
///
/// Create from raw UTF-16 string with certain length
///
String(const Char16* str, size_t len);
///
/// Create from existing String16 (UTF-16)
///
String(const String16& str);
///
/// Create from existing String32 (UTF-32)
///
String(const String32& str);
///
/// Copy constructor
///
String(const String& other);
///
/// Destructor
///
~String();
///
/// Assign string from another, copy is made
///
String& operator=(const String& other);
///
/// Append string with another
///
String& operator+=(const String& other);
///
/// Concatenation operator
///
inline friend String operator+(String lhs, const String& rhs) { lhs += rhs; return lhs; }
///
/// Get native UTF-16 string
///
String16& utf16() { return str_; }
///
/// Get native UTF-16 string
///
const String16& utf16() const { return str_; }
///
/// Convert to UTF-8 string
///
String8 utf8() const;
///
/// Convert to UTF-32 string
///
String32 utf32() const;
///
/// Check if string is empty or not
///
bool empty() const { return utf16().empty(); }
private:
String16 str_;
};
} // namespace ultralight

View File

@ -1,130 +0,0 @@
///
/// @file String16.h
///
/// @brief The header for the String16 class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <stddef.h>
namespace ultralight {
namespace detail {
template<int> struct selector;
template<> struct selector<4> { typedef char16_t Char16; };
template<> struct selector<2> { typedef wchar_t Char16; };
}
#ifdef DISABLE_NATIVE_WCHAR_T
// Force Char16 type to use char16_t, used on Windows when native wchar_t support is disabled.
typedef char16_t Char16;
#else
// We use wchar_t if size == 2, otherwise use char16_t
typedef detail::selector<sizeof(wchar_t)>::Char16 Char16;
#endif
///
/// @brief A UTF-16 string container.
///
class UExport String16 {
public:
// Make an empty String16
String16();
// Make a String16 from null-terminated ASCII C-string
String16(const char* c_str);
// Make a String16 from ASCII C-string with certain length
String16(const char* c_str, size_t len);
// Make a String16 from raw UTF-16 buffer with certain length
String16(const Char16* str, size_t len);
// Make a String16 from raw unsigned short UTF-16 buffer with certain length. Useful on Windows
// when native support for wchar_t is disabled (eg, /Zc:wchar_t-).
String16(const unsigned short* str, size_t len);
// Make a deep copy of String16
String16(const String16& other);
~String16();
// Assign a String16 to this one, deep copy is made
String16& operator=(const String16& other);
// Append a String16 to this one.
String16& operator+=(const String16& other);
// Concatenation operator
inline friend String16 operator+(String16 lhs, const String16& rhs) { lhs += rhs; return lhs; }
// Get raw UTF-16 data
Char16* data() { return data_; }
// Get raw UTF-16 data (const)
const Char16* data() const { return data_; }
// Get raw UTF-16 data as unsigned short. This is useful on Windows if you compile without native
// support for wchar_t (eg, /Zc:wchar_t-)
unsigned short* udata() { return reinterpret_cast<unsigned short*>(data_); }
// Get raw UTF-16 data as unsigned short (const).
const unsigned short* udata() const { return reinterpret_cast<const unsigned short*>(data_); }
// Get length in characters.
size_t length() const { return length_; }
// Get size in characters (synonym for length)
size_t size() const { return length_; }
// Check if string is empty.
bool empty() const { return !data_ || length_ == 0; }
// Get character at specific position
Char16& operator[](size_t pos) { return data_[pos]; }
// Get character at specific position (const)
const Char16& operator[](size_t pos) const { return data_[pos]; }
private:
Char16* data_;
size_t length_;
};
///
/// @brief A UTF-16 string vector.
///
class UExport String16Vector : public RefCounted {
public:
// Create an empty string vector
static Ref<String16Vector> Create();
// Create a string vector from an existing array (a deep copy is made)
static Ref<String16Vector> Create(const String16* stringArray, size_t len);
// Add an element to the back of the string vector
virtual void push_back(const String16& val) = 0;
// Get raw String16 vector array
virtual String16* data() = 0;
// Get the number of elements in vector
virtual size_t size() const = 0;
protected:
String16Vector();
virtual ~String16Vector();
String16Vector(const String16Vector&);
void operator=(const String16Vector&);
};
} // namespace ultralight

View File

@ -1,71 +0,0 @@
///
/// @file String32.h
///
/// @brief The header for the String32 class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <stddef.h>
namespace ultralight {
///
/// @brief A UTF-32 string container.
///
class UExport String32 {
public:
// Make an empty String32
String32();
// Make a String32 from raw UTF-32 string with certain length
String32(const char32_t* c_str, size_t len);
// Make a deep copy of String32
String32(const String32& other);
~String32();
// Assign a String32 to this one, deep copy is made
String32& operator=(const String32& other);
// Append a String32 to this one.
String32& operator+=(const String32& other);
// Concatenation operator
inline friend String32 operator+(String32 lhs, const String32& rhs) { lhs += rhs; return lhs; }
// Get raw UTF-32 data
char32_t* data() { return data_; }
// Get raw UTF-32 data (const)
const char32_t* data() const { return data_; }
// Get length in characters.
size_t length() const { return length_; }
// Get size in characters (synonym for length)
size_t size() const { return length_; }
// Check if string is empty.
bool empty() const { return !data_ || length_ == 0; }
// Get character at specific position
char32_t& operator[](size_t pos) { return data_[pos]; }
// Get character at specific position (const)
const char32_t& operator[](size_t pos) const { return data_[pos]; }
private:
char32_t* data_;
size_t length_;
};
} // namespace ultralight

View File

@ -1,74 +0,0 @@
///
/// @file String8.h
///
/// @brief The header for the String8 class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <stddef.h>
namespace ultralight {
///
/// @brief A UTF-8 string container.
//
class UExport String8 {
public:
// Make an empty String8
String8();
// Make a String8 from raw, null-terminated UTF-8 string
String8(const char* c_str);
// Make a String8 from raw UTF-8 string with certain length
String8(const char* c_str, size_t len);
// Make a deep copy of String8
String8(const String8& other);
~String8();
// Assign a String8 to this one, deep copy is made
String8& operator=(const String8& other);
// Append a String8 to this one.
String8& operator+=(const String8& other);
// Concatenation operator
inline friend String8 operator+(String8 lhs, const String8& rhs) { lhs += rhs; return lhs; }
// Get raw UTF-8 data
char* data() { return data_; }
// Get raw UTF-8 data (const)
const char* data() const { return data_; }
// Get length in characters.
size_t length() const { return length_; }
// Get size in characters (synonym for length)
size_t size() const { return length_; }
// Check if string is empty.
bool empty() const { return !data_ || length_ == 0; }
// Get character at specific position
char& operator[](size_t pos) { return data_[pos]; }
// Get character at specific position (const)
const char& operator[](size_t pos) const { return data_[pos]; }
private:
char* data_;
size_t length_;
};
} // namespace ultralight

View File

@ -1,29 +0,0 @@
// Copyright 2020 Ultralight, Inc. All rights reserved.
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/String8.h>
#include <Ultralight/String16.h>
#include <Ultralight/String32.h>
#include <Ultralight/String.h>
#include <Ultralight/Bitmap.h>
#include <Ultralight/Buffer.h>
#include <Ultralight/View.h>
#include <Ultralight/Session.h>
#include <Ultralight/KeyCodes.h>
#include <Ultralight/KeyEvent.h>
#include <Ultralight/Listener.h>
#include <Ultralight/Matrix.h>
#include <Ultralight/MouseEvent.h>
#include <Ultralight/Renderer.h>
#include <Ultralight/Geometry.h>
#include <Ultralight/RenderTarget.h>
#include <Ultralight/ScrollEvent.h>
#include <Ultralight/platform/Platform.h>
#include <Ultralight/platform/Config.h>
#include <Ultralight/platform/GPUDriver.h>
#include <Ultralight/platform/FileSystem.h>
#include <Ultralight/platform/FontLoader.h>
#include <Ultralight/platform/Surface.h>
#include <Ultralight/platform/Clipboard.h>
#include <Ultralight/platform/Logger.h>

View File

@ -1,307 +0,0 @@
///
/// @file View.h
///
/// @brief The header for the View class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/KeyEvent.h>
#include <Ultralight/JavaScript.h>
#include <Ultralight/MouseEvent.h>
#include <Ultralight/ScrollEvent.h>
#include <Ultralight/RenderTarget.h>
#include <Ultralight/Bitmap.h>
#include <Ultralight/Listener.h>
#include <Ultralight/platform/Surface.h>
namespace ultralight {
///
/// @brief The View class is used to load and display web content.
///
/// View is an offscreen web-page container that can be used to display
/// web-content in your application.
///
/// You can load content into a View via View::LoadURL() or View::LoadHTML()
/// and interact with it via View::FireMouseEvent() and similar API.
///
/// When displaying a View, the API is different depending on whether you
/// are using the CPU renderer or the GPU renderer:
///
/// When using the CPU renderer, you would get the underlying pixel-buffer
/// surface for a View via View::surface().
///
/// When using the GPU renderer, you would get the underlying render target
/// and texture information via View::render_target().
///
/// @note The API is not currently thread-safe, all calls must be made on the
/// same thread that the Renderer/App was created on.
///
class UExport View : public RefCounted {
public:
///
/// Get the URL of the current page loaded into this View, if any.
///
virtual String url() = 0;
///
/// Get the title of the current page loaded into this View, if any.
///
virtual String title() = 0;
///
/// Get the width of the View, in pixels.
///
virtual uint32_t width() const = 0;
///
/// Get the height of the View, in pixels.
///
virtual uint32_t height() const = 0;
///
/// Check if the main frame of the page is currently loading.
///
virtual bool is_loading() = 0;
///
/// Get the offscreen RenderTarget for the View.
///
/// @note Only valid when the GPU renderer is enabled in Config.
///
/// You can use this with your GPUDriver implementation to bind
/// and display the corresponding texture in your application.
///
virtual RenderTarget render_target() = 0;
///
/// Get the offscreen Surface for the View (pixel-buffer container).
///
/// @note Only valid when the CPU is enabled (will return a nullptr
/// otherwise)
///
/// The default Surface is BitmapSurface but you can provide your
/// own Surface implementation via Platform::set_surface_factory.
///
virtual Surface* surface() = 0;
///
/// Load a raw string of HTML, the View will navigate to it as a new page.
///
/// @param html The raw HTML string to load.
///
/// @param url An optional URL for this load (to make it appear as if we
/// we loaded this HTML from a certain URL). Can be used for
/// resolving relative URLs and cross-origin rules.
///
/// @param add_to_history Whether or not this load should be added to the
/// session's history (back/forward list).
///
virtual void LoadHTML(const String& html,
const String& url = "",
bool add_to_history = false) = 0;
///
/// Load a URL, the View will navigate to it as a new page.
///
/// @note You can use File URLs (eg, file:///page.html) but you must define
/// your own FileSystem implementation if you are not using AppCore.
/// @see Platform::set_file_system
///
virtual void LoadURL(const String& url) = 0;
///
/// Resize View to a certain size.
///
/// @param width The initial width, in pixels.
///
/// @param height The initial height, in pixels.
///
///
virtual void Resize(uint32_t width, uint32_t height) = 0;
///
/// Acquire the page's JSContext for use with the JavaScriptCore API
///
/// @note You can use the underlying JSContextRef with the JavaScriptCore
/// C API. This allows you to marshall C/C++ objects to/from
/// JavaScript, bind callbacks, and call JS functions directly.
///
/// @note The JSContextRef gets reset after each page navigation. You
/// should initialize your JavaScript state within the
/// OnWindowObjectReady and OnDOMReady events, @see ViewListener.
///
/// @note This call locks the internal context for the current thread.
/// It will be unlocked when the returned JSContext's ref-count goes
/// to zero. The lock is recursive, you can call this multiple times.
///
virtual Ref<JSContext> LockJSContext() = 0;
///
/// Helper function to evaluate a raw string of JavaScript and return the
/// result as a String.
///
/// @param script A string of JavaScript to evaluate in the main frame.
///
/// @param exception A string to store the exception in, if any. Pass a
/// nullptr if you don't care about exceptions.
///
/// @return Returns the JavaScript result typecast to a String.
///
///
/// @note You do not need to lock the JS context, it is done automatically.
///
/// @note If you need lower-level access to native JavaScript values, you
/// should instead lock the JS context and call JSEvaluateScript() in
/// the JavaScriptCore C API. @see <JavaScriptCore/JSBase.h>
///
virtual String EvaluateScript(const String& script, String* exception = nullptr) = 0;
///
/// Whether or not we can navigate backwards in history
///
virtual bool CanGoBack() = 0;
///
/// Whether or not we can navigate forwards in history
///
virtual bool CanGoForward() = 0;
///
/// Navigate backwards in history
///
virtual void GoBack() = 0;
///
/// Navigate forwards in history
///
virtual void GoForward() = 0;
///
/// Navigate to an arbitrary offset in history
///
virtual void GoToHistoryOffset(int offset) = 0;
///
/// Reload current page
///
virtual void Reload() = 0;
///
/// Stop all page loads
///
virtual void Stop() = 0;
///
/// Give focus to the View.
///
/// You should call this to give visual indication that the View has input
/// focus (changes active text selection colors, for example).
///
virtual void Focus() = 0;
///
/// Remove focus from the View and unfocus any focused input elements.
///
/// You should call this to give visual indication that the View has lost
/// input focus.
///
virtual void Unfocus() = 0;
///
/// Whether or not the View has focus.
///
virtual bool HasFocus() = 0;
///
/// Whether or not the View has an input element with visible keyboard focus
/// (indicated by a blinking caret).
///
/// You can use this to decide whether or not the View should consume
/// keyboard input events (useful in games with mixed UI and key handling).
///
virtual bool HasInputFocus() = 0;
///
/// Fire a keyboard event
///
/// @note Only 'Char' events actually generate text in input fields.
///
virtual void FireKeyEvent(const KeyEvent& evt) = 0;
///
/// Fire a mouse event
///
virtual void FireMouseEvent(const MouseEvent& evt) = 0;
///
/// Fire a scroll event
///
virtual void FireScrollEvent(const ScrollEvent& evt) = 0;
///
/// Set a ViewListener to receive callbacks for View-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_view_listener(ViewListener* listener) = 0;
///
/// Get the active ViewListener, if any
///
virtual ViewListener* view_listener() const = 0;
///
/// Set a LoadListener to receive callbacks for Load-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_load_listener(LoadListener* listener) = 0;
///
/// Get the active LoadListener, if any
///
virtual LoadListener* load_listener() const = 0;
///
/// Set whether or not this View should be repainted during the next
/// call to Renderer::Render
///
/// @note This flag is automatically set whenever the page content changes
/// but you can set it directly in case you need to force a repaint.
///
virtual void set_needs_paint(bool needs_paint) = 0;
///
/// Whether or not this View should be repainted during the next call to
/// Renderer::Render.
///
virtual bool needs_paint() const = 0;
///
/// Get the inspector for this View, this is useful for debugging and
/// inspecting pages locally. This will only succeed if you have the
/// inspector assets in your filesystem-- the inspector will look for
/// file:///inspector/Main.html when it first loads.
///
/// @note The inspector View is owned by the View and lazily-created on
/// first call. The initial dimensions are 10x10, you should call
/// View::Resize() on the returned View to resize it to your desired
/// dimensions.
///
virtual RefPtr<View> inspector() = 0;
protected:
virtual ~View();
};
} // namespace ultralight

View File

@ -1,51 +0,0 @@
///
/// @file Clipboard.h
///
/// @brief The header for the Clipboard interface.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String16.h>
namespace ultralight {
///
/// @brief Clipboard interface.
///
/// This is used for reading and writing data to the platform Clipboard.
///
/// AppCore automatically provides a platform-specific implementation of this
/// that cuts/copies/pastes to the OS clipboard when you call App::Create().
///
/// If you are using Renderer::Create() instead, you will need to provide your
/// own implementation of this. @see Platform::set_clipboard().
///
class UExport Clipboard {
public:
virtual ~Clipboard();
///
/// Clear the clipboard.
///
virtual void Clear() = 0;
///
/// Read plain text from the clipboard
///
virtual String16 ReadPlainText() = 0;
///
/// Write plain text to the clipboard.
///
virtual void WritePlainText(const String16& text) = 0;
};
} // namespace ultralight

View File

@ -1,230 +0,0 @@
///
/// @file Config.h
///
/// @brief The header for the Config struct.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String16.h>
namespace ultralight {
///
/// The winding order for front-facing triangles. (This is only used when the
/// GPU renderer is enabled)
///
/// @note In most 3D engines, there is the concept that triangles have a
/// a "front" and a "back". All the front-facing triangles (eg, those
/// that are facing the camera) are rendered, and all back-facing
/// triangles are culled (ignored). The winding-order of the triangle's
/// vertices is used to determine which side is front and back. You
/// should tell Ultralight which winding-order your 3D engine uses.
///
enum FaceWinding {
///
/// Clockwise Winding (Direct3D, etc.)
///
kFaceWinding_Clockwise,
///
/// Counter-Clockwise Winding (OpenGL, etc.)
///
kFaceWinding_CounterClockwise,
};
enum FontHinting {
///
/// Lighter hinting algorithm-- glyphs are slightly fuzzier but better
/// resemble their original shape. This is achieved by snapping glyphs to the
/// pixel grid only vertically which better preserves inter-glyph spacing.
///
kFontHinting_Smooth,
///
/// Default hinting algorithm-- offers a good balance between sharpness and
/// shape at smaller font sizes.
///
kFontHinting_Normal,
///
/// Strongest hinting algorithm-- outputs only black/white glyphs. The result
/// is usually unpleasant if the underlying TTF does not contain hints for
/// this type of rendering.
///
kFontHinting_Monochrome,
};
///
/// @brief Configuration settings for Ultralight.
///
/// This is intended to be implemented by users and defined before creating the
/// Renderer. @see Platform::set_config.
///
struct UExport Config {
///
/// The file path to the directory that contains Ultralight's bundled
/// resources (eg, cacert.pem and other localized resources).
///
String16 resource_path;
///
/// The file path to a writable directory that will be used to store cookies,
/// cached resources, and other persistent data.
///
String16 cache_path;
///
/// When enabled, each View will be rendered to an offscreen GPU texture
/// using the GPU driver set in Platform::set_gpu_driver. You can fetch
/// details for the texture via View::render_target.
///
/// When disabled (the default), each View will be rendered to an offscreen
/// pixel buffer. This pixel buffer can optionally be provided by the user--
/// for more info see <Ultralight/platform/Surface.h> and View::surface.
///
bool use_gpu_renderer = false;
///
/// The amount that the application DPI has been scaled (200% = 2.0).
/// This should match the device scale set for the current monitor.
///
/// Note: Device scales are rounded to nearest 1/8th (eg, 0.125).
///
double device_scale = 1.0;
///
/// The winding order for front-facing triangles. @see FaceWinding
///
/// Note: This is only used when the GPU renderer is enabled.
///
FaceWinding face_winding = kFaceWinding_CounterClockwise;
///
/// Whether or not images should be enabled.
///
bool enable_images = true;
///
/// Whether or not JavaScript should be enabled.
///
bool enable_javascript = true;
///
/// The hinting algorithm to use when rendering fonts. @see FontHinting
///
FontHinting font_hinting = kFontHinting_Normal;
///
/// The gamma to use when compositing font glyphs, change this value to
/// adjust contrast (Adobe and Apple prefer 1.8, others may prefer 2.2).
///
double font_gamma = 1.8;
///
/// Default font-family to use.
///
String16 font_family_standard = "Times New Roman";
///
/// Default font-family to use for fixed fonts. (pre/code)
///
String16 font_family_fixed = "Courier New";
///
/// Default font-family to use for serif fonts.
///
String16 font_family_serif = "Times New Roman";
///
/// Default font-family to use for sans-serif fonts.
///
String16 font_family_sans_serif = "Arial";
///
/// Default user-agent string.
///
String16 user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/608.3.10 (KHTML, like Gecko) "
"Ultralight/1.2.0 Safari/608.3.10";
///
/// Default user stylesheet. You should set this to your own custom CSS
/// string to define default styles for various DOM elements, scrollbars,
/// and platform input widgets.
///
String16 user_stylesheet;
///
/// Whether or not we should continuously repaint any Views or compositor
/// layers, regardless if they are dirty or not. This is mainly used to
/// diagnose painting/shader issues.
///
bool force_repaint = false;
///
/// When a CSS animation is active, the amount of time (in seconds) to wait
/// before triggering another repaint. Default is 60 Hz.
///
double animation_timer_delay = 1.0 / 60.0;
///
/// When a smooth scroll animation is active, the amount of time (in seconds)
/// to wait before triggering another repaint. Default is 60 Hz.
///
double scroll_timer_delay = 1.0 / 60.0;
///
/// The amount of time (in seconds) to wait before running the recycler (will
/// attempt to return excess memory back to the system).
///
double recycle_delay = 4.0;
///
/// Size of WebCore's memory cache in bytes.
///
/// @note You should increase this if you anticipate handling pages with
/// large resources, Safari typically uses 128+ MiB for its cache.
///
uint32_t memory_cache_size = 64 * 1024 * 1024;
///
/// Number of pages to keep in the cache. Defaults to 0 (none).
///
/// @note Safari typically caches about 5 pages and maintains an on-disk
/// cache to support typical web-browsing activities. If you increase
/// this, you should probably increase the memory cache size as well.
///
uint32_t page_cache_size = 0;
///
/// JavaScriptCore tries to detect the system's physical RAM size to set
/// reasonable allocation limits. Set this to anything other than 0 to
/// override the detected value. Size is in bytes.
///
/// This can be used to force JavaScriptCore to be more conservative with
/// its allocation strategy (at the cost of some performance).
///
uint32_t override_ram_size = 0;
///
/// The minimum size of large VM heaps in JavaScriptCore. Set this to a
/// lower value to make these heaps start with a smaller initial value.
///
uint32_t min_large_heap_size = 32 * 1024 * 1024;
///
/// The minimum size of small VM heaps in JavaScriptCore. Set this to a
/// lower value to make these heaps start with a smaller initial value.
///
uint32_t min_small_heap_size = 1 * 1024 * 1024;
};
} // namespace ultralight

View File

@ -1,93 +0,0 @@
///
/// @file FileSystem.h
///
/// @brief The header for the FileSystem interface.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String16.h>
namespace ultralight {
///
/// File Handle type used as unique ID for opened files.
///
#if defined(__WIN32__) || defined(_WIN32)
typedef size_t FileHandle;
#else
typedef int FileHandle;
#endif
///
/// Handle used to denote an invalid file.
///
const FileHandle invalidFileHandle = (FileHandle)-1;
///
/// @brief FileSystem interface.
///
/// This is used for loading File URLs (eg, <file:///page.html>).
///
/// You can provide the library with your own FileSystem implementation so that
/// file assets are loaded from your own pipeline (useful if you would like
/// to encrypt/compress your file assets or ship it in a custom format).
///
/// AppCore automatically provides a platform-specific implementation of this
/// that loads files from a local directory when you call App::Create().
///
/// If you are using Renderer::Create() instead, you will need to provide your
/// own implementation via `Platform::instance().set_file_system(). For
/// convenience, you can still use AppCore's file system implementation--
/// see the helper functions defined in <AppCore/Platform.h>.
///
/// To provide your own custom FileSystem implementation, you should inherit
/// from this class, handle the virtual member functions, and then pass an
/// instance of your class to `Platform::instance().set_file_system()` before
/// calling Renderer::Create() or App::Create().
///
class UExport FileSystem {
public:
virtual ~FileSystem();
///
/// Check if file path exists, return true if exists.
///
virtual bool FileExists(const String16& path) = 0;
///
/// Get file size of previously opened file, store result in 'result'. Return true on success.
///
virtual bool GetFileSize(FileHandle handle, int64_t& result) = 0;
///
/// Get file mime type (eg "text/html"), store result in 'result'. Return true on success.
///
virtual bool GetFileMimeType(const String16& path, String16& result) = 0;
///
/// Open file path for reading or writing. Return file handle on success, or invalidFileHandle on failure.
///
/// @NOTE: As of this writing (v1.2), this function is only used for reading.
///
virtual FileHandle OpenFile(const String16& path, bool open_for_writing) = 0;
///
/// Close previously-opened file.
///
virtual void CloseFile(FileHandle& handle) = 0;
///
/// Read from currently-opened file, return number of bytes read or -1 on failure.
///
virtual int64_t ReadFromFile(FileHandle handle, char* data, int64_t length) = 0;
};
} // namespace ultralight

View File

@ -1,132 +0,0 @@
///
/// @file FontLoader.h
///
/// @brief The header for the FontLoader interface.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String16.h>
#include <Ultralight/Buffer.h>
namespace ultralight {
///
/// Represents a font file, either on-disk path or in-memory file contents.
///
class UExport FontFile : public RefCounted {
public:
///
/// Create a font file from an on-disk file path.
///
/// @note The file path should already exist.
///
static Ref<FontFile> Create(const String16& filepath);
///
/// Create a font file from an in-memory buffer.
///
static Ref<FontFile> Create(Ref<Buffer> buffer);
///
/// Whether or not this font file was created from an in-memory buffer.
///
virtual bool is_in_memory() const = 0;
///
/// The file path (if any).
///
virtual String16 filepath() const = 0;
///
/// The in-memory buffer (if any).
///
virtual RefPtr<Buffer> buffer() const = 0;
///
/// Unique hash (if this is a filepath, only the path string is hashed).
///
virtual uint32_t hash() const = 0;
protected:
FontFile();
virtual ~FontFile();
FontFile(const FontFile&);
void operator=(const FontFile&);
};
///
/// @brief Font Loader interface, used for all font lookup operations.
///
/// Every operating system has its own library of installed system fonts. The
/// FontLoader interface is used to lookup these fonts and fetch the actual
/// font data (raw TTF/OTF file data) for a given a certain font description.
///
/// AppCore automatically provides a platform-specific implementation of this
/// that loads installed fonts from the OS when you call App::Create().
///
/// If you are using Renderer::Create() instead, you will need to provide your
/// own implementation via `Platform::instance().set_font_loader(). For
/// convenience, you can still use AppCore's font loader implementation--
/// see the helper functions defined in <AppCore/Platform.h>.
///
/// To provide your own custom FontLoader implementation, you should inherit
/// from this class, handle the virtual member functions, and then pass an
/// instance of your class to `Platform::instance().set_font_loader()` before
/// calling Renderer::Create() or App::Create().
///
class UExport FontLoader {
public:
virtual ~FontLoader();
///
/// Fallback font family name. Will be used if all other fonts fail to load.
///
/// @note This font should be guaranteed to exist (eg, FontLoader::Load
/// won't fail when passed this font family name).
///
virtual String16 fallback_font() const = 0;
///
/// Fallback font family name that can render the specified characters. This
/// is mainly used to support CJK (Chinese, Japanese, Korean) text display.
///
/// @param characters One or more UTF-16 characters. This is almost always
/// a single character.
///
/// @param weight Font weight.
///
/// @param italic Whether or not italic is requested.
///
/// @return Should return a font family name that can render the text.
///
virtual String16 fallback_font_for_characters(const String16& characters,
int weight,
bool italic) const = 0;
///
/// Get the actual font file data (TTF/OTF) for a given font description.
///
/// @param family Font family name.
///
/// @param weight Font weight.
///
/// @param italic Whether or not italic is requested.
///
/// @return A font file matching the given description (either an on-disk
/// font filepath or an in-memory file contents). You can return
/// NULL here and the loader will fallback to another font.
///
virtual RefPtr<FontFile> Load(const String16& family,
int weight,
bool italic) = 0;
};
} // namespace ultralight

Some files were not shown because too many files have changed in this diff Show More