Ejemplo n.º 1
0
int main(int argc, char **argv)
{
    glfwSetErrorCallback(error_callback);

    /* Initialize the library */
    if (!glfwInit()){
        fprintf(stderr, "Initialization failed.\n");
        return 1;
    }

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(width, height, "Hello World", NULL, NULL);
    if (!window) {
        glfwTerminate();
        fprintf(stderr, "Error creating window.\n");
        return 1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);
    glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, 1);
    glfwSetKeyCallback(window, key_callback);
    glfwSetMouseButtonCallback(window, mouse_button_callback);
    glfwSetCursorPosCallback(window, cursor_pos_callback);

    //**************************** generowanie przykładowych piksli
    hs_init(&argc, &argv);
    initOctTree();
    hs_exit();
    float *piksele = malloc(height*width*3*sizeof(*piksele));

    printf("sizeof(OctTreeNode)=%d\n", (int)sizeof(OctTreeNode));

    //****************************

    init_cl();
    turnCamera(0.f,0.f,0.f); // Calculates initial camera direction
    fflush(stderr);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        for (int i = 0; i < height * width * 3; i++)
            piksele[i] = 0.0;

        clock_t start = clock();
        captureOctTree(camera_pos, camera_target, up, width, height, piksele);
        clock_t end = clock();

        // show render time in window title
        char title[16];
        snprintf(title, 16, "%d ms", (int)((end - start) / (CLOCKS_PER_SEC / 1000)));
        glfwSetWindowTitle(window, title);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    if (num_platforms > 0) {
        clReleaseMemObject(mainOctCL);
        clReleaseMemObject(image);
        clReleaseKernel(kernel);
        clReleaseCommandQueue(queue);
    }
    glfwDestroyWindow(window);

    glfwTerminate();
    return 0;
}
Ejemplo n.º 2
0
Archivo: main.cpp Proyecto: nyaxt/dmix
 GLFWInitHelper() {
   glfwSetErrorCallback(onErr);
   if (!glfwInit()) throw std::runtime_error("glfwInit failed");
 }
Ejemplo n.º 3
0
/* Register an error callback function */
void GLWrapper::setErrorCallback(void(*func)(int error, const char* description))
{
    this->error_callback = func;
    glfwSetErrorCallback(func);
}
Ejemplo n.º 4
0
/* ------------------------------------------------------------------ main - */
int main( int argc, char **argv )
{
    GLFWwindow* window;

    glfwSetErrorCallback( error_callback );

    if (!glfwInit( ))
    {
        exit( EXIT_FAILURE );
    }

    glfwWindowHint( GLFW_VISIBLE, GL_TRUE );
    glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );

    window = glfwCreateWindow( 1, 1, argv[0], NULL, NULL );

    if (!window)
    {
        glfwTerminate( );
        exit( EXIT_FAILURE );
    }

    glfwMakeContextCurrent( window );
    glfwSwapInterval( 1 );

    glfwSetFramebufferSizeCallback( window, reshape );
    glfwSetWindowRefreshCallback( window, display );
    glfwSetKeyCallback( window, keyboard );

#ifndef __APPLE__
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
        exit( EXIT_FAILURE );
    }
    fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif

    buffer = text_buffer_new( LCD_FILTERING_OFF );
    vec4 black = {{0.0, 0.0, 0.0, 1.0}};
    vec4 none  = {{1.0, 1.0, 1.0, 0.0}};

    markup_t markup;
    markup.family  = "fonts/VeraMono.ttf",
    markup.size    = 15.0;
    markup.bold    = 0;
    markup.italic  = 0;
    markup.rise    = 0.0;
    markup.spacing = 0.0;
    markup.gamma   = 1.0;
    markup.foreground_color    = black;
    markup.background_color    = none;
    markup.underline           = 0;
    markup.underline_color     = black;
    markup.overline            = 0;
    markup.overline_color      = black;
    markup.strikethrough       = 0;
    markup.strikethrough_color = black;
    markup.font = 0;

    vec2 pen = {{10.0, 480.0}};
    FILE *file = fopen ( "data/256colors.txt", "r" );
    if ( file != NULL )
    {
        wchar_t line[1024];
        while( fgetws ( line, sizeof(line), file ) != NULL )
        {
            print( buffer, &pen, line, &markup );
        }
        fclose ( file );
    }

    mat4_set_identity( &projection );
    mat4_set_identity( &model );
    mat4_set_identity( &view );

    glfwSetWindowSize( window, 800, 500 );
    glfwShowWindow( window );

    while(!glfwWindowShouldClose( window ))
    {
        display( window );
        glfwPollEvents( );
    }

    glfwDestroyWindow( window );
    glfwTerminate( );

    return 0;
}
Ejemplo n.º 5
0
int main()
{
	GLFWwindow* window;
	struct DemoData data;
	struct NVGcontext* vg = NULL;
	struct FPScounter fps;
	double prevt = 0;

	if (!glfwInit()) {
		printf("Failed to init GLFW.");
		return -1;
	}

	initFPS(&fps);

	glfwSetErrorCallback(errorcb);

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL);
	if (!window) {
		glfwTerminate();
		return -1;
	}

	glfwSetKeyCallback(window, key);

	glfwMakeContextCurrent(window);
#ifdef NANOVG_GLEW
	glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK) {
		printf("Could not init glew.\n");
		return -1;
	}
#endif

	vg = nvgCreateGL3(512,512);
	if (vg == NULL) {
		printf("Could not init nanovg.\n");
		return -1;
	}

	if (loadDemoData(vg, &data) == -1)
		return -1;

	glfwSwapInterval(0);

	glfwSetTime(0);
	prevt = glfwGetTime();

	while (!glfwWindowShouldClose(window))
	{
		double mx, my, t, dt;
		int width, height;

		t = glfwGetTime();
		dt = t - prevt;
		prevt = t;
		updateFPS(&fps, dt);

		glfwGetCursorPos(window, &mx, &my);
		glfwGetFramebufferSize(window, &width, &height);

		// Update and render
		glViewport(0, 0, width, height);
		glClearColor(0.3f, 0.3f, 0.32f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_CULL_FACE);
		glDisable(GL_DEPTH_TEST);

		nvgBeginFrame(vg, width, height);

		renderDemo(vg, mx,my, width,height, t, blowup, &data);
		renderFPS(vg, 5,5, &fps);

		glEnable(GL_DEPTH_TEST);

		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	freeDemoData(vg, &data);

	nvgDeleteGL3(vg);

	glfwTerminate();
	return 0;
}
Ejemplo n.º 6
0
    Game::Game()
        : _initialized(false)
        , _state(UNINITIALIZED)
        , _pausedCount(0)
        , _frameLastFPS(0)
        , _frameCount(0)
        , _frameRate(0)
        , _width(0)
        , _height(0)
        , _clearDepth(1.0f)
        , _clearStencil(0)
        , _scene{std::make_shared<Scene>()}
    {
        glfwSetErrorCallback(&glErrorCallback);

        if( glfwInit() != GLFW_TRUE )
        {
            BOOST_LOG_TRIVIAL(fatal) << "Failed to initialize GLFW";
            BOOST_THROW_EXCEPTION(std::runtime_error("Failed to initialize GLFW"));
        }

        atexit(&glfwTerminate);

        // Get the window configuration values
        int width = 1280, height = 800, samples = 1;
        bool fullscreen = false;

        glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE);
        glfwWindowHint(GLFW_DEPTH_BITS, 24);
        glfwWindowHint(GLFW_STENCIL_BITS, 8);
        glfwWindowHint(GLFW_SAMPLES, samples);
        glfwWindowHint(GLFW_RED_BITS, 8);
        glfwWindowHint(GLFW_GREEN_BITS, 8);
        glfwWindowHint(GLFW_BLUE_BITS, 8);
        glfwWindowHint(GLFW_ALPHA_BITS, 8);
        glfwWindowHint(GLFW_DECORATED, fullscreen ? GLFW_FALSE : GLFW_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
#ifndef NDEBUG
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
#endif

        _multiSampling = samples > 0;

        // Create the windows
        _window = glfwCreateWindow(width, height, "EdisonEngine", fullscreen ? glfwGetPrimaryMonitor() : nullptr, nullptr);
        if(_window == nullptr)
        {
            BOOST_LOG_TRIVIAL(fatal) << "Failed to create window";
            BOOST_THROW_EXCEPTION(std::runtime_error("Failed to create window"));
        }

        glfwMakeContextCurrent(_window);

        glfwSetInputMode(_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

        // Use OpenGL 2.x with GLEW
        glewExperimental = GL_TRUE;
        const auto err = glewInit();
        if( err != GLEW_OK )
        {
            BOOST_LOG_TRIVIAL(error) << "glewInit: " << reinterpret_cast<const char*>(glewGetErrorString(err));
        }

#ifndef NDEBUG
        glEnable(GL_DEBUG_OUTPUT);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);

        glDebugMessageCallback(&debugCallback, nullptr);
#endif
    }
