Skip to content

Commit

Permalink
Fix SDL2 examples + remove SDL3's SDL_GL_BindTexture
Browse files Browse the repository at this point in the history
  • Loading branch information
madebr committed Apr 18, 2024
1 parent 12c42b3 commit 018c398
Show file tree
Hide file tree
Showing 32 changed files with 216 additions and 402 deletions.
15 changes: 12 additions & 3 deletions .github/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ if(USE_FIND_PACKAGE)
find_package(Vulkan REQUIRED)
endif()

find_package(JNI REQUIRED)

message(STATUS "sdlwiki root folder is ${sdlwiki_root}")
message(STATUS "output root folder is ${OUTPUT_ROOT}")

Expand Down Expand Up @@ -69,6 +71,8 @@ foreach(example_path IN LISTS example_paths)
string(MAKE_C_IDENTIFIER "${example_relative}" target)

add_library(${target} OBJECT "${example_path}")
target_compile_definitions(${target} PRIVATE __ANDROID__)
target_link_libraries(${target} PRIVATE JNI::JNI)

get_filename_component(example_relative_directory "${example_relative}" DIRECTORY)
get_filename_component(sdl_project "${example_relative_directory}" NAME)
Expand All @@ -86,13 +90,18 @@ foreach(example_path IN LISTS example_paths)
endif()
else()
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/${sdl_project}/include")
if(sdl_project MATCHES "^SDL2_[rt]tf")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL2_ttf")
elseif(sdl_project MATCHES "^SDL3_[rt]tf")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL3_ttf/include")
endif()
if(sdl_project MATCHES "^SDL2_rtf")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL2_ttf/include")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL2_rtf")
elseif(sdl_project MATCHES "^SDL3_ttf")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL3_ttf/include")
endif()
if(sdl_project MATCHES "^SDL2")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL2/include")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL2/include/SDL2")
elseif(sdl_project MATCHES "^SDL3")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL3/include")
target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../external/SDL3/src/video/khronos")
Expand Down Expand Up @@ -126,6 +135,6 @@ foreach(src IN LISTS MARKDOWN_SOURCES MEDIAWIKI_SOURCES)
NAME "${src_relative}"
COMMAND "${PANDOC_BIN}" --fail-if-warnings --verbose -f ${fmt} -t html -o "${OUTPUT_ROOT}/${src_relative}.html" "${src}"
)
set_property(TEST "${src_relative}" PROPERTY TIMEOUT 2)
set_property(TEST "${src_relative}" PROPERTY TIMEOUT 5)
endforeach()

83 changes: 51 additions & 32 deletions .github/extract_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@


def markdown_extract(path: Path):
results = []
in_example_section = False
in_example_block = False
in_code_block = False
Expand All @@ -34,14 +35,19 @@ def markdown_extract(path: Path):
block_language = "c"
assert block_language in ("c", "c++", "output"), f"language is \"{block_language}\""
in_code_block = not in_code_block
was_in_example_block = in_example_block
in_example_block = in_code_block and block_language in ("c", "c++")
if was_in_example_block and not in_example_block:
results.append((language, "".join(example_code_lines)))
language = None
example_code_lines = []
if in_example_block:
language = block_language
continue
if in_example_block:
example_code_lines.append(line)

return language, "".join(example_code_lines)
return results


RE_MEDIAWIKI_SECTION = re.compile(r"^==([^=]+)==")
Expand All @@ -50,6 +56,7 @@ def markdown_extract(path: Path):


def mediawiki_extract(path: Path):
results = []
in_example_section = False
in_code_block = False
language = None
Expand All @@ -70,13 +77,16 @@ def mediawiki_extract(path: Path):
in_code_block = True
continue
if in_code_block:
if m:= RE_MEDIAWIKI_CODE_END.match(line):
if m := RE_MEDIAWIKI_CODE_END.match(line):
in_code_block = False
results.append((language, "".join(example_code_lines)))
language = None
example_code_lines = []
continue
if in_code_block:
example_code_lines.append(line)

return language, "".join(example_code_lines)
return results


def headers_from_path(path: Path) -> list[str]:
Expand Down Expand Up @@ -110,51 +120,57 @@ def headers_from_path(path: Path) -> list[str]:
return headers


def extract_example(path: Path, docroot: Path, outdir: Path) -> Optional[Union[Path, int]]:
def extract_example(path: Path, docroot: Path, outdir: Path) -> list[Optional[Union[Path, int]]]:
if path.suffix == ".mediawiki":
language, example_code = mediawiki_extract(path)
examples = mediawiki_extract(path)
elif path.suffix == ".md":
language, example_code = markdown_extract(path)
examples = markdown_extract(path)
else:
print(f"Invalid document \"{path}\"", file=sys.stderr)
return 2

if not example_code or not language:
if not examples:
print(f"No example code found in \"{path}\"", file=sys.stderr)
return None

if "int argc" not in example_code:
example_code = "int main(int argc, char *argv[]) {\n (void)argc;\n (void)argv;\n" + example_code + " return 0;\n}\n"
outpaths = []

if "#include" not in example_code:
headers = headers_from_path(path)
if language == "c++":
for example_i, (language, example_code) in enumerate(examples):
if "int argc" not in example_code and "#include" not in example_code:
example_code = "int example_function(void) {\n" + example_code + " return 0;\n}\n"

if "#include" not in example_code:
headers = headers_from_path(path)
if language == "c++":
headers.extend([
"iostream",
"vector",
])
headers.extend([
"iostream",
"vector",
"stdio.h",
"stdlib.h",
])
headers.extend([
"stdio.h",
"stdlib.h",
])
example_code = "\n".join(f"#include <{f}>" for f in headers) + "\n" + example_code
example_code = "\n".join(f"#include <{f}>" for f in headers) + "\n" + example_code

doc_relative = path.relative_to(docroot)
doc_relative = path.relative_to(docroot)

out_suffix = {
"c": ".c",
"c++": ".cpp",
}[language]
outpath = outdir / doc_relative
outpath = outpath.with_suffix(out_suffix)
out_suffix = {
"c": ".c",
"c++": ".cpp",
}[language]
outpath = outdir / doc_relative
if len(examples) > 1:
outpath = outpath.with_stem(outpath.stem + f"-{example_i + 1}")
outpath = outpath.with_suffix(out_suffix)

parent = outpath.parent
parent.mkdir(exist_ok=True)
parent = outpath.parent
parent.mkdir(exist_ok=True)

with outpath.open("w") as f:
f.write(example_code)
with outpath.open("w") as f:
f.write(example_code)

return outpath
outpaths.append(outpath)
return outpaths


def main():
Expand All @@ -171,12 +187,15 @@ def main():

