Beispiel #1
0
Datei: main.c Projekt: needs/anko
int main(int argc, char **argv)
{
	world_t world;
	game_t game;
	double last_time = 0;
	double current_time = 0;
	float deltatime = 0;
	float sleep_time;

	if (config_from_file("anko.cfg", 1) == 2)
		return EXIT_FAILURE;
	if (config_from_args(argc, argv))
		return EXIT_FAILURE;

	if (!init())
		goto err_init;
	if (!new_game(&game, config.board_width, config.board_height, &config.gen_params, config.sim_speed * 1000))
		goto err_game;
	if (!create_world(&world, &game))
		goto err_world;
	if ((current_ui = init_ui_game(&world)) == NULL)
		goto err_ui;

	world_set_active_player(&world, add_player(&game, TEAM_BURNER));
	events_link_frame(&current_ui); // link window event to game ui frame
	glClearColor(0, 0, 0, 1);

	last_time = 0;
	while(!glfwWindowShouldClose(window)) {
	    current_time = glfwGetTime();
		deltatime = current_time - last_time;
		update_speed(deltatime);
		glfwPollEvents();

		// Update
		update_ui(current_ui, deltatime);
		update_world(&world);
		if (update_game(&game, deltatime * 1000))
			refresh_world(&world);
		if(should_quit)
			glfwSetWindowShouldClose(window, GL_TRUE);

		// Rendering
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		draw_ui(current_ui);
		font_swap_buffers();
		glfwSwapBuffers(window);

		// Update speed and sleep if necessary
		last_time = current_time;
		sleep_time = (current_time + MAX_MSPF - glfwGetTime()) * 1000 * 1000;
		if(sleep_time > 0)
			usleep(sleep_time);
	}

	destroy_ui(current_ui);
	game_over(&game);
	end_of_the_world(&world); // Tin tin tin
	terminate();

	return EXIT_SUCCESS;
err_ui:
	end_of_the_world(&world);
err_world:
	game_over(&game);
err_game:
	terminate();
err_init:
	return EXIT_FAILURE;
}
Beispiel #2
0
void update(){
    //update time

    thisTime = glfwGetTime();
    diff = thisTime - lastTime;
    if(doRotate){
        degree += diff * 180.0f;
        if(degree > 360.0f){
            degree -= 360.0f;
        }
    }
    lastTime = thisTime;

    //handle keys
    //forward, back
    if(glfwGetKey('S')){
        camera.offsetPosition( diff * moveSpeed * -camera.forward());
    } else if(glfwGetKey('W')){
        camera.offsetPosition( diff * moveSpeed * camera.forward());
    }

    //left, right
    if(glfwGetKey('A')){
        camera.offsetPosition( diff * moveSpeed * -camera.right());
    } else if(glfwGetKey('D')){
        camera.offsetPosition( diff * moveSpeed * camera.right());
    }

    //up, down
    if(glfwGetKey('Z')){
        camera.offsetPosition( diff * moveSpeed * -glm::vec3(0,1,0));
    }else if(glfwGetKey('X')){
        camera.offsetPosition( diff * moveSpeed * glm::vec3(0,1,0));
    }

    if(glfwGetKey(GLFW_KEY_SPACE)){
        doRotate = false;
    }else{
        doRotate = true;
    }

    if(glfwGetKey('1')){
        light.intensities = glm::vec3(1,1,1);
    }

    if(glfwGetKey('2')){
        light.intensities = glm::vec3(1,0,0);
    }

    if(glfwGetKey('3')){
        light.intensities = glm::vec3(0,1,0);
    }

    if(glfwGetKey('4')){
        light.intensities = glm::vec3(0,0,1);
    }

    if(glfwGetKey('5')){
        light.intensities = glm::vec3(0,0,0);
    }

    const float mouseSensitivity = 0.1;
    int mouseX, mouseY;
    glfwGetMousePos(&mouseX, &mouseY);
    camera.offsetOrientation(mouseSensitivity * mouseY, mouseSensitivity * mouseX);
    glfwSetMousePos(0, 0);

    const float zoomSensitivity = -0.2;
    float fieldOfView = camera.fieldOfView() + zoomSensitivity * (float)glfwGetMouseWheel();
    if(fieldOfView < 5.0f) fieldOfView = 5.0f;
    if(fieldOfView > 130.0f) fieldOfView = 130.0f;
    camera.setFieldOfView(fieldOfView);
    glfwSetMouseWheel(0);

}
Beispiel #3
0
double Window::get_current_time()
{
	return glfwGetTime();
}
Animutator::Animutator(){
	_startTime = glfwGetTime();
	_duration = 0;
}
Beispiel #5
0
int main(int argc, char** argv)
{
	if (!glfwInit())	// 初始化glfw库
	{
		std::cout << "Error::GLFW could not initialize GLFW!" << std::endl;
		return -1;
	}

	// 开启OpenGL 3.3 core profile
	std::cout << "Start OpenGL core profile version 3.3" << std::endl;
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	// 创建窗口
	GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
		"Demo of PBO(asynchronous DMA transfer)", NULL, NULL);
	if (!window)
	{
		std::cout << "Error::GLFW could not create winddow!" << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwSetWindowPos(window, 300, 100);
	// 创建的窗口的context指定为当前context
	glfwMakeContextCurrent(window);

	// 注册窗口键盘事件回调函数
	glfwSetKeyCallback(window, key_callback);
	// 注册鼠标事件回调函数
	glfwSetCursorPosCallback(window, mouse_move_callback);
	// 注册鼠标滚轮事件回调函数
	glfwSetScrollCallback(window, mouse_scroll_callback);
	// 鼠标捕获 停留在程序内
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	// 初始化GLEW 获取OpenGL函数
	glewExperimental = GL_TRUE; // 让glew获取所有拓展函数
	GLenum status = glewInit();
	if (status != GLEW_OK)
	{
		std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION)
			<< " error string:" << glewGetErrorString(status) << std::endl;
		glfwTerminate();
		return -1;
	}
	// 设置视口参数
	glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

	// Section1 准备顶点数据
	setupQuadVAO();
	preparePBO();
	initColorBuffer();

	// Section2 加载字体
	FontResourceManager::getInstance().loadFont("arial", "../../resources/fonts/arial.ttf");
	FontResourceManager::getInstance().loadASCIIChar("arial", 38, unicodeCharacters);

	// Section3 加载纹理
	cubeTextId = TextureHelper::load2DTexture("../../resources/textures/wood.png");
	initPixelText();

	// Section4 准备着色器程序
	Shader shader("scene.vertex", "scene.frag");
	Shader textShader("text.vertex", "text.frag");

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	// 开始游戏主循环
	while (!glfwWindowShouldClose(window))
	{
		GLfloat currentFrame = (GLfloat)glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;
		glfwPollEvents(); // 处理例如鼠标 键盘等事件
		do_movement(); // 根据用户操作情况 更新相机属性

		// 清除颜色缓冲区 重置为指定颜色
		glClearColor(0.18f, 0.04f, 0.14f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glm::mat4 projection;
		glm::mat4 view;
		glm::mat4 model;
		// 这里填写场景绘制代码
		// 先绘制纹理图片
		shader.use();
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		model = glm::mat4();
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));
		if (!isFirstRendered)
		{
			renderInitScene(shader);
			isFirstRendered = true;
		}
		else
		{
			renderScene(shader);
		}
		// 在右侧绘制信息文字 否则左侧文字会复制到右侧
		textShader.use();
		projection = glm::ortho(0.0f, (GLfloat)(SINGLE_SCREEN_WIDTH),
		0.0f, (GLfloat)SINGLE_SCREEN_HEIGHT);
		view = glm::mat4();
		glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		model = glm::mat4();
		glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));
		renderInfo(textShader);
		printTransferRate();

		glBindVertexArray(0);
		glUseProgram(0);
		glfwSwapBuffers(window); // 交换缓存
	}
	// 释放资源
	glDeleteVertexArrays(1, &quadVAOId);
	glDeleteBuffers(1, &quadVBOId);
	glDeleteVertexArrays(1, &textVAOId);
	glDeleteBuffers(1, &textVBOId);
	glDeleteBuffers(2, PBOIds);  // 注意释放PBO
	releaseColorBuffer();

	glfwTerminate();
	return 0;
}
// The MAIN function, from here we start our application and run our Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    Shader shader("parallax_mapping.vs", "parallax_mapping.frag");

    // Load textures
    GLuint diffuseMap = loadTexture(FileSystem::getPath("resources/textures/bricks2.jpg").c_str());
	GLuint normalMap = loadTexture(FileSystem::getPath("resources/textures/bricks2_normal.jpg").c_str());
	GLuint heightMap = loadTexture(FileSystem::getPath("resources/textures/bricks2_disp.jpg").c_str());
    //GLuint diffuseMap = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str();
    //GLuint normalMap = loadTexture(FileSystem::getPath("resources/textures/toy_box_normal.png").c_str());
    //GLuint heightMap = loadTexture(FileSystem::getPath("resources/textures/toy_box_disp.png").c_str());

    // Set texture units 
    shader.Use();
    glUniform1i(glGetUniformLocation(shader.Program, "diffuseMap"), 0);
	glUniform1i(glGetUniformLocation(shader.Program, "normalMap"), 1);
	glUniform1i(glGetUniformLocation(shader.Program, "depthMap"), 2);

    // Light position
    glm::vec3 lightPos(0.5f, 1.0f, 0.3f);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

        // Clear the colorbuffer
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Configure view/projection matrices
        shader.Use();
        glm::mat4 view = camera.GetViewMatrix();
        glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)SCR_WIDTH / (GLfloat)SCR_HEIGHT, 0.1f, 100.0f);
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // Render normal-mapped quad
        glm::mat4 model; 
        //model = glm::rotate(model, (GLfloat)glfwGetTime() * -10, glm::normalize(glm::vec3(1.0, 0.0, 1.0))); // Rotates the quad to show parallax mapping works in all directions
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]);
		glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]);
		glUniform1f(glGetUniformLocation(shader.Program, "height_scale"), height_scale);
		glUniform1i(glGetUniformLocation(shader.Program, "parallax"), parallax_mapping);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, diffuseMap);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, normalMap);
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, heightMap);
        RenderQuad();

        // render light source (simply renders a smaller plane at the light's position for debugging/visualization)
        model = glm::mat4();
        model = glm::translate(model, lightPos);
        model = glm::scale(model, glm::vec3(0.1f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        //RenderQuad();

        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Beispiel #7
0
static void frameWait(float frameStart) {
    static const float FPS = 60.0f;
    long wait = ((1.0f / FPS) * 1000) - (glfwGetTime() - frameStart);
    sleep_for(milliseconds(wait));
}
Beispiel #8
0
// uiloop
void uiloop() {
    auto ok = glfwInit();
    error_if_not(ok, "glfw init error");

    // setting an error callback
    glfwSetErrorCallback([](int ecode, const char* msg) {
        return error(msg);
    });

    // glfwWindowHint(GLFW_SAMPLES, scene->image_samples*scene->image_samples);

    auto window = glfwCreateWindow(scene->image_width, scene->image_height,
                                   "graphics13 | animate", NULL, NULL);
    error_if_not(window, "glfw window error");

    glfwMakeContextCurrent(window);

    glfwSetCharCallback(window, [](GLFWwindow* window, unsigned int key) {
        switch (key) {
        case 's':
            scene->draw_captureimage = true;
            break;
        case ' ':
            scene->draw_animated = ! scene->draw_animated;
            break;
        case '.':
            animate_update(scene);
            break;
        case 'g':
            scene->animation->gpu_skinning = ! scene->animation->gpu_skinning;
            animate_reset(scene);
            break;
        case 'n':
            scene->draw_normals = ! scene->draw_normals;
            break;
        case 'w':
            scene->draw_wireframe = ! scene->draw_wireframe;
            break;
        }
    });

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);

#ifdef _WIN32
    auto ok1 = glewInit();
    error_if_not(GLEW_OK == ok1, "glew init error");
#endif

    auto state = new ShadeState();
    init_shaders(state);
    init_textures(scene,state);

    animate_reset(scene);

    auto mouse_last_x = -1.0;
    auto mouse_last_y = -1.0;

    auto last_update_time = glfwGetTime();

    while(! glfwWindowShouldClose(window)) {
        auto title = tostring("graphics14 | animate | %03d", scene->animation->time);
        glfwSetWindowTitle(window, title.c_str());

        if(scene->draw_animated) {
            if(glfwGetTime() - last_update_time > scene->animation->dt) {
                last_update_time = glfwGetTime();
                animate_update(scene);
            }
        }

        glfwGetFramebufferSize(window, &scene->image_width, &scene->image_height);
        scene->camera->width = (scene->camera->height * scene->image_width) / scene->image_height;

        shade(scene,state);

        if(glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT)) {
            double x, y;
            glfwGetCursorPos(window, &x, &y);
            if (mouse_last_x < 0 || mouse_last_y < 0) {
                mouse_last_x = x;
                mouse_last_y = y;
            }
            auto delta_x = x - mouse_last_x, delta_y = y - mouse_last_y;

            set_view_turntable(scene->camera, delta_x*0.01, -delta_y*0.01, 0, 0, 0);

            mouse_last_x = x;
            mouse_last_y = y;
        } else {
            mouse_last_x = -1;
            mouse_last_y = -1;
        }

        if(scene->draw_captureimage) {
            auto image = image3f(scene->image_width,scene->image_height);
            glReadPixels(0, 0, scene->image_width, scene->image_height, GL_RGB, GL_FLOAT, &image.at(0,0));
            write_png(image_filename, image, true);
            scene->draw_captureimage = false;
        }

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();

    delete state;
}
Beispiel #9
0
static void window_focus_callback(GLFWwindow window, int focused)
{
    printf("%0.3f: Window %s\n",
           glfwGetTime(),
           focused ? "focused" : "defocused");
}
Beispiel #10
0
int main(int argc, char *argv[])
{
	GLFWwindow* window;
	glfwSetErrorCallback(error_callback);
	if (!glfwInit())
		exit(EXIT_FAILURE);
	// OpenGL 3.3, Mac OS X is reported to have some problem. However I don't have Mac to test
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	// For Mac OS X
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	window = glfwCreateWindow(1280, 960, "Mesh Smoothing Demo", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return EXIT_FAILURE;
	}

	glfwMakeContextCurrent(window);

	// This line MUST put below glfwMakeContextCurrent
	glewExperimental = GL_TRUE;
	glewInit();

	// Enable vsync
	glfwSwapInterval(1);

	// Setup input callback
	glfwSetKeyCallback(window, key_callback);
	glfwSetMouseButtonCallback(window, mouse_callback);

	setup_gui_texture();
	setup_gui_render_obj();

	filenames[0] = "smoothing";
	filenames[1] = "/ori/";
	filenames[2] = "/lap/";
	filenames[3] = "/tau/";

	// load shader program
	shaders[0] = setup_shader(readfile("shaders/vs.txt").c_str(), readfile("shaders/fs.txt").c_str());
	gui_shader = setup_shader(readfile("shaders/guivs.txt").c_str(), readfile("shaders/guifs.txt").c_str());
	shaders[1] = setup_shader(readfile("shaders/nvs.txt").c_str(), readfile("shaders/nfs.txt").c_str());
	shaders[2] = setup_shader(readfile("shaders/fvs.txt").c_str(), readfile("shaders/ffs.txt").c_str());
	printf("we have:%d, %d, %d\n", shaders[0], shaders[1], shaders[2]);
	program1 = shaders[0];

	show_obj = add_obj("smoothing/ori/bunny.obj");
	glm::vec3 light_pos(0.0f, 0.0f, 0.0f);
	camera_location = glm::vec4(0.0f, 0.0f, 2.0f, 1.0f);
	up_direction = glm::vec4(0.0f, 1.0f, 0.0f, 1.0f);

	glEnable(GL_DEPTH_TEST);
	glCullFace(GL_BACK);

	glm::vec3 camera_location_xyz = glm::vec3(camera_location.x, camera_location.y, camera_location.z);
	glm::vec3 up_direction_xyz = glm::vec3(up_direction.x, up_direction.y, up_direction.z);
	setUniformMat4(shaders[0], "p", glm::perspective(glm::radians(45.0f), 640.0f/480, 0.1f, 100.f) *glm::mat4(1.0f));
	setUniformMat4(shaders[0], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), glm::vec3(0, 1, 0))*glm::mat4(1.0f));

	setUniformMat4(shaders[1], "p", glm::perspective(glm::radians(45.0f), 640.0f/480, 0.1f, 100.f) *glm::mat4(1.0f));
	setUniformMat4(shaders[1], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), glm::vec3(0, 1, 0))*glm::mat4(1.0f));

	setUniformMat4(shaders[2], "p", glm::perspective(glm::radians(45.0f), 640.0f/480, 0.1f, 100.f) *glm::mat4(1.0f));
	setUniformMat4(shaders[2], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), glm::vec3(0, 1, 0))*glm::mat4(1.0f));



	glm::mat4 rot;
	glm::mat4 rev;

	float last, start;
	last = start = glfwGetTime();
	float fps = 0;
	while (!glfwWindowShouldClose(window))
	{
		rotate();
		zoom();

		camera_location_xyz = glm::vec3(camera_location.x, camera_location.y, camera_location.z);
		up_direction_xyz = glm::vec3(up_direction.x, up_direction.y, up_direction.z);
		setUniformMat4(shaders[0], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), up_direction_xyz)*glm::mat4(1.0f));
		setUniformMat4(shaders[1], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), up_direction_xyz)*glm::mat4(1.0f));
		setUniformMat4(shaders[2], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), up_direction_xyz)*glm::mat4(1.0f));

		render();

		glfwSwapBuffers(window);
		glfwPollEvents();
		fps++;
		if(glfwGetTime() - last > 1.0)
		{
			std::cout<<(double)fps/(glfwGetTime()-last)<<std::endl;
			fps = 0;
			last = glfwGetTime();
		}
	}

	releaseObjects();
	glfwDestroyWindow(window);
	glfwTerminate();
	return EXIT_SUCCESS;
}
Beispiel #11
0
int main(int argc, char* argv[])
{
	g_pApp = new FZApp();
	g_pApp->InitInstance(SCREEN_WIDTH, SCREEN_HEIGHT);

	int fontIndex = g_pApp->m_renderer->addFont("Assets/Arial.ttf", 20);
	int font2 = g_pApp->m_renderer->addFont("Assets/HARNGTON.TTF", 30);

	Resource snd("Assets/guitar.wav");
	g_pApp->m_resMan->getHandle(&snd);
	

	float xPos = 0;
	float speed = 100.0f;
	
	double circBuffer[120];
	int index = 0;
	double delta = 0;
	double lastFrame = 0;

	bool running = true;

	Texture2D tex1;
	tex1.load("Assets/thing.png", false);
	Texture2D tex2;
	tex2.load("Assets/thing2.png", false);

	std::wstring text = L"The quick brown fox jumped over the lazy dog.";

	float x = 0; float y = 0;
	int sx = 0; int sy = 0; int sw = 128; int sh = 128; int w = 256; int h = 256;
	while (running)
	{
		if (glfwGetKey(GLFW_KEY_ESC) || !glfwGetWindowParam(GLFW_OPENED))
		{
			running = false;
		}
		x+= 90.f * delta;
		y += 1.f * delta;
		h =  256*sinf(y);
		w =  256*cosf(y);

		g_pApp->m_renderer->clear(0.4f, 0.3f, 0.8f);
		g_pApp->m_renderer->beginBatch();


		g_pApp->m_renderer->draw(tex1, 512, 384, w, h, sx, sy, sw, sh, Color::White, 0.1f, x);
		g_pApp->m_renderer->draw(tex2, 64 + abs(768*sinf(y)), 200, 200, 200, Color::Green, 0.1f, x);

		g_pApp->m_renderer->drawString(fontIndex,
										text,
										(int)(1024/2 - g_pApp->m_renderer->stringSize(fontIndex, text)/2.f),
										400,
										Color::Red);
		g_pApp->m_renderer->drawString(font2,
										text,
										(int)(1024/2 - g_pApp->m_renderer->stringSize(font2, text)/2.f),
										200,
										Color::Yellow);
		g_pApp->m_renderer->endBatch();

		glfwSwapBuffers();

		double curTime = glfwGetTime();
		delta = curTime - lastFrame;
		lastFrame = curTime;
		circBuffer[index] = delta;
		++index;
		if (index > 119) {
			double avg = 0;
			for (int i = 0; i < 120; ++i)
			{
				avg += circBuffer[i];
			}
			avg /= 120;
			index = 0;
			//std::cout << 1 / avg << std::endl;
		}
	}
	delete g_pApp;
	return 0;
}
double elapsed() { return glfwGetTime(); }
Beispiel #13
0
int main(int argc, char **argv)
{
    if (argc > 1) {
        Time_Seed = atoi(argv[1]);
    }

    init_path();

    srand(Time_Seed);
    std::string config_file;
    if (!search_path(CONFIG_FILE, config_file)) {
        DEBUG_ERROR("error loading config file " << CONFIG_FILE);
    }
    loadConfig(config_file, &Config_Info);

    if (glfwInit() != true) {
        std::cerr << "glfwInit() fail!" << std::endl;
        return 1;
    }
    if (glfwOpenWindow(1000, 600, 8, 8, 8, 8, 8, 8, GLFW_WINDOW) != GL_TRUE) {
        /* 1000 because the player big timer doesn't show if 800 */
        std::cerr << "glfwOpenWindow() fail!" << std::endl;
    }

    generalStartup(&Resources_Manager);

    gameInitialize();
    newMatch();

    glfwSetWindowTitle("maze rush");

    glfwSetWindowSizeCallback(reshape);
    glfwSetWindowCloseCallback(closeCallback);
    glfwSetMousePosCallback(mouseMotion);
    glfwSetMouseButtonCallback(mouseButton);
    glfwSetKeyCallback(keypressCallback);
    const double fps = 1/30.0;
    double lastTime = 0.0;
    double fpsCountTime = 0.0f;
    int framesThisSecond = 0;
    Quit = false;
    while (!Quit) {
        pollKeyboard();
        double timeNow = glfwGetTime();
        if ((timeNow - lastTime) >= fps) { // one "time tick between frames"
            update();
            display();

            Quit = (Quit || !glfwGetWindowParam(GLFW_OPENED));

            ++framesThisSecond;
            lastTime = timeNow;
        }
        if (timeNow - fpsCountTime >= 1.0) { // one second
            Current_FPS = framesThisSecond; // global containing the Current_FPS;
            fpsCountTime = timeNow;
            framesThisSecond = 0;
        }
    }

    return 0;
}
Beispiel #14
0
int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    glfwMakeContextCurrent(window);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // tell GLFW to capture our mouse
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // configure global opengl state
    // -----------------------------
    glEnable(GL_DEPTH_TEST);

    // build and compile shaders
    // -------------------------
    Shader shader("1.2.pbr.vs", "1.2.pbr.fs");

    shader.use();
    shader.setInt("albedoMap", 0);
    shader.setInt("normalMap", 1);
    shader.setInt("metallicMap", 2);
    shader.setInt("roughnessMap", 3);
    shader.setInt("aoMap", 4);

    // load PBR material textures
    // --------------------------
    unsigned int albedo    = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/albedo.png").c_str());
    unsigned int normal    = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/normal.png").c_str());
    unsigned int metallic  = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/metallic.png").c_str());
    unsigned int roughness = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/roughness.png").c_str());
    unsigned int ao        = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/ao.png").c_str());

    // lights
    // ------
    glm::vec3 lightPositions[] = {
        glm::vec3(0.0f, 0.0f, 10.0f),
    };
    glm::vec3 lightColors[] = {
        glm::vec3(150.0f, 150.0f, 150.0f),
    };
    int nrRows = 7;
    int nrColumns = 7;
    float spacing = 2.5;

    // initialize static shader uniforms before rendering
    // --------------------------------------------------
    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
    shader.use();
    shader.setMat4("projection", projection);

    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // per-frame time logic
        // --------------------
        float currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // input
        // -----
        processInput(window);

        // render
        // ------
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        shader.use();
        glm::mat4 view = camera.GetViewMatrix();
        shader.setMat4("view", view);
        shader.setVec3("camPos", camera.Position);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, albedo);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, normal);
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, metallic);
        glActiveTexture(GL_TEXTURE3);
        glBindTexture(GL_TEXTURE_2D, roughness);
        glActiveTexture(GL_TEXTURE4);
        glBindTexture(GL_TEXTURE_2D, ao);

        // render rows*column number of spheres with material properties defined by textures (they all have the same material properties)
        glm::mat4 model = glm::mat4(1.0f);
        for (int row = 0; row < nrRows; ++row)
        {
            for (int col = 0; col < nrColumns; ++col)
            {
                model = glm::mat4(1.0f);
                model = glm::translate(model, glm::vec3(
                    (float)(col - (nrColumns / 2)) * spacing,
                    (float)(row - (nrRows / 2)) * spacing,
                    0.0f
                ));
                shader.setMat4("model", model);
                renderSphere();
            }
        }

        // render light source (simply re-render sphere at light positions)
        // this looks a bit off as we use the same shader, but it'll make their positions obvious and 
        // keeps the codeprint small.
        for (unsigned int i = 0; i < sizeof(lightPositions) / sizeof(lightPositions[0]); ++i)
        {
            glm::vec3 newPos = lightPositions[i] + glm::vec3(sin(glfwGetTime() * 5.0) * 5.0, 0.0, 0.0);
            newPos = lightPositions[i];
            shader.setVec3("lightPositions[" + std::to_string(i) + "]", newPos);
            shader.setVec3("lightColors[" + std::to_string(i) + "]", lightColors[i]);

            model = glm::mat4(1.0f);
            model = glm::translate(model, newPos);
            model = glm::scale(model, glm::vec3(0.5f));
            shader.setMat4("model", model);
            renderSphere();
        }

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}
Beispiel #15
0
int main()
{
	GLFWwindow* window;
	DemoData data;
	NVGcontext* vg = NULL;
	GPUtimer gpuTimer;
	PerfGraph fps, cpuGraph, gpuGraph;
	double prevt = 0, cpuTime = 0;

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

	initGraph(&fps, GRAPH_RENDER_FPS, "Frame Time");
	initGraph(&cpuGraph, GRAPH_RENDER_MS, "CPU Time");
	initGraph(&gpuGraph, GRAPH_RENDER_MS, "GPU Time");

	glfwSetErrorCallback(errorcb);
#ifndef _WIN32 // don't require this on win32, and works with more cards
	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);