Ejemplo n.º 7
0
int main(int argc, char* argv[])
{
    GLFWwindow* window;
    double t, dt_total, t_old;
    int width, height;

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    window = glfwCreateWindow(640, 480, "Wave Simulation", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);
    glfwSetWindowSizeCallback(window, window_size_callback);
    glfwSetMouseButtonCallback(window, mouse_button_callback);
    glfwSetCursorPosCallback(window, cursor_position_callback);
    glfwSetScrollCallback(window, scroll_callback);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    glfwGetWindowSize(window, &width, &height);
    window_size_callback(window, width, height);

    // Initialize OpenGL
    init_opengl();

    // Initialize simulation
    init_vertices();
    init_grid();
    adjust_grid();

    // Initialize timer
    t_old = glfwGetTime() - 0.01;

    while (!glfwWindowShouldClose(window))
    {
        t = glfwGetTime();
        dt_total = t - t_old;
        t_old = t;

        // Safety - iterate if dt_total is too large
        while (dt_total > 0.f)
        {
            // Select iteration time step
            dt = dt_total > MAX_DELTA_T ? MAX_DELTA_T : dt_total;
            dt_total -= dt;

            // Calculate wave propagation
            calc_grid();
        }

        // Compute height of each vertex
        adjust_grid();

        // Draw wave grid to OpenGL display
        draw_scene(window);

        glfwPollEvents();
    }

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 8
0
int main()
{
    GLFWwindow *window;
    char *userptr = "userptr";

    glfwSetErrorCallback(errorcb);
    assert(glfwInit() == GL_TRUE);
    assert(!strcmp(glfwGetVersionString(), "3.2.1 JS WebGL Emscripten"));
    assert(glfwGetCurrentContext() == NULL);

    {
        int major, minor, rev;
        glfwGetVersion(&major, &minor, &rev);
        assert(major == 3);
        assert(minor == 2);
        assert(rev == 1);
    }

    {
        int count, x, y, w, h;
        GLFWmonitor **monitors = glfwGetMonitors(&count);
        assert(count == 1);
        for (int i = 0; i < count; ++i) {
            assert(monitors[i] != NULL);
        }

        assert(glfwGetPrimaryMonitor() != NULL);
        glfwGetMonitorPos(monitors[0], &x, &y);
        glfwGetMonitorPhysicalSize(monitors[0], &w, &h);
        assert(glfwGetMonitorName(monitors[0]) != NULL);
        glfwSetMonitorCallback(monitcb);

        // XXX: not implemented
        // assert(glfwGetVideoModes(monitors[0], &count) != NULL);
        // assert(glfwGetVideoMode(monitors[0]) != NULL);
        // glfwSetGamma(monitors[0], 1.0f);
        // assert(glfwGetGammaRamp(monitors[0]) != NULL);
        // glfwSetGammaRamp(monitors[0], ramp);
    }

    {
        int x, y, w, h;
        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        glfwSetWindowPosCallback(window, wposicb);
        glfwSetWindowSizeCallback(window, wsizecb);
        glfwSetWindowCloseCallback(window, wcloscb);
        glfwSetWindowRefreshCallback(window, wrfrscb);
        glfwSetWindowFocusCallback(window, wfocucb);
        glfwSetWindowIconifyCallback(window, wiconcb);
        glfwSetFramebufferSizeCallback(window, wfsizcb);

        assert(glfwWindowShouldClose(window) == 0);
        glfwSetWindowShouldClose(window, 1);
        assert(glfwWindowShouldClose(window) == 1);

        glfwSetWindowTitle(window, "test");
        glfwSetWindowTitle(window, "glfw3.c");

        // XXX: not implemented
        // glfwSetWindowPos(window, 1, 1);

        glfwGetWindowPos(window, &x, &y); // stub
        glfwGetWindowSize(window, &w, &h);
        assert(w == 640 && h == 480);

        glfwSetWindowSize(window, 1, 1);
        glfwGetWindowSize(window, &w, &h);
        assert(w == 1 && h == 1);

        glfwSetWindowSize(window, 640, 480);
        glfwGetFramebufferSize(window, &w, &h);

        // XXX: not implemented
        // glfwIconifyWindow(window);
        // glfwRestoreWindow(window);
        // glfwShowWindow(window);
        // glfwHideWindow(window);

        assert(glfwGetWindowMonitor(window) == NULL);
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", glfwGetPrimaryMonitor(), NULL);
        assert(window != NULL);
        assert(glfwGetWindowMonitor(window) == glfwGetPrimaryMonitor());
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        assert(glfwGetWindowAttrib(window, GLFW_CLIENT_API) == GLFW_OPENGL_ES_API);

        assert(glfwGetWindowUserPointer(window) == NULL);
        glfwSetWindowUserPointer(window, userptr);
        assert(glfwGetWindowUserPointer(window) == userptr);
    }

    {
        double x, y;

        glfwSetKeyCallback(window, wkeypcb);
        glfwSetCharCallback(window, wcharcb);
        glfwSetMouseButtonCallback(window, wmbutcb);
        glfwSetCursorPosCallback(window, wcurpcb);
        glfwSetCursorEnterCallback(window, wcurecb);
        glfwSetScrollCallback(window, wscrocb);

        // XXX: stub, events come immediatly
        // glfwPollEvents();
        // glfwWaitEvents();

        assert(glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_NORMAL);

        // XXX: not implemented
        // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

        glfwGetKey(window, GLFW_KEY_A);
        glfwGetMouseButton(window, 0);
        glfwGetCursorPos(window, &x, &y);

        // XXX: not implemented
        // glfwSetCursorPos(window, 0, 0);
    }

    {
        // XXX: not implemented
        // glfwJoystickPresent(joy);
        // glfwGetJoystickAxes(joy, &count);
        // glfwGetJoystickButtons(joy, &count);
        // glfwGetJoystickName(joy);
    }

    {
        // XXX: not implemented
        // glfwSetClipboardString(window, "string");
        // glfwGetClipboardString(window);
    }

    {
        glfwGetTime();
        glfwSetTime(0);
    }

    {
        glfwMakeContextCurrent(window); // stub
        assert(glfwGetCurrentContext() == window);
        glfwSwapBuffers(window); // stub
        glfwSwapInterval(0); // stub
    }

    {
        assert(glfwExtensionSupported("nonexistant") == 0);
        assert(glfwGetProcAddress("nonexistant") == NULL);
    }

    glfwTerminate();

#ifdef REPORT_RESULT
    REPORT_RESULT(1);
#endif
    return 0;
}
Ejemplo n.º 9
0
/********************************************************************************
 Initialise this program
 ********************************************************************************/
void Application::Init()
{
	ReadingLua();

	//Set the error callback
	glfwSetErrorCallback(error_callback);

	//Initialize GLFW
	if (!glfwInit())
	{
		exit(EXIT_FAILURE);
	}

	//Set the GLFW window creation hints - these are optional
	glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL 


	//Create a window and create its OpenGL context
	m_window = glfwCreateWindow(m_window_width, m_window_height, "Y2S2_Framework", NULL, NULL);

	//If the window couldn't be created
	if (!m_window)
	{
		fprintf( stderr, "Failed to open GLFW window.\n" );
		glfwTerminate();
		exit(EXIT_FAILURE);
	}

	//This function makes the context of the specified window current on the calling thread. 
	glfwMakeContextCurrent(m_window);

	//Sets the key callback
	//glfwSetKeyCallback(m_window, key_callback);
	glfwSetWindowSizeCallback(m_window, resize_callback);

	glewExperimental = true; // Needed for core profile
	//Initialize GLEW
	GLenum err = glewInit();

	//If GLEW hasn't initialized
	if (err != GLEW_OK) 
	{
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
		//return -1;
	}

	// Hide the cursor
	glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

	// Set these 2 variables to zero
	m_dElapsedTime = 0.0;
	m_dAccumulatedTime_ThreadOne = 0.0;
	m_dAccumulatedTime_ThreadTwo = 0.0;

	// Init Game State Manager
	m_GSM = new CGameStateManager();
	m_GSM->Init("GSM", m_window_width, m_window_height);
	m_GSM->ChangeState(CPlayState::Instance());

	S_GSM = m_GSM;
}
Ejemplo n.º 10
0
int main(int argc, char** argv)
{
    int ch, api = 0, profile = 0, strategy = 0, major = 1, minor = 0, revision;
    GLboolean debug = GL_FALSE, forward = GL_FALSE, list = GL_FALSE;
    GLint flags, mask;
    GLFWwindow* window;

    if (!valid_version())
        exit(EXIT_FAILURE);

    while ((ch = getopt(argc, argv, "a:dfhlm:n:p:r:")) != -1)
    {
        switch (ch)
        {
            case 'a':
                if (strcasecmp(optarg, API_OPENGL) == 0)
                    api = GLFW_OPENGL_API;
                else if (strcasecmp(optarg, API_OPENGL_ES) == 0)
                    api = GLFW_OPENGL_ES_API;
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
            case 'd':
                debug = GL_TRUE;
                break;
            case 'f':
                forward = GL_TRUE;
                break;
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
            case 'l':
                list = GL_TRUE;
                break;
            case 'm':
                major = atoi(optarg);
                break;
            case 'n':
                minor = atoi(optarg);
                break;
            case 'p':
                if (strcasecmp(optarg, PROFILE_NAME_CORE) == 0)
                    profile = GLFW_OPENGL_CORE_PROFILE;
                else if (strcasecmp(optarg, PROFILE_NAME_COMPAT) == 0)
                    profile = GLFW_OPENGL_COMPAT_PROFILE;
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 'r':
                if (strcasecmp(optarg, STRATEGY_NAME_NONE) == 0)
                    strategy = GLFW_NO_RESET_NOTIFICATION;
                else if (strcasecmp(optarg, STRATEGY_NAME_LOSE) == 0)
                    strategy = GLFW_LOSE_CONTEXT_ON_RESET;
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

    argc -= optind;
    argv += optind;

    // Initialize GLFW and create window

    glfwSetErrorCallback(error_callback, NULL);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    if (major != 1 || minor != 0)
    {
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
    }

    if (api != 0)
        glfwWindowHint(GLFW_CLIENT_API, api);

    if (debug)
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

    if (forward)
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    if (profile != 0)
        glfwWindowHint(GLFW_OPENGL_PROFILE, profile);

    if (strategy)
        glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, strategy);

    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

    window = glfwCreateWindow(200, 200, "Version", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);

    // Report client API version

    api = glfwGetWindowAttrib(window, GLFW_CLIENT_API);
    major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
    minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
    revision = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);

    printf("%s context version string: \"%s\"\n",
           get_client_api_name(api),
           glGetString(GL_VERSION));

    printf("%s context version parsed by GLFW: %u.%u.%u\n",
           get_client_api_name(api),
           major, minor, revision);

    // Report client API context properties

    if (api == GLFW_OPENGL_API)
    {
        if (major >= 3)
        {
            glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
            printf("%s context flags (0x%08x):", get_client_api_name(api), flags);

            if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
                printf(" forward-compatible");
            if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
                printf(" debug");
            if (flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB)
                printf(" robustness");
            putchar('\n');

            printf("%s context flags parsed by GLFW:", get_client_api_name(api));

            if (glfwGetWindowAttrib(window, GLFW_OPENGL_FORWARD_COMPAT))
                printf(" forward-compatible");
            if (glfwGetWindowAttrib(window, GLFW_OPENGL_DEBUG_CONTEXT))
                printf(" debug");
            if (glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS) != GLFW_NO_ROBUSTNESS)
                printf(" robustness");
            putchar('\n');
        }

        if (major > 3 || (major == 3 && minor >= 2))
        {
            int profile = glfwGetWindowAttrib(window, GLFW_OPENGL_PROFILE);

            glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);
            printf("%s profile mask (0x%08x): %s\n",
                   get_client_api_name(api),
                   mask,
                   get_profile_name_gl(mask));

            printf("%s profile mask parsed by GLFW: %s\n",
                   get_client_api_name(api),
                   get_profile_name_glfw(profile));
        }

        if (glfwExtensionSupported("GL_ARB_robustness"))
        {
            int robustness;
            GLint strategy;
            glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);

            printf("%s robustness strategy (0x%08x): %s\n",
                   get_client_api_name(api),
                   strategy,
                   get_strategy_name_gl(strategy));

            robustness = glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS);

            printf("%s robustness strategy parsed by GLFW: %s\n",
                   get_client_api_name(api),
                   get_strategy_name_glfw(robustness));
        }
    }

    printf("%s context renderer string: \"%s\"\n",
           get_client_api_name(api),
           glGetString(GL_RENDERER));
    printf("%s context vendor string: \"%s\"\n",
           get_client_api_name(api),
           glGetString(GL_VENDOR));

    if (major > 1)
    {
        printf("%s context shading language version: \"%s\"\n",
               get_client_api_name(api),
               glGetString(GL_SHADING_LANGUAGE_VERSION));
    }

    // Report client API extensions
    if (list)
        list_extensions(api, major, minor);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 11
0
int main(int argc, char* argv[])
{
	glfwSetErrorCallback(error_callback);
	if (!glfwInit()) return 1;
	glfwWindowHint(GLFW_RED_BITS, 8);
	glfwWindowHint(GLFW_GREEN_BITS, 8);
	glfwWindowHint(GLFW_BLUE_BITS, 8);
	glfwWindowHint(GLFW_ALPHA_BITS, 8);
	glfwWindowHint(GLFW_DEPTH_BITS, 32);
	glfwWindowHint(GLFW_STENCIL_BITS, GLFW_DONT_CARE);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
	glfwWindowHint(GLFW_SAMPLES, 4);
	GLFWwindow *window = glfwCreateWindow(1024, 768, "Lightmapping Example", NULL, NULL);
	if (!window) return 1;
	glfwMakeContextCurrent(window);
	gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
	glfwSwapInterval(1);

	scene_t scene = {0};
	if (!initScene(&scene))
	{
		fprintf(stderr, "Could not initialize scene.\n");
		return 1;
	}

	printf("Ambient Occlusion Baking Example.\n");
	printf("Use your mouse and the W, A, S, D, E, Q keys to navigate.\n");
	printf("Press SPACE to start baking one light bounce!\n");
	printf("This will take a few seconds and bake a lightmap illuminated by:\n");
	printf("1. The mesh itself (initially black)\n");
	printf("2. A white sky (1.0f, 1.0f, 1.0f)\n");

	while (!glfwWindowShouldClose(window))
	{
		glfwPollEvents();
		if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
			bake(&scene);

		int w, h;
		glfwGetFramebufferSize(window, &w, &h);
		glViewport(0, 0, w, h);

		// camera for glfw window
		float view[16], projection[16];
		fpsCameraViewMatrix(window, view);
		perspectiveMatrix(projection, 45.0f, (float)w / (float)h, 0.01f, 100.0f);
		
		// draw to screen with a blueish sky
		glClearColor(0.6f, 0.8f, 1.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		drawScene(&scene, view, projection);

		glfwSwapBuffers(window);
	}

	destroyScene(&scene);
	glfwDestroyWindow(window);
	glfwTerminate();
	return 0;
}
Ejemplo n.º 12
0
int main(int, char**)
{
    // Setup window
    glfwSetErrorCallback(glfw_error_callback);
    if (!glfwInit())
        return 1;

    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
    GLFWwindow* window = glfwCreateWindow(1280, 720, "ImGui GLFW+Vulkan example", NULL, NULL);

    // Setup Vulkan
    if (!glfwVulkanSupported())
    {
        printf("GLFW: Vulkan Not Supported\n");
        return 1;
    }
    setup_vulkan(window);
    glfwSetFramebufferSizeCallback(window, glfw_resize_callback);

    // Setup ImGui binding
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    ImGui_ImplGlfwVulkan_Init_Data init_data = {};
    init_data.allocator = g_Allocator;
    init_data.gpu = g_Gpu;
    init_data.device = g_Device;
    init_data.render_pass = g_RenderPass;
    init_data.pipeline_cache = g_PipelineCache;
    init_data.descriptor_pool = g_DescriptorPool;
    init_data.check_vk_result = check_vk_result;

    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;  // Enable Keyboard Controls
    ImGui_ImplGlfwVulkan_Init(window, true, &init_data);

    // Setup style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. 
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. 
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'misc/fonts/README.txt' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

    // Upload Fonts
    {
        VkResult err;
        err = vkResetCommandPool(g_Device, g_CommandPool[g_FrameIndex], 0);
        check_vk_result(err);
        VkCommandBufferBeginInfo begin_info = {};
        begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
        begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
        err = vkBeginCommandBuffer(g_CommandBuffer[g_FrameIndex], &begin_info);
        check_vk_result(err);

        ImGui_ImplGlfwVulkan_CreateFontsTexture(g_CommandBuffer[g_FrameIndex]);

        VkSubmitInfo end_info = {};
        end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
        end_info.commandBufferCount = 1;
        end_info.pCommandBuffers = &g_CommandBuffer[g_FrameIndex];
        err = vkEndCommandBuffer(g_CommandBuffer[g_FrameIndex]);
        check_vk_result(err);
        err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE);
        check_vk_result(err);

        err = vkDeviceWaitIdle(g_Device);
        check_vk_result(err);
        ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects();
    }

    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);


    // Main loop
    while (!glfwWindowShouldClose(window))
    {
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        glfwPollEvents();

        if (g_ResizeWanted)
            resize_vulkan(g_ResizeWidth, g_ResizeHeight);
        g_ResizeWanted = false;

        ImGui_ImplGlfwVulkan_NewFrame();

        // 1. Show a simple window.
        // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
        {
            static float f = 0.0f;
            static int counter = 0;
            ImGui::Text("Hello, world!");                           // Display some text (you can use a format string too)
            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f    
            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our windows open/close state
            ImGui::Checkbox("Another Window", &show_another_window);

            if (ImGui::Button("Button"))                            // Buttons return true when clicked (NB: most widgets return true when edited/activated)
                counter++;
            ImGui::SameLine();
            ImGui::Text("counter = %d", counter);

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
        }

        // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name your windows.
        if (show_another_window)
        {
            ImGui::Begin("Another Window", &show_another_window);
            ImGui::Text("Hello from another window!");
            if (ImGui::Button("Close Me"))
                show_another_window = false;
            ImGui::End();
        }

        // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow(). Read its code to learn more about Dear ImGui!
        if (show_demo_window)
        {
            ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
            ImGui::ShowDemoWindow(&show_demo_window);
        }

        memcpy(&g_ClearValue.color.float32[0], &clear_color, 4 * sizeof(float));
        frame_begin();
        ImGui_ImplGlfwVulkan_Render(g_CommandBuffer[g_FrameIndex]);
        frame_end();
        frame_present();
    }

    // Cleanup
    VkResult err = vkDeviceWaitIdle(g_Device);
    check_vk_result(err);
    ImGui_ImplGlfwVulkan_Shutdown();
    ImGui::DestroyContext();
    cleanup_vulkan();
    glfwTerminate();

    return 0;
}
Ejemplo n.º 13
0
int main(int, char**){

    const double FRAME_INTERVAL = 1.0 / 60.0;

    // Setup window
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        return 1;
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    GLFWwindow* window = glfwCreateWindow(1280, 720, "Falton Debug Visualizer", NULL, NULL);
    glfwMakeContextCurrent(window);
    gl3wInit();

    // Setup ImGui binding
    ImGui_ImplGlfwGL3_Init(window, true);

    ImVec4 clear_color = ImColor(0, 0, 0);

    Phyvis::Context ctx;
    Phyvis::Init(&ctx);

    double prevTime = glfwGetTime();
    double lag = 0.0f;

    // Main loop
    while (!glfwWindowShouldClose(window))
    {
        double time0 = glfwGetTime();
        double delta = time0- prevTime;
        lag += delta;
        prevTime = time0;

        while (lag >= FRAME_INTERVAL) {
            glfwPollEvents();
            ImGui_ImplGlfwGL3_NewFrame();
            
            // Rendering
            int display_w, display_h;
            glfwGetFramebufferSize(window, &display_w, &display_h);
            glViewport(0, 0, display_w, display_h);
            glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            Phyvis::Tick(&ctx, display_w, display_h);
            ImGui::Render();
            
            glfwSwapBuffers(window);
            lag -= FRAME_INTERVAL;
        }
    }

    Phyvis::Cleanup(&ctx);

    // Cleanup
    ImGui_ImplGlfwGL3_Shutdown();
    glfwTerminate();

    return 0;
}
Ejemplo n.º 14
0
int Game::Initialize(){
    
    LOG(info) << "Jarg initialization start";
    glfwSetErrorCallback([](int a,const char* description){LOG(error) << description;});

    int glfwErrorCode = glfwInit();
    if (!glfwErrorCode)
    {
        LOG(error) << "glfwInit error " << glfwErrorCode;
        return glfwErrorCode;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, Game::MAJOR_GL);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, Game::MINOR_GL);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    monitor = nullptr;
    if(fullscreen)
    {
        monitor = glfwGetPrimaryMonitor();
    }

    window = glfwCreateWindow(width, height, title.c_str(), monitor, nullptr);
    if (!window)
    {
        glfwTerminate();
        LOG(fatal) << "Ошибка создания окна GLFW.";
        return false;
    }
    glfwMakeContextCurrent(window);
    //glfwSetWindowTitle(window, AutoVersion::GetTitle().c_str());

    glfwSwapInterval(0);

    if (glewInit() != GLEW_OK) 
    {
        LOG(fatal) << "GLEW не инициализирован.";
        return false;
    }

    GameObject go;
    go.seed = 123;
    for (int i =0; i<100; i++)
    {
        GenerateStar(&go);
    }

    int glVersion[2] = {-1, -1};
    glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); 
    glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); 

    LOG(info) << "Renderer: " << glGetString(GL_RENDERER);
    LOG(info) << "Vendor: " <<  glGetString(GL_VENDOR);
    LOG(info) << "Version: " <<  glGetString(GL_VERSION);
    LOG(info) << "GLSL version: " <<  glGetString(GL_SHADING_LANGUAGE_VERSION);
    LOG(info) << "using OpenGL: " << std::to_string(glVersion[0]) << "." << std::to_string(glVersion[1]);
    LOG(info) << "glfw: " << glfwGetVersionString();

    Keyboard::Initialize();
    glfwSetKeyCallback(window, [](GLFWwindow *win, int key, int scancode, int action, int mods){Keyboard::SetKey(key, scancode, action, mods);});

    Mouse::Initialize(window);
    Mouse::SetWindowSize(width, height);
    //	Mouse::SetFixedPosState(true);
    glfwSetCursorPosCallback(window, [](GLFWwindow *window, double xpos, double ypos){Mouse::SetCursorPos(xpos, ypos);});
    glfwSetCursorEnterCallback(window, [](GLFWwindow *window, int entered){Mouse::CursorClientArea(entered);});	
    glfwSetWindowFocusCallback(window, [](GLFWwindow *window, int focused){Mouse::WindowFocus(focused);});
    glfwSetMouseButtonCallback(window, [](GLFWwindow *window, int a, int b, int c){Mouse::SetButton(a, b, c);});
    glfwSetWindowSizeCallback(window, [](GLFWwindow *window, int a, int b){Game::Resize(a, b); Mouse::SetWindowSize(a, b);});
    glfwSetScrollCallback(window, [](GLFWwindow *window, double a, double b){Mouse::Scroll(b);});
    wire = 1;
    spd = 1;

    //////////////////////////////////////////////////////////////////////////
    LinesShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    LinesShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/colored.glsl");
    LinesShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/colored.glsl");
    LinesShader->Link();
    mvpLine = LinesShader->locateVars("MVP");

    TextureShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    TextureShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/textured.glsl");
    TextureShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/textured.glsl");
    TextureShader->Link();
    mvpTex = TextureShader->locateVars("MVP");

    FXAAShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    FXAAShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/fxaa.glsl");
    FXAAShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/fxaa.glsl");
    FXAAShader->Link();

    BasicShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    BasicShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/minnaert.glsl");
    BasicShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/minnaert.glsl");
    BasicShader->loadShaderFromSource(GL_TESS_CONTROL_SHADER, "Shaders/minnaert.glsl");
    BasicShader->loadShaderFromSource(GL_TESS_EVALUATION_SHADER, "Shaders/minnaert.glsl");
    BasicShader->Link();
    BasicShader->UpdateUniforms();
    BasicShader->locateVars("transform.viewProjection"); //var0
    BasicShader->locateVars("transform.model"); //var1
    BasicShader->locateVars("transform.normal"); //var2
    BasicShader->locateVars("material.texture");

    testtex = std::shared_ptr<Texture>(new Texture());
    testtex->Empty(vec2(256,256));

    uptex = std::shared_ptr<Texture>(new Texture());
    uptex->Load("up.png");

    //////////////////////////////////////////////////////////////////////////

    light.position = vec4(5.0f, 12.0f, 3.0f, 1.0f);
    light.ambient = vec4(0.2f, 0.2f, 0.2f, 1.0f);
    light.diffuse = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    light.specular = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    light.attenuation = vec3(0.000f, 0.0f, 0.00000f);

    batched = std::unique_ptr<Batched>(new Batched());
    batched->Initialize(TextureShader.get(), LinesShader.get());

    font = std::unique_ptr<Font>(new Font());
    font->Initialize();
    //actually not load json
    if(!font->Create("font.json")){
        LOG(error) << "failed to load\process font.json";
    }

    WindowsDesigner();

    camera = std::unique_ptr<Camera>(new Camera());
    camera->SetViewport(0, 0, width, height);
    camera->SetPosition(vec3(2,2,2));
    camera->SetLookAt(vec3(0));
    gt = std::unique_ptr<GameTimer>(new GameTimer);

    Generation gen;

    rs = new QuadTreePlane();
    rs->Init(BasicShader, *camera);

    auto tex = std::shared_ptr<Texture>(new Texture());
    tex->Load("normal.png");

    icos = std::unique_ptr<Mesh>(new Mesh(Cube::getMesh()));
    icos->Bind();
    icos->shader = BasicShader;
    icos->material = std::shared_ptr<Material>(new Material());
    icos->material->texture = tex;

    //test.LoadBinary("untitled.m");
    test.Bind();
    for (int i = 0; i<test.meshes.size(); i++)
    {
        test.meshes[i]->shader = BasicShader;
    }

    return true;
}
Ejemplo n.º 15
0
void Application::Init()
{
	//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	//Set the error callback
	glfwSetErrorCallback(error_callback);

	//Initialize GLFW
	if (!glfwInit())
	{
		exit(EXIT_FAILURE);
	}

	//Set the GLFW window creation hints - these are optional
	glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL 
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); //Does not allow scaleable window
	
	CheckInit();

	theAppLua = new LuaUsage();
	theAppLua->LuaUsageInit("Application");
	m_window_height = theAppLua->get<float>("WindowSize.ScreenSize.ScreenHeight");
	m_window_width = theAppLua->get<float>("WindowSize.ScreenSize.ScreenWidth");
	theAppLua->LuaUsageClose();


	WindowHeight = m_window_height;
	WindowWidth = m_window_width;
	//Create a window and create its OpenGL context
	m_window = glfwCreateWindow(m_window_width, m_window_height, "Y2S2_Framework", NULL, NULL);

	//If the window couldn't be created
	if (!m_window)
	{
		fprintf( stderr, "Failed to open GLFW window.\n" );
		glfwTerminate();
		exit(EXIT_FAILURE);
	}

	//This function makes the context of the specified window current on the calling thread. 
	glfwMakeContextCurrent(m_window);

	//Sets the key callback
	//glfwSetKeyCallback(m_window, key_callback);
	glfwSetWindowSizeCallback(m_window, resize_callback);

	glewExperimental = true; // Needed for core profile
	//Initialize GLEW
	GLenum err = glewInit();

	//If GLEW hasn't initialized
	if (err != GLEW_OK) 
	{
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
		//return -1;
	}

	// Hide the cursor
	//glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

	// Set these 2 variables to zero
	m_dElapsedTime = 0.0;
	m_dAccumulatedTime_ThreadOne = 0.0;
	m_dAccumulatedTime_ThreadTwo = 0.0;
	
	// Initialise the GSM
	theGSM = new CGameStateManager();
	theGSM->Init("DM2240 with Game State Management", m_window_width, m_window_height);
	theGSM->ChangeState(CMenuState::Instance());
}
Ejemplo n.º 16
0
int main(void)
{
    GLFWwindow* window;

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	
	window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);

    glfwSetKeyCallback(window, key_callback);

    // Initialize GLEW
    glewExperimental = GL_TRUE;
    glewInit();
	
	// Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers(1, &vbo);

    GLfloat vertices[] = {
    //  Position   Color             Texcoords
        -0.5f,  0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Top-left
         0.5f,  0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top-right
         0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // Bottom-right
        -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f  // Bottom-left
    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Create an element array
    GLuint ebo;
    glGenBuffers(1, &ebo);

    GLuint elements[] = {
        0, 1, 2,
        2, 3, 0
    };

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
    
	GLint result = GL_FALSE;
	
	GLchar*   vertexSource;
    GLchar*   fragmentSource;

    // Create and compile the vertex shader
    loadShaderSource("./resources/shaders/transformations/vertexShader.vert", vertexSource);
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, (const GLchar**)&vertexSource, NULL);
    glCompileShader(vertexShader);
    
    // Check Vertex Shader
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &result);
    if (result != GL_TRUE) {
    	std::cout<<"Failed to load vertex shader"<<std::endl;
    }
    
    unloadShaderSource(vertexSource);

    // Create and compile the fragment shader
	loadShaderSource("./resources/shaders/transformations/fragmentShader.frag", fragmentSource);
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, (const GLchar**)&fragmentSource, NULL);
    glCompileShader(fragmentShader);
    
    // Check Fragment Shader
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &result);
    if (result != GL_TRUE) {
    	std::cout<<"Failed to load fragment shader"<<std::endl;
    }
    
    unloadShaderSource(vertexSource);

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outColor");
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), 0);

    GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colAttrib);
    glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));

    GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
    glEnableVertexAttribArray(texAttrib);
    glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (void*)(5 * sizeof(GLfloat)));

    // Load textures
    GLuint textures[2];
    glGenTextures(2, textures);
    
    int width, height;
    unsigned char* image;

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textures[0]);
        image = SOIL_load_image("./resources/textures/kitty.png", &width, &height, 0, SOIL_LOAD_RGB);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
        SOIL_free_image_data(image);
    glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, textures[1]);
        image = SOIL_load_image("./resources/textures/puppy.png", &width, &height, 0, SOIL_LOAD_RGB);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
        SOIL_free_image_data(image);
    glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    GLint uniModel = glGetUniformLocation(shaderProgram, "model");
    
    // Set up projection
    glm::mat4 view = glm::lookAt(
        glm::vec3(1.2f, 1.2f, 1.2f),
        glm::vec3(0.0f, 0.0f, 0.0f),
        glm::vec3(0.0f, 0.0f, 1.0f)
    );
    GLint uniView = glGetUniformLocation(shaderProgram, "view");
    glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view));

    glm::mat4 proj = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 10.0f);
    GLint uniProj = glGetUniformLocation(shaderProgram, "proj");
    glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj));   

    while (!glfwWindowShouldClose(window))
    {
    	
    	// Clear the screen to black
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Calculate transformation
        glm::mat4 model;
        model = glm::rotate(
            model,
            (GLfloat)clock() / (GLfloat)CLOCKS_PER_SEC * 180.0f,
            glm::vec3(0.0f, 0.0f, 1.0f)
        );
        glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr(model));
        
        // Draw a rectangle from the 2 triangles using 6 indices
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glDeleteTextures(2, textures);

    glDeleteProgram(shaderProgram);
    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);

    glDeleteBuffers(1, &ebo);
    glDeleteBuffers(1, &vbo);

    glDeleteVertexArrays(1, &vao);

    glfwDestroyWindow(window);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 17
0
int main(int argc, char* argv[]) {
	//#ifdef __MINGW32__
	//	WORD versionWanted = MAKEWORD(1, 1);
	//	WSADATA wsaData;
	//	WSAStartup(versionWanted, &wsaData);
	//#endif
	char ncwd[strlen(argv[0]) + 1];
	memcpy(ncwd, argv[0], strlen(argv[0]) + 1);
	char* ecwd =
#ifdef __MINGW32__
			strrchr(ncwd, '\\');
#else
			strrchr(ncwd, '/');
#endif
	if (ecwd != NULL) {
		ecwd++;
		ecwd[0] = 0;
		chdir(ncwd);
	}
	printf("Loading... [FROM=%s]\n", ncwd);
	main_preinit();
	width = 800;
	height = 600;
	if (!glfwInit()) return -1;
	glfwWindowHint(GLFW_DOUBLEBUFFER, 1);
	//glfwWindowHint(GLFW_SAMPLES, 4); // antialiasing
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwSetErrorCallback(__error_callback);
	window = glfwCreateWindow(800, 600, windowTitle, NULL, NULL);
	if (!window) {
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent (window);
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (err != GLEW_OK) {
		printf("GLEW Init error: %s\n", glewGetErrorString(err));
		glfwTerminate();
		return -1;
	}
	if (!glewIsSupported("GL_VERSION_2_1") || !glewIsSupported("GL_ARB_vertex_program")) {
		printf("OpenGL version 2.1+ or GL_ARB_vertex_program not satisfied.\n");
		glfwTerminate();
		return -1;
	}
	printf("OpenGL Version: %s\n", glGetString(GL_VERSION));
	glfwSetInputMode(window, GLFW_STICKY_KEYS, 1);
	main_init();
	__gui_load();
	guistate_set(0);
	clock_gettime(CLOCK_MONOTONIC, &__main_ts);
	__main_lt = (double) __main_ts.tv_sec * 1000. + (double) __main_ts.tv_nsec / 1000000.;
	__main_lf = __main_lt;
	glfwSetKeyCallback(window, __gui_keyboardCallback);
	glfwSetCharCallback(window, __gui_textCallback);
	glfwSetCursorPosCallback(window, __gui_mouseMotionCallback);
	glfwSetMouseButtonCallback(window, __gui_mouseCallback);
	glfwSetScrollCallback(window, __gui_scrollCallback);
	printf("Loaded.\n");
	while (!glfwWindowShouldClose(window)) {
		displayCallback();
		glfwSwapBuffers(window);
		glfwSwapInterval(1);
		glfwPollEvents();
	}
	glfwTerminate();
	return 0;
}
Ejemplo n.º 18
0
GLFWView::GLFWView(bool fullscreen_, bool benchmark_)
    : fullscreen(fullscreen_), benchmark(benchmark_) {
    glfwSetErrorCallback(glfwError);

    std::srand(std::time(0));

    if (!glfwInit()) {
        mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize glfw");
        exit(1);
    }

    GLFWmonitor *monitor = nullptr;
    if (fullscreen) {
        monitor = glfwGetPrimaryMonitor();
        auto videoMode = glfwGetVideoMode(monitor);
        width = videoMode->width;
        height = videoMode->height;
    }

#ifdef DEBUG
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif

#ifdef GL_ES_VERSION_2_0
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
#endif

    glfwWindowHint(GLFW_RED_BITS, 8);
    glfwWindowHint(GLFW_GREEN_BITS, 8);
    glfwWindowHint(GLFW_BLUE_BITS, 8);
    glfwWindowHint(GLFW_ALPHA_BITS, 8);
    glfwWindowHint(GLFW_STENCIL_BITS, 8);
    glfwWindowHint(GLFW_DEPTH_BITS, 16);

    window = glfwCreateWindow(width, height, "Mapbox GL", monitor, NULL);
    if (!window) {
        glfwTerminate();
        mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize window");
        exit(1);
    }

    glfwSetWindowUserPointer(window, this);
    glfwMakeContextCurrent(window);
    if (benchmark) {
        // Disables vsync on platforms that support it.
        glfwSwapInterval(0);
    } else {
        glfwSwapInterval(1);
    }


    glfwSetCursorPosCallback(window, onMouseMove);
    glfwSetMouseButtonCallback(window, onMouseClick);
    glfwSetWindowSizeCallback(window, onWindowResize);
    glfwSetFramebufferSizeCallback(window, onFramebufferResize);
    glfwSetScrollCallback(window, onScroll);
    glfwSetKeyCallback(window, onKey);

    mbgl::gl::InitializeExtensions(glfwGetProcAddress);

    glfwGetWindowSize(window, &width, &height);
    glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
    pixelRatio = static_cast<float>(fbWidth) / width;

    glfwMakeContextCurrent(nullptr);

    printf("\n");
    printf("================================================================================\n");
    printf("\n");
    printf("- Press `S` to cycle through bundled styles\n");
    printf("- Press `X` to reset the transform\n");
    printf("- Press `N` to reset north\n");
    printf("- Press `R` to toggle any available `night` style class\n");
    printf("- Press `Z` to cycle through north orientations\n");
    printf("- Prezz `X` to cycle through the viewport modes\n");
    printf("- Press `A` to cycle through Mapbox offices in the world + dateline monument\n");
    printf("\n");
    printf("- Press `1` through `6` to add increasing numbers of point annotations for testing\n");
    printf("- Press `7` through `0` to add increasing numbers of shape annotations for testing\n");
    printf("\n");
    printf("- Press `Q` to remove annotations\n");
    printf("- Press `P` to add a random custom runtime imagery annotation\n");
    printf("- Press `W` to pop the last-added annotation off\n");
    printf("\n");
    printf("- `Control` + mouse drag to rotate\n");
    printf("- `Shift` + mouse drag to tilt\n");
    printf("\n");
    printf("- Press `Tab` to cycle through the map debug options\n");
    printf("- Press `Esc` to quit\n");
    printf("\n");
    printf("================================================================================\n");
    printf("\n");
}
Ejemplo n.º 19
0
int main(void) {


	// initialise the windows
	GLFWwindow *window;
	glfwSetErrorCallback(error_callback);



	if (!glfwInit()) {

		return -1;
	}
	window = glfwCreateWindow(640, 480, "Test", NULL, NULL);

	if (window == nullptr) {
		std::cout << "Erreur lors du chargement de la fenetree ";
		glfwTerminate();
		return -1;

	}
	glfwMakeContextCurrent(window);

	printf("OpenGL Version:%s\n", glGetString(GL_VERSION));
	printf("GLSL Version  :%s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));

	// create  a windows


	if (!window) {
		fprintf(stderr, "Failed to initialize GLFW\n");
		glfwTerminate();
		return -1;
	}


	// make the window's current context

	// loop until the window close


	glfwSetKeyCallback(window, key_callback);


	// triangle

	// must be normalized to be inside the screen 

	// GLEW INITIALISATION

	glewExperimental = GL_TRUE;

	if (glewInit() != GLEW_OK)
	{
		std::cout << "Failed to initialize GLEW" << std::endl;
	}

	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	GLuint fragmentShaderOrange = glCreateShader(GL_FRAGMENT_SHADER); // The first fragment shader that outputs the color orange
	GLuint fragmentShaderYellow = glCreateShader(GL_FRAGMENT_SHADER); // The second fragment shader that outputs the color yellow
	GLuint shaderProgramOrange = glCreateProgram();
	GLuint shaderProgramYellow = glCreateProgram(); // The second shader program
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);
	glShaderSource(fragmentShaderOrange, 1, &fragmentShader1Source, NULL);
	glCompileShader(fragmentShaderOrange);
	glShaderSource(fragmentShaderYellow, 1, &fragmentShader2Source, NULL);
	glCompileShader(fragmentShaderYellow);
	// Link the first program object
	glAttachShader(shaderProgramOrange, vertexShader);
	glAttachShader(shaderProgramOrange, fragmentShaderOrange);
	glLinkProgram(shaderProgramOrange);
	// Then link the second program object using a different fragment shader (but same vertex shader) this time.
	// This is perfectly allowed since the inputs and outputs of both the vertex and fragment shaders are equally matched.
	glAttachShader(shaderProgramYellow, vertexShader);
	glAttachShader(shaderProgramYellow, fragmentShaderYellow);
	glLinkProgram(shaderProgramYellow);




	GLfloat firstTriangle[] = {
		-0.9f, -0.5f, 0.0f,  // Left 
		-0.0f, -0.5f, 0.0f,  // Right
		-0.45f, 0.5f, 0.0f,  // Top 
	};
	GLfloat secondTriangle[] = {
		0.0f, -0.5f, 0.0f,  // Left
		0.9f, -0.5f, 0.0f,  // Right
		0.45f, 0.5f, 0.0f   // Top 
	};
	GLuint VBOs[2], VAOs[2];
	glGenVertexArrays(2, VAOs);
	glGenBuffers(2, VBOs);
	// ================================
	// First Triangle setup
	// ===============================
	glBindVertexArray(VAOs[0]);
	glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), firstTriangle, GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);	// Vertex attributes stay the same
	glEnableVertexAttribArray(0);
	glBindVertexArray(0);
	// ================================
	// Second Triangle setup
	// ===============================
	glBindVertexArray(VAOs[1]);	// Note that we bind to a different VAO now
	glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]);	// And a different VBO
	glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), secondTriangle, GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); // Because the vertex data is tightly packed we can also specify 0 as the vertex attribute's stride to let OpenGL figure it out.
	glEnableVertexAttribArray(0);
	glBindVertexArray(0);


	while (!glfwWindowShouldClose(window)) {
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
		// swap back and front buffers

		// every object drawn after this will use those shaders

		glUseProgram(shaderProgramOrange);
		// Draw the first triangle using the data from our first VAO
		glBindVertexArray(VAOs[0]);
		glDrawArrays(GL_TRIANGLES, 0, 3);	// This call should output an orange triangle
											// Then we draw the second triangle using the data from the second VAO
											// When we draw the second triangle we want to use a different shader program so we switch to the shader program with our yellow fragment shader.
		glUseProgram(shaderProgramYellow);
		glBindVertexArray(VAOs[1]);
		glDrawArrays(GL_TRIANGLES, 0, 3);	// This call should output a yellow triangle
		glBindVertexArray(0);

		// Swap the screen buffers
		glfwSwapBuffers(window);

		// poll the events

		glfwPollEvents();
	}

	std::cout << "finished ";
	// de allocate all ressources

	glDeleteVertexArrays(2, VAOs);
	glDeleteBuffers(2, VBOs);


	glfwTerminate();

	return 0;
}
Ejemplo n.º 20
0
///
/// \brief main
/// \return
///
int
main( void )
{

  std::cout << "Running graphics program" << std::endl;


  GLFWwindow *window;

  if ( !glfwInit( ) )
  {

    std::cerr << "GLFW initialization failed" << std::endl;
    return -1; // failure

  }

  glfwSetErrorCallback( error_callback );
  
  int WIDTH  = 640;
  int HEIGHT = 480;


  glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR,                 3 );
  glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR,                 2 );
  glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT,           GL_TRUE );
  glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
  glfwWindowHint( GLFW_RESIZABLE,                      GL_FALSE );

  window = glfwCreateWindow( WIDTH, HEIGHT, "Windows Test", 0, 0 );

  if ( !window )
  {

    glfwTerminate( );
    return -1; // failure

  }

  glfwMakeContextCurrent( window );
  glfwSwapInterval( 1 );
  glfwSetKeyCallback( window, key_callback );


  if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
  {
	  std::cout << "Failed to initialize OpenGL context" << std::endl;
	  return -1;
  }

  // Define the viewport dimensions and clear color
  glViewport(0, 0, WIDTH, HEIGHT);
  glClearColor(1.f, 0.5f, 0.1f, 1.f);



  std::cout << "Entering main loop" << std::endl;


  while ( !glfwWindowShouldClose( window ) )
  {
	
	glClear(GL_COLOR_BUFFER_BIT);

    glfwSwapBuffers( window );
    glfwPollEvents( );

  }


  glfwTerminate( );


  std::cout << "Exiting program..." << std::endl;

} // main
Ejemplo n.º 21
0
void Application::Init()
{
	//Set the error callback
	glfwSetErrorCallback(error_callback);

	//Initialize GLFW
	if (!glfwInit())
	{
		exit(EXIT_FAILURE);
	}

	//Set the GLFW window creation hints - these are optional
	glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL 

	const GLFWvidmode *win_data = glfwGetVideoMode(glfwGetPrimaryMonitor());
	glfwWindowHint(GLFW_RED_BITS, win_data->redBits);
	glfwWindowHint(GLFW_GREEN_BITS, win_data->greenBits);
	glfwWindowHint(GLFW_BLUE_BITS, win_data->blueBits);
	glfwWindowHint(GLFW_REFRESH_RATE, win_data->refreshRate);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	FPS = win_data->refreshRate; // FPS of this game
	frameTime = 1000 / FPS;

	//Create a window and create its OpenGL context
	if (FULL_SCREEN)
	{
		i_WINDOW_WIDTH = win_data->width;
		i_WINDOW_HEIGHT = win_data->height;
		glfwWindowHint(GLFW_DECORATED, GL_FALSE);
		m_window = glfwCreateWindow(win_data->width, win_data->height, WIN_NAME, NULL, NULL);
	}
	else
	{
		glfwWindowHint(GLFW_DECORATED, GL_TRUE);
		m_window = glfwCreateWindow(i_WINDOW_WIDTH, i_WINDOW_HEIGHT, WIN_NAME, NULL, NULL);
	}

	glfwSetWindowSizeCallback(m_window, resize_callback);
	//If the window couldn't be created
	if (!m_window)
	{
		fprintf(stderr, "Failed to open GLFW window.\n");
		glfwTerminate();
		exit(EXIT_FAILURE);
	}

	//This function makes the context of the specified window current on the calling thread. 
	glfwMakeContextCurrent(m_window);

	//Sets the key callback
	//glfwSetKeyCallback(m_window, key_callback);

	glewExperimental = true; // Needed for core profile
	//Initialize GLEW
	GLenum err = glewInit();

	//If GLEW hasn't initialized
	if (err != GLEW_OK)
	{
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
		//return -1;
	}

	togglefullscreen = false;
	m_dElapsedTime = 0.0;
	m_dAccumulatedTime_ThreadOne = 0.0;
	m_dAccumulatedTime_ThreadTwo = 0.0;

	S_MANAGER = SceneManager::Instance();
	S_MANAGER->Init(SceneManager::S_MAIN_MENU_SPLASH);
}
Ejemplo n.º 22
0
// the program starts here
void AppMain() {
    // initialise GLFW
    glfwSetErrorCallback(OnError);
    if(!glfwInit())
        throw std::runtime_error("glfwInit failed");

    // open a window with GLFW
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    gWindow = glfwCreateWindow((int)SCREEN_SIZE.x, (int)SCREEN_SIZE.y, "OpenGL Tutorial", NULL, NULL);
    if(!gWindow)
        throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.2?");

    // GLFW settings
    glfwMakeContextCurrent(gWindow);

    // initialise GLEW
    glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/
    if(glewInit() != GLEW_OK)
        throw std::runtime_error("glewInit failed");

    // GLEW throws some errors, so discard all the errors so far
    while(glGetError() != GL_NO_ERROR) {}

    // print out some info about the graphics drivers
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
    std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

    // make sure OpenGL version 3.2 API is available
    if(!GLEW_VERSION_3_2)
        throw std::runtime_error("OpenGL 3.2 API is not available.");

    // OpenGL settings
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // load vertex and fragment shaders into opengl
    LoadShaders();

    // load the texture
    LoadTexture();

    // create buffer and fill it with the points of the triangle
    LoadCube();

    // run while the window is open
    double lastTime = glfwGetTime();
    while(!glfwWindowShouldClose(gWindow)){
        // process pending events
        glfwPollEvents();

        // update the scene based on the time elapsed since last update
        double thisTime = glfwGetTime();
        Update((float)(thisTime - lastTime));
        lastTime = thisTime;

        // draw one frame
        Render();

        // check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR)
            std::cerr << "OpenGL Error " << error << std::endl;
    }

    // clean up and exit
    glfwTerminate();
}
Ejemplo n.º 23
0
int main(void)
{
    chdir(getenv("HOME"));
    std::srand(std::time(NULL));

    // In JavaScript, this would be "var window;"
    GLFWwindow* window; // This creates a variable to store the GLFW window

    glfwSetErrorCallback(error_callback); // Gives GLFW a function to call when there's an error.

    if (!glfwInit()) // Allows GLFW to do some initial setup and initialization.
        exit(EXIT_FAILURE); // If initialization fails, we can't continue with the program.

    // ODE initialization
    dInitODE();
    gODEWorld = dWorldCreate();
    gODESpace = dHashSpaceCreate(0);
    dWorldSetGravity(gODEWorld, 0, 0, -0.98);
    dWorldSetCFM(gODEWorld, 1e-5);
    dCreatePlane(gODESpace, 0, 0, 1, 0); // create the base plane
    gODEContactGroup = dJointGroupCreate (0);
    
    static dBodyID playBody = dBodyCreate (gODEWorld);
    static dGeomID playGeom = dCreateSphere (gODESpace, 4);
    dGeomSetBody (playGeom, playBody);
    
    

    dMass* mass2;
    mass2 = new dMass;
    dMassSetBox(mass2, 1, 1, 1, 1);
    dBodySetMass(playBody, mass2);

    static dBodyID sphereBody = dBodyCreate (gODEWorld);
    static dGeomID sphereGeom  = dCreateSphere(gODESpace, 1);
    
    dGeomSetBody (sphereGeom, sphereBody);

    dMass mass3;
    dMassSetSphere(&mass3, 2, 1);
    dBodySetMass(sphereBody, &mass3);

    // Builds a new GLFW window and saves the result in the variable above.
    // If there's an error here, window will be set to 0.
    // 640x480 is the initial size, and "Simple example" is the name of the window.
    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);

    // If window == 0, this will be true, and we've hit an error.
    if (!window /*same as saying `window == 0`*/)
    {
        glfwTerminate(); // This is the opposite of glfwInit, and allows GLFW to close up shop.
        exit(EXIT_FAILURE); // This kills the application.
    }

    glfwMakeContextCurrent(window); // Tells GLFW which window is going to be drawn to.
    glfwSwapInterval(1); // Tells GLFW how often the window should be redrawn.

    // key_callback is the function that GLFW should call when the user hits
    // a key on the keyboard. So we give that function to GLFW with this routine.
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, cursor_pos_callback);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    
    // Set some OpenGL gODEWorld options.
    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glCullFace(GL_BACK);

    //comment this out to go to normal colors
    glEnable(GL_TEXTURE_2D);

    gTextureSteel.load();
    gTexture.load();
    gTextureWood.load();
    gTextureLeaves.load();
    gTextureRoad.load();
    gTextureRoadY.load();
    gTextureWhite.load();
    gTextureBall.load();
    gTextureClear.load();
    gTextureCerealbox.load();
    gTextureCerealboxNutFacts.load();
    gTextureCerealboxBlank.load();
    
    cubeD_D myCube;
    myCube.setTexture(gTextureBall);
    myCube.SetLocation(-10, 0, 20);
    myCube.density=0.5;
    myCube.SetSize(0.5, 0.5, 0.5);
    
    cubeD_D myCube1;
    myCube1.setTexture(gTextureWhite);
    myCube1.SetLocation(5, 1, 49);
    myCube1.density=6;
    myCube1.SetSize(2, 2, 2);    
    
    BGcubeD_D BGCube1;
    BGCube1.BGsetTexture(gTextureRoad);
    BGCube1.BGSetLocation(4, 5, 7);
    BGCube1.BGSetSize(20, 1, 14);
    
    BGcubeD_D BGCube2;
    BGCube2.BGsetTexture(gTextureRoad);
    BGCube2.BGSetLocation(14.5, 14.5, 7);
    BGCube2.BGSetSize(1, 20, 14);
    
    BGcubeD_D BGCube3;
    BGCube3.BGsetTexture(gTextureRoad);
    BGCube3.BGSetLocation(-6.5, 14.5, 7);
    BGCube3.BGSetSize(1, 20, 14);
    
    BGcubeD_D BGCube4;
    BGCube4.BGsetTexture(gTextureRoad);
    BGCube4.BGSetLocation(4, 24, 7);
    BGCube4.BGSetSize(20, 1, 14);
    
    BGcubeD_D Road1;
    Road1.BGsetTexture(gTextureRoad);
    Road1.BGSetLocation(0, 0, 0.1);
    Road1.BGSetSize(1000, 8, 0.5);
    
    cubeD_D myCube3;
    myCube3.setTexture(gTextureRoadY);
    myCube3.SetLocation(4, 0, 89);
    myCube3.density=2;
    myCube1.SetSize(4, 4, 4);
    
    

    cubeD_D BouncyBlock;
    BouncyBlock.setTexture(gTextureSteel);
    BouncyBlock.SetLocation(0, 3, 40);
    BouncyBlock.r_m=255;
    BouncyBlock.g_m=0;
    BouncyBlock.b_m=0;
    dBodyAddForce(BouncyBlock.boxBody_m, 5, 5, 0);
    myCube1.SetSize(7, 7, 7);
    
    cubeD_D cerealbox;
    cerealbox.tex4=gTextureCerealbox;
    cerealbox.tex3=gTextureCerealboxNutFacts;
    cerealbox.tex2=gTextureCerealboxNutFacts;
    cerealbox.tex1=gTextureCerealboxBlank;
    cerealbox.tex5=gTextureCerealboxBlank;
    cerealbox.tex6=gTextureCerealboxBlank;
    cerealbox.SetLocation(4, -20, 1);
    cerealbox.density=1;
    cerealbox.SetSize(2, 1, 2.5);
    
    cubeD_D freezerBack;
    freezerBack.setTexture(gTextureWhite);
    freezerBack.SetLocation(20, 30, 2.5);
    freezerBack.SetSize(10,1,5);
    

    dBodySetPosition(sphereBody,0,0,50);

    static const float simulation_start_k = glfwGetTime();
    static const float real_min_per_game_day_k = 24; // CHANGE ONLY HERE TO AFFECT DAY/NIGHT SPEED
    static const float real_sec_per_game_day_k = real_min_per_game_day_k * 60;
    static const float real_sec_per_game_hrs_k = real_sec_per_game_day_k / 24;
    static const float real_sec_per_game_min_k = real_sec_per_game_hrs_k / 60;
    static const float game_min_per_real_sec_k = 1 / real_sec_per_game_min_k;
    static const float min_per_day_k = 24 * 60;

    //look position
    camRotateX=-90;

    // This is the main processing loop that draws the spinning rectangle.
    while (!glfwWindowShouldClose(window)) // this will loop until the window should close.
    {
        
        float elapsed_real_sec = glfwGetTime() - simulation_start_k;
        float elapsed_game_min = game_min_per_real_sec_k * elapsed_real_sec;
        float elapsed_game_hrs = elapsed_game_min / 60;
        float percent_of_day = (static_cast<int>(elapsed_game_min) % static_cast<int>(min_per_day_k)) / min_per_day_k;
        float sky_cycle = std::sin(percent_of_day * M_PI);
        float sky = 0 * (1-sky_cycle) + 0.9803921569 * sky_cycle;
        // int game_hrs_mil = static_cast<int>(elapsed_game_hrs) % 24; // military hours

// Set to #if 1 to enable displaying the time
#if 0
        std::cout.width(2);
        std::cout.fill('0');
        std::cout << game_hrs_mil << ":";
        std::cout.width(2);
        std::cout << (static_cast<int>(elapsed_game_min)%60) << '\n';
#endif

        // Simulate the physics engine
        // find collisions and add contact joints
        dSpaceCollide (gODESpace, 0, &ODEContactCallback);
        // step the simulation
        dWorldQuickStep (gODEWorld, 0.1);  
        // remove all contact joints
        dJointGroupEmpty (gODEContactGroup);

        // These are variable declarations.
        int width, height; // these variables store the dimensions of the window

        glfwGetFramebufferSize(window, &width, &height); // Get the height and width of the window from GLFW.
        float ratio = width / (float) height; // compute the aspect ratio of the window, which we need below.

        glViewport(0, 0, width, height); // This tells OpenGL how big the window is,
        glClearColor(0.5294117648+sky-0.9803921569, 0.8078431373+sky-0.9803921569, sky, 0);                              // and OpenGL goes off and creates a space
                                         // for drawing.
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // This asks OpenGL to wipe clean the drawing space.
                                      // The default color is black. If you want it to be
                                      // another color, you have to call glClearColor with
                                      // the new color values before making this call.

        /*
            These operations tell OpenGL how to convert the 3D world we are about
            to create into a 2D image that can be displayed on the computer screen.
        */
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(60, ratio, 1, 1000);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glRotatef(camRotateX, 1.f, 0.f, 0.f);
        glRotatef(camRotateY, 0.f, 0.f, 1.f);
        const dReal* pos = dBodyGetPosition(playBody);

        if(MoveForward){
            
            //dBodySetPosition (playBody, camX-2,camY+2.5,camZ);
            //camX -= std::sin(DegreesToRads(camRotateY))*0.1;
            //camY -= std::cos(DegreesToRads(camRotateY))*0.1;
            dBodySetForce(playBody, std::sin(DegreesToRads(camRotateY))*1, std::cos(DegreesToRads(camRotateY))*1, 0);
            
            
            
        }
        if(MoveRight){
            //camY += std::cos(DegreesToRads(camRotateY-90))*0.1;
            //camX += std::sin(DegreesToRads(camRotateY-90))*0.1;
            dBodySetForce(playBody, -std::sin(DegreesToRads(camRotateY-90))*1, -std::cos(DegreesToRads(camRotateY-90))*1, 0);
        }
        if(MoveLeft){
            //camY += std::cos(DegreesToRads(camRotateY+90))*0.1;
            //camX += std::sin(DegreesToRads(camRotateY+90))*0.1;
            dBodySetForce(playBody, -std::sin(DegreesToRads(camRotateY+90))*1, -std::cos(DegreesToRads(camRotateY+90))*1, 0);
        }
        if(MoveBackward){
            //camY += std::cos(DegreesToRads(camRotateY))*0.1;
            //camX += std::sin(DegreesToRads(camRotateY))*0.1;
            dBodySetForce(playBody, -std::sin(DegreesToRads(camRotateY))*1, -std::cos(DegreesToRads(camRotateY))*1, 0);
        }
        
        
        if(MoveUp){
            //camZ += DecreaseClimbRate;
            //DecreaseClimbRate-=0.0077;
            camZ=pos[2]-1;
            dBodySetForce(playBody, 0,0,2);
        }
        if(MoveDown){
            //camZ += DecreaseClimbRate;
            //DecreaseClimbRate-=0.0077;
            camZ=pos[2]-1;
            dBodySetForce(playBody, 0,0,-2);
        }
        if(Sprint && CarSprint){
            camY += std::cos(DegreesToRads(camRotateY))*-0.55;
            camX += std::sin(DegreesToRads(camRotateY))*-0.55;
        }
        if(CarSprint){
            camY -= std::cos(DegreesToRads(camRotateY))*1;
            camX -= std::sin(DegreesToRads(camRotateY))*1;
        }
        if(Zoom){
            camY -= std::cos(DegreesToRads(camRotateY))*50.5;
            camX -= std::sin(DegreesToRads(camRotateY))*50.5;
        }
        
        if(MoveUp==true){
            camZ=pos[2]-1;
            
            
        }
        
        if(MoveUp==false && MoveDown==false){
            camZ=pos[2]-1;
            
            
            
            
        }
        const dReal* speedSAVE = dBodyGetLinearVel(playBody);
        //std::cout << "X=" << speedSAVE[1] << '\n';
        
        
        
        
        
        if(MoveForward==false && MoveBackward==false && MoveLeft==false && MoveRight==false){
            //dBodyGetLinearVel(cubeD_D().boxBody_m);
            
            
           
            
            //speedy = -std::cos(DegreesToRads(camRotateY))*1
            if(speedSAVE[0]>0.2){
                dBodySetForce(playBody, -2.5, 0, 0);
            }
            if(speedSAVE[0]<-0.2){
                dBodySetForce(playBody, 2.5 , 0, 0);
            }
            
            if(speedSAVE[1]>0.2){
                dBodySetForce(playBody, 0, -2.5, 0);
            }
            if(speedSAVE[1]<-0.2){
                dBodySetForce(playBody, 0, 2.5, 0);
            }
           
            
            
            //dBodySetPosition (playBody, camX,camY,camZ);
            
        }
        
        /*if(MoveLeft==false){
            //dBodyGetLinearVel(cubeD_D().boxBody_m);
            
            
            
            
            //speedy = -std::cos(DegreesToRads(camRotateY))*4
            if(speedSAVE[1]<0.2){
                dBodySetForce(playBody, 0, -std::cos(DegreesToRads(camRotateY))*4, 0);
            }
            if(speedSAVE[1]>-0.2){
                dBodySetForce(playBody, 0, -std::cos(DegreesToRads(camRotateY))*4, 0);
            }
            
            
            
           
            
        }*/
        //dBodySetPosition (playBody, -camX-2,-camY+2.5,camZ+1);
        
        if(camZ<=0){
            camZ += 0.1;
            
            DecreaseClimbRate=0.2;
            MoveUp=false;
        }
        if(camX>=1){
            fall=true;
        }
        else{fall=false;}
        if(MouseOut==true){
            glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
        }
        if(MouseOut==false){
            glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
        }
        if(MouseOut==true){
            glfwSetCursorPosCallback(window, 0);
        }
        if(MouseOut==false){
            glfwSetCursorPosCallback(window, cursor_pos_callback);
        }

        glTranslatef(camX+2, camY-2.5, -camZ-2);

        gTexture.activate();
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        
        glBegin(GL_QUADS); // All OpenGL drawing begins with a glBegin.
            glColor3f(1, 1, 1);
            glTexCoord2f(0, 0); glVertex3f(-450, -450, 0);
            glTexCoord2f(450, 0); glVertex3f(450, -450 ,0);
            glTexCoord2f(450, 450); glVertex3f(450, 450, 0);
            glTexCoord2f(0, 450); glVertex3f(-450, 450, 0);
        glEnd(); // All OpenGL drawing ends with a glEnd.

        //If you would like to make a custom make change this to true v
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        camX=-pos[0]-2;
        camY=-pos[1]+2.5;
        
        /*glPushMatrix();
        orient_body_in_opengl(playBody);
        gTextureBall.activate();
        GLUquadricObj*quad2=gluNewQuadric();
        gluQuadricTexture( quad2, GL_TRUE);
        gluSphere(quad2, 0.5, 15, 15);
        gluDeleteQuadric(quad2);
        glPopMatrix();*/

        // Position and draw the sphere
        glPushMatrix();
            orient_body_in_opengl(sphereBody);
            gTextureBall.activate();
            GLUquadricObj*quad=gluNewQuadric();
            gluQuadricTexture( quad, GL_TRUE);
            gluSphere(quad, 0.5, 15, 15);
            gluDeleteQuadric(quad);
        glPopMatrix();

        myCube.draw();
        myCube1.draw();
        
        BGCube1.BGdraw();
        BGCube2.BGdraw();
        BGCube3.BGdraw();
        BGCube4.BGdraw();
        
        //dBodyDisable(myCube2.boxBody_m);

        myCube3.draw();
        BouncyBlock.draw();
        
        Road1.BGdraw();
        cerealbox.draw();
        
        freezerBack.draw();
        
        
        
        
        
        /*const dReal* pos = dBodyGetPosition(BouncyBlock.boxBody_m);
        camX=-pos[0]-2;
        camY=-pos[1]+2.5;
        camZ=pos[2];*/
        //dBodySetPosition (playBody, camX-2,camY+2.5,camZ);
        
        
        camX=-pos[0]-2;
        camY=-pos[1]+2.5;
        
        
        dBodySetPosition (playBody, pos[0],pos[1],camZ+1);
        
        //std::cout << "X=" << camX << '\n';
        //std::cout << "Y=" << camY << '\n';
        //std::cout << "Z=" << camZ << '\n';
        
        
        
        
        
        //dMatrix3* R;
        
        

        //dBodySetRotation(playBody, *R);
        //dBodySetForce(playBody, 0, 0, 0);
        // SwapBuffers causes the background drawing to get slapped onto the
        // display for the user to see.
        glfwSwapBuffers(window);

        // This lets GLFW monitor event queues like keyboard and mouse events.
        // It's at this time GLFW will call your callbacks to let you handle
        // the events any way you would like.
        glfwPollEvents();
    } // end of the while loop - do it all again!

    // At this point the window should be destroyed. This is the opposite routine
    // for glfwCreateWindow.
    glfwDestroyWindow(window);

    // ODE teardown
    dJointGroupDestroy (gODEContactGroup);
    dSpaceDestroy (gODESpace);
    dWorldDestroy (gODEWorld);
    dCloseODE();

    // This is the opposite of glfwInit - do some final cleanup before quitting.
    glfwTerminate();

    // Quit the program.
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 24
0
int main(int argc, const char * argv[]) {
    
    // Initialize glfw
    if (!glfwInit()){
        std::cerr << "Failed to initialize glfw" << std::endl;
        exit(EXIT_FAILURE);
    }
    
    // Set the error callback for glfw
    glfwSetErrorCallback(error_callback);
    
    // Set window settings
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    
    GLFWwindow *window = glfwCreateWindow(800,600, "OpenGL Renderer", NULL, NULL);
    
    if (!window) {
        std::cerr << "Could not create glfw window!" << std::endl;
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);
    
    glfwSetKeyCallback(window, key_callback);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);
    float ratio = width / (float) height;
    
    Camera cam(glm::vec3(0,0,-2));
    cam.setProjMatrix(ratio);
    
    DefaultMaterial m(glm::vec3(.2f,.2f,.9f));
    
    MeshObject cube;
    cube.setMaterial(&m);
    
    SceneNode cubeNode(&cube);
    cubeNode.setTransform(glm::scale(glm::mat4(), glm::vec3(2)));
    
    double lastFrameTime = glfwGetTime();
    double xpos, ypos;
    
    while (!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        
        double currentFrameTime = glfwGetTime();
        
        double delta = currentFrameTime - lastFrameTime;
        
        lastFrameTime = currentFrameTime;
        
        cam.translate(glm::vec3(delta * camXSpeed, delta * camYSpeed, delta * camZSpeed));
        
        glfwGetCursorPos(window, &xpos, &ypos);
        
        // Cursor rotation is currently broken.
        //cam.rotateFromCursor(2*xpos/width - 1, 2*ypos/height - 1);
        
        cubeNode.render(window, cam.getViewMatrix(), cam.getProjMatrix());
        
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    
    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}
Ejemplo n.º 25
0
	JNIEXPORT jboolean JNICALL Java_com_badlogic_jglfw_Glfw_glfwInitJni(JNIEnv* env, jclass clazz) {


//@line:447

		env->GetJavaVM(&staticVM);
		createTLS();

		jclass exception = env->FindClass("java/lang/Exception");
	
		jclass callbackClass = env->FindClass("com/badlogic/jglfw/GlfwCallback");
		if(!callbackClass) {
			env->ThrowNew(exception, "Couldn't find class GlfwCallback");
			return false;
		}
	
		errorId = env->GetMethodID(callbackClass, "error", "(ILjava/lang/String;)V");
		if(!errorId) {
			env->ThrowNew(exception, "Couldn't find error() method");
			return false;
		}
	
		monitorId = env->GetMethodID(callbackClass, "monitor", "(JZ)V");
		if(!monitorId) {
			env->ThrowNew(exception, "Couldn't find monitor() method");
			return false;
		}

		windowPosId = env->GetMethodID(callbackClass, "windowPos", "(JII)V");
		if(!windowPosId) {
			env->ThrowNew(exception, "Couldn't find windowPosId() method");
			return false;
		}
		
		windowSizeId = env->GetMethodID(callbackClass, "windowSize", "(JII)V");
		if(!windowSizeId) {
			env->ThrowNew(exception, "Couldn't find windowSizeId() method");
			return false;
		}

		windowCloseId = env->GetMethodID(callbackClass, "windowClose", "(J)Z");
		if(!windowCloseId) {
			env->ThrowNew(exception, "Couldn't find windowCloseId() method");
			return false;
		}

		windowRefreshId = env->GetMethodID(callbackClass, "windowRefresh", "(J)V");
		if(!windowRefreshId) {
			env->ThrowNew(exception, "Couldn't find windowRefresh() method");
			return false;
		}

		windowFocusId = env->GetMethodID(callbackClass, "windowFocus", "(JZ)V");
		if(!windowFocusId) {
			env->ThrowNew(exception, "Couldn't find windowFocus() method");
			return false;
		}

		windowIconifyId = env->GetMethodID(callbackClass, "windowIconify", "(JZ)V");
		if(!windowIconifyId) {
			env->ThrowNew(exception, "Couldn't find windowIconify() method");
			return false;
		}

		keyId = env->GetMethodID(callbackClass, "key", "(JIIII)V");
		if(!keyId) {
			env->ThrowNew(exception, "Couldn't find key() method");
			return false;
		}

		characterId = env->GetMethodID(callbackClass, "character", "(JC)V");
		if(!characterId) {
			env->ThrowNew(exception, "Couldn't find character() method");
			return false;
		}
		
		mouseButtonId = env->GetMethodID(callbackClass, "mouseButton", "(JIZI)V");
		if(!mouseButtonId) {
			env->ThrowNew(exception, "Couldn't find mouseButton() method, looked for (JIZI)V");
			return false;
		}
		
		cursorPosId = env->GetMethodID(callbackClass, "cursorPos", "(JDD)V");
		if(!cursorPosId) {
			env->ThrowNew(exception, "Couldn't find cursorPos() method");
			return false;
		}
		
		cursorEnterId = env->GetMethodID(callbackClass, "cursorEnter", "(JZ)V");
		if(!cursorEnterId) {
			env->ThrowNew(exception, "Couldn't find cursorEnter() method");
			return false;
		}
		
		scrollId = env->GetMethodID(callbackClass, "scroll", "(JDD)V");
		if(!scrollId) {
			env->ThrowNew(exception, "Couldn't find scroll() method");
			return false;
		}

		dropId = env->GetMethodID(callbackClass, "drop", "(J[Ljava/lang/String;)V");
		if(!dropId) {
			env->ThrowNew(exception, "Couldn't find drop() method");
			return false;
		}

		jboolean result = glfwInit() == GL_TRUE;
		if(result) {
			glfwSetErrorCallback(error);
			glfwSetMonitorCallback(monitor);
			
		}
		return result;
	

}
Ejemplo n.º 26
0
int main(int argc, char **argv )
{
    bool headless_mode=false;
    for(int i=0;;i++) {
        if(!argv[i])break;
        if(strcmp(argv[i], "--headless") == 0 ) headless_mode = true;
    }

    print("program start");

#ifdef __APPLE__    
    setlocale( LC_ALL, "ja_JP");
#endif
#ifdef WIN32    
    setlocale( LC_ALL, "jpn");
#endif    
    
    // glfw
    if( !glfwInit() ) {
        print("can't init glfw");
        return 1;
    }

    GLFWwindow *window;
    glfwSetErrorCallback( glfw_error_cb );
    window =  glfwCreateWindow( SCRW, SCRH, "min2d", NULL, NULL );
    if(window == NULL ) {
        print("can't open glfw window");
        glfwTerminate();
        return 1;
    }
    glfwMakeContextCurrent(window);    
    glfwSetWindowCloseCallback( window, winclose_callback );
    glfwSetInputMode( window, GLFW_STICKY_KEYS, GL_TRUE );
    glfwSwapInterval(0); // set 1 to use vsync. Use 0 for fast screen capturing and headless
    glfwSetKeyCallback( window, kbdCallback );
#ifdef WIN32
	glewInit();
#endif
    glClearColor(0.2,0.2,0.2,1);

    SoundSystem *ss = new SoundSystem();
    Sound *bgm = ss->newSound( "assets/gymno1short.wav" );
    bgm->play();

    g_keyboard = new Keyboard();
    
    MoyaiClient *moyai_client = new MoyaiClient(window,SCRW,SCRH);
    
    if( headless_mode ) {
        Moyai::globalInitNetwork();
        RemoteHead *rh = new RemoteHead();
        int port = 22222;
        if( rh->startServer(port) == false ) {
            print("headless server: can't start server. port:%d", 22222 );
            exit(1);
        } else {
            print("Start headless server port:%d",port);
        }
        rh->enableSpriteStream();
        rh->enableReprecation(REPRECATOR_SERVER_PORT);
        moyai_client->setRemoteHead(rh);
        rh->setTargetMoyaiClient(moyai_client);
        ss->setRemoteHead(rh);
        rh->setTargetSoundSystem(ss);
        rh->setOnKeyboardCallback(onRemoteKeyboardCallback);
    }

    
    Viewport *viewport = new Viewport();
    int retina = 1;
#if defined(__APPLE__)
    retina = 2;
#endif    
    viewport->setSize(SCRW*retina,SCRH*retina); // set actual framebuffer size to output
    viewport->setScale2D(SCRW,SCRH); // set scale used by props that will be rendered

    float zoom_rate = 1.0f;
    Vec2 center(0,0);
    Camera *camera = new Camera();
    camera->setLoc(0,0);

    Layer *l = new Layer();
    moyai_client->insertLayer(l);
    l->setViewport(viewport);
    l->setCamera(camera);

    Texture *t = new Texture();
    t->load( "./assets/base.png" );
    
    TileDeck *deck = new TileDeck();
    deck->setTexture(t);
    deck->setSize(32,32,8,8);

    Prop2D *p=NULL, *pp=NULL;
    Grid *g=NULL;
    CharGrid *cg=NULL;
    

    // normal single
    p = new Prop2D();
    p->setDeck(deck);
    p->setIndex(1);
    p->setScl(64,64);
    p->setLoc(0,0);
    l->insertProp(p);
#if 0
    // with prim
    pp = new Prop2D();
    pp->setScl(1.0f);
    pp->setLoc(100,0);
    pp->addRect( Vec2(0,0), Vec2(-100,-100), Color(0,0,1,0.5) );
    pp->addLine( Vec2(0,0), Vec2(100,100), Color(1,0,0,1) );
    pp->addLine( Vec2(0,0), Vec2(100,-100), Color(0,1,0,1), 5 );
    l->insertProp(pp);
   

    // grid
    g = new Grid(4,4);
    for(int x=0;x<4;x++) {
        for(int y=0;y<4;y++) {
            //        g->set(x,y,80+((x+y)%10));
            g->set(x,y,((x+y)%3));
        }
    }
    g->setXFlip(0,0,true); 
    g->setYFlip(0,1,true);
    g->setUVRot(0,2,true);

    Prop2D *gp = new Prop2D();
    gp->setDeck(deck);
    gp->addGrid(g);
    gp->setScl(32)    ;
    gp->setLoc(50,0);
    gp->setRot(20);
    gp->setIndex(0);
    l->insertProp(gp);

    // uvrot 
    Prop2D *rotp = new Prop2D();
    rotp->setDeck(deck);
    rotp->setScl(32);
    rotp->setLoc(-300,-100);
    rotp->setUVRot(true);
    rotp->setIndex(0);
    l->insertProp(rotp);

    // chargrid
    Texture *ft = new Texture();
    ft->load("./assets/font_only.png");
    TileDeck *fdeck =new TileDeck();
    fdeck->setTexture(ft);
    fdeck->setSize(32,32,8,8);
    cg = new CharGrid(8,8);
    cg->ascii_offset = -32;
    cg->setDeck(fdeck);
    cg->printf(0,0,Color(1,1,1,1), "WHITE" );
    cg->printf(1,1,Color(1,0,0,1), "RED" );
    cg->printf(2,2,Color(0,1,0,1), "GREEN" );
    cg->printf(3,3,Color(0,0,1,1), "BLUE" );
    Prop2D *cgp = new Prop2D();
    cgp->addGrid(cg);
    cgp->setScl(16);
    cgp->setLoc(50,-100);
    l->insertProp(cgp);

    // children
    Prop2D *chp = new Prop2D();
    chp->setLoc(-200,-200);
    chp->setDeck(deck);
    chp->setScl(48);
    chp->setIndex(0);
    for(int i=0;i<8;i++) {
        Prop2D *p = new Prop2D();
        p->setDeck(deck);
        p->setLoc( chp->loc + Vec2( (i+1)*30,0 ) );
        p->setIndex(0);
        p->setScl( 36-i*3 );
        chp->addChild(p);
    }
    
    Prop2D *dynchp = new Prop2D();
    dynchp->setLoc( chp->loc + Vec2(0,-30) );
    dynchp->setIndex(0);
    dynchp->setScl(32);
    dynchp->setDeck(deck);
    chp->addChild(dynchp);
    l->insertProp(chp);
#endif    

#if 0
    // text
    wchar_t charcodes[] = L" !\"#$%&\'()*+,-./0123456789:;<=>[email protected][\\]^_`abcdefghijklmnopqrstuvwxyz{|}~あいうえお";
    
    Font *font = new Font();
    font->loadFromTTF("./assets/cinecaption227.ttf", charcodes, 24 );
    TextBox *tbs[20];
    for(int i=0;i<20;i++) {
        tbs[i] = new TextBox();
        tbs[i]->setFont(font);
        tbs[i]->setString("A");
        tbs[i]->setScl(1+(float)i/10.0f);
        tbs[i]->setLoc(i*10-250,0);
        l->insertProp(tbs[i]);
    }
    TextBox *movtb = new TextBox();
    movtb->setFont(font);
    movtb->setString("ABCabc\n01234あいうえお");
    movtb->setScl(3);
    movtb->setLoc(0,-150);
    l->insertProp(movtb);

    // multiple viewport and layer
    Viewport *vp2 = new Viewport(); // testing multiple viewport scaling
    vp2->setSize(SCRW*retina,SCRH*retina); 
    vp2->setScale2D(SCRW*2,SCRH*2); 
    Camera *cam2 = new Camera();
    Layer *l2 = new Layer();
    l2->setViewport(vp2);
    l2->setCamera(cam2);
    Prop2D *p2 = new Prop2D();
    p2->setDeck(deck);
    p2->setScl(48,48);
    p2->setIndex(0);
    p2->setLoc(200,-200);
    l2->insertProp(p2);
    moyai_client->insertLayer(l2);

#endif
    
    // main loop

    while( !glfwWindowShouldClose(window) ){
        static int frame_counter = 0;
        static int loop_counter = 0;

        static double last_t = now();
        
        double t = now();
        double dt = t -last_t;
        last_t = t;

        double loop_start_at = t;
                
        frame_counter ++;
        loop_counter++;
        
        Vec2 at(::sin(t)*100,0);
        if(p){
            p->setLoc(at);
            if( loop_counter%21==0 )  p->setIndex( irange(0,3));
            static float rot=0;
            rot+=0.05;
            p->setRot(rot);
            p->setScl( 40 + ::sin(t/2) * 30 );
            if(pp) {
                pp->setRot(rot/2.0f);
            }

            if( loop_counter % 50 == 0 ) {
                float alpha = range(0.2, 1.0f);
                Color col(range(0,1),range(0,1),range(0,1),alpha);
                p->setColor(col);
            }
            if( loop_counter % 120 == 0 ) {
                switch(irange(0,3)) {
                case 0: p->setXFlip( irange(0,2)); break;
                case 1: p->setYFlip( irange(0,2)); break;
                case 2: p->setUVRot( irange(0,2)); break;
                }
            }            
        }

        int cnt = moyai_client->poll(dt);        

        if(g) {
            g->set( irange(0,4), irange(0,4), irange(0,3) );
            g->setColor( irange(0,4), irange(0,4), Color( range(0,1), range(0,1), range(0,1), range(0,1) ) );
        }
#if 0
        float tbr = 4 + ::sin(t)*3;
        movtb->setScl(tbr);

        Format fmt("%d", loop_counter);
        tbs[19]->setString(fmt.buf);
#endif
        
        // fps disp
        static double last_print_at = 0;
        if(last_print_at == 0){
            last_print_at = t;
        } else if( last_print_at < t-1 ){
        fprintf(stderr,"FPS:%d prop:%d drawcall:%d\n", frame_counter, cnt, moyai_client->last_draw_call_count  );
            frame_counter = 0;
            last_print_at = t;
        }

        moyai_client->render();
        //        print("drawcnt:%d", moyai_client->last_draw_call_count );
        if( g_keyboard->getKey( 'Q') ) {
            print("Q pressed");
            exit(0);
            break;
        }
        if( g_keyboard->getKey( 'L' ) ) {
            zoom_rate += 0.2;
            if( zoom_rate > 8 ) zoom_rate = 8;
        }
        if( g_keyboard->getKey( 'K' ) ) {
            zoom_rate -= 0.1;
            if( zoom_rate < 0.1 ) zoom_rate = 0.1;
        }
        viewport->setScale2D(SCRW * zoom_rate,SCRH * zoom_rate); 

        float scrollspeed = 10;
        if( g_keyboard->getKey( 'W' ) ) {
            center.y -= scrollspeed;
        }
        if( g_keyboard->getKey( 'S' ) ) {
            center.y += scrollspeed;
        }
        if( g_keyboard->getKey( 'A' ) ) {
            center.x += scrollspeed;
        }
        if( g_keyboard->getKey( 'D' ) ) {
            center.x -= scrollspeed;
        }
        camera->setLoc(center);

        
        if( g_keyboard->getKey( '1' ) ) {
            for(int i=0;i<50;i++) {
                Prop *p = new Particle(deck);
                l->insertProp(p);
            }
        }
        if( g_keyboard->getKey( '2' ) ) {
            if(cg) cg->printf(0,4, Color(1,1,1,1), Format( "CNT:%d", loop_counter).buf);
        }
#if 0        
        if( loop_counter % 25 == 0 ) {
            if( dynchp ) {
                bool res = chp->clearChild(dynchp);
                assert(res);
                delete dynchp;
                dynchp = NULL;
            } else {
                dynchp = new Prop2D();
                dynchp->setLoc( chp->loc + Vec2(0,-30) );
                dynchp->setIndex(0);
                dynchp->setScl(32);
                dynchp->setDeck(deck);
                chp->addChild(dynchp);
            }            
        }
#endif        
        glfwPollEvents();

        double loop_end_at = now();
        double loop_time = loop_end_at - loop_start_at;
        double ideal_frame_time = 1.0f / 60.0f;
        if(loop_time < ideal_frame_time ) {
            double to_sleep_sec = ideal_frame_time - loop_time;
            int to_sleep_msec = (int) (to_sleep_sec*1000);
            if( to_sleep_msec > 0 ) sleepMilliSec(to_sleep_msec);
        }
    }
    glfwTerminate();

    print("program finished");
    

    return 0;
}
Ejemplo n.º 27
0
int main(void)
{
    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(EXIT_FAILURE);

    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);
    glfwSetKeyCallback(window, key_callback);

    while (!glfwWindowShouldClose(window))
    {
        float ratio;
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;
        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        // glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
        glBegin(GL_TRIANGLES); // segitiga kiri bawah
        glColor3f(1.f, 0.f, 0.f);
        glVertex3f(-0.8f, -0.6f, 0.f);
        glVertex3f(0.f, -0.6f, 0.f);
        glVertex3f(-0.4f, 0.f, 0.f);
        glEnd();

        glBegin(GL_TRIANGLES); // segitiga kanan bawah
        glColor3f(0.f, 1.f, 0.f);
        glVertex3f(0.f, -0.6f, 0.f);
        glVertex3f(0.8f, -0.6f, 0.f);
        glVertex3f(0.4f, 0.f, 0.f);
        glEnd();

        glBegin(GL_TRIANGLES); // segitiga atas
        glColor3f(0.f, 0.f, 1.f);
        glVertex3f(-0.4f, 0.f, 0.f);
        glVertex3f(0.4f, 0.f, 0.f);
        glVertex3f(0.f, 0.6f, 0.f);
        glEnd();

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
    
}
Ejemplo n.º 28
0
int main(void) {
	unsigned int stage = grow_tree_stage;
	
	glfwSetErrorCallback(error_callback);
	if (!glfwInit()) {
	    exit(EXIT_FAILURE);		
	};

#ifdef __APPLE__
			syslog(LOG_NOTICE, "Starting trees");
#else
			// need to implement for other platforms...
#endif
		
	// make sure we're using OpenGL 3
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
		
	GLFWwindow* window = glfwCreateWindow(1024, 768, "Test tree logic", NULL, NULL);
	if (window) {
		glfwMakeContextCurrent(window);
		
		// init GLEW
		glewExperimental=true;
		GLenum err = glewInit();
		if (err != GLEW_OK) {
#ifdef __APPLE__
			syslog(LOG_ALERT, "Error: %s", glewGetErrorString(err));
#else
			// need to implement for other platforms...
#endif
		} else {
#ifdef __APPLE__
			syslog(LOG_NOTICE, "Using GLEW %s", glewGetString(GLEW_VERSION));
#else
			// need to implement for other platforms...
#endif
		};
		
		glfwSetKeyCallback(window, key_callback);
		glfwSetScrollCallback(window, scroll_callback);

		// our new tree
		treelogic * tree = new treelogic();
	
		// add just one branch to start of with, you could build the start of a tree here manually
		tree->growBranch(0, vec3(0.0, 10.0, 0.0));
	
		// and generate our attraction points, as a sample I've staged the points to get larger concentrations of points nearer to the center
		tree->generateAttractionPoints(800, 75.0, 50.0, 1.5, 50.0);
		tree->generateAttractionPoints(300, 90.0, 75.0, 1.5, 60.0, false);
		tree->generateAttractionPoints(50, 100.0, 90.0, 1.5, 70.0, false);

		// and an example with very few attraction points:
//		tree->generateAttractionPoints(50, 100.0, 40.0, 2.0, 50.0, false);
		
		tree->initShaders();
		
		while (!glfwWindowShouldClose(window)) {
	        int width, height;

			// get our width and height, may have been resized
	        glfwGetFramebufferSize(window, &width, &height);
			
			// clear our viewport
	        glViewport(0, 0, width, height);
			glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

			// setup our projection matrix
			mat4 projection;
	        float ratio = width / (float) height;
			projection.perspective(45, ratio, 1.0, 10000.0);
			tree->setProjection(projection);

			// note, with just an identity matrix our "camera" is at 0.0 ,0.0 ,0.0 looking straight ahead (looking towards 0.0 ,0.0 , -1.0)..
			// but we do adjust our view
			mat4 view;			
			view += vec3(0.0f, -100.0f, -distance);
			view.rotate(rotate, 0.f, 1.f, 0.f);
			tree->setView(view);
			
			// we leave our model alone for now...
			
			// and render
			tree->setWireframe(wireframe);
			tree->render();
			
			if ((stage == grow_tree_stage) && !paused) {
				// This is just for testing, if we were generating for real we would call this until it returns false in our initialisation... 
				if (!tree->doIteration(100.0, 1.0, 10.0, vec3(0.1, 0.2, 0.0))) {
					stage = grow_roots_stage;
					
					// we also add a small point cloud for our roots to grow next
//					tree->generateAttractionPoints(150, 50.0, 20.0, 0.2, -3.0, false);					
				};
			} else if ((stage == grow_roots_stage) && !paused) {
				if (!tree->doIteration(30.0, 2.0, 10.0, vec3(0.0, 0.0, 0.0))) {
					stage = optimise_tree_stage;
					paused = true;
				};
			} else if ((stage == optimise_tree_stage) && !paused) {
				tree->optimiseNodes();
				stage = build_mesh_stage;
				paused = true;
			} else if ((stage == build_mesh_stage) && !paused) {
				tree->setMinRadius(0.4f);
				tree->setRadiusFactor(0.0005f);
				tree->createModel();
				stage = add_leaves_stage;
				paused = true;
			};
						
			glfwSwapBuffers(window);
			glfwPollEvents();
		};
	
		glfwDestroyWindow(window);	

		delete tree;
	};	
	
	glfwTerminate();
};
Ejemplo n.º 29
0
int main(void)
{
    int jid, hat_buttons = GLFW_FALSE;
    struct nk_context* nk;
    struct nk_font_atlas* atlas;

    memset(joysticks, 0, sizeof(joysticks));

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    window = glfwCreateWindow(800, 600, "Joystick Test", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
    glfwSwapInterval(1);

    nk = nk_glfw3_init(window, NK_GLFW3_INSTALL_CALLBACKS);
    nk_glfw3_font_stash_begin(&atlas);
    nk_glfw3_font_stash_end();

    for (jid = GLFW_JOYSTICK_1;  jid <= GLFW_JOYSTICK_LAST;  jid++)
    {
        if (glfwJoystickPresent(jid))
            joysticks[joystick_count++] = jid;
    }

    glfwSetJoystickCallback(joystick_callback);

    while (!glfwWindowShouldClose(window))
    {
        int i, width, height;

        glfwGetWindowSize(window, &width, &height);

        glClear(GL_COLOR_BUFFER_BIT);
        nk_glfw3_new_frame();

        if (nk_begin(nk,
                     "Joysticks",
                     nk_rect(width - 200.f, 0.f, 200.f, (float) height),
                     NK_WINDOW_MINIMIZABLE |
                     NK_WINDOW_TITLE))
        {
            nk_layout_row_dynamic(nk, 30, 1);

            nk_checkbox_label(nk, "Hat buttons", &hat_buttons);

            if (joystick_count)
            {
                for (i = 0;  i < joystick_count;  i++)
                {
                    if (nk_button_label(nk, joystick_label(joysticks[i])))
                        nk_window_set_focus(nk, joystick_label(joysticks[i]));
                }
            }
            else
                nk_label(nk, "No joysticks connected", NK_TEXT_LEFT);
        }

        nk_end(nk);

        for (i = 0;  i < joystick_count;  i++)
        {
            if (nk_begin(nk,
                         joystick_label(joysticks[i]),
                         nk_rect(i * 20.f, i * 20.f, 550.f, 570.f),
                         NK_WINDOW_BORDER |
                         NK_WINDOW_MOVABLE |
                         NK_WINDOW_SCALABLE |
                         NK_WINDOW_MINIMIZABLE |
                         NK_WINDOW_TITLE))
            {
                int j, axis_count, button_count, hat_count;
                const float* axes;
                const unsigned char* buttons;
                const unsigned char* hats;
                GLFWgamepadstate state;

                nk_layout_row_dynamic(nk, 30, 1);
                nk_label(nk, "Joystick state", NK_TEXT_LEFT);

                axes = glfwGetJoystickAxes(joysticks[i], &axis_count);
                buttons = glfwGetJoystickButtons(joysticks[i], &button_count);
                hats = glfwGetJoystickHats(joysticks[i], &hat_count);

                if (!hat_buttons)
                    button_count -= hat_count * 4;

                for (j = 0;  j < axis_count;  j++)
                    nk_slide_float(nk, -1.f, axes[j], 1.f, 0.1f);

                nk_layout_row_dynamic(nk, 30, 12);

                for (j = 0;  j < button_count;  j++)
                {
                    char name[16];
                    snprintf(name, sizeof(name), "%i", j + 1);
                    nk_select_label(nk, name, NK_TEXT_CENTERED, buttons[j]);
                }

                nk_layout_row_dynamic(nk, 30, 8);

                for (j = 0;  j < hat_count;  j++)
                    hat_widget(nk, hats[j]);

                nk_layout_row_dynamic(nk, 30, 1);

                if (glfwGetGamepadState(joysticks[i], &state))
                {
                    int hat = 0;
                    const char* names[GLFW_GAMEPAD_BUTTON_LAST + 1 - 4] =
                    {
                        "A", "B", "X", "Y",
                        "LB", "RB",
                        "Back", "Start", "Guide",
                        "LT", "RT",
                    };

                    nk_label(nk, "Gamepad state", NK_TEXT_LEFT);

                    nk_layout_row_dynamic(nk, 30, 2);

                    for (j = 0;  j <= GLFW_GAMEPAD_AXIS_LAST;  j++)
                        nk_slide_float(nk, -1.f, state.axes[j], 1.f, 0.1f);

                    nk_layout_row_dynamic(nk, 30, GLFW_GAMEPAD_BUTTON_LAST + 1 - 4);

                    for (j = 0;  j <= GLFW_GAMEPAD_BUTTON_LAST - 4;  j++)
                        nk_select_label(nk, names[j], NK_TEXT_CENTERED, state.buttons[j]);

                    if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_UP])
                        hat |= GLFW_HAT_UP;
                    if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT])
                        hat |= GLFW_HAT_RIGHT;
                    if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_DOWN])
                        hat |= GLFW_HAT_DOWN;
                    if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_LEFT])
                        hat |= GLFW_HAT_LEFT;

                    nk_layout_row_dynamic(nk, 30, 8);
                    hat_widget(nk, hat);
                }
                else
                    nk_label(nk, "Joystick has no gamepad mapping", NK_TEXT_LEFT);
            }

            nk_end(nk);
        }

        nk_glfw3_render(NK_ANTI_ALIASING_ON, 10000, 1000);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{
    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    glfwInit();
    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    glewInit();

    //glfwWindowHint(GLFW_SAMPLES, 0);    // 0x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);  // 设置OPENGL版本3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    glfwSwapInterval(1);
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, cursorpos_callback);
    glfwSetMouseButtonCallback(window, mousebutton_callback);


    glClearColor(0,0,0,1);      // 清理屏幕为黑色
    glEnable(GL_CULL_FACE);     // 启用面剔除
    glCullFace(GL_BACK);

    glEnable(GL_DEPTH_TEST);    // 启用深度测试

    glEnable(GL_LIGHT0);        // 启用灯光0
    glEnable(GL_NORMALIZE);     // 启用法线
    glEnable(GL_COLOR_MATERIAL);// 启用材质模式
    glEnable(GL_LIGHTING);      // 打开灯光

    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER ,0.9);//0.5可以换成任何在0~1之间的数
    glShadeModel(GL_SMOOTH);

    // 设置灯光的颜色
    const GLfloat light_ambient[]  = { 0.0f, 0.0f, 0.0f, 1.0f };
    const GLfloat light_diffuse[]  = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat light_position[] = { 0.0f, 3.0f, -5.0f, 0.0f };
    glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);  // 设置环境光颜色
    glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);  // 设置漫反射的颜色
    glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);  // 设置镜面反射的颜色
    //glLightfv(GL_LIGHT0, GL_POSITION, light_position);  // 设置灯的位置

    // 设置材质的颜色
    const GLfloat mat_ambient[]    = { 0.7f, 0.7f, 0.7f, 1.0f };
    const GLfloat mat_diffuse[]    = { 0.8f, 0.8f, 0.8f, 1.0f };
    const GLfloat mat_specular[]   = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat high_shininess[] = { 100.0f };
    glMaterialfv(GL_FRONT, GL_AMBIENT,   mat_ambient);   // 设置环境光颜色
    glMaterialfv(GL_FRONT, GL_DIFFUSE,   mat_diffuse);   // 设置漫反射的颜色
    glMaterialfv(GL_FRONT, GL_SPECULAR,  mat_specular);  // 设置镜面反射的颜色
    glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);// 镜面指数 该值越小,表示材质越粗糙,点光源发射的光线照射到上面,也可以产生较大的亮点

    obj_data_t* t = obj_create();
    obj_read("Data/panel.obj","Data/panel.mtl",t);
    obj_render_t* rt = obj_create_render(t);
    obj_render_dump(rt);

    float rx = -90.0f;
    float ry = 0.0f;

    while (!glfwWindowShouldClose(window))
    {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        float ratio = (float) width / (float) height;
        glViewport(0, 0, width, height);                // 把图像按照指定宽,高显示到屏幕上
        glMatrixMode(GL_PROJECTION);                    // 选择透视矩阵
        glLoadIdentity();                               // 重置矩阵
        glFrustum(-ratio, ratio, -1.0, 1.0, 2.0, 100.0);// 设置透视矩阵
        glMatrixMode(GL_MODELVIEW);                     // 选择模型矩阵
        glLoadIdentity();

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清理颜色和深度缓存
        //glTranslatef(0.0f ,0.0f, -3.0f);
        gluLookAt(0.0f,0.0f,-3.0f, 0.0f,0.0f,1.0f, 0.0f,1.0f,0.0);
        glLightfv(GL_LIGHT0, GL_POSITION, light_position);

        glRotatef(rx + g_roll_y, 1.0f, 0.0f, 0.0f);
        glRotatef(ry + g_roll_x, 0.0f, 1.0f, 0.0f);

        //======================================================================
        obj_render(rt);
        //======================================================================
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    obj_destory_data(t);
    obj_destory_render(rt);


    glfwDestroyWindow(window);
    glfwTerminate();
    return EXIT_SUCCESS;
}