cmake_example_paths = []
rc = 0
for path, example_path in zip(args.doc, example_paths):
for example_path in example_paths:
if example_path is None:
continue
if isinstance(example_path, Path):
cmake_example_paths.append(str(example_path))
continue
if isinstance(example_path, list):
cmake_example_paths.extend(str(p) for p in example_path)
continue
if example_path == 2:
rc = 2
continue
Expand Down
13 changes: 7 additions & 6 deletions SDL2/SDL_AddHintCallback.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,28 +40,29 @@ This function is available since SDL 2.0.0.
void callback(void* f_name, const char* name, const char* oldValue, const char* newValue) {
if (newValue == (const char*)"1") {
printf("Hi %s\n", static_cast<char*>(f_name));
printf("Hi %s\n", (const char *)f_name);
}
}
...
/* ... */
SDL_SetHint(SDL_HINT_XINPUT_ENABLED, "0");
...
/* ... */
SDL_Init(SDL_INIT_EVERYTHING);
...
/* ... */
SDL_Event event;
while(SDL_PollEvent(&event) != 0)
{
// You can change hint here
}
...
/* ... */
SDL_AddHintCallback(SDL_HINT_XINPUT_ENABLED, callback, const_cast<char*>("SDL"));
SDL_AddHintCallback(SDL_HINT_XINPUT_ENABLED, callback, "SDL");
```

----
Expand Down
15 changes: 8 additions & 7 deletions SDL2/SDL_AddTimer.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,27 +67,28 @@ This function is available since SDL 2.0.0.
Uint32 callback(Uint32 interval, void* name) {
printf("Hello %s!\n", static_cast<char*>(name));
printf("Hello %s!\n", (const char *)name);
return 0;
}
...
/* ... */
// Initialize timer
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
...
/* ... */
// Set timer to 1 second
SDL_TimerID timerID = SDL_AddTimer(1000, callback, const_cast<char*>("SDL"));
SDL_TimerID timerID = SDL_AddTimer(1000, callback, "SDL");
// Main loop
while(!quit) {
...
SDL_bool quit;
while (!quit) {
/* ... */
}
// Remove timer after main loop
Expand Down
6 changes: 3 additions & 3 deletions SDL2/SDL_AllocFormat.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ This function is available since SDL 2.0.0.
```c
SDL_PixelFormat* pixel_format = NULL;
...
/* ... */
SDL_Init(SDL_INIT_EVERYTHING);
pixel_format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA32)
pixel_format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA32);
if (pixel_format == NULL) printf( "Error: %s\n", SDL_GetError() );
...
/* ... */
printf("Amount of bytes: %i\n", pixel_format->BytesPerPixel);
Expand Down
22 changes: 14 additions & 8 deletions SDL2/SDL_AllocPalette.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,25 @@ This function is available since SDL 2.0.0.
## Example
```c
SDL_Palette* palette = nullptr;
SDL_Palette* palette = NULL;
...
/* ... */
SDL_Init(SDL_EVERYTHING);
SDL_Init(SDL_INIT_VIDEO);
// Create window and renderer
SDL_Window *window;
SDL_Renderer *renderer;
SDL_CreateWindowAndRenderer(640, 480, 0, &window, &renderer);
// Create new palette with 4 colors
palette = SDL_AllocPalette(4);
if (palette == nullptr) printf( "Error: %s\n", SDL_GetError() );
if (palette == NULL) printf( "Error: %s\n", SDL_GetError() );
...
/* ... */
// Set green and blue of the first color in the palette to 0
Expand All @@ -63,12 +69,12 @@ palette->colors[0].b = 0;
// Set render draw color to red
SDL_SetRenderDrawColor(renderer, palette->colors[0].r, palette->colors[0].g, palette->colors.b, palette->colors[0].a);
SDL_SetRenderDrawColor(renderer, palette->colors[0].r, palette->colors[0].g, palette->colors[0].b, palette->colors[0].a);
...
/* ... */
SDL_FreePalette(palette);
palette = nullptr;
palette = NULL;
```

----
Expand Down
3 changes: 2 additions & 1 deletion SDL2/SDL_AudioSpec.mediawiki
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ SR (7.1 surround)

== Code Examples ==

<syntaxhighlight lang='c++'>
<syntaxhighlight lang='c'>
SDL_AudioSpec want, have;
SDL_AudioDeviceID dev;
extern void SDLCALL MyAudioCallback(void *userdata, Uint8 *stream, int len);

SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */
want.freq = 48000;
Expand Down
12 changes: 11 additions & 1 deletion SDL2/SDL_AudioStatus.mediawiki
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ An enumeration of audio device states.
|}

== Code Examples ==
<syntaxhighlight lang='c++'>
<syntaxhighlight lang='c'>
void printStatus(SDL_AudioDeviceID dev)
{
switch (SDL_GetAudioDeviceStatus(dev))
Expand All @@ -30,6 +30,16 @@ void printStatus(SDL_AudioDeviceID dev)

// device starts paused
SDL_AudioDeviceID dev;
SDL_AudioSpec desired;
SDL_AudioSpec obtained;
extern void SDLCALL audio_callback(void *userdata, Uint8 * stream, int len);

SDL_zero(desired);
desired.freq = 44100;
desired.format = AUDIO_F32SYS;
desired.channels = 1;
desired.samples = 4096;
desired.callback = audio_callback;
dev = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, 0);
if (dev != 0)
{
Expand Down
6 changes: 5 additions & 1 deletion SDL2/SDL_BlitSurface.mediawiki
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ If either \c srcrect or \c dstrect are NULL, the entire surface (\c src or

== Code Examples ==

<syntaxhighlight lang='c++'>
<syntaxhighlight lang='c'>
extern SDL_Surface *surface;
extern SDL_Rect source_rect;
SDL_Surface *temp_surface;

SDL_BlitSurface(surface, &source_rect, temp_surface, NULL);
</syntaxhighlight>

Expand Down
Loading

0 comments on commit 018c398

Please sign in to comment.