#endif
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);

#ifdef DEMO_MSAA
	glfwWindowHint(GLFW_SAMPLES, 4);
#endif
	window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL);
//	window = glfwCreateWindow(1000, 600, "NanoVG", glfwGetPrimaryMonitor(), 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;
	}
	// GLEW generates GL error because it calls glGetString(GL_EXTENSIONS), we'll consume it here.
	glGetError();
#endif

#ifdef DEMO_MSAA
	vg = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_DEBUG);
#else
	vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_STENCIL_STROKES | NVG_DEBUG);
#endif
	if (vg == NULL) {
		printf("Could not init nanovg.\n");
		return -1;
	}

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

	glfwSwapInterval(0);

	initGPUTimer(&gpuTimer);

	glfwSetTime(0);
	prevt = glfwGetTime();

	while (!glfwWindowShouldClose(window))
	{
		double mx, my, t, dt;
		int winWidth, winHeight;
		int fbWidth, fbHeight;
		float pxRatio;
		float gpuTimes[3];
		int i, n;

		t = glfwGetTime();
		dt = t - prevt;
		prevt = t;

		startGPUTimer(&gpuTimer);

		glfwGetCursorPos(window, &mx, &my);
		glfwGetWindowSize(window, &winWidth, &winHeight);
		glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
		// Calculate pixel ration for hi-dpi devices.
		pxRatio = (float)fbWidth / (float)winWidth;

		// Update and render
		glViewport(0, 0, fbWidth, fbHeight);
		if (premult)
			glClearColor(0,0,0,0);
		else
			glClearColor(0.3f, 0.3f, 0.32f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);

		nvgBeginFrame(vg, winWidth, winHeight, pxRatio);

		renderDemo(vg, mx,my, winWidth,winHeight, t, blowup, &data);

		renderGraph(vg, 5,5, &fps);
		renderGraph(vg, 5+200+5,5, &cpuGraph);
		if (gpuTimer.supported)
			renderGraph(vg, 5+200+5+200+5,5, &gpuGraph);

		nvgEndFrame(vg);

		// Measure the CPU time taken excluding swap buffers (as the swap may wait for GPU)
		cpuTime = glfwGetTime() - t;

		updateGraph(&fps, dt);
		updateGraph(&cpuGraph, cpuTime);

		// We may get multiple results.
		n = stopGPUTimer(&gpuTimer, gpuTimes, 3);
		for (i = 0; i < n; i++)
			updateGraph(&gpuGraph, gpuTimes[i]);

		if (screenshot) {
			screenshot = 0;
			saveScreenShot(fbWidth, fbHeight, premult, "dump.png");
		}

		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	freeDemoData(vg, &data);

	nvgDeleteGL3(vg);

	printf("Average Frame Time: %.2f ms\n", getGraphAverage(&fps) * 1000.0f);
	printf("          CPU Time: %.2f ms\n", getGraphAverage(&cpuGraph) * 1000.0f);
	printf("          GPU Time: %.2f ms\n", getGraphAverage(&gpuGraph) * 1000.0f);

	glfwTerminate();
	return 0;
}
Beispiel #16
0
static int window_close_callback(GLFWwindow window)
{
    printf("%0.3f: User closed window\n", glfwGetTime());
    running = GL_FALSE;
    return GL_TRUE;
}
Beispiel #17
0
void GameLoop( void )
{
    int playing, event;

    // Initialize a new game
    NewGame();

    // Enable sticky keys
    glfwEnable( GLFW_STICKY_KEYS );

    // Loop until the game ends
    playing = GL_TRUE;
    while( playing && glfwGetWindowParam( GLFW_OPENED ) )
    {
        // Frame timer
        oldtime = thistime;
        thistime = glfwGetTime();
        dt = thistime - oldtime;

        // Get user input and update player positions
        PlayerControl();

        // Move the ball, and check if a player hits/misses the ball
        event = BallControl();

        // Did we have a winner?
        switch( event )
        {
        case PLAYER1_WINS:
            winner = PLAYER1;
            playing = GL_FALSE;
            break;
        case PLAYER2_WINS:
            winner = PLAYER2;
            playing = GL_FALSE;
            break;
        default:
            break;
        }

        // Did the user press ESC?
        if( glfwGetKey( GLFW_KEY_ESC ) )
        {
            playing = GL_FALSE;
        }

        // Did the user change camera view?
        if( glfwGetKey( '1' ) )
        {
            camerapos = CAMERA_CLASSIC;
        }
        else if( glfwGetKey( '2' ) )
        {
            camerapos = CAMERA_ABOVE;
        }
        else if( glfwGetKey( '3' ) )
        {
            camerapos = CAMERA_SPECTATOR;
        }

        // Draw display
        UpdateDisplay();

        // Swap buffers
        glfwSwapBuffers();
    }

    // Disable sticky keys
    glfwDisable( GLFW_STICKY_KEYS );

    // Show winner
    GameOver();
}
int main(int argc, char** argv)
{
    int ch, width, height;
    float position;
    unsigned long frame_count = 0;
    double last_time, current_time;
    GLboolean fullscreen = GL_FALSE;
    GLFWmonitor* monitor = NULL;
    GLFWwindow* window;

    while ((ch = getopt(argc, argv, "fh")) != -1)
    {
        switch (ch)
        {
            case 'h':
                usage();
                exit(EXIT_SUCCESS);

            case 'f':
                fullscreen = GL_TRUE;
                break;
        }
    }

    glfwSetErrorCallback(error_callback);

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

    if (fullscreen)
    {
        const GLFWvidmode* mode;

        monitor = glfwGetPrimaryMonitor();
        mode = glfwGetVideoMode(monitor);

        glfwWindowHint(GLFW_RED_BITS, mode->redBits);
        glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
        glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
        glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

        width = mode->width;
        height = mode->height;
    }
    else
    {
        width = 640;
        height = 480;
    }

    window = glfwCreateWindow(width, height, "", monitor, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    set_swap_interval(window, 0);

    last_time = glfwGetTime();
    frame_rate = 0.0;
    swap_tear = (glfwExtensionSupported("WGL_EXT_swap_control_tear") ||
                 glfwExtensionSupported("GLX_EXT_swap_control_tear"));

    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetKeyCallback(window, key_callback);

    glMatrixMode(GL_PROJECTION);
    glOrtho(-1.f, 1.f, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);

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

        position = cosf((float) glfwGetTime() * 4.f) * 0.75f;
        glRectf(position - 0.25f, -1.f, position + 0.25f, 1.f);

        glfwSwapBuffers(window);
        glfwPollEvents();

        frame_count++;

        current_time = glfwGetTime();
        if (current_time - last_time > 1.0)
        {
            frame_rate = frame_count / (current_time - last_time);
            frame_count = 0;
            last_time = current_time;
            update_window_title(window);
        }
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Beispiel #19
0
int main(void)
{
    GLFWwindow* window;
    GLuint vertex_buffer, vertex_shader, fragment_shader, program;
    GLint mvp_location, vpos_location, vcol_location;

    glfwSetErrorCallback(error_callback);

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

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

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

    glfwSetKeyCallback(window, key_callback);

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

    // NOTE: OpenGL error checks have been omitted for brevity

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
    glCompileShader(vertex_shader);

    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
    glCompileShader(fragment_shader);

    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);

    mvp_location = glGetUniformLocation(program, "MVP");
    vpos_location = glGetAttribLocation(program, "vPos");
    vcol_location = glGetAttribLocation(program, "vCol");

    glEnableVertexAttribArray(vpos_location);
    glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
                          sizeof(vertices[0]), (void*) 0);
    glEnableVertexAttribArray(vcol_location);
    glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE,
                          sizeof(vertices[0]), (void*) (sizeof(float) * 2));

    while (!glfwWindowShouldClose(window))
    {
        float ratio;
        int width, height;
        mat4x4 m, p, mvp;

        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;

        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);

        mat4x4_identity(m);
        mat4x4_rotate_Z(m, m, (float) glfwGetTime());
        mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 1.f, -1.f);
        mat4x4_mul(mvp, p, m);

        glUseProgram(program);
        glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
void ImGui_ImplGlfwGL3_NewFrame()
{
    if (!g_FontTexture)
        ImGui_ImplGlfwGL3_CreateDeviceObjects();

    ImGuiIO& io = ImGui::GetIO();

    // Setup display size (every frame to accommodate for window resizing)
    int w, h;
    int display_w, display_h;
    glfwGetWindowSize(g_Window, &w, &h);
    glfwGetFramebufferSize(g_Window, &display_w, &display_h);
    io.DisplaySize = ImVec2((float)w, (float)h);
    io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);

    // Setup time step
    double current_time =  glfwGetTime();
    io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
    g_Time = current_time;

    // Setup inputs
    // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
    if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
    {
        // Set OS mouse position if requested (only used when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
        if (io.WantSetMousePos)
        {
            glfwSetCursorPos(g_Window, (double)io.MousePos.x, (double)io.MousePos.y);
        }
        else
        {
            double mouse_x, mouse_y;
            glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
            io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
        }
    }
    else
    {
        io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX);
    }

    for (int i = 0; i < 3; i++)
    {
        // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
        io.MouseDown[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0;
        g_MouseJustPressed[i] = false;
    }

    // Update OS/hardware mouse cursor if imgui isn't drawing a software cursor
    if ((io.ConfigFlags & ImGuiConfigFlags_NoSetMouseCursor) == 0 && glfwGetInputMode(g_Window, GLFW_CURSOR) != GLFW_CURSOR_DISABLED)
    {
        ImGuiMouseCursor cursor = ImGui::GetMouseCursor();
        if (io.MouseDrawCursor || cursor == ImGuiMouseCursor_None)
        {
            glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
        }
        else
        {
            glfwSetCursor(g_Window, g_MouseCursors[cursor] ? g_MouseCursors[cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
            glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
        }
    }

    // Gamepad navigation mapping [BETA]
    memset(io.NavInputs, 0, sizeof(io.NavInputs));
    if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad)
    {
        // Update gamepad inputs
        #define MAP_BUTTON(NAV_NO, BUTTON_NO)       { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; }
        #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; }
        int axes_count = 0, buttons_count = 0;
        const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
        const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
        MAP_BUTTON(ImGuiNavInput_Activate,   0);     // Cross / A
        MAP_BUTTON(ImGuiNavInput_Cancel,     1);     // Circle / B
        MAP_BUTTON(ImGuiNavInput_Menu,       2);     // Square / X
        MAP_BUTTON(ImGuiNavInput_Input,      3);     // Triangle / Y
        MAP_BUTTON(ImGuiNavInput_DpadLeft,   13);    // D-Pad Left
        MAP_BUTTON(ImGuiNavInput_DpadRight,  11);    // D-Pad Right
        MAP_BUTTON(ImGuiNavInput_DpadUp,     10);    // D-Pad Up
        MAP_BUTTON(ImGuiNavInput_DpadDown,   12);    // D-Pad Down
        MAP_BUTTON(ImGuiNavInput_FocusPrev,  4);     // L1 / LB
        MAP_BUTTON(ImGuiNavInput_FocusNext,  5);     // R1 / RB
        MAP_BUTTON(ImGuiNavInput_TweakSlow,  4);     // L1 / LB
        MAP_BUTTON(ImGuiNavInput_TweakFast,  5);     // R1 / RB
        MAP_ANALOG(ImGuiNavInput_LStickLeft, 0,  -0.3f,  -0.9f);
        MAP_ANALOG(ImGuiNavInput_LStickRight,0,  +0.3f,  +0.9f);
        MAP_ANALOG(ImGuiNavInput_LStickUp,   1,  +0.3f,  +0.9f);
        MAP_ANALOG(ImGuiNavInput_LStickDown, 1,  -0.3f,  -0.9f);
        #undef MAP_BUTTON
        #undef MAP_ANALOG
        if (axes_count > 0 && buttons_count > 0) 
            io.BackendFlags |= ImGuiBackendFlags_HasGamepad; 
        else 
            io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
    }

    // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
    ImGui::NewFrame();
}
Beispiel #21
0
static void handleFrameTiming(float& frameStart) {
    frameWait(frameStart);
    frameStart = glfwGetTime();
}
Beispiel #22
0
void start_video(void *data)
{
	Nepgear::State *ng = (Nepgear::State*)data;
	Nepgear::Window *w;
	Nepgear::Logger log(NULL);
	log.print_header();

	// wait for the window to be created.
	while(ng->windows.empty());

	w = ng->windows[0];

	// Bind the OpenGL context to this thread
	const Nepgear::WindowFlags f = w->GetFlags();
	w->MakeCurrent();
	w->VSync(true);
	if (!w->Prepare(f.gl_major, f.gl_minor))
	{
		/* We shouldn't ever get here if window creation succeeded, unless
		 * the driver lied to us when we created the window. */
		log.warn(
			"OpenGL %d.%d is not supported. Please check your drivers "
			"or hardware for support.", f.gl_major, f.gl_minor
		);
		w->ClearCurrent();
		return;
	}

	// HACK: NVIDIA 295.20 drivers specifically doesn't wait properly.
	if (strcmp((const char*)glGetString(GL_VERSION), "3.2.0 NVIDIA 295.20")==0)
		ng->configuration["enable_wait_hack"] = true;
	ng->start = true;

	std::vector<Nepgear::Screen> screen_stack;

	Nepgear::Screen scr("Base");
	scr.load(ng);

	screen_stack.push_back(scr);

	glm::vec4 clear = glm::vec4(0.1, 0.4, 0.8, 1.0);

	glClearColor(clear.r, clear.g, clear.b, clear.a);
	glEnable(GL_DEPTH_TEST);

	double now = glfwGetTime();
	double then = now;
	double delta = 0.0;

	while(ng->running)
	{
		now = glfwGetTime();
		delta = now - then;
		then = now;

		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

		for (size_t i = 0; i < screen_stack.size(); i++)
			screen_stack[i].update(delta);

		for (size_t i = 0; i < screen_stack.size(); i++)
			screen_stack[i].draw();

		w->SwapBuffers();

		// This only needs to happen for the first update!
		if (ng->configuration["enable_wait_hack"])
		{
			glfwPollEvents();
			ng->configuration["enable_wait_hack"] = false;
		}
	}

	screen_stack.clear();

	w->ClearCurrent();
}
Beispiel #23
0
int main(int argc, const char * argv[]) {
  CommonSettings Settings;
  
  GLFWwindow *window = Settings.CreateWindow("EX_GS_T_1");
  if (window == nullptr) {
    std::cout << "Create window failed" << std::endl;
    glfwTerminate();
    return -1;
  }
  
  GLfloat vertices[] = {
    0.5f, 0.5f, 0.0f, 1.0f, 1.0f,
    0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
    -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
  };
  GLuint indices[] = {
    0, 1, 2,
    0, 2, 3,
  };
  GLuint VAO, VBO, EBO;
  glGenVertexArrays(1, &VAO);
  glGenBuffers(1, &VBO);
  glGenBuffers(1, &EBO);
  
  glBindVertexArray(VAO);
  
  glBindBuffer(GL_ARRAY_BUFFER, VBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
  
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
  
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);

  
#ifdef __APPLE__
  string path = "/Transformations/2/";
#else
  string path = "\\Transformations\\2\\";
#endif
  
  ShaderReader shader(Settings.CCExercisesPath(path + "EX_GS_T_2_Vertex.shader").c_str(), Settings.CCExercisesPath(path + "EX_GS_T_2_Fragment.shader").c_str());
  
  GLuint textures[2];
  TextureReader tex1(Settings.CCResourcesPath("container.jpg").c_str());
  textures[0] = tex1.getTexture();
  TextureReader tex2(Settings.CCResourcesPath("awesomeface.png").c_str());
  textures[1] = tex2.getTexture();
  
  const GLchar* names[] = {
    "tex1", "tex2",
  };
  
  while (!glfwWindowShouldClose(window)) {
    glfwPollEvents();
    
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    
    for (int i = 0; i < 2; i++) {
      glActiveTexture(GL_TEXTURE0 + i);
      glBindTexture(GL_TEXTURE_2D, textures[i]);
      glUniform1i(glGetUniformLocation(shader.GetProgram(), names[i]), i);
      
    }

    shader.Use();

    glm::mat4 trans;
    trans = glm::translate(trans, glm::vec3(-0.5f, 0.5f, 0.0f));
    trans = glm::scale(trans, glm::vec3(sin(glfwGetTime()), sin(glfwGetTime()), 1.0f));
    glUniformMatrix4fv(glGetUniformLocation(shader.GetProgram(), "transform"), 1, GL_FALSE, glm::value_ptr(trans));
    
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    
    trans = glm::mat4();
    trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f));
    trans = glm::rotate(trans, glm::radians((float)glfwGetTime() * 90.0f), glm::vec3(0.0f, 0.0f, 1.0f));
    glUniformMatrix4fv(glGetUniformLocation(shader.GetProgram(), "transform"), 1, GL_FALSE, glm::value_ptr(trans));
    
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    
    glBindTexture(GL_TEXTURE_2D, 0);
    glBindVertexArray(0);
    
    glfwSwapBuffers(window);
  }
  
  return 0;
}
Beispiel #24
0
void Xyt::Game::calculate_delta()
{
	GLfloat currentFrame = glfwGetTime();
	m_delta_time = currentFrame - m_last_frame;
	m_last_frame = currentFrame;
}
Beispiel #25
0
    -1.0f, 1.0f,-1.0f,   1.0f, 0.0f,   -1.0f, 0.0f, 0.0f,
    -1.0f,-1.0f,-1.0f,   0.0f, 0.0f,   -1.0f, 0.0f, 0.0f,
    -1.0f,-1.0f, 1.0f,   0.0f, 1.0f,   -1.0f, 0.0f, 0.0f,
    -1.0f, 1.0f, 1.0f,   1.0f, 1.0f,   -1.0f, 0.0f, 0.0f,
    -1.0f, 1.0f,-1.0f,   1.0f, 0.0f,   -1.0f, 0.0f, 0.0f,

    // right
     1.0f,-1.0f, 1.0f,   1.0f, 1.0f,   1.0f, 0.0f, 0.0f,
     1.0f,-1.0f,-1.0f,   1.0f, 0.0f,   1.0f, 0.0f, 0.0f,
     1.0f, 1.0f,-1.0f,   0.0f, 0.0f,   1.0f, 0.0f, 0.0f,
     1.0f,-1.0f, 1.0f,   1.0f, 1.0f,   1.0f, 0.0f, 0.0f,
     1.0f, 1.0f,-1.0f,   0.0f, 0.0f,   1.0f, 0.0f, 0.0f,
     1.0f, 1.0f, 1.0f,   0.0f, 1.0f,   1.0f, 0.0f, 0.0f
};

double lastTime = glfwGetTime();
double thisTime = lastTime;
float diff = 0;
const float moveSpeed = 4.0;

Light light;

struct imgdata {
    int height;
    int width;
    unsigned char* data;
};

void glPrintError(){

    GLenum errorCode = glGetError();
// The MAIN function, from here we start our application and run our Game loop
void depthTesting()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    
    GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);
    
    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);
    
    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    
    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();
    
    // Define the viewport dimensions
    glViewport(0, 0, screenWidth, screenHeight);
    
    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS); // Set to always pass the depth test (same effect as glDisable(GL_DEPTH_TEST))
    
    // Setup and compile our shaders
    Shader shader(vertexShaderSource, fragmentShaderSource);
    
#pragma region "object_initialization"
    // Set the object data (buffers, vertex attributes)
    GLfloat cubeVertices[] = {
        // Positions          // Texture Coords
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
        0.5f, -0.5f, -0.5f,  1.0f, 0.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
        
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  1.0f, 1.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f
    };
    GLfloat planeVertices[] = {
        // Positions            // Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat)
        5.0f,  -0.5f,  5.0f,  2.0f, 0.0f,
        -5.0f, -0.5f,  5.0f,  0.0f, 0.0f,
        -5.0f, -0.5f, -5.0f,  0.0f, 2.0f,
        
        5.0f,  -0.5f,  5.0f,  2.0f, 0.0f,
        -5.0f, -0.5f, -5.0f,  0.0f, 2.0f,
        5.0f,  -0.5f, -5.0f,  2.0f, 2.0f
    };
    // Setup cube VAO
    GLuint cubeVAO, cubeVBO;
    glGenVertexArrays(1, &cubeVAO);
    glGenBuffers(1, &cubeVBO);
    glBindVertexArray(cubeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glBindVertexArray(0);
    // Setup plane VAO
    GLuint planeVAO, planeVBO;
    glGenVertexArrays(1, &planeVAO);
    glGenBuffers(1, &planeVBO);
    glBindVertexArray(planeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glBindVertexArray(0);
    
    // Load textures
    GLuint cubeTexture = loadTexture("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/container2.png");
    GLuint floorTexture = loadTexture("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/awesomeface.png");
#pragma endregion
    
    // Game loop
    while(!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;
        
        // Check and call events
        glfwPollEvents();
        Do_Movement();
        
        // Clear the colorbuffer
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        
        // Draw objects
        shader.Use();
        glm::mat4 model;
        glm::mat4 view = camera.GetViewMatrix();
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f);
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // Cubes
        glBindVertexArray(cubeVAO);
        glBindTexture(GL_TEXTURE_2D, cubeTexture);  // We omit the glActiveTexture part since TEXTURE0 is already the default active texture unit. (sampler used in fragment is set to 0 as well as default)
        model = glm::translate(model, glm::vec3(-1.0f, 0.01f, -1.0f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);
        // Floor
        glBindVertexArray(planeVAO);
        glBindTexture(GL_TEXTURE_2D, floorTexture);
        model = glm::mat4();
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);
        
        
        // Swap the buffers
        glfwSwapBuffers(window);
    }
    
    glfwTerminate();

}
Beispiel #27
0
int main(void)
{
    int i;
    GLboolean running = GL_TRUE;

    glfwSetErrorCallback(error_callback);

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

    for (i = 0; i < 2; i++)
    {
        windows[i] = glfwCreateWindow(W, H, "Cursor testing", NULL, NULL);

        if (!windows[i])
        {
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        glfwSetWindowPos(windows[i], 100 + (i & 1) * (W + 50), 100);

        glfwSetWindowRefreshCallback(windows[i], refresh_callback);
        glfwSetFramebufferSizeCallback(windows[i], framebuffer_size_callback);
        glfwSetKeyCallback(windows[i], key_callback);
        glfwSetWindowFocusCallback(windows[i], focus_callback);

        glfwMakeContextCurrent(windows[i]);
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(windows[i]);
    }

    activeWindow = windows[0];

    key_callback(NULL, GLFW_KEY_H, 0, GLFW_PRESS, 0);

    while (running)
    {
        if (delay)
        {
            int i;
            double t = glfwGetTime();

            for (i = 0; i < CommandCount; i++)
            {
                if (commands[i].time != 0 && t - commands[i].time >= 3.0)
                {
                    command_callback(commands[i].key);
                    commands[i].time = 0;
                }
            }
        }

        running = !(glfwWindowShouldClose(windows[0]) || glfwWindowShouldClose(windows[1]));

        glfwPollEvents();
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Beispiel #28
0
int main(int argc, char **argv)
{
	Octree<int,16> octree;

	//for (int i = 0; i < 64; i++)
	//	std::cout << i << ": " << octree[i] << std::endl;

	Octree<int,16>::Element e = octree[1];  e.element = &octree;
	//octree[1] = true;

	//std::cin.get();

	for (int i = 0; i < 64; i++)
		std::cout << i << ": " << octree[i].element << std::endl;

	std::cout << octree[1337].element;


	GLFWwindow *window;

	glfwSetErrorCallback(ErrorCallback);

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

	window = glfwCreateWindow(800, 600, "voxicron", nullptr, nullptr);
		//glfwGetPrimaryMonitor(), nullptr);
	if (!window)
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}

	glfwMakeContextCurrent(window);
	
	glfwSetKeyCallback(window, KeyCallback);
	/*glfwSetMouseButtonCallback(MouseButtonCallback);

	glfwSetWindowSizeCallback( reshape );
	glfwSetCharCallback( characterInput );
	glfwSetMousePosCallback( mousePos );
	glfwSetMouseWheelCallback( mouseWheel );*/
	

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

		glfwGetFramebufferSize(window, &width, &height);//glfwSetFramebufferSizeCallback(window, FramebufferSizeCallback);
		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);
        glColor3f(1.f, 0.f, 0.f);
        glVertex3f(-0.6f, -0.4f, 0.f);
        glColor3f(0.f, 1.f, 0.f);
        glVertex3f(0.6f, -0.4f, 0.f);
        glColor3f(0.f, 0.f, 1.f);
        glVertex3f(0.f, 0.6f, 0.f);
        glEnd();
		
		glfwSwapBuffers(window);
		glfwPollEvents();
	}
	/*glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowSize(800, 600);
	glutInitWindowPosition(100, 100);
	glutCreateWindow("Voxicron?");

    glEnable(GL_DEPTH_TEST);

	glutDisplayFunc(Display);
	glutIdleFunc(Idle);
	glutReshapeFunc(Reshape);
	glutMouseFunc(Mouse);
	glutKeyboardFunc(Keyboard);

	glClearColor(0.125, 0.125, 0.125, 1.0);
    glEnable(GL_DEPTH_TEST);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_LIGHTING);
	glLightfv(GL_LIGHT0, GL_POSITION,  lightposition);
	glLightfv(GL_LIGHT0, GL_AMBIENT,  muljus);*/
	glfwDestroyWindow(window);
	glfwTerminate();
	exit(EXIT_SUCCESS);
}
Beispiel #29
0
	void Asteroid::init_buffer()
	{
		ModelMgr::getInstance()->loadOGLModel("rock/rock.obj");

		glm::mat4* modelMatrices = new glm::mat4[ASTEROID_AMOUNT];
		srand(glfwGetTime()); // initialize random seed	
		GLfloat radius = 15.0f;
		GLfloat offset = 2.0f;

		for (GLuint i = 0; i < ASTEROID_AMOUNT; i++)
		{
			glm::mat4 model;
			// 1. Translation: Randomly displace along circle with radius 'radius' in range [-offset, offset]
			GLfloat angle = (GLfloat)i / (GLfloat)ASTEROID_AMOUNT * 360.0f;
			GLfloat displacement = (rand() % (GLint)(2 * offset * 100)) / 100.0f - offset;
			GLfloat x = sin(angle) * radius + displacement;
			displacement = (rand() % (GLint)(2 * offset * 100)) / 100.0f - offset;
			GLfloat y = -2.5f + displacement * 0.4f; // Keep height of asteroid field smaller compared to width of x and z
			displacement = (rand() % (GLint)(2 * offset * 100)) / 100.0f - offset;
			GLfloat z = cos(angle) * radius + displacement;
			model = glm::translate(model, glm::vec3(x, y, z));

			// 2. Scale: Scale between 0.05 and 0.25f
			GLfloat scale = (rand() % 20) / 100.0f + 0.05;
			model = glm::scale(model, glm::vec3(scale));

			// 3. Rotation: add random rotation around a (semi)randomly picked rotation axis vector
			GLfloat rotAngle = (rand() % 360);
			model = glm::rotate(model, rotAngle, glm::vec3(0.4f, 0.6f, 0.8f));

			// 4. Now add to list of matrices
			modelMatrices[i] = model;
		}

		for (GLuint i = 0; i < ModelMgr::getInstance()->getMeshCount("rock/rock.obj") ; i++)
		{
			m_vao = ModelMgr::getInstance()->getMeshVAO("rock/rock.obj", i);

			GLuint buffer;
			glBindVertexArray(m_vao);
			glGenBuffers(1, &buffer);
			glBindBuffer(GL_ARRAY_BUFFER, buffer);
			glBufferData(GL_ARRAY_BUFFER, ASTEROID_AMOUNT * sizeof(glm::mat4), &modelMatrices[0], GL_STATIC_DRAW);

			// Set attribute pointers for matrix (4 times vec4) for instance
			glEnableVertexAttribArray(3);
			glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)0);
			glEnableVertexAttribArray(4);
			glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(sizeof(glm::vec4)));
			glEnableVertexAttribArray(5);
			glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(2 * sizeof(glm::vec4)));
			glEnableVertexAttribArray(6);
			glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(3 * sizeof(glm::vec4)));

			glVertexAttribDivisor(3, 1);
			glVertexAttribDivisor(4, 1);
			glVertexAttribDivisor(5, 1);
			glVertexAttribDivisor(6, 1);

			glBindVertexArray(0);
			glBindBuffer(GL_ARRAY_BUFFER, 0);
		}
		delete[] modelMatrices;
	}
