SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
공간 분할
Spatial Partition
게임 프로그래밍 패턴
이데아 게임즈 손진화
의도
객체를 효과적으로 찾기 위해 객체 위치에 따라
구성되는 자료구조에 저장한다
동기 – 전장 위의 유닛들
맵에서 가까이에 있는 유닛들을 싸우도록 만드는 코드
복잡도 O(n2)
유닛 수가 많아지면 검사 횟수가 주체할 수 없을 정도로
늘어날 수 있다
동기 – 1차원 전장
 앞의 코드의 문제는 실제로 멀리 떨어진 유닛들을
모두 계산하고 있다는 점이다
 위치에 따라 유닛을 정렬했다면 전체 배열을
훑지 않고 주변 유닛을 쉽게 찾을 수 있을 것이다
패턴
 객체들은 공간 위에서의 위치 값을 갖는다
 이들 객체를 객체 위치에 따라 구성되는
공간 자료구조에 저장한다
 공간 자료구조를 통해서 같은 위치 혹은 주변에 있는
객체를 빠르게 찾을 수 있다
 객체 위치가 바뀌면 공간 자료구조도 업데이트해
계속해서 객체를 찾을 수 있도록 한다
패턴 – 언제 쓸 것인가
 살아 움직이는 객체뿐 아니라 정적인 프랍이나 지형을
저장하는 데에도 흔하게 사용된다
 위치 값이 있는 객체가 많고, 위치에 따라 객체를 찾는
질의가 성능에 영향을 줄 정도로 잦을 때 사용한다
패턴 – 주의 사항
 객체의 수가 적다면 굳이 패턴을 적용할 필요가 없다
 객체의 위치를 변경할 때 바뀐 위치에 따라
자료구조를 업데이트 해주어야 한다
 위치 자료구조를 위해서 메모리를 더 사용하게 된다
예제 코드 – 고정 격자
 전투를 처리 할 때는
같은 칸에 들어있는
유닛끼리만
처리하면 된다
예제 코드 – 고정 격자
예제 코드 – 고정 격자
예제 코드 – 검의 격돌
예제 코드 – 검의 격돌
 하나의 유닛이 모든 유닛을 확인하지 않는다
 복잡도 분석만 놓고 보면 4중첩 루프이기 때문에
오히려 성능이 떨어진 것처럼 보일 수 있다
 하지만 내부 2중 루프(handleCell)에서 검사하는
유닛 개수가 훨씬 적기 때문에 칸마다 순회하는
외부 루프 비용을 상쇄하기 충분하다
 다만 칸이 잘게 쪼개져 있으면 외부 루프도 문제가
될 수 있다
예제 코드 – 이동
 유닛이 이동하면
Grid 정보를
업데이트
시켜줘야 한다
예제 코드 – 이동
예제 코드 – 사정거리 안에서
 칸이 달라도 거리가 가까우면 처리를 해야 한다
예제 코드 – 사정거리 안에서
예제 코드 – 사정거리 안에서
 이전 예제의 내부 루프를 함수로 분리
 주변 8칸을 모두 검사할 경우 똑같은 두 객체를
두 번 검사하게 되기 때문에 반만 검사한다
 검사 범위가 한 칸의 크기보다 더 크다면 보다 많은
칸을 검사해야 한다
디자인 결정
공간을 계층적으로 나눌 것인가, 균등하게 나눌 것인가?
계층적으로 나눈다면
공간을 몇 개의 영역으로 나눈 뒤 객체가 많은 영역은
다시 분할한다. 모든 영역에 들어있는 유닛 개수가 특정
최대 개수 이하로 떨어질 때까지 재귀적으로 반복
 빈 공간을 훨씬 효율적으로 처리할 수 있다
비어있는 칸은 공간을 할당하지 않을 수도 있다
 밀집된 영역도 효과적으로 처리할 수 있다
한 칸에 있는 최대 유닛 개수를 일정하게
유지할 수 있다
디자인 결정
공간을 계층적으로 나눌 것인가, 균등하게 나눌 것인가?
균등하게 나눈다면
 더 단순하다
 메모리 사용량이 일정하다
객체의 수와 관계없이 공간분할에 할당되는
메모리양은 같다
 객체가 위치를 이동할 때 자료구조의 업데이트 속도가
빠르다
계층형 방식일 경우 여러 계층을 고쳐야 할 수도 있다
디자인 결정
객체 개수에 따라 분할 횟수가 달라지는가?
객체 개수와 상관없이 분할한다면
 객체는 순차적으로 추가될 수 있다
 객체가 빠르게 이동할 수 있다
공간이 고정되어 있기 때문
 영역이 균형 잡혀 있지 않을 수 있다
디자인 결정
객체 개수에 따라 영역이 다르게 분할된다면
객체 개수에 따라 영역이 다르게 분할된다면
 영역의 균형 잡힘을 보장할 수 있다
성능을 일정하게 유지할 수 있다
 전체 객체에 대해 한 번에 분할해놓는 게
훨씬 효과적이다
공간을 분할하기 전에 전체 객체를 준비해놓는
것이 좋다 정적 지형이나 아트 리소스에서 많이
사용한다
디자인 결정
객체 개수에 따라 영역이 다르게 분할된다면
영역 분할은 고정되어 있지만,
계층은 객체 개수에 따라 달라진다면
 객체를 순차적으로 추가할 수 있다
 객체 이동이 빠르다
 분할 영역이 균형 잡혀 있다
디자인 결정
객체를 공간 분할 자료구조에만 저장하는가?
객체를 공간 분할 자료구조에만 저장한다면
 컬렉션이 두 개가 되면서 생기는 메모리 비용과
복잡도를 피할 수 있다
다른 컬렉션에도 객체를 둔다면
 전체 객체를 더 빠르게 순회할 수 있다
A3 사용 예
관련자료
버킷 정렬 기반
 격자
이진 검색 트리 기반
 이진 공간 분할(BSP)
 k-d 트리
 경계 볼륨 계층 구조(BVH)
트라이 기반
 쿼드트리
비둘기집 정렬
http://blog.naver.com/dntkrl79/220730718896
시간복잡도 : O(k + n), k 원소의 범위값
버킷 정렬
https://wedul.site/348
버킷 정렬
데이터가 특정 범위 내에 확률적으로 균등하게
분포한다고 가정할 수 있을 때 사용
시간복잡도(평균) : O(n)
시간복잡도(최악) : O(n2)
k-d 트리
k차원 공간의 점들을 구조화 하는 공간 분할 자료 구조
탐색, 삽입, 삭제(평균) : O(logn)
탐색, 삽입, 삭제(최악) : O(n)
쿼드 트리
https://developer.tonvolt.com/entry/QuadTree

Mais conteúdo relacionado

Mais de 진화 손

C++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdfC++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdf진화 손
 
C++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdfC++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdf진화 손
 
C++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templatesC++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templates진화 손
 
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...진화 손
 
C++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functionsC++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functions진화 손
 
C++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdfC++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdf진화 손
 
C++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete typesC++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete types진화 손
 
C++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirementsC++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirements진화 손
 
C++20 Concepts library
C++20 Concepts libraryC++20 Concepts library
C++20 Concepts library진화 손
 
C++20 Coroutine
C++20 CoroutineC++20 Coroutine
C++20 Coroutine진화 손
 
C++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rulesC++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rules진화 손
 
C++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rulesC++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rules진화 손
 
C++20 explicit(bool)
C++20 explicit(bool)C++20 explicit(bool)
C++20 explicit(bool)진화 손
 
C++20 std::map::contains
C++20 std::map::containsC++20 std::map::contains
C++20 std::map::contains진화 손
 
C++20 Comparing unordered containers
C++20 Comparing unordered containersC++20 Comparing unordered containers
C++20 Comparing unordered containers진화 손
 
C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]진화 손
 
C++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contextsC++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contexts진화 손
 
C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>진화 손
 
C++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptrC++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptr진화 손
 
C++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fieldsC++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fields진화 손
 

Mais de 진화 손 (20)

C++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdfC++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdf
 
C++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdfC++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdf
 
C++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templatesC++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templates
 
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
 
C++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functionsC++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functions
 
C++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdfC++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdf
 
C++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete typesC++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete types
 
C++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirementsC++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirements
 
C++20 Concepts library
C++20 Concepts libraryC++20 Concepts library
C++20 Concepts library
 
C++20 Coroutine
C++20 CoroutineC++20 Coroutine
C++20 Coroutine
 
C++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rulesC++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rules
 
C++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rulesC++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rules
 
C++20 explicit(bool)
C++20 explicit(bool)C++20 explicit(bool)
C++20 explicit(bool)
 
C++20 std::map::contains
C++20 std::map::containsC++20 std::map::contains
C++20 std::map::contains
 
C++20 Comparing unordered containers
C++20 Comparing unordered containersC++20 Comparing unordered containers
C++20 Comparing unordered containers
 
C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]
 
C++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contextsC++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contexts
 
C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>
 
C++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptrC++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptr
 
C++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fieldsC++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fields
 

게임 프로그래밍 패턴 20장

  • 1. 공간 분할 Spatial Partition 게임 프로그래밍 패턴 이데아 게임즈 손진화
  • 2. 의도 객체를 효과적으로 찾기 위해 객체 위치에 따라 구성되는 자료구조에 저장한다
  • 3. 동기 – 전장 위의 유닛들 맵에서 가까이에 있는 유닛들을 싸우도록 만드는 코드 복잡도 O(n2) 유닛 수가 많아지면 검사 횟수가 주체할 수 없을 정도로 늘어날 수 있다
  • 4. 동기 – 1차원 전장  앞의 코드의 문제는 실제로 멀리 떨어진 유닛들을 모두 계산하고 있다는 점이다  위치에 따라 유닛을 정렬했다면 전체 배열을 훑지 않고 주변 유닛을 쉽게 찾을 수 있을 것이다
  • 5. 패턴  객체들은 공간 위에서의 위치 값을 갖는다  이들 객체를 객체 위치에 따라 구성되는 공간 자료구조에 저장한다  공간 자료구조를 통해서 같은 위치 혹은 주변에 있는 객체를 빠르게 찾을 수 있다  객체 위치가 바뀌면 공간 자료구조도 업데이트해 계속해서 객체를 찾을 수 있도록 한다
  • 6. 패턴 – 언제 쓸 것인가  살아 움직이는 객체뿐 아니라 정적인 프랍이나 지형을 저장하는 데에도 흔하게 사용된다  위치 값이 있는 객체가 많고, 위치에 따라 객체를 찾는 질의가 성능에 영향을 줄 정도로 잦을 때 사용한다
  • 7. 패턴 – 주의 사항  객체의 수가 적다면 굳이 패턴을 적용할 필요가 없다  객체의 위치를 변경할 때 바뀐 위치에 따라 자료구조를 업데이트 해주어야 한다  위치 자료구조를 위해서 메모리를 더 사용하게 된다
  • 8. 예제 코드 – 고정 격자  전투를 처리 할 때는 같은 칸에 들어있는 유닛끼리만 처리하면 된다
  • 9. 예제 코드 – 고정 격자
  • 10. 예제 코드 – 고정 격자
  • 11. 예제 코드 – 검의 격돌
  • 12. 예제 코드 – 검의 격돌  하나의 유닛이 모든 유닛을 확인하지 않는다  복잡도 분석만 놓고 보면 4중첩 루프이기 때문에 오히려 성능이 떨어진 것처럼 보일 수 있다  하지만 내부 2중 루프(handleCell)에서 검사하는 유닛 개수가 훨씬 적기 때문에 칸마다 순회하는 외부 루프 비용을 상쇄하기 충분하다  다만 칸이 잘게 쪼개져 있으면 외부 루프도 문제가 될 수 있다
  • 13. 예제 코드 – 이동  유닛이 이동하면 Grid 정보를 업데이트 시켜줘야 한다
  • 15. 예제 코드 – 사정거리 안에서  칸이 달라도 거리가 가까우면 처리를 해야 한다
  • 16. 예제 코드 – 사정거리 안에서
  • 17. 예제 코드 – 사정거리 안에서  이전 예제의 내부 루프를 함수로 분리  주변 8칸을 모두 검사할 경우 똑같은 두 객체를 두 번 검사하게 되기 때문에 반만 검사한다  검사 범위가 한 칸의 크기보다 더 크다면 보다 많은 칸을 검사해야 한다
  • 18. 디자인 결정 공간을 계층적으로 나눌 것인가, 균등하게 나눌 것인가? 계층적으로 나눈다면 공간을 몇 개의 영역으로 나눈 뒤 객체가 많은 영역은 다시 분할한다. 모든 영역에 들어있는 유닛 개수가 특정 최대 개수 이하로 떨어질 때까지 재귀적으로 반복  빈 공간을 훨씬 효율적으로 처리할 수 있다 비어있는 칸은 공간을 할당하지 않을 수도 있다  밀집된 영역도 효과적으로 처리할 수 있다 한 칸에 있는 최대 유닛 개수를 일정하게 유지할 수 있다
  • 19. 디자인 결정 공간을 계층적으로 나눌 것인가, 균등하게 나눌 것인가? 균등하게 나눈다면  더 단순하다  메모리 사용량이 일정하다 객체의 수와 관계없이 공간분할에 할당되는 메모리양은 같다  객체가 위치를 이동할 때 자료구조의 업데이트 속도가 빠르다 계층형 방식일 경우 여러 계층을 고쳐야 할 수도 있다
  • 20. 디자인 결정 객체 개수에 따라 분할 횟수가 달라지는가? 객체 개수와 상관없이 분할한다면  객체는 순차적으로 추가될 수 있다  객체가 빠르게 이동할 수 있다 공간이 고정되어 있기 때문  영역이 균형 잡혀 있지 않을 수 있다
  • 21. 디자인 결정 객체 개수에 따라 영역이 다르게 분할된다면 객체 개수에 따라 영역이 다르게 분할된다면  영역의 균형 잡힘을 보장할 수 있다 성능을 일정하게 유지할 수 있다  전체 객체에 대해 한 번에 분할해놓는 게 훨씬 효과적이다 공간을 분할하기 전에 전체 객체를 준비해놓는 것이 좋다 정적 지형이나 아트 리소스에서 많이 사용한다
  • 22. 디자인 결정 객체 개수에 따라 영역이 다르게 분할된다면 영역 분할은 고정되어 있지만, 계층은 객체 개수에 따라 달라진다면  객체를 순차적으로 추가할 수 있다  객체 이동이 빠르다  분할 영역이 균형 잡혀 있다
  • 23. 디자인 결정 객체를 공간 분할 자료구조에만 저장하는가? 객체를 공간 분할 자료구조에만 저장한다면  컬렉션이 두 개가 되면서 생기는 메모리 비용과 복잡도를 피할 수 있다 다른 컬렉션에도 객체를 둔다면  전체 객체를 더 빠르게 순회할 수 있다
  • 25. 관련자료 버킷 정렬 기반  격자 이진 검색 트리 기반  이진 공간 분할(BSP)  k-d 트리  경계 볼륨 계층 구조(BVH) 트라이 기반  쿼드트리
  • 28. 버킷 정렬 데이터가 특정 범위 내에 확률적으로 균등하게 분포한다고 가정할 수 있을 때 사용 시간복잡도(평균) : O(n) 시간복잡도(최악) : O(n2)
  • 29. k-d 트리 k차원 공간의 점들을 구조화 하는 공간 분할 자료 구조 탐색, 삽입, 삭제(평균) : O(logn) 탐색, 삽입, 삭제(최악) : O(n)