Commit c6f9fb97 authored by Niklas Haas's avatar Niklas Haas
Browse files

demos: refactor components and integrate into build system

Major refactor of the demos/ directory, accomplishing a number of goals:

1. Allowing easy switching between OpenGL and Vulkan variants.
2. Supporting both GLFW and SDL2, chosen at compile time. The window
   management itself was made entirely modular for this purpose.
3. Refactor all of the demo programs atop these new abstractions.
4. Building them correctly and automatically (via meson).

I also plan on factoring out the nuklear code to its own helper, but I
avoided making that part of the same commit to prevent it from blowing
up any further.
parent 0697e572
Pipeline #78998 passed with stages
in 9 minutes and 15 seconds
/demos/sdl2
/demos/colors
/demos/nuklear
/demos/plplay
/demos/video-filtering
/build*
/tags
/TAGS
......
[submodule "demos/3rdparty/nuklear"]
path = demos/3rdparty/nuklear
url = https://github.com/Immediate-Mode-UI/Nuklear.git
Subproject commit 0a2b04bfaa4b132a9c8bf56d13ea6b0065451077
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
/* Compiling:
*
* gcc colors.c glfw.c -o ./colors -O2 -lm -DUSE_VK \
* $(pkg-config --cflags --libs glfw3 vulkan libplacebo)
*
* or:
*
* gcc colors.c glfw.c -o ./colors -O2 -lm -DUSE_GL \
* $(pkg-config --cflags --libs glfw3 libplacebo)
/* Simplistic demo that just makes the window colorful, including alpha
* transparency if supported by the windowing system.
*
* License: CC0 / Public Domain
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <libplacebo/renderer.h>
#include "common.h"
#include "window.h"
#include "glfw.h"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
struct pl_context *ctx;
static struct winstate win;
static struct pl_context *ctx;
static struct window *win;
static void uninit(int ret)
{
glfw_uninit(&win);
window_destroy(&win);
pl_context_destroy(&ctx);
exit(ret);
}
......@@ -51,40 +37,36 @@ static void evolve_rgba(float rgba[4], int *pos)
int main(int argc, char **argv)
{
ctx = pl_context_create(PL_API_VER, &(struct pl_context_params) {
.log_cb = pl_log_color,
.log_level = PL_LOG_DEBUG,
});
assert(ctx);
if (!glfw_init(ctx, &win, WINDOW_WIDTH, WINDOW_HEIGHT, WIN_ALPHA))
ctx = demo_context();
win = window_create(ctx, "colors demo", 640, 480, WIN_ALPHA);
if (!win)
uninit(1);
float rgba[4] = {0.0, 0.0, 0.0, 1.0};
int rainbow_pos = 0;
while (!win.window_lost) {
while (!win->window_lost) {
struct pl_swapchain_frame frame;
bool ok = pl_swapchain_start_frame(win.swapchain, &frame);
bool ok = pl_swapchain_start_frame(win->swapchain, &frame);
if (!ok) {
// Something unexpected happened, perhaps the window is not
// visible? Wait for events and try again.
glfwWaitEvents();
window_poll(win, true);
continue;
}
assert(frame.fbo->params.blit_dst);
evolve_rgba(rgba, &rainbow_pos);
pl_tex_clear(win.gpu, frame.fbo, rgba);
pl_tex_clear(win->gpu, frame.fbo, rgba);
ok = pl_swapchain_submit_frame(win.swapchain);
ok = pl_swapchain_submit_frame(win->swapchain);
if (!ok) {
fprintf(stderr, "libplacebo: failed submitting frame!\n");
uninit(3);
}
pl_swapchain_swap_buffers(win.swapchain);
glfwPollEvents();
pl_swapchain_swap_buffers(win->swapchain);
window_poll(win, false);
}
uninit(0);
......
#pragma once
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// Needed to include the generated in-tree config.h
#include "../src/config.h"
#include <libplacebo/context.h>
#include <libplacebo/renderer.h>
static inline struct pl_context *demo_context() {
return pl_context_create(PL_API_VER, &(struct pl_context_params) {
.log_cb = isatty(fileno(stdout)) ? pl_log_color : pl_log_simple,
#ifdef NDEBUG
.log_level = PL_LOG_INFO,
#else
.log_level = PL_LOG_DEBUG,
#endif
});
}
// License: CC0 / Public Domain
#pragma once
#if !defined(USE_GL) && !defined(USE_VK) || defined(USE_GL) && defined(USE_VK)
#error Specify exactly one of -DUSE_GL or -DUSE_VK when compiling!
#endif
#ifdef USE_VK
#define GLFW_INCLUDE_VULKAN
#endif
#include <GLFW/glfw3.h>
#ifdef USE_VK
#include <libplacebo/vulkan.h>
#endif
#ifdef USE_GL
#include <libplacebo/opengl.h>
#endif
struct winstate {
struct pl_context *ctx;
const struct pl_swapchain *swapchain;
const struct pl_gpu *gpu;
bool window_lost;
GLFWwindow *win;
#ifdef USE_VK
VkSurfaceKHR surf;
const struct pl_vulkan *vk;
const struct pl_vk_inst *vk_inst;
#endif
#ifdef USE_GL
const struct pl_opengl *gl;
#endif
};
enum winflags {
WIN_ALPHA,
WIN_HDR,
};
bool glfw_init(struct pl_context *ctx, struct winstate *w,
int width, int height, enum winflags flags);
void glfw_uninit(struct winstate *w);
/* Compiling:
*
* gcc sdl2.c -o ./sdl2 -O2 \
* $(pkg-config --cflags --libs sdl2 SDL2_image vulkan libplacebo)
*
* Notes:
*
* - This proof-of-concept is extremely naive. It uses global state, and
* ignores uninitialization on errors (just exit()s). This is probably not
* what you should be doing for a real program, but I wanted to avoid the
* example becoming too complicated.
/* Simple image viewer that opens an image using SDL2_image and presents it
* to the screen.
*
* License: CC0 / Public Domain
*/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>
#include <SDL2/SDL_image.h>
#include <vulkan/vulkan.h>
#include "common.h"
#include "window.h"
#include <libplacebo/renderer.h>
#include <libplacebo/shaders/lut.h>
#include <libplacebo/utils/upload.h>
#include <libplacebo/vulkan.h>
// static configuration
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
// Static configuration, done in the file to keep things simple
static const char *icc_profile = ""; // path to ICC profile
static const char *lut_file = ""; // path to .cube lut
// program state
SDL_Window *window;
VkSurfaceKHR surf;
struct pl_context *ctx;
// Program state
static struct pl_context *ctx;
static struct window *win;
const struct pl_vulkan *vk;
const struct pl_vk_inst *vk_inst;
const struct pl_swapchain *swapchain;
// for rendering
const struct pl_tex *img_tex;
const struct pl_tex *osd_tex;
struct pl_plane img_plane;
struct pl_plane osd_plane;
struct pl_renderer *renderer;
struct pl_custom_lut *lut;
struct file icc_file;
// For rendering
static const struct pl_tex *img_tex;
static const struct pl_tex *osd_tex;
static struct pl_plane img_plane;
static struct pl_plane osd_plane;
static struct pl_renderer *renderer;
static struct pl_custom_lut *lut;
static struct file icc_file;
struct file
{
......@@ -105,138 +83,32 @@ static void close_file(struct file *file)
*file = (struct file) {0};
}
static void uninit()
static void uninit(int ret)
{
pl_renderer_destroy(&renderer);
pl_tex_destroy(vk->gpu, &img_tex);
pl_tex_destroy(vk->gpu, &osd_tex);
pl_swapchain_destroy(&swapchain);
pl_vulkan_destroy(&vk);
vkDestroySurfaceKHR(vk_inst->instance, surf, NULL);
pl_vk_inst_destroy(&vk_inst);
pl_context_destroy(&ctx);
pl_tex_destroy(win->gpu, &img_tex);
pl_tex_destroy(win->gpu, &osd_tex);
close_file(&icc_file);
pl_lut_free(&lut);
SDL_DestroyWindow(window);
SDL_Quit();
}
static void init_sdl() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "Failed to initialize SDL2: %s\n", SDL_GetError());
exit(1);
}
uint32_t window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE |
SDL_WINDOW_VULKAN;
window = SDL_CreateWindow("libplacebo demo",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
WINDOW_WIDTH, WINDOW_HEIGHT, window_flags);
if (!window) {
fprintf(stderr, "Failed creating window: %s\n", SDL_GetError());
exit(1);
}
}
static void init_placebo() {
ctx = pl_context_create(PL_API_VER, &(struct pl_context_params) {
.log_cb = pl_log_color,
.log_level = PL_LOG_DEBUG,
});
assert(ctx);
}
static void init_vulkan()
{
struct pl_vk_inst_params iparams = pl_vk_inst_default_params;
#ifndef NDEBUG
iparams.debug = true;
#endif
unsigned int num = 0;
if (!SDL_Vulkan_GetInstanceExtensions(window, &num, NULL)) {
fprintf(stderr, "Failed enumerating vulkan extensions: %s\n", SDL_GetError());
exit(1);
}
iparams.extensions = malloc(num * sizeof(const char *));
iparams.num_extensions = num;
assert(iparams.extensions);
bool ok = SDL_Vulkan_GetInstanceExtensions(window, &num,(const char **) iparams.extensions);
assert(ok);
if (num > 0) {
printf("Requesting %d additional vulkan extensions:\n", num);
for (int i = 0; i < num; i++)
printf(" %s\n", iparams.extensions[i]);
}
vk_inst = pl_vk_inst_create(ctx, &iparams);
if (!vk_inst) {
fprintf(stderr, "Failed creating vulkan instance!\n");
exit(2);
}
free((const char **) iparams.extensions);
if (!SDL_Vulkan_CreateSurface(window, vk_inst->instance, &surf)) {
fprintf(stderr, "Failed creating vulkan surface: %s\n", SDL_GetError());
exit(1);
}
struct pl_vulkan_params params = pl_vulkan_default_params;
params.instance = vk_inst->instance;
params.surface = surf;
params.allow_software = true;
vk = pl_vulkan_create(ctx, &params);
if (!vk) {
fprintf(stderr, "Failed creating vulkan device!\n");
exit(2);
}
swapchain = pl_vulkan_create_swapchain(vk, &(struct pl_vulkan_swapchain_params) {
.surface = surf,
.present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR,
});
if (!swapchain) {
fprintf(stderr, "Failed creating vulkan swapchain!\n");
exit(2);
}
int w = WINDOW_WIDTH, h = WINDOW_HEIGHT;
if (!pl_swapchain_resize(swapchain, &w, &h)) {
fprintf(stderr, "Failed resizing vulkan swapchain!\n");
exit(2);
}
if (w != WINDOW_WIDTH || h != WINDOW_HEIGHT)
printf("Note: window dimensions differ (got %dx%d)\n", w, h);
window_destroy(&win);
pl_context_destroy(&ctx);
exit(ret);
}
static bool upload_plane(const char *filename, const struct pl_tex **tex,
static bool upload_plane(const SDL_Surface *img, const struct pl_tex **tex,
struct pl_plane *plane)
{
if (!filename)
return true;
SDL_Surface *img = IMG_Load(filename);
if (!img) {
fprintf(stderr, "Failed loading '%s': %s\n", filename, SDL_GetError());
if (!img)
return false;
}
SDL_Surface *fixed = NULL;
const SDL_PixelFormat *fmt = img->format;
if (SDL_ISPIXELFORMAT_INDEXED(fmt->format)) {
SDL_Surface *fixed;
// libplacebo doesn't handle indexed formats yet
fixed = SDL_CreateRGBSurfaceWithFormat(0, img->w, img->h, 32,
SDL_PIXELFORMAT_ABGR8888);
SDL_BlitSurface(img, NULL, fixed, NULL);
SDL_FreeSurface(img);
SDL_BlitSurface((SDL_Surface *) img, NULL, fixed, NULL);
img = fixed;
fmt = img->format;
}
......@@ -253,37 +125,12 @@ static bool upload_plane(const char *filename, const struct pl_tex **tex,
uint64_t masks[4] = { fmt->Rmask, fmt->Gmask, fmt->Bmask, fmt->Amask };
pl_plane_data_from_mask(&data, masks);
bool ok = pl_upload_plane(vk->gpu, plane, tex, &data);
SDL_FreeSurface(img);
bool ok = pl_upload_plane(win->gpu, plane, tex, &data);
SDL_FreeSurface(fixed);
return ok;
}
static void init_rendering(const char *img, const char *osd)
{
if (!upload_plane(img, &img_tex, &img_plane)) {
fprintf(stderr, "Failed uploading image plane!\n");
exit(2);
}
if (!upload_plane(osd, &osd_tex, &osd_plane))
fprintf(stderr, "Failed uploading OSD plane.. continuing anyway\n");
if (!open_file(icc_profile, &icc_file))
fprintf(stderr, "Failed opening ICC profile.. continuing anyway\n");
struct file lutf;
if (open_file(lut_file, &lutf) && lutf.size) {
if (!(lut = pl_lut_parse_cube(ctx, lutf.data, lutf.size)))
fprintf(stderr, "Failed parsing LUT.. continuing anyway\n");
close_file(&lutf);
}
// Create a renderer instance
renderer = pl_renderer_create(ctx, vk->gpu);
}
static void render_frame(const struct pl_swapchain_frame *frame)
static bool render_frame(const struct pl_swapchain_frame *frame)
{
const struct pl_tex *img = img_plane.texture;
struct pl_frame image = {
......@@ -321,64 +168,89 @@ static void render_frame(const struct pl_swapchain_frame *frame)
}
if (pl_frame_is_cropped(&target))
pl_frame_clear(vk->gpu, &target, (float[3]) {0} );
pl_frame_clear(win->gpu, &target, (float[3]) {0} );
// Use the heaviest preset purely for demonstration/testing purposes
struct pl_render_params params = pl_render_high_quality_params;
params.lut = lut;
if (!pl_render_image(renderer, &image, &target, &params)) {
fprintf(stderr, "Failed rendering frame!\n");
uninit();
exit(2);
}
return pl_render_image(renderer, &image, &target, &params);
}
int main(int argc, char **argv)
{
if (argc < 2 || argc > 3) {
fprintf(stderr, "Usage: ./sdl2 <image> [<overlay>]\n");
fprintf(stderr, "Usage: %s <image> [<overlay>]\n", argv[0]);
return 255;
}
const char *file = argv[1];
const char *overlay = argc > 2 ? argv[2] : NULL;
ctx = demo_context();
// Load image, do this first so we can use it for the window size
SDL_Surface *img = IMG_Load(file);
if (!img) {
fprintf(stderr, "Failed loading '%s': %s\n", file, SDL_GetError());
uninit(1);
}
// Create window
unsigned int start = SDL_GetTicks();
win = window_create(ctx, "SDL2_image demo", img->w, img->h, 0);
if (!win)
uninit(1);
int ret = 0;
init_sdl();
init_placebo();
init_vulkan();
init_rendering(argv[1], argc > 2 ? argv[2] : NULL);
// Initialize rendering state
if (!upload_plane(img, &img_tex, &img_plane)) {
fprintf(stderr, "Failed uploading image plane!\n");
uninit(2);
}
SDL_FreeSurface(img);
// Resize the window to match the content
const struct pl_tex *img = img_plane.texture;
SDL_SetWindowSize(window, img->params.w, img->params.h);
if (overlay) {
SDL_Surface *osd = IMG_Load(file);
if (!upload_plane(osd, &osd_tex, &osd_plane))
fprintf(stderr, "Failed uploading OSD plane.. continuing anyway\n");
SDL_FreeSurface(osd);