Mentions légales du service

Skip to content
Snippets Groups Projects
Commit 29d6fe3e authored by danh huynh's avatar danh huynh
Browse files

replace all code by version 1.0.2rc

parent 62be9c3c
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 1185 deletions
usr/lib/*/lib*.so.*
cmake_minimum_required(VERSION 2.8)
project(00-build)
include(FindPkgConfig)
# GL libraries
find_package(OpenGL REQUIRED)
pkg_search_module(glfw3 REQUIRED glfw3)
pkg_search_module(EPOXY REQUIRED epoxy)
# libshadertoy
find_package(shadertoy REQUIRED)
include_directories(
${OPENGL_INCLUDE_DIRS}
${EPOXY_INCLUDE_DIRS}
${glfw3_INCLUDE_DIRS})
add_executable(example00-build
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
target_link_libraries(example00-build
${OPENGL_LIBRARY}
${EPOXY_LIBRARIES}
${glfw3_LIBRARIES}
shadertoy)
# C++14
set_property(TARGET example00-build PROPERTY CXX_STANDARD 14)
# libshadertoy - 00-build
This example is used as a test for the development package. The program only
initializes the rendering context and then exits with status code 0 if no error
occurred.
## Dependencies
* libglfw3-dev
* cmake
* git
* g++
* ca-certificates
* pkg-config
## Copyright
libshadertoy - Vincent Tavernier <vincent.tavernier@inria.fr>
#include <iostream>
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <shadertoy/Shadertoy.hpp>
int main(int argc, char *argv[])
{
int code = 0;
shadertoy::ContextConfig contextConfig;
contextConfig.width = 640;
contextConfig.height = 480;
contextConfig.targetFramerate = 60.0;
if (!glfwInit())
{
std::cerr << "Failed to initialize glfw" << std::endl;
return 1;
}
// Initialize window
GLFWwindow *window = glfwCreateWindow(contextConfig.width,
contextConfig.height,
"libshadertoy example 00-build",
nullptr,
nullptr);
if (!window)
{
std::cerr << "Failed to create glfw window" << std::endl;
code = 1;
}
else
{
glfwMakeContextCurrent(window);
{
shadertoy::RenderContext context(contextConfig);
std::cout << "Created context based on config" << std::endl;
}
glfwDestroyWindow(window);
}
glfwTerminate();
return code;
}
cmake_minimum_required(VERSION 2.8)
project(10-gradient)
include(FindPkgConfig)
# GL libraries
find_package(OpenGL REQUIRED)
pkg_search_module(glfw3 REQUIRED glfw3)
pkg_search_module(EPOXY REQUIRED epoxy)
# libshadertoy
find_package(shadertoy REQUIRED)
include_directories(
${OPENGL_INCLUDE_DIRS}
${EPOXY_INCLUDE_DIRS}
${glfw3_INCLUDE_DIRS})
add_executable(example10-gradient
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
target_link_libraries(example10-gradient
${OPENGL_LIBRARY}
${EPOXY_LIBRARIES}
${glfw3_LIBRARIES}
shadertoy)
# C++14
set_property(TARGET example10-gradient PROPERTY CXX_STANDARD 14)
# libshadertoy - 10-gradient
This example shows how the *gradient* default shadertoy can be rendered using
libshadertoy.
## Dependencies
* libglfw3-dev
* cmake
* git
* g++
* ca-certificates
* pkg-config
## Copyright
libshadertoy - Vincent Tavernier <vincent.tavernier@inria.fr>
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <boost/filesystem.hpp>
#include <iostream>
#include <shadertoy/Shadertoy.hpp>
namespace fs = boost::filesystem;
using shadertoy::OpenGL::glCall;
void SetFramebufferSize(GLFWwindow *window, int width, int height)
{
// Get the context from the window user pointer
shadertoy::RenderContext &context =
*static_cast<shadertoy::RenderContext*>(glfwGetWindowUserPointer(window));
// Reallocate textures
context.GetConfig().width = width;
context.GetConfig().height = height;
context.AllocateTextures();
}
int main(int argc, char *argv[])
{
int code = 0;
shadertoy::ContextConfig contextConfig;
contextConfig.width = 640;
contextConfig.height = 480;
contextConfig.targetFramerate = 60.0;
shadertoy::BufferConfig imageBuffer;
imageBuffer.name = "image";
imageBuffer.shaderFiles.push_back(fs::path("..") / fs::path("shader.glsl"));
contextConfig.bufferConfigs.insert(make_pair(imageBuffer.name,
imageBuffer));
if (!glfwInit())
{
std::cerr << "Failed to initialize glfw" << std::endl;
return 1;
}
// Initialize window
GLFWwindow *window = glfwCreateWindow(contextConfig.width,
contextConfig.height,
"libshadertoy example 10-gradient",
nullptr,
nullptr);
if (!window)
{
std::cerr << "Failed to create glfw window" << std::endl;
code = 1;
}
else
{
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
{
shadertoy::RenderContext context(contextConfig);
std::cout << "Created context based on config" << std::endl;
try
{
// Initialize context
context.Initialize();
std::cout << "Initialized rendering context" << std::endl;
}
catch (shadertoy::OpenGL::ShaderCompilationError &sce)
{
std::cerr << "Failed to compile shader: " << sce.log();
code = 2;
}
catch (shadertoy::ShadertoyError &err)
{
std::cerr << "Error: "
<< err.what();
code = 2;
}
if (code)
exit(code);
// Now render for 5s
int frameCount = 0;
double t = 0.;
// Set the resize callback
glfwSetWindowUserPointer(window, &context);
glfwSetFramebufferSizeCallback(window, SetFramebufferSize);
while (!glfwWindowShouldClose(window))
{
// Poll events
glfwPollEvents();
// Update uniforms
context.GetState().V<shadertoy::iTime>() = t;
context.GetState().V<shadertoy::iFrame>() = frameCount;
// Render to texture
context.Render();
// Render to screen
// Setup framebuffer
glCall(glBindFramebuffer, GL_DRAW_FRAMEBUFFER, 0);
glCall(glViewport, 0, 0, contextConfig.width, contextConfig.height);
// Load texture and program
context.BindResult();
// Render result
context.RenderScreenQuad();
// Buffer swapping
glfwSwapBuffers(window);
// Update time and framecount
t = glfwGetTime();
frameCount++;
if (t > 5.)
glfwSetWindowShouldClose(window, true);
}
}
glfwDestroyWindow(window);
}
glfwTerminate();
return code;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
fragColor = vec4(uv,0.5+0.5*sin(iTime),1.0);
}
cmake_minimum_required(VERSION 2.8)
project(15-uniforms)
include(FindPkgConfig)
# GL libraries
find_package(OpenGL REQUIRED)
pkg_search_module(glfw3 REQUIRED glfw3)
pkg_search_module(EPOXY REQUIRED epoxy)
# libshadertoy
find_package(shadertoy REQUIRED)
include_directories(
${OPENGL_INCLUDE_DIRS}
${EPOXY_INCLUDE_DIRS}
${glfw3_INCLUDE_DIRS})
add_executable(example15-uniforms
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp
${CMAKE_CURRENT_SOURCE_DIR}/uniforms.cpp)
target_link_libraries(example15-uniforms
${OPENGL_LIBRARY}
${EPOXY_LIBRARIES}
${glfw3_LIBRARIES}
shadertoy)
# C++14
set_property(TARGET example15-uniforms PROPERTY CXX_STANDARD 14)
# libshadertoy - 15-uniforms
This example shows how to use custom uniforms defined at runtime
with a custom shader, using libshadertoy.
## Dependencies
* libglfw3-dev
* cmake
* git
* g++
* ca-certificates
* pkg-config
## Copyright
libshadertoy - Vincent Tavernier <vincent.tavernier@inria.fr>
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <boost/filesystem.hpp>
#include <iostream>
#include <shadertoy/Shadertoy.hpp>
#include "uniforms.hpp"
namespace fs = boost::filesystem;
using shadertoy::OpenGL::glCall;
// Create a ShaderInputs type, which references the custom
// uniforms (either static, known at compile time, or dynamic, defined at
// runtime)
typedef shadertoy::ShaderInputs<
iDynamicFloats
> ExampleInputsType;
// Create a custom render context that uses the extra input state
class ExampleRenderContext : public shadertoy::RenderContext {
// Declare the variable holding the extra uniform state
ExampleInputsType extraInputs;
// Add auto-generated wrapper to the sources of all compiled programs
void LoadBufferSources(std::vector<std::pair<std::string, std::string>> &sources) override
{
sources.push_back(std::make_pair(
std::string("internal:example-uniforms"),
extraInputs.GetDefinitions()
));
}
// After compiling a program, bind the inputs from the extra state into the program
void BindInputs(std::vector<std::shared_ptr<shadertoy::BoundInputsBase>> &inputs,
shadertoy::OpenGL::Program &program) override
{
inputs.push_back(extraInputs.GetBoundInputs(program));
}
public:
// Extra state accessor
ExampleInputsType &ExtraInputs() { return extraInputs; }
ExampleRenderContext(shadertoy::ContextConfig &config)
: shadertoy::RenderContext(config),
extraInputs()
{
// Add a custom runtime input
extraInputs.V<iDynamicFloats>().Add<float>("iCustomTime", 0.0f);
}
};
void SetFramebufferSize(GLFWwindow *window, int width, int height)
{
// Get the context from the window user pointer
shadertoy::RenderContext &context =
*static_cast<shadertoy::RenderContext*>(glfwGetWindowUserPointer(window));
// Reallocate textures
context.GetConfig().width = width;
context.GetConfig().height = height;
context.AllocateTextures();
}
int main(int argc, char *argv[])
{
int code = 0;
shadertoy::ContextConfig contextConfig;
contextConfig.width = 640;
contextConfig.height = 480;
contextConfig.targetFramerate = 60.0;
shadertoy::BufferConfig imageBuffer;
imageBuffer.name = "image";
imageBuffer.shaderFiles.push_back(fs::path("..") / fs::path("shader.glsl"));
contextConfig.bufferConfigs.insert(make_pair(imageBuffer.name,
imageBuffer));
if (!glfwInit())
{
std::cerr << "Failed to initialize glfw" << std::endl;
return 1;
}
// Initialize window
GLFWwindow *window = glfwCreateWindow(contextConfig.width,
contextConfig.height,
"libshadertoy example 10-gradient",
nullptr,
nullptr);
if (!window)
{
std::cerr << "Failed to create glfw window" << std::endl;
code = 1;
}
else
{
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
{
ExampleRenderContext context(contextConfig);
std::cout << "Created context based on config" << std::endl;
try
{
// Initialize context
context.Initialize();
std::cout << "Initialized rendering context" << std::endl;
}
catch (shadertoy::OpenGL::ShaderCompilationError &sce)
{
std::cerr << "Failed to compile shader: " << sce.log();
code = 2;
}
catch (shadertoy::ShadertoyError &err)
{
std::cerr << "Error: "
<< err.what();
code = 2;
}
if (code)
exit(code);
// Now render for 5s
int frameCount = 0;
double t = 0.;
// Set the resize callback
glfwSetWindowUserPointer(window, &context);
glfwSetFramebufferSizeCallback(window, SetFramebufferSize);
while (!glfwWindowShouldClose(window))
{
// Poll events
glfwPollEvents();
// Update uniforms
context.GetState().V<shadertoy::iTime>() = t;
context.GetState().V<shadertoy::iFrame>() = frameCount;
// Update custom uniform
context.ExtraInputs().V<iDynamicFloats>().Get<float>("iCustomTime") = (int(t) % 2) == 0 ? 1.0f : 0.0f;
// Render to texture
context.Render();
// Render to screen
// Setup framebuffer
glCall(glBindFramebuffer, GL_DRAW_FRAMEBUFFER, 0);
glCall(glViewport, 0, 0, contextConfig.width, contextConfig.height);
// Load texture and program
context.BindResult();
// Render result
context.RenderScreenQuad();
// Buffer swapping
glfwSwapBuffers(window);
// Update time and framecount
t = glfwGetTime();
frameCount++;
if (t > 5.)
glfwSetWindowShouldClose(window, true);
}
}
glfwDestroyWindow(window);
}
glfwTerminate();
return code;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
fragColor = vec4(uv,0.5+0.5*sin(iCustomTime),1.0);
}
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <shadertoy/Shadertoy.hpp>
#include "uniforms.hpp"
#define IMPLEMENT_UNIFORM_STATE
#include "uniforms.hpp"
#include "shadertoy/UniformState_decl.hpp"
DECLARE_DYNAMIC_UNIFORM(iDynamicFloats, float, glm::vec2, glm::vec3, glm::vec4);
cmake_minimum_required(VERSION 2.8)
project(50-shadertoy)
include(FindPkgConfig)
# GL libraries
find_package(OpenGL REQUIRED)
find_package(Boost 1.58 REQUIRED COMPONENTS filesystem log serialization
date_time program_options)
find_package(CURL REQUIRED)
pkg_search_module(glfw3 REQUIRED glfw3)
pkg_search_module(jsoncpp REQUIRED jsoncpp)
pkg_search_module(EPOXY REQUIRED epoxy)
# libshadertoy
find_package(shadertoy REQUIRED)
include_directories(
${OPENGL_INCLUDE_DIRS}
${EPOXY_INCLUDE_DIRS}
${glfw3_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS}
${CURL_INCLUDE_DIRS}
${jsoncpp_INCLUDE_DIRS})
add_executable(example50-shadertoy
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
target_link_libraries(example50-shadertoy
${OPENGL_LIBRARY}
${EPOXY_LIBRARIES}
${glfw3_LIBRARIES}
${Boost_LIBRARIES}
${CURL_LIBRARIES}
${jsoncpp_LIBRARIES}
shadertoy)
# C++14
set_property(TARGET example50-shadertoy PROPERTY CXX_STANDARD 14)
# libshadertoy - 50-shadertoy
This example implements a desktop version of ShaderToy using the implemented
functionality in libshadertoy. Note that in order to support progressive JPEG
(not supported by SOIL).
## Example of invocation
```bash
./example50-shadertoy -i ltfSDl -a fdnKWn
```
## Tested shaders
* [ltfSDl](https://www.shadertoy.com/view/ltfSDl): no sound support
* [ldl3z2](https://www.shadertoy.com/view/ldl3z2)
* [XsfXW8](https://www.shadertoy.com/view/XsfXW8): no keyboard support
* [lljSDy](https://www.shadertoy.com/view/lljSDy)
* [ldlSzX](https://www.shadertoy.com/view/ldlSzX): no keyboard support
* [4sl3RX](https://www.shadertoy.com/view/4sl3RX): shaking seems stronger on desktop?
* [MsfXzM](https://www.shadertoy.com/view/MsfXzM): all black, no keyboard support
* [4tfSzS](https://www.shadertoy.com/view/4tfSzS)
* [4dGGz1](https://www.shadertoy.com/view/4dGGz1): no keyboard support
* [lt33zl](https://www.shadertoy.com/view/lt33zl)
## Dependencies
* libcurl4-openssl-dev
* libjsoncpp-dev
* libboost-all-dev
* libglfw3-dev
* cmake
* git
* g++
* ca-certificates
* pkg-config
## Copyright
libshadertoy - Vincent Tavernier <vincent.tavernier@inria.fr>
#include <iostream>
#include <string>
#include <sstream>
#include <curl/curl.h>
#include <json/json.h>
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <boost/log/trivial.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <shadertoy/Shadertoy.hpp>
using namespace std;
using shadertoy::OpenGL::glCall;
namespace fs = boost::filesystem;
namespace po = boost::program_options;
struct MyContext
{
shadertoy::RenderContext *context;
};
void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
// Close on ESC key press
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
}
void FramebufferSizeCallback(GLFWwindow *window, int width, int height)
{
// Get the context from the window user pointer
MyContext &ctx = *static_cast<MyContext*>(glfwGetWindowUserPointer(window));
// Reallocate textures
ctx.context->GetConfig().width = width;
ctx.context->GetConfig().height = height;
ctx.context->AllocateTextures();
}
size_t curl_write_data(char *buffer, size_t size, size_t nmemb, void *userp)
{
ostream &ss = *static_cast<ostream*>(userp);
size_t sz = size * nmemb;
ss.write(buffer, sz);
return sz;
}
void file_get(CURL *curl, const string &url, const fs::path &dst)
{
ofstream ofs(dst.string());
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ofs);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
throw runtime_error(curl_easy_strerror(res));
}
}
stringstream curl_get(CURL *curl, const string &url)
{
stringstream ss;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ss);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
throw runtime_error(curl_easy_strerror(res));
}
return ss;
}
Json::Value json_get(CURL *curl, const string &url)
{
Json::Value result;
curl_get(curl, url) >> result;
return result;
}
int parseOptions(string &shaderId, string &shaderApiKey, bool &dump, int argc, char *argv[])
{
// Read and parse options
bool help;
po::options_description desc("libshadertoy 50-shadertoy example");
desc.add_options()
("help,h", po::bool_switch(&help)->default_value(false), "show a help message")
("dump,d", po::bool_switch(&dump)->default_value(false), "Dump binary formats of the loaded programs")
("id,i", po::value<string>(&shaderId)->required(), "ID of the ShaderToy to render")
("api,a", po::value<string>(&shaderApiKey)->required(), "API key for ShaderToy query");
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
po::notify(vm);
}
catch (po::error &ex)
{
BOOST_LOG_TRIVIAL(error) << ex.what();
return 2;
}
if (help)
{
cout << desc << endl;
return 1;
}
return 0;
}
int loadRemote(const string &shaderId, const string &shaderApiKey,
shadertoy::ContextConfig &contextConfig)
{
// Init CURL
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl = curl_easy_init();
if (!curl)
{
BOOST_LOG_TRIVIAL(error) << "Failed to initialize curl.";
curl_global_cleanup();
return 1;
}
int code = 0;
try
{
string endpoint =
string("https://www.shadertoy.com/api/v1/shaders/") + shaderId +
string("?key=") + shaderApiKey;
BOOST_LOG_TRIVIAL(info) << "Fetching shader info from " << endpoint;
Json::Value shaderSpec = json_get(curl, endpoint);
// Check errors from ShaderToy
if (!shaderSpec["Error"].isNull())
{
throw runtime_error(shaderSpec["Error"].asString().c_str());
}
ofstream dump(shaderId + string(".json"));
dump << shaderSpec;
dump.close();
// Create buffer configs for each render pass
for (int i = 0; i < shaderSpec["Shader"]["renderpass"].size(); ++i)
{
auto &pass(shaderSpec["Shader"]["renderpass"][i]);
// Create buffer
shadertoy::BufferConfig imageBuffer;
imageBuffer.name = pass["name"].asString();
if (imageBuffer.name.empty())
imageBuffer.name = pass["type"].asString();
// Skip if sound buffer
if (pass["type"].asString().compare("sound") == 0)
{
BOOST_LOG_TRIVIAL(warning) << "Skipping unsupported sound shader.";
continue;
}
// Load code
stringstream sspath;
sspath << shaderId << "-" << i << ".glsl";
fs::path p(sspath.str());
if (!fs::exists(p))
{
ofstream ofs(p.string());
ofs << pass["code"].asString();
ofs.close();
}
// Load inputs
for (int j = 0; j < pass["inputs"].size(); ++j)
{
auto &input(pass["inputs"][j]);
auto &conf(imageBuffer.inputConfig[input["channel"].asInt()]);
auto &sampler(input["sampler"]);
stringstream ssname;
ssname << imageBuffer.name << "." << input["channel"].asInt();
conf.id = ssname.str();
if (sampler["filter"].compare("mipmap") == 0)
{
conf.minFilter = GL_LINEAR_MIPMAP_LINEAR;
conf.magFilter = GL_LINEAR;
}
else if (sampler["filter"].compare("linear") == 0)
{
conf.minFilter = GL_LINEAR;
conf.magFilter = GL_LINEAR;
}
else if (sampler["filter"].compare("nearest") == 0)
{
conf.minFilter = GL_NEAREST;
conf.magFilter = GL_NEAREST;
}
if (sampler["wrap"].compare("repeat") == 0)
{
conf.wrap = GL_REPEAT;
}
else if (sampler["wrap"].compare("clamp") == 0)
{
conf.wrap = GL_CLAMP_TO_EDGE;
}
conf.vflip = sampler["vflip"].compare("true") == 0;
if (input["ctype"].compare("texture") == 0
|| input["ctype"].compare("cubemap") == 0)
{
conf.type = "texture";
fs::path srcpath(input["src"].asString());
string url =
string("https://www.shadertoy.com")
+ input["src"].asString();
fs::path dstpath(srcpath.filename());
if (!fs::exists(dstpath))
{
BOOST_LOG_TRIVIAL(info) << "Downloading " << url;
file_get(curl, url, dstpath);
}
else
{
BOOST_LOG_TRIVIAL(info) << "Using cache for " << url;
}
conf.source = dstpath.string();
}
else if (input["ctype"].compare("buffer") == 0)
{
conf.type = "buffer";
conf.source = "Buf A";
conf.source.back() = 'A' + (input["id"].asInt() - 257);
BOOST_LOG_TRIVIAL(debug) <<
"Pass " << i << ", input " << input["channel"].asInt()
<< ": binding " << conf.source << " buffer " <<
conf.enabled();
}
else
{
stringstream ss;
ss << "Unsupported input " << input["ctype"].asString()
<< " for pass " << i << ", input " << input["channel"].asInt();
BOOST_LOG_TRIVIAL(warning) << ss.str();
}
}
// Add to context
imageBuffer.shaderFiles.push_back(p);
contextConfig.bufferConfigs.insert(make_pair(imageBuffer.name,
imageBuffer));
}
// Image buffer should be last
pair<string, shadertoy::BufferConfig> imagebuf(*contextConfig.bufferConfigs.begin());
contextConfig.bufferConfigs.erase(contextConfig.bufferConfigs.begin());
contextConfig.bufferConfigs.insert(imagebuf);
}
catch (exception &ex)
{
BOOST_LOG_TRIVIAL(error) << ex.what();
code = 1;
}
// Free CURL
curl_easy_cleanup(curl);
curl_global_cleanup();
return code;
}
int render(GLFWwindow* window, shadertoy::ContextConfig &contextConfig)
{
int code = 0;
shadertoy::RenderContext context(contextConfig);
auto &state(context.GetState());
MyContext ctx = {&context};
try
{
// Initialize context
context.Initialize();
BOOST_LOG_TRIVIAL(info) << "Initialized rendering context";
}
catch (shadertoy::OpenGL::ShaderCompilationError &sce)
{
std::cerr << "Failed to compile shader: " << sce.log();
code = 2;
}
catch (shadertoy::ShadertoyError &err)
{
std::cerr << "Error: "
<< err.what();
code = 2;
}
if (code == 0)
{
// Now render for 5s
int frameCount = 0;
// Set the resize callback
glfwSetWindowUserPointer(window, &ctx);
glfwSetKeyCallback(window, KeyCallback);
glfwSetFramebufferSizeCallback(window, FramebufferSizeCallback);
while (!glfwWindowShouldClose(window))
{
// Poll events
glfwPollEvents();
// Update uniforms
// iTime and iFrame
state.V<shadertoy::iTime>() += 1.0 / contextConfig.targetFramerate;
state.V<shadertoy::iFrame>() = frameCount;
// iDate
boost::posix_time::ptime dt = boost::posix_time::microsec_clock::local_time();
state.V<shadertoy::iDate>() = glm::vec4(dt.date().year() - 1,
dt.date().month(),
dt.date().day(),
dt.time_of_day().total_nanoseconds() / 1e9f);
// iMouse
int btnstate = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);
if (btnstate == GLFW_PRESS)
{
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
state.V<shadertoy::iMouse>()[0] =
state.V<shadertoy::iMouse>()[2] = xpos;
state.V<shadertoy::iMouse>()[1] =
state.V<shadertoy::iMouse>()[3] = contextConfig.height - ypos;
}
else
{
state.V<shadertoy::iMouse>()[2] =
state.V<shadertoy::iMouse>()[3] = 0.f;
}
// End update uniforms
// Render to texture
context.Render();
// Render to screen
// Setup framebuffer
glCall(glBindFramebuffer, GL_DRAW_FRAMEBUFFER, 0);
glCall(glViewport, 0, 0, contextConfig.width, contextConfig.height);
// Load texture and program
context.BindResult();
// Render result
context.RenderScreenQuad();
// Print execution time
auto buffer = context.GetBufferByName();
if (buffer)
{
auto renderTime = buffer->GetElapsedTime();
std::cerr << "frame time: " << renderTime
<< "ns fps: " << (1e9 / renderTime)
<< " mpx/s: " << (contextConfig.width * contextConfig.height / (renderTime / 1e3))
<< std::endl;
}
// Buffer swapping
glfwSwapBuffers(window);
// Update time and framecount
frameCount++;
}
}
return code;
}
int performRender(shadertoy::ContextConfig &contextConfig)
{
int code = 0;
if (!glfwInit())
{
BOOST_LOG_TRIVIAL(error) << "Failed to initialize glfw";
return 1;
}
// Initialize window
GLFWwindow *window = glfwCreateWindow(contextConfig.width,
contextConfig.height,
"libshadertoy example 50-shadertoy",
nullptr,
nullptr);
if (!window)
{
BOOST_LOG_TRIVIAL(error) << "Failed to create glfw window";
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
code = render(window, contextConfig);
glfwDestroyWindow(window);
glfwTerminate();
return code;
}
int main(int argc, char *argv[])
{
int code = 0;
// Options
string shaderId, shaderApiKey;
bool dumpShaders;
// Parse options from ARGV
code = parseOptions(shaderId, shaderApiKey, dumpShaders, argc, argv);
if (code > 0)
return code;
// Context configuration
shadertoy::ContextConfig contextConfig;
contextConfig.width = 640;
contextConfig.height = 480;
contextConfig.targetFramerate = 60.0;
contextConfig.dumpShaders = dumpShaders;
// Fetch shader code
code = loadRemote(shaderId, shaderApiKey, contextConfig);
if (code > 0)
return code;
// Render
code = performRender(contextConfig);
return code;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
fragColor = vec4(uv,0.5+0.5*sin(iTime),1.0);
}
#ifndef _SHADERTOY_BUFFER_CONFIG_HPP_
#define _SHADERTOY_BUFFER_CONFIG_HPP_
#include "shadertoy/pre.hpp"
namespace shadertoy
{
/**
* @brief Represents the configuration of a ToyBuffer channel input
*/
struct shadertoy_EXPORT InputConfig
{
/// Input identifier, in the form <buffer>.<input-id>
std::string id;
/// Type of the actual input
std::string type;
/// Source for this input (texture path, or procedural parameters)
std::string source;
/// true to flip vertically when loading texture
bool vflip;
/// Texture wrap mode
GLint wrap;
/// Texture minification filtering mode
GLint minFilter;
/// Texture magnification filtering mode
GLint magFilter;
/**
* @brief Returns a value indicating if this input is enabled
*
* @return true if this input is enabled
*/
bool enabled() const;
/**
* @brief Initialize an empty input config
*/
InputConfig();
};
/**
* @brief Represents the configuration of a ToyBuffer
*/
struct shadertoy_EXPORT BufferConfig
{
/// Name of the current buffer
std::string name;
/// Path to the shader files to load
std::vector<boost::filesystem::path> shaderFiles;
/// Specification of inputs for this buffer
InputConfig inputConfig[4];
};
}
#endif /* _SHADERTOY_BUFFER_CONFIG_HPP_ */
#ifndef _SHADERTOY_CONTEXT_CONFIG_HPP_
#define _SHADERTOY_CONTEXT_CONFIG_HPP_
#include "shadertoy/pre.hpp"
namespace shadertoy
{
/**
* @brief Holds the configuration for a ShaderToy rendering context.
*/
struct shadertoy_EXPORT ContextConfig
{
/// Width of the rendering
int width;
/// Height of the rendering
int height;
/// Target framerate for the rendering (in frames per second)
double targetFramerate;
/// List of pre-processor definitions to be compiled with the programs
std::vector<std::pair<std::string, std::string>> preprocessorDefines;
/// List of configured buffers for this context
std::map<std::string, BufferConfig> bufferConfigs;
/// True if binary versions of the compiled shaders should be dumped
bool dumpShaders;
};
}
#endif /* _SHADERTOY_CONTEXT_CONFIG_HPP_ */
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment