OpenGL 쉐이더 프로그래밍 - 시간 측정

타입·2025년 7월 23일

컴퓨터 그래픽스

목록 보기
10/24

부드러운 애니메이션

애니메이션 소요 시간 - Elapsed Time

  • main 함수
    while 루프에서 반복
    loop iteration에 소요되는 시간 (Elapsed Time)을 update 시에 반영 필요
    다음 프레임까지 걸린 시간에 따라 움직이는 정도를 다르게 반영해야함
while (!glfwWindowShouldClose(window)) {
	updateFunc();	// 2. update
	drawFunc();		// 3. draw
	glfwSwapBuffers(window);
	glfwPollEvents();	// 1. input processing
}

GLFW 시간 처리

  • glfwGetTime()
    GLFW가 가진 타이머가 시작되고 몇초가 흘렀는지 반환 (double 타입)
  • glfwSetTime()
    GLFW 내부 timer를 주어진 시간으로 세팅 (초 단위)

GLFW의 타이머가 높은 정밀도를 보장하는 건 아님!
(보통 수십 ms 정도의 정밀도는 보장)

  • ElapsedTime 적용
    4초마다 1회전하도록 구현 = 4초간 2PI만큼 회전 (1초에 1/2PI 회전)
float theta = 0.0F;

void updateFunc(void) {
	float elapsedTime = (float)glfwGetTime(); // double로 반환되는 시간
	theta = elapsedTime * (float)M_PI_2; // in <math.h>, M_PI_2 = pi/2
}

// R키 입력 시 타이머 리셋
void keyFunc(GLFWwindow* window, int key, int scancode, int action, int mods) {
	switch (key) {
	case GLFW_KEY_R:
		if (action == GLFW_PRESS) {
			glfwSetTime(0.0); // reset the timer
		}
		break;
	}
}

C++ 시간 처리 - Chrono

C++ < chrono >

ns 단위의 고정밀도 시간 제공 (wall-clock time)
ms 뿐만 아니라 us, ns까지도 사용 가능

  • class std::chrono::time_point
    시간을 저장하고 시간끼리 연산 가능
  • system_clock::now()
    현재 시간을 반환
system_clock::time_point lastTime = system_clock::now();
// do something
system_clock::time_point curTime = system_clock::now();
milliseconds duration = duration_cast<milliseconds>(curTime-lastTime);

sleep_for()

해당 thread를 일정 시간동안 sleep 시킴, CPU는 idle 상태

#include <thread>
// 100ms동안 시스템 sleep
std::this_thread::sleep_for(std::chrono::milliseconds(100));

chrono를 이용한 삼각형 돌리기

lastTime을 기준으로 각도 회전

float theta = 0.0F;
system_clock::time_point lastTime = system_clock::now();

void updateFunc(void) {
	system_clock::time_point curTime = system_clock::now();
	milliseconds elapsedTimeMSEC = duration_cast<milliseconds>(curTime - lastTime); // in millisecond
	theta = (elapsedTimeMSEC.count() / 1000.0F) * (float)M_PI_2; // in <math.h>, M_PI_2 = pi/2
}

void keyFunc(GLFWwindow* window, int key, int scancode, int action, int mods) {
	switch (key) {
	case GLFW_KEY_R:
		if (action == GLFW_PRESS) {
			lastTime = system_clock::now();
		}
		break;
	}
}
profile
언리얼 프로그래머

0개의 댓글