Beispiel #30
0
int main(int argc, char** argv)
{
	AppInfo info = {};
	GLFWwindow* window = NULL;
	Config::init(argc, argv);

	int w = Config::screenWidth;
	int h = Config::screenHeight;
	
	if (!glfwInit()) {
		printf("Failed to init GLFW.");
		return -1;
	}

	glfwSetErrorCallback(errorcb);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
	glfwWindowHint(GLFW_SAMPLES, 4);

	window = glfwCreateWindow(w, h, "CanTK Runtime", NULL, NULL);

	if (!window) {
		glfwTerminate();
		return -1;
	}

	glfwSetKeyCallback(window, onKey);
	glfwSetCursorPosCallback(window, onMouseMove);
	glfwSetMouseButtonCallback(window, onMouseButton);
	glfwMakeContextCurrent(window);

    if(glewInit() != GLEW_OK) {
		printf("Could not init glew.\n");
		return -1;
	}

	glfwSwapInterval(0);
	glfwSetTime(0);

	info.width = w;
	info.height = h;
	info.window = window;
	info.shouldQuit = 0;
	info.lastEventTime = glfwGetTime();
/////////////////////////////////////////////////////
	V8Wrapper::init(argc, argv);
	V8Wrapper::loadApp(NULL);
	V8Wrapper::resize(w, h);
	
	uv_idle_t idle;
	uv_loop_t* loop = uv_default_loop();

	uv_idle_init(loop, &idle);
	uv_idle_start(&idle, pollEvents);

	idle.data = &info;

#if 0	
	int count = 0;
	while(!info.shouldQuit) {
		count++;
		printf("%d\n", count);
		uv_run(loop, UV_RUN_NOWAIT);
	}
#else
	uv_run(loop, UV_RUN_DEFAULT);
#endif
	glfwTerminate();
///////////////////////////////////////////////	
	V8Wrapper::deinit();
///////////////////////////////////////////////	

	return 0;
}