three.js에서 실제 3D 지도 사용하기
TerraPrinter는 3D 프린팅용으로 실제 장소의 3D 모델을 만들어요. 모든 모델은 three.js가 그대로 불러올 수 있는 GLB로도 다운로드돼요. 똑바로 선 방향에 미터 단위이고, 지도 레이어마다 이름 붙은 별도 파트로 나뉘며, 지도의 GPS 범위도 파일에 들어 있어요.
GLB에 담긴 것
GLB는 바이너리 glTF 2.0으로, three.js가 GLTFLoader로 불러오는 형식이에요. 변환할 필요가 전혀 없어요.
- 똑바로 선 방향, 출력 크기 그대로. glTF 규칙대로 Y가 위쪽이고 단위는 미터라서, 200 mm 모델은 폭이 0.2 단위예요. 원점을 중심으로 놓이고 바닥은 y = 0에 있으며, 북쪽은 −Z 방향이에요.
- 레이어마다 이름 붙은 파트 하나. Terrain, Buildings, Roads, Water, Parks, Trees 등은 각각 별도의 메시이고, 저마다 색이 있어요.
- 위치 정보. 지도 가장자리의 경도와 위도, 축척, 수직 과장, 데이터 출처 표기가 파일에 들어 있어요. three.js에서는 모델의
userData에 있어요. - 어떤 용도로든 무료이며, 상업용 게임과 앱도 포함돼요. 파일에 들어 있는 데이터 출처 표기는 남겨 주세요.
GLB 다운로드하기
- TerraPrinter를 열고 장소를 찾으세요. 검색하거나 준비된 지도 중 하나에서 시작하면 돼요.
- 영역을 그리고 건물, 도로, 물, 나무처럼 원하는 레이어를 켜세요.
- 3D 모델 생성을 누르세요.
- 다운로드 창에서 STL과 OBJ 옆에 있는 GLB를 클릭하세요.
미리보기에서 숨긴 레이어는 파일에서 빠져요. 추가한 프레임, 이름판, 받침대는 각각 별도의 파트로 들어가요.
three.js에서 불러오기
실제로 동작하는 모습 보기: three.js로 보는 파리, 이 가이드대로 만들었어요.
이건 완성된 페이지 하나예요. 장면, 조명 두 개, 마우스로 돌릴 수 있는 카메라, 그리고 모델이 들어 있어요. GLB 옆에 저장하고 파일 이름을 내 파일 이름으로 바꾼 다음, 아무 로컬 웹 서버로 여세요. 브라우저는 디스크의 파일을 바로 불러오지 않기 때문이에요.
<!doctype html>
<html>
<body style="margin: 0">
<script type="importmap">
{ "imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.183.1/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.183.1/examples/jsm/"
} }
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1b1f24');
scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5));
const sun = new THREE.DirectionalLight(0xffffff, 2.5);
sun.position.set(-1, 2, 1);
scene.add(sun);
// The model is at its printed size: a 200 mm print is 0.2 units across.
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.001, 100);
camera.position.set(0.2, 0.2, 0.25);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.01, 0);
const gltf = await new GLTFLoader().loadAsync('paris-terraprinter.com.glb');
scene.add(gltf.scene);
renderer.setAnimationLoop(() => {
controls.update();
renderer.render(scene, camera);
});
</script>
</body>
</html>Vite 같은 번들러를 쓴다면 npm install three로 three를 설치하고 import map은 빼세요. import 문은 그대로예요.
레이어 바꾸거나 숨기기
각 레이어는 이름으로 찾으세요. three.js는 이름의 공백을 밑줄로 바꾸므로 Sports fields는 Sports_fields가 되고, TerraPrinter가 쓴 원래 이름은 userData.name에 남아 있어요. 같은 색의 파트는 머티리얼 하나를 공유하므로, 색을 바꾸기 전에 그 파트에 전용 머티리얼을 지정하세요.
const model = gltf.scene;
// hide the trees
const trees = model.getObjectByName('Trees');
if (trees) trees.visible = false;
// paint the buildings
const buildings = model.getObjectByName('Buildings');
if (buildings) buildings.material = new THREE.MeshStandardMaterial({ color: '#d9d4c7', roughness: 0.9 });
// every part, by its name in TerraPrinter
model.traverse(o => { if (o.isMesh) console.log(o.userData.name, o.geometry.attributes.position.count); }); 실제 크기와 높이
모델의 루트인 gltf.scene.children[0]의 userData에 필요한 정보가 들어 있어요:
bounds와centre: 지도 가장자리와 중심의 경도와 위도.scale(예: 1:10,005)과groundMetresPerUnit: 모델 1단위가 지상에서 몇 미터인지.verticalExaggeration: 출력용으로 높이를 얼마나 늘렸는지. 1이면 실제 높이예요.mapBoxInModel: 지도의 서쪽, 동쪽, 북쪽, 남쪽 가장자리가 모델 안 어디에 있는지.printSizeMm,baseThicknessMm, 데이터 출처 표기, 라이선스.
1단위를 지상의 1미터로 만들고 높이도 실제대로 하려면:
const root = gltf.scene.children[0];
const info = root.userData;
const k = info.groundMetresPerUnit;
root.scale.set(k, k / (info.verticalExaggeration || 1), k);베이스는 Terrain 메시의 일부라서 함께 커지고, 두께가 수십 미터가 돼요. 직접 만든 지면 아래에 숨기거나, 다운로드하기 전에 TerraPrinter에서 베이스 두께를 줄이세요. 실제 크기에서는 모델이 그 장소만큼 커지므로, 카메라를 멀리 빼고 far 클리핑 평면도 그에 맞게 늘리세요.
모델 위에 GPS 지점 표시하기
경도와 위도는 지도 박스 전체에 고르게 펼쳐져 있고, 북쪽은 −Z 방향이에요. 이 함수는 어떤 축척에서든 모델 위의 아무 경도와 위도 아래에 있는 지면을 찾아요:
const raycaster = new THREE.Raycaster();
function groundAt(lon, lat, root) {
const { bounds: b, mapBoxInModel: m } = root.userData;
const x = m.xWest + (lon - b.west) / (b.east - b.west) * (m.xEast - m.xWest);
const z = m.zNorth + (b.north - lat) / (b.north - b.south) * (m.zSouth - m.zNorth);
// a ray straight down onto the terrain
root.updateWorldMatrix(true, true);
const from = root.localToWorld(new THREE.Vector3(x, 1000, z));
const to = root.localToWorld(new THREE.Vector3(x, 0, z));
raycaster.set(from, to.sub(from).normalize());
const hit = raycaster.intersectObject(root.getObjectByName('Terrain'))[0];
return hit ? hit.point : null;
}
// a red marker on the ground under the Eiffel Tower
const marker = new THREE.Mesh(new THREE.SphereGeometry(0.002), new THREE.MeshStandardMaterial({ color: 'red' }));
marker.position.copy(groundAt(2.2945, 48.8583, gltf.scene.children[0]));
scene.add(marker);지붕과 나무 꼭대기에도 닿게 하려면 Terrain 파트 대신 root 전체에 레이를 쏘세요. 모델을 실제 크기로 키웠다면 마커도 크게 만드세요.
파일 크기와 속도
- 폭 2 km 정도의 도심에 모든 건물과 나무를 넣으면 60~110 MB가 돼요. 대부분을 나무가 차지하는 경우가 많으니, 필요 없다면 TerraPrinter에서 나무를 끄세요.
- 웹사이트용이라면 glTF Transform으로 파일을 압축하세요.
npm install --global @gltf-transform/cli로 설치한 다음gltf-transform meshopt input.glb output.glb를 실행하면 돼요. 지오메트리가 압축되고, 모든 파트와 이름은 그대로 유지돼요. - 압축된 파일에는 three.js에 포함된 디코더가 필요해요:
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
const gltf = await loader.loadAsync('output.glb');