Author SHA1 Message Date
que01 7f4ebe8fb7 Improve Cesium preview loading state 2026-07-31 18:11:21 +08:00
que01 0def373c09 Extract Cesium preview assets 2026-07-31 16:56:22 +08:00
que01 41a07a78ef Add scrub edge bushes 2026-07-31 16:53:28 +08:00
8 changed files with 1286 additions and 383 deletions

No files matched your search

Binary file not shown.
+7
View File
@@ -576,6 +576,13 @@ def export(args):
center_lon = center_lat = 0.0 center_lon = center_lat = 0.0
metadata = { metadata = {
"asset": os.path.basename(args["glb"]), "asset": os.path.basename(args["glb"]),
"assets": [{
"id": "main",
"label": "Scene",
"type": "model",
"url": os.path.basename(args["glb"]),
"enabled": True,
}],
"coordinate_system": "local ENU meters (X east, Y north, Z up)", "coordinate_system": "local ENU meters (X east, Y north, Z up)",
"heading_correction_degrees": -90.0, "heading_correction_degrees": -90.0,
"anchor": {"longitude": center_lon, "latitude": center_lat, "height": 0.35}, "anchor": {"longitude": center_lon, "latitude": center_lat, "height": 0.35},
+167 -9
View File
@@ -40,6 +40,9 @@ from osmassets.geom import ( # noqa: E402 (needs the sys.path line above)
feature_in_bounds, feature_in_bounds,
geometry_rings, geometry_rings,
point_in_polygon, point_in_polygon,
polygon_area,
sample_polygon_interior,
sample_ring_boundary,
sample_tree_row, sample_tree_row,
) )
from osmassets.materials import ( # noqa: E402 from osmassets.materials import ( # noqa: E402
@@ -94,6 +97,9 @@ def _assemble_building(ring, way_id, tag, args, buildings_c, building_mats):
MODEL_ROOT = os.path.abspath(os.path.join( MODEL_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), "..", "assets", "models", "polyhaven" os.path.dirname(__file__), "..", "assets", "models", "polyhaven"
)) ))
CUSTOM_MODEL_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), "..", "assets", "models", "custom"
))
# Vendored under the name shrub_02, but the plant reads as a tufted grass, not # Vendored under the name shrub_02, but the plant reads as a tufted grass, not
# as a bush: it belongs on the lawns. Scrub beds stay flat ground cover until a # as a bush: it belongs on the lawns. Scrub beds stay flat ground cover until a
@@ -116,6 +122,22 @@ TUFT_LIMIT_PER_LAWN = 100
TUFT_TINT = (0.15, 0.52, 0.09) TUFT_TINT = (0.15, 0.52, 0.09)
TUFT_TINT_FACTOR = 0.66 TUFT_TINT_FACTOR = 0.66
SCRUB_BUSH_MODEL = os.path.join(CUSTOM_MODEL_ROOT, "bush", "bush.glb")
SCRUB_BUSH_SPACING = 0.82
SCRUB_BUSH_INSET = 0.38
SCRUB_BUSH_LIMIT_PER_PATCH = 180
SCRUB_BUSH_HEIGHT = 1.575
SCRUB_BUSH_SCALE_JITTER = 0.16
SCRUB_BUSH_LEAF_TINT = (0.075, 0.31, 0.055)
SCRUB_BUSH_LEAF_TINT_FACTOR = 0.36
SCRUB_BUSH_TRUNK_TINT = (0.13, 0.095, 0.055)
SCRUB_BUSH_TRUNK_TINT_FACTOR = 0.18
SCRUB_TREE_MIN_AREA = 45.0
SCRUB_TREE_SPACING = 8.0
SCRUB_TREE_EDGE_CLEARANCE = 2.8
SCRUB_TREE_LIMIT_PER_PATCH = 5
SCRUB_TREE_HEIGHT_RANGE = (4.6, 6.2)
# Tree styles. The two built from mesh batches live in this file; the rest are # Tree styles. The two built from mesh batches live in this file; the rest are
# vendored models handled by osmassets.tree, which owns that list. A model style # vendored models handled by osmassets.tree, which owns that list. A model style
# whose asset is missing falls back to "natural" rather than planting nothing. # whose asset is missing falls back to "natural" rather than planting nothing.
@@ -476,25 +498,142 @@ def add_grass_tufts(name, ring, variants, collection):
return len(spots) return len(spots)
def add_scrub_patch(name, ring, ground_material, collection): def _bake_imported_mesh(obj, name):
if len(ring) < 3: mesh = obj.data.copy()
mesh.transform(obj.matrix_world.to_3x3().to_4x4())
mesh.name = name
mesh.use_fake_user = True
return mesh
def _measure_meshes(meshes):
zs = [vertex.co.z for mesh in meshes for vertex in mesh.vertices]
if not zs:
return 1.0, 0.0
low, high = min(zs), max(zs)
return max(high - low, 1e-6), low
def _discard_imported_mesh_objects(objects):
for obj in objects:
mesh = obj.data if obj.type == "MESH" else None
bpy.data.objects.remove(obj, do_unlink=True)
if mesh is not None and mesh.users == 0:
bpy.data.meshes.remove(mesh)
def load_scrub_bush_variant():
"""Import the optional custom bush once for edge instancing."""
if not os.path.exists(SCRUB_BUSH_MODEL):
return None return None
before = set(bpy.data.objects)
try:
bpy.ops.import_scene.gltf(filepath=SCRUB_BUSH_MODEL)
except (RuntimeError, AttributeError) as error:
print("Scrub bush import failed, scrub stays flat:", error)
return None
imported = [obj for obj in set(bpy.data.objects) - before if obj.type == "MESH"]
if not imported:
print("Scrub bush import produced no mesh objects, scrub stays flat")
return None
meshes = []
for index, obj in enumerate(sorted(imported, key=lambda item: item.name)):
mesh = _bake_imported_mesh(obj, f"ScrubBush_{index:02d}_{obj.name}")
mesh.calc_loop_triangles()
for material in mesh.materials:
if material is None:
continue
material_name = material.name.lower()
if "leaf" in material_name:
tint_base_color(
material, SCRUB_BUSH_LEAF_TINT,
SCRUB_BUSH_LEAF_TINT_FACTOR)
elif "trunk" in material_name or "twig" in material_name:
tint_base_color(
material, SCRUB_BUSH_TRUNK_TINT,
SCRUB_BUSH_TRUNK_TINT_FACTOR)
if getattr(material, "blend_method", "OPAQUE") == "BLEND":
material.blend_method = "HASHED"
material.alpha_threshold = 0.45
material.show_transparent_back = False
meshes.append(mesh)
height, base_z = _measure_meshes(meshes)
_discard_imported_mesh_objects(imported)
tris = sum(len(mesh.loop_triangles) for mesh in meshes)
print(f"Scrub bush loaded: {len(meshes)} mesh(es), {tris} tris shared")
return {"meshes": meshes, "height": height, "base_z": base_z}
def add_scrub_edge_bushes(name, ring, variant, collection):
if not variant:
return 0
samples = sample_ring_boundary(
ring, SCRUB_BUSH_SPACING, inset=SCRUB_BUSH_INSET,
max_samples=SCRUB_BUSH_LIMIT_PER_PATCH)
if not samples:
return 0
base_scale = SCRUB_BUSH_HEIGHT / variant["height"]
for index, (x, y, angle, seed) in enumerate(samples):
jitter = 1.0 + SCRUB_BUSH_SCALE_JITTER * (
2.0 * ((seed * 0.61803398875) % 1.0) - 1.0)
scale = base_scale * jitter
z = 0.065 - variant["base_z"] * scale
rotation = angle + math.tau * 0.08 * ((seed * 0.41421356237) % 1.0 - 0.5)
for mesh_index, mesh in enumerate(variant["meshes"]):
obj = bpy.data.objects.new(
f"{name}_Bush_{index:03d}_{mesh_index:02d}", mesh)
obj.location = (x, y, z)
obj.rotation_euler = (0.0, 0.0, rotation)
obj.scale = (scale, scale, scale)
collection.objects.link(obj)
return len(samples)
def add_scrub_patch(name, ring, ground_material, collection, bush_variant=None):
if len(ring) < 3:
return None, 0
if ring[0] == ring[-1]: if ring[0] == ring[-1]:
ring = ring[:-1] ring = ring[:-1]
if len(ring) < 3: if len(ring) < 3:
return None return None, 0
ground = MeshBatch(name, collection, ground_material) ground = MeshBatch(name, collection, ground_material)
ground.add_polygon(ring, 0.055) ground.add_polygon(ring, 0.055)
obj = ground.finish() obj = ground.finish()
bush_count = add_scrub_edge_bushes(name, ring, bush_variant, collection)
# The vendored plant asset reads as grass, so it went to the lawns. Until a
# bush-shaped model lands, scrub beds stay flat ground cover: the previous
# procedural hedge mass read as blocky colour patches, not as planting.
if obj: if obj:
obj["scrub_texture"] = "Poly Haven leafy_grass, scrub-tinted" obj["scrub_texture"] = "Poly Haven leafy_grass, scrub-tinted"
obj["scrub_style"] = "flat foliage ground cover" obj["scrub_style"] = (
return obj "edge bush instances" if bush_count else "flat foliage ground cover"
)
obj["scrub_edge_bushes"] = bush_count
return obj, bush_count
def sample_scrub_interior_trees(ring, way_id):
if polygon_area(ring) < SCRUB_TREE_MIN_AREA:
return []
try:
seed = int(way_id)
except (TypeError, ValueError):
seed = sum(ord(char) for char in str(way_id))
samples = sample_polygon_interior(
ring, SCRUB_TREE_SPACING,
edge_clearance=SCRUB_TREE_EDGE_CLEARANCE,
max_samples=SCRUB_TREE_LIMIT_PER_PATCH,
seed=seed)
min_height, max_height = SCRUB_TREE_HEIGHT_RANGE
span = max_height - min_height
trees = []
for x, y, sample_seed in samples:
height = min_height + span * ((sample_seed * 0.754877666) % 1.0)
trees.append((x, y, height))
return trees
def add_fountain(name, x, y, collection, materials): def add_fountain(name, x, y, collection, materials):
@@ -605,6 +744,7 @@ def build(args):
# between the ground materials and the props. Material creation order fixes # between the ground materials and the props. Material creation order fixes
# the material indices in the exported GLB. # the material indices in the exported GLB.
tuft_variants = load_tuft_variants() tuft_variants = load_tuft_variants()
scrub_bush_variant = load_scrub_bush_variant()
fountain_mats = { fountain_mats = {
key: material_from_spec(catalog.MATERIALS[key]) key: material_from_spec(catalog.MATERIALS[key])
for key in ("fountain_stone", "fountain_water", "fountain_spray") for key in ("fountain_stone", "fountain_water", "fountain_spray")
@@ -631,6 +771,7 @@ def build(args):
ground_batch.finish() ground_batch.finish()
grass_rings = [] grass_rings = []
scrub_trees = []
tree_rows = [] tree_rows = []
# Counters were previously individual ints scattered through the loop body. # Counters were previously individual ints scattered through the loop body.
# Collecting them into a dict lets the scene[...] and SCENE_DONE sections # Collecting them into a dict lets the scene[...] and SCENE_DONE sections
@@ -643,8 +784,17 @@ def build(args):
"grass_tuft_count": 0, "grass_tuft_count": 0,
"industrial_count": 0, "industrial_count": 0,
"lake_count": 0, "lake_count": 0,
"scrub_bush_count": 0,
"scrub_count": 0, "scrub_count": 0,
"scrub_tree_count": 0,
} }
def add_scrub_patch_with_bushes(name, ring, ground_material, collection):
obj, bush_count = add_scrub_patch(
name, ring, ground_material, collection, scrub_bush_variant)
counts["scrub_bush_count"] += bush_count
return obj
focus_points = [] focus_points = []
for way in ways: for way in ways:
coords = way["coords"] coords = way["coords"]
@@ -668,10 +818,13 @@ def build(args):
elif tag.get("natural") == "scrub" and len(ring) >= 3: elif tag.get("natural") == "scrub" and len(ring) >= 3:
added, ring_pts = _scrub.assemble(ring, way["id"], scene_xmin, scene_xmax, added, ring_pts = _scrub.assemble(ring, way["id"], scene_xmin, scene_xmax,
scene_ymin, scene_ymax, green_c, scrub_mat, scene_ymin, scene_ymax, green_c, scrub_mat,
add_scrub_patch) add_scrub_patch_with_bushes)
counts["scrub_count"] += added counts["scrub_count"] += added
if ring_pts: if ring_pts:
focus_points.extend(ring_pts) focus_points.extend(ring_pts)
new_scrub_trees = sample_scrub_interior_trees(ring_pts, way["id"])
scrub_trees.extend(new_scrub_trees)
counts["scrub_tree_count"] += len(new_scrub_trees)
elif tag.get("natural") == "tree_row": elif tag.get("natural") == "tree_row":
tree_rows.append((ring, tag)) tree_rows.append((ring, tag))
focus_points.extend(ring) focus_points.extend(ring)
@@ -712,6 +865,7 @@ def build(args):
x, y = projector.xy(feature["coord"]) x, y = projector.xy(feature["coord"])
trees.append((x, y, parse_height(feature["tags"], 5.5))) trees.append((x, y, parse_height(feature["tags"], 5.5)))
individual_tree_count += 1 individual_tree_count += 1
trees.extend(scrub_trees)
row_tree_count = 0 row_tree_count = 0
for row, row_tags in tree_rows: for row, row_tags in tree_rows:
row_samples = sample_tree_row(row, spacing=5.0, row_samples = sample_tree_row(row, spacing=5.0,
@@ -800,6 +954,8 @@ def build(args):
scene["grass_count"] = counts["grass_count"] scene["grass_count"] = counts["grass_count"]
scene["grass_tuft_count"] = counts["grass_tuft_count"] scene["grass_tuft_count"] = counts["grass_tuft_count"]
scene["scrub_count"] = counts["scrub_count"] scene["scrub_count"] = counts["scrub_count"]
scene["scrub_bush_count"] = counts["scrub_bush_count"]
scene["scrub_tree_count"] = counts["scrub_tree_count"]
scene["fountain_count"] = counts["fountain_count"] scene["fountain_count"] = counts["fountain_count"]
scene["tree_node_count"] = individual_tree_count scene["tree_node_count"] = individual_tree_count
scene["tree_row_count"] = row_tree_count scene["tree_row_count"] = row_tree_count
@@ -829,6 +985,8 @@ def build(args):
"grass": counts["grass_count"], "grass": counts["grass_count"],
"grass_tufts": counts["grass_tuft_count"], "grass_tufts": counts["grass_tuft_count"],
"scrub": counts["scrub_count"], "scrub": counts["scrub_count"],
"scrub_bushes": counts["scrub_bush_count"],
"scrub_trees": counts["scrub_tree_count"],
"fountains": counts["fountain_count"], "fountains": counts["fountain_count"],
"tree_nodes": individual_tree_count, "tree_nodes": individual_tree_count,
"tree_row_instances": row_tree_count, "tree_row_instances": row_tree_count,
+94 -1
View File
@@ -103,12 +103,105 @@ def sample_tree_row(points, spacing, height):
def polygon_area(ring): def polygon_area(ring):
"""Unsigned shoelace area; 0.0 for degenerate rings.""" """Unsigned shoelace area; 0.0 for degenerate rings."""
return abs(signed_polygon_area(ring))
def signed_polygon_area(ring):
"""Signed shoelace area; positive for counter-clockwise rings."""
if len(ring) < 3: if len(ring) < 3:
return 0.0 return 0.0
area = 0.0 area = 0.0
for (x1, y1), (x2, y2) in zip(ring, ring[1:] + ring[:1]): for (x1, y1), (x2, y2) in zip(ring, ring[1:] + ring[:1]):
area += x1 * y2 - x2 * y1 area += x1 * y2 - x2 * y1
return abs(area) * 0.5 return area * 0.5
def sample_ring_boundary(ring, spacing, inset=0.0, max_samples=None):
"""Evenly sample a closed ring's boundary.
Returns (x, y, angle, index) samples. ``angle`` follows the local edge
direction, and ``inset`` moves the sample toward the polygon interior.
"""
if len(ring) > 1 and ring[0] == ring[-1]:
ring = ring[:-1]
if len(ring) < 3 or spacing <= 0.0:
return []
edges = []
perimeter = 0.0
winding = signed_polygon_area(ring)
for index, (start, end) in enumerate(zip(ring, ring[1:] + ring[:1])):
dx = end[0] - start[0]
dy = end[1] - start[1]
length = math.hypot(dx, dy)
if length <= 1e-9:
continue
ux = dx / length
uy = dy / length
# Counter-clockwise rings have their interior on the left side of each
# edge; clockwise rings have it on the right.
inward = (-uy, ux) if winding >= 0.0 else (uy, -ux)
edges.append((perimeter, start, ux, uy, length, inward, index))
perimeter += length
if not edges:
return []
count = max(1, int(perimeter / spacing))
if max_samples:
count = min(count, max_samples)
step = perimeter / count
samples = []
edge_cursor = 0
for sample_index in range(count):
target = (sample_index + 0.5) * step
while edge_cursor + 1 < len(edges) and (
edges[edge_cursor][0] + edges[edge_cursor][4] < target
):
edge_cursor += 1
edge_start, start, ux, uy, length, inward, _ = edges[edge_cursor]
along = max(0.0, min(length, target - edge_start))
x = start[0] + ux * along
y = start[1] + uy * along
sx = x + inward[0] * inset
sy = y + inward[1] * inset
if inset > 0.0 and not point_in_polygon((sx, sy), ring):
sx, sy = x, y
samples.append((sx, sy, math.atan2(uy, ux), sample_index))
return samples
def sample_polygon_interior(ring, spacing, edge_clearance=0.0, max_samples=None,
seed=0):
"""Jittered interior samples for sparse planting inside a polygon."""
if len(ring) > 1 and ring[0] == ring[-1]:
ring = ring[:-1]
if len(ring) < 3 or spacing <= 0.0 or polygon_area(ring) <= 1e-9:
return []
xmin = min(x for x, _ in ring)
xmax = max(x for x, _ in ring)
ymin = min(y for _, y in ring)
ymax = max(y for _, y in ring)
cols = max(1, int(math.ceil((xmax - xmin) / spacing)))
rows = max(1, int(math.ceil((ymax - ymin) / spacing)))
samples = []
for col in range(cols):
for row in range(rows):
sample_seed = ((col + 1) * 73856093) ^ ((row + 1) * 19349663) ^ seed
jx = ((sample_seed * 0.61803398875) % 1.0 - 0.5) * spacing * 0.7
jy = ((sample_seed * 0.41421356237) % 1.0 - 0.5) * spacing * 0.7
x = xmin + (col + 0.5) * spacing + jx
y = ymin + (row + 0.5) * spacing + jy
if not point_in_polygon((x, y), ring):
continue
if edge_clearance > 0.0 and distance_to_ring((x, y), ring) < edge_clearance:
continue
samples.append((x, y, sample_seed))
if max_samples and len(samples) > max_samples:
samples.sort(key=lambda item: (item[2] * 0.754877666) % 1.0)
samples = samples[:max_samples]
return samples
def point_in_polygon(point, ring): def point_in_polygon(point, ring):
+58
View File
@@ -25,7 +25,10 @@ from osmassets.geom import (
geometry_rings, geometry_rings,
point_in_polygon, point_in_polygon,
polygon_area, polygon_area,
sample_polygon_interior,
sample_ring_boundary,
sample_tree_row, sample_tree_row,
signed_polygon_area,
) )
from osmassets.osm import Projector, parse_height, parse_osm, tags from osmassets.osm import Projector, parse_height, parse_osm, tags
@@ -84,11 +87,66 @@ class PolygonAreaTest(unittest.TestCase):
def test_winding_does_not_change_the_sign(self): def test_winding_does_not_change_the_sign(self):
self.assertAlmostEqual(polygon_area(list(reversed(SQUARE))), 100.0) self.assertAlmostEqual(polygon_area(list(reversed(SQUARE))), 100.0)
self.assertGreater(signed_polygon_area(SQUARE), 0.0)
self.assertLess(signed_polygon_area(list(reversed(SQUARE))), 0.0)
def test_degenerate(self): def test_degenerate(self):
self.assertEqual(polygon_area([(0.0, 0.0), (1.0, 1.0)]), 0.0) self.assertEqual(polygon_area([(0.0, 0.0), (1.0, 1.0)]), 0.0)
class SampleRingBoundaryTest(unittest.TestCase):
def test_samples_closed_boundary_evenly(self):
samples = sample_ring_boundary(SQUARE, spacing=10.0)
self.assertEqual(len(samples), 4)
self.assertEqual([(round(x, 6), round(y, 6)) for x, y, _, _ in samples],
[(5.0, 0.0), (10.0, 5.0), (5.0, 10.0), (0.0, 5.0)])
def test_repeated_closing_point_is_ignored(self):
open_samples = sample_ring_boundary(SQUARE, spacing=10.0)
closed_samples = sample_ring_boundary(SQUARE + [SQUARE[0]], spacing=10.0)
self.assertEqual(open_samples, closed_samples)
def test_inset_moves_samples_inside_for_either_winding(self):
ccw = sample_ring_boundary(SQUARE, spacing=10.0, inset=1.0)
cw = sample_ring_boundary(list(reversed(SQUARE)), spacing=10.0, inset=1.0)
self.assertTrue(all(point_in_polygon((x, y), SQUARE) for x, y, _, _ in ccw))
self.assertTrue(all(point_in_polygon((x, y), SQUARE) for x, y, _, _ in cw))
self.assertEqual([(round(x, 6), round(y, 6)) for x, y, _, _ in ccw],
[(5.0, 1.0), (9.0, 5.0), (5.0, 9.0), (1.0, 5.0)])
def test_max_samples_reduces_density(self):
samples = sample_ring_boundary(SQUARE, spacing=1.0, max_samples=5)
self.assertEqual(len(samples), 5)
def test_degenerate_input(self):
self.assertEqual(sample_ring_boundary([(0.0, 0.0)], spacing=1.0), [])
self.assertEqual(sample_ring_boundary(SQUARE, spacing=0.0), [])
class SamplePolygonInteriorTest(unittest.TestCase):
def test_samples_are_inside_and_clear_of_edges(self):
samples = sample_polygon_interior(SQUARE, spacing=3.0, edge_clearance=1.0,
seed=42)
self.assertTrue(samples)
for x, y, _ in samples:
self.assertTrue(point_in_polygon((x, y), SQUARE))
self.assertGreaterEqual(distance_to_ring((x, y), SQUARE), 1.0)
def test_seed_is_deterministic(self):
first = sample_polygon_interior(SQUARE, spacing=3.0, seed=7)
second = sample_polygon_interior(SQUARE, spacing=3.0, seed=7)
self.assertEqual(first, second)
def test_max_samples_reduces_density(self):
samples = sample_polygon_interior(SQUARE, spacing=1.0, max_samples=4,
seed=99)
self.assertEqual(len(samples), 4)
def test_degenerate_input(self):
self.assertEqual(sample_polygon_interior([(0.0, 0.0)], spacing=1.0), [])
self.assertEqual(sample_polygon_interior(SQUARE, spacing=0.0), [])
class PointInPolygonTest(unittest.TestCase): class PointInPolygonTest(unittest.TestCase):
def test_inside_and_outside(self): def test_inside_and_outside(self):
self.assertTrue(point_in_polygon((5.0, 5.0), SQUARE)) self.assertTrue(point_in_polygon((5.0, 5.0), SQUARE))
+58 -373
View File
@@ -316,6 +316,7 @@ function writeCesiumPreview(area) {
fs.mkdirSync(path.dirname(htmlPath), { recursive: true }); fs.mkdirSync(path.dirname(htmlPath), { recursive: true });
writeVehicleRoute(area); writeVehicleRoute(area);
writeVehicleModel(area); writeVehicleModel(area);
writeCesiumPreviewSupportFiles(path.dirname(htmlPath));
const glbName = path.basename(area.outputs.glb); const glbName = path.basename(area.outputs.glb);
const metadataName = path.basename(area.outputs.metadata); const metadataName = path.basename(area.outputs.metadata);
const routeName = path.basename(area.outputs.vehicleRoute); const routeName = path.basename(area.outputs.vehicleRoute);
@@ -324,6 +325,14 @@ function writeCesiumPreview(area) {
console.log(`Cesium preview: ${htmlPath}`); console.log(`Cesium preview: ${htmlPath}`);
} }
function writeCesiumPreviewSupportFiles(outDir) {
for (const file of ["cesium-preview.css", "cesium-preview.js"]) {
const source = path.join(repoRoot, "scripts", "lib", file);
ensureFile(source, `Cesium preview support file '${file}'`);
fs.copyFileSync(source, path.join(outDir, file));
}
}
function writeVehicleRoute(area) { function writeVehicleRoute(area) {
const route = buildVehicleRoute(area.input); const route = buildVehicleRoute(area.input);
fs.mkdirSync(path.dirname(area.outputs.vehicleRoute), { recursive: true }); fs.mkdirSync(path.dirname(area.outputs.vehicleRoute), { recursive: true });
@@ -686,6 +695,13 @@ function cylinderY(cx, lateral, up, radius, width, segments) {
} }
function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, areaId) { function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, areaId) {
const previewConfig = {
areaId,
glbName,
metadataName,
routeName,
vehicleModelName,
};
return `<!doctype html> return `<!doctype html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
@@ -694,383 +710,47 @@ function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, a
<title>${escapeHtml(areaId)} Cesium Preview</title> <title>${escapeHtml(areaId)} Cesium Preview</title>
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Cesium.js"></script> <script src="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Cesium.js"></script>
<link href="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Widgets/widgets.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
<style> <link href="cesium-preview.css" rel="stylesheet">
html, body, #cesiumContainer {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #d9e0e2;
}
#status {
position: absolute;
left: 12px;
bottom: 12px;
z-index: 1;
max-width: 520px;
padding: 8px 10px;
border-radius: 4px;
background: rgba(20, 24, 28, 0.78);
color: #fff;
font-size: 12px;
line-height: 1.45;
}
#controls {
position: absolute;
top: 12px;
left: 12px;
z-index: 1;
display: flex;
gap: 8px;
align-items: center;
padding: 8px;
border-radius: 4px;
background: rgba(20, 24, 28, 0.78);
color: #fff;
font-size: 12px;
}
#controls button {
height: 28px;
border: 0;
border-radius: 4px;
padding: 0 10px;
background: #f2f5f7;
color: #111;
cursor: pointer;
}
#controls input {
width: 120px;
}
</style>
</head> </head>
<body> <body>
<div id="cesiumContainer"></div> <div id="cesiumContainer"></div>
<div id="controls"> <div id="controls">
<button id="toggleCruise">Pause</button> <div class="control-group">
<button id="toggleFollow">Follow</button> <button id="toggleCruise">Pause</button>
<label>Vehicle <select id="vehicleSelect"></select></label> <button id="toggleFollow">Follow</button>
<label>Speed <input id="speedControl" type="range" min="2" max="22" step="1" value="8"></label> <label>Vehicle <select id="vehicleSelect"></select></label>
<span id="speedLabel">8 m/s</span> <label>Speed <input id="speedControl" type="range" min="2" max="22" step="1" value="8"></label>
<span id="speedLabel">8 m/s</span>
</div>
<div class="control-group">
<label><input id="toggleScene" type="checkbox" checked> Scene</label>
<span id="assetToggles" class="control-subgroup"></span>
<label><input id="toggleRoutes" type="checkbox" checked> Routes</label>
<label><input id="toggleVehicles" type="checkbox" checked> Vehicles</label>
<label><input id="toggleFps" type="checkbox"> FPS</label>
<label><input id="toggleDiagnostics" type="checkbox" checked> Info</label>
</div>
<div class="control-group">
<button data-camera="overview">Overview</button>
<button data-camera="oblique">Oblique</button>
<button data-camera="detail">Detail</button>
<button data-camera="route">Route</button>
</div>
</div> </div>
<div id="diagnostics">Loading diagnostics...</div>
<div id="status">Loading ${escapeHtml(glbName)}...</div> <div id="status">Loading ${escapeHtml(glbName)}...</div>
<script> <div id="loadingOverlay">
const statusEl = document.getElementById("status"); <div class="loading-card">
const toggleCruise = document.getElementById("toggleCruise"); <div class="loading-spinner" aria-hidden="true"></div>
const toggleFollow = document.getElementById("toggleFollow"); <div class="loading-copy">
const vehicleSelect = document.getElementById("vehicleSelect"); <strong>Loading scene</strong>
const speedControl = document.getElementById("speedControl"); <span>${escapeHtml(areaId)}</span>
const speedLabel = document.getElementById("speedLabel"); </div>
Cesium.Ion.defaultAccessToken = ""; <div class="loading-bar" aria-hidden="true"><span></span></div>
</div>
async function main() { </div>
const metadata = await fetch("${escapeJs(metadataName)}").then((r) => r.json()); <script>window.OSM_ASSET_PREVIEW_CONFIG = ${escapeScriptJson(JSON.stringify(previewConfig))};</script>
const routeData = await fetch("${escapeJs(routeName)}").then((r) => r.json()); <script src="cesium-preview.js"></script>
const anchor = metadata.anchor || {};
const longitude = Number(anchor.longitude || 0);
const latitude = Number(anchor.latitude || 0);
const height = Number(anchor.height || 0);
const heading = Number(metadata.heading_correction_degrees || 0);
const viewer = new Cesium.Viewer("cesiumContainer", {
animation: false,
timeline: false,
baseLayerPicker: false,
geocoder: false,
navigationHelpButton: false,
sceneModePicker: false,
homeButton: true,
fullscreenButton: true,
infoBox: false,
selectionIndicator: false,
baseLayer: false
});
viewer.scene.globe.depthTestAgainstTerrain = true;
viewer.scene.backgroundColor = Cesium.Color.fromCssColorString("#d9e0e2");
viewer.scene.skyAtmosphere.show = false;
viewer.scene.skyBox.show = false;
viewer.scene.sun.show = false;
viewer.scene.moon.show = false;
viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString("#d4dcde");
const p = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(p);
const correction = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(heading));
const modelMatrix = Cesium.Matrix4.multiplyByMatrix3(enu, correction, new Cesium.Matrix4());
const model = await Cesium.Model.fromGltfAsync({
url: "${escapeJs(glbName)}",
modelMatrix,
scale: 1.0
});
viewer.scene.primitives.add(model);
const cruise = addVehicleCruises(viewer, routeData);
const center = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(center, 900.0),
{ duration: 0.0 }
);
statusEl.textContent = "${escapeJs(glbName)} | vehicles " + cruise.vehicles.length;
}
function addVehicleCruises(viewer, routeData) {
const segments = (routeData.segments || [])
.filter((segment) => segment.coordinates && segment.coordinates.length >= 2)
.slice(0, 5);
if (!segments.length) {
throw new Error("No drivable route found in ${escapeJs(routeName)}");
}
const speed = Number(routeData.speedMetersPerSecond || 8);
const start = Cesium.JulianDate.now();
viewer.clock.startTime = start.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
viewer.clock.multiplier = 1;
viewer.clock.shouldAnimate = true;
const vehicles = segments.map((segment, index) => {
const vehicle = addCruiseVehicle(viewer, segment, index, start, speed);
const option = document.createElement("option");
option.value = String(index);
option.textContent = "#" + (index + 1) + " " + segment.name + " " + Math.round(segment.lengthMeters) + "m";
vehicleSelect.appendChild(option);
return vehicle;
});
const state = { selectedIndex: 0 };
toggleCruise.addEventListener("click", () => {
viewer.clock.shouldAnimate = !viewer.clock.shouldAnimate;
toggleCruise.textContent = viewer.clock.shouldAnimate ? "Pause" : "Play";
});
speedControl.addEventListener("input", () => {
const value = Number(speedControl.value);
viewer.clock.multiplier = value / speed;
speedLabel.textContent = value + " m/s";
});
vehicleSelect.addEventListener("change", () => {
state.selectedIndex = Number(vehicleSelect.value || 0);
statusEl.textContent = selectedVehicle().label;
});
function selectedVehicle() {
return vehicles[state.selectedIndex] || vehicles[0];
}
const follow = createChaseFollow(viewer, () => selectedVehicle().positions);
toggleFollow.addEventListener("click", () => {
if (follow.enabled) {
follow.stop();
toggleFollow.textContent = "Follow";
} else {
follow.start();
toggleFollow.textContent = "Free";
}
});
statusEl.textContent = selectedVehicle().label;
return { vehicles };
}
function addCruiseVehicle(viewer, segment, index, start, speed) {
const route = prepareRoute(segment);
const positions = new Cesium.CallbackProperty((time, result) => {
return routePosition(route, start, time, speed, result);
}, false);
const flat = [];
for (const coord of segment.coordinates) {
flat.push(coord[0], coord[1], 1.05);
}
const routeColor = [Cesium.Color.CYAN, Cesium.Color.LIME, Cesium.Color.YELLOW, Cesium.Color.ORANGE, Cesium.Color.DEEPSKYBLUE][index % 5];
viewer.entities.add({
name: "Cruise route " + (index + 1),
polyline: {
positions: Cesium.Cartesian3.fromDegreesArrayHeights(flat),
width: 2,
material: routeColor.withAlpha(0.75),
clampToGround: false
}
});
const vehicle = viewer.entities.add({
name: "Cruise vehicle " + (index + 1),
position: positions,
orientation: routeOrientation(route, start, speed, 0.0),
model: {
uri: "${escapeJs(vehicleModelName)}",
scale: 1.0,
minimumPixelSize: 24,
maximumScale: 80
}
});
return {
entity: vehicle,
positions,
segment,
label: "Vehicle #" + (index + 1) + " | route " + segment.id + " | " + Math.round(segment.lengthMeters) + "m"
};
}
function prepareRoute(segment) {
const distances = [0.0];
for (let i = 1; i < segment.coordinates.length; i += 1) {
distances.push(distances[i - 1] + distanceMeters(segment.coordinates[i - 1], segment.coordinates[i]));
}
return {
coordinates: segment.coordinates,
distances,
length: Math.max(1.0, distances[distances.length - 1])
};
}
function routePosition(route, start, time, speed, result) {
const seconds = Math.max(0, Cesium.JulianDate.secondsDifference(time, start));
const distance = (seconds * speed) % route.length;
let index = 1;
while (index < route.distances.length - 1 && route.distances[index] < distance) {
index += 1;
}
const prevDist = route.distances[index - 1];
const nextDist = route.distances[index];
const t = nextDist > prevDist ? (distance - prevDist) / (nextDist - prevDist) : 0;
const a = route.coordinates[index - 1];
const b = route.coordinates[index];
const lon = a[0] + (b[0] - a[0]) * t;
const lat = a[1] + (b[1] - a[1]) * t;
return Cesium.Cartesian3.fromDegrees(lon, lat, 1.15, Cesium.Ellipsoid.WGS84, result);
}
function routeOrientation(route, start, speed, yawDegrees) {
const correction = Cesium.Quaternion.fromAxisAngle(
Cesium.Cartesian3.UNIT_Z,
Cesium.Math.toRadians(yawDegrees)
);
const current = new Cesium.Cartesian3();
const ahead = new Cesium.Cartesian3();
const direction = new Cesium.Cartesian3();
const up = new Cesium.Cartesian3();
const east = new Cesium.Cartesian3();
const north = new Cesium.Cartesian3();
return new Cesium.CallbackProperty((time, result) => {
routePosition(route, start, time, speed, current);
const aheadTime = Cesium.JulianDate.addSeconds(time, 0.8, new Cesium.JulianDate());
routePosition(route, start, aheadTime, speed, ahead);
Cesium.Cartesian3.subtract(ahead, current, direction);
if (Cesium.Cartesian3.magnitudeSquared(direction) < 0.0001) {
return result;
}
Cesium.Cartesian3.normalize(direction, direction);
Cesium.Cartesian3.normalize(current, up);
Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, up, east);
if (Cesium.Cartesian3.magnitudeSquared(east) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, east);
} else {
Cesium.Cartesian3.normalize(east, east);
}
Cesium.Cartesian3.cross(up, east, north);
Cesium.Cartesian3.normalize(north, north);
const eastComponent = Cesium.Cartesian3.dot(direction, east);
const northComponent = Cesium.Cartesian3.dot(direction, north);
const heading = Math.atan2(eastComponent, northComponent);
const base = Cesium.Transforms.headingPitchRollQuaternion(
current,
new Cesium.HeadingPitchRoll(heading, 0.0, 0.0)
);
return Cesium.Quaternion.multiply(base, correction, result || new Cesium.Quaternion());
}, false);
}
function createChaseFollow(viewer, positionsProvider) {
const scratchPosition = new Cesium.Cartesian3();
const scratchPrevious = new Cesium.Cartesian3();
const scratchDirection = new Cesium.Cartesian3();
const scratchEast = new Cesium.Cartesian3();
const scratchNorth = new Cesium.Cartesian3();
const scratchUp = new Cesium.Cartesian3();
const offset = new Cesium.Cartesian3();
const state = { enabled: false, distance: 36.0, height: 18.0 };
function update(clock) {
const time = clock.currentTime;
const positions = positionsProvider();
const position = positions.getValue(time, scratchPosition);
if (!position) return;
const previousTime = Cesium.JulianDate.addSeconds(time, -0.8, new Cesium.JulianDate());
const previous = positions.getValue(previousTime, scratchPrevious);
if (previous) {
Cesium.Cartesian3.subtract(position, previous, scratchDirection);
} else {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchDirection);
}
if (Cesium.Cartesian3.magnitudeSquared(scratchDirection) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchDirection);
}
Cesium.Cartesian3.normalize(scratchDirection, scratchDirection);
Cesium.Cartesian3.normalize(position, scratchUp);
Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, scratchUp, scratchEast);
if (Cesium.Cartesian3.magnitudeSquared(scratchEast) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchEast);
} else {
Cesium.Cartesian3.normalize(scratchEast, scratchEast);
}
Cesium.Cartesian3.cross(scratchUp, scratchEast, scratchNorth);
Cesium.Cartesian3.normalize(scratchNorth, scratchNorth);
const eastComponent = Cesium.Cartesian3.dot(scratchDirection, scratchEast);
const northComponent = Cesium.Cartesian3.dot(scratchDirection, scratchNorth);
const heading = Math.atan2(eastComponent, northComponent);
Cesium.Cartesian3.fromElements(0.0, -state.distance, state.height, offset);
const transform = Cesium.Transforms.headingPitchRollToFixedFrame(
position,
new Cesium.HeadingPitchRoll(heading, 0.0, 0.0)
);
viewer.camera.lookAtTransform(transform, offset);
}
function onWheel(event) {
if (!state.enabled) return;
event.preventDefault();
const zoom = event.deltaY > 0 ? 1.12 : 0.88;
state.distance = Cesium.Math.clamp(state.distance * zoom, 12.0, 160.0);
state.height = Cesium.Math.clamp(state.height * zoom, 6.0, 90.0);
update(viewer.clock);
}
return {
get enabled() {
return state.enabled;
},
start() {
if (state.enabled) return;
state.enabled = true;
viewer.trackedEntity = undefined;
viewer.canvas.addEventListener("wheel", onWheel, { passive: false });
viewer.clock.onTick.addEventListener(update);
update(viewer.clock);
},
stop() {
if (!state.enabled) return;
state.enabled = false;
viewer.clock.onTick.removeEventListener(update);
viewer.canvas.removeEventListener("wheel", onWheel);
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
};
}
function distanceMeters(a, b) {
const radius = 6371008.8;
const lat1 = Cesium.Math.toRadians(a[1]);
const lat2 = Cesium.Math.toRadians(b[1]);
const dLat = Cesium.Math.toRadians(b[1] - a[1]);
const dLon = Cesium.Math.toRadians(b[0] - a[0]);
const sinLat = Math.sin(dLat / 2);
const sinLon = Math.sin(dLon / 2);
const h = sinLat * sinLat + Math.cos(lat1) * Math.cos(lat2) * sinLon * sinLon;
return 2 * radius * Math.asin(Math.min(1, Math.sqrt(h)));
}
main().catch((error) => {
console.error(error);
statusEl.textContent = "Failed to load Cesium preview: " + error.message;
});
</script>
</body> </body>
</html> </html>
`; `;
@@ -1084,6 +764,11 @@ function escapeHtml(value) {
.replaceAll('"', "&quot;"); .replaceAll('"', "&quot;");
} }
function escapeJs(value) { function escapeScriptJson(value) {
return String(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"'); return String(value)
.replaceAll("<", "\\u003c")
.replaceAll(">", "\\u003e")
.replaceAll("&", "\\u0026")
.replaceAll("\u2028", "\\u2028")
.replaceAll("\u2029", "\\u2029");
} }
+230
View File
@@ -0,0 +1,230 @@
html,
body,
#cesiumContainer {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #d9e0e2;
}
#cesiumContainer {
opacity: 0;
transition: opacity 180ms ease-out;
}
body.scene-ready #cesiumContainer {
opacity: 1;
}
#controls,
#diagnostics,
#status {
position: absolute;
z-index: 1;
border-radius: 4px;
background: rgba(20, 24, 28, 0.82);
color: #fff;
font-size: 12px;
line-height: 1.45;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
}
#loadingOverlay {
position: absolute;
inset: 0;
z-index: 3;
display: grid;
place-items: center;
background: #d9e0e2;
color: #1b2528;
font-size: 13px;
letter-spacing: 0;
transition: opacity 220ms ease-out, visibility 220ms ease-out;
}
.loading-card {
display: grid;
grid-template-columns: 32px minmax(180px, 260px);
gap: 12px;
align-items: center;
padding: 14px 16px;
border: 1px solid rgba(70, 86, 90, 0.16);
border-radius: 6px;
background: rgba(244, 248, 248, 0.88);
box-shadow: 0 12px 34px rgba(54, 68, 72, 0.20);
}
.loading-spinner {
width: 28px;
height: 28px;
border: 3px solid rgba(42, 67, 72, 0.18);
border-top-color: #147d8a;
border-radius: 50%;
animation: loading-spin 840ms linear infinite;
}
.loading-copy {
display: grid;
gap: 3px;
}
.loading-copy strong {
font-size: 13px;
font-weight: 650;
}
#loadingOverlay span {
color: #526064;
}
.loading-bar {
grid-column: 1 / -1;
position: relative;
height: 3px;
overflow: hidden;
border-radius: 999px;
background: rgba(42, 67, 72, 0.12);
}
.loading-bar span {
position: absolute;
inset: 0 auto 0 0;
width: 42%;
border-radius: inherit;
background: #147d8a;
animation: loading-bar 1.2s ease-in-out infinite;
}
@keyframes loading-spin {
to {
transform: rotate(360deg);
}
}
@keyframes loading-bar {
0% {
transform: translateX(-110%);
}
55% {
transform: translateX(70%);
}
100% {
transform: translateX(250%);
}
}
body.scene-ready #loadingOverlay {
visibility: hidden;
opacity: 0;
}
body.scene-error #loadingOverlay {
color: #5b1414;
}
body.scene-error .loading-spinner {
border-color: rgba(120, 30, 30, 0.18);
border-top-color: #9f2f2f;
animation-play-state: paused;
}
body.scene-error .loading-bar span {
background: #9f2f2f;
animation-play-state: paused;
}
#controls {
top: 12px;
left: 12px;
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
}
#status {
left: 12px;
bottom: 12px;
max-width: 560px;
padding: 8px 10px;
}
#diagnostics {
right: 12px;
top: 12px;
min-width: 280px;
max-width: 360px;
padding: 10px 12px;
white-space: pre-line;
}
#controls button,
#controls select {
height: 28px;
border: 0;
border-radius: 4px;
}
#controls button {
padding: 0 10px;
background: #f2f5f7;
color: #111;
cursor: pointer;
}
#controls button:active:not(:disabled) {
transform: translateY(1px);
}
#controls :disabled {
opacity: 0.45;
cursor: default;
}
#controls label:has(:disabled) {
opacity: 0.45;
}
#controls input[type="range"] {
width: 120px;
}
#controls label {
display: inline-flex;
gap: 5px;
align-items: center;
white-space: nowrap;
}
/* Playback / layers / camera each read as their own row of the panel. */
.control-group {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
align-items: center;
}
.control-group + .control-group {
padding-top: 6px;
border-top: 1px solid rgba(255, 255, 255, 0.16);
}
/* Per-asset checkboxes hang off the master "Scene" toggle. */
.control-subgroup {
display: inline-flex;
flex-wrap: wrap;
gap: 8px 10px;
align-items: center;
padding-left: 10px;
border-left: 1px solid rgba(255, 255, 255, 0.16);
}
.control-subgroup:empty {
display: none;
}
.hidden {
display: none;
}
+672
View File
@@ -0,0 +1,672 @@
(function () {
"use strict";
const config = window.OSM_ASSET_PREVIEW_CONFIG || {};
const statusEl = document.getElementById("status");
const diagnosticsEl = document.getElementById("diagnostics");
const loadingOverlay = document.getElementById("loadingOverlay");
const toggleCruise = document.getElementById("toggleCruise");
const toggleFollow = document.getElementById("toggleFollow");
const toggleScene = document.getElementById("toggleScene");
const toggleRoutes = document.getElementById("toggleRoutes");
const toggleVehicles = document.getElementById("toggleVehicles");
const toggleFps = document.getElementById("toggleFps");
const toggleDiagnostics = document.getElementById("toggleDiagnostics");
const assetToggles = document.getElementById("assetToggles");
const vehicleSelect = document.getElementById("vehicleSelect");
const speedControl = document.getElementById("speedControl");
const speedLabel = document.getElementById("speedLabel");
const cameraButtons = Array.from(document.querySelectorAll("[data-camera]"));
// Status carries two kinds of message: the scene summary, which is what the
// panel should read whenever nothing else is going on, and transient notes
// from a control the user just touched. Keep the summary so the transient
// note can be replaced instead of destroying it.
let baseStatus = "";
const PREVIEW_BACKGROUND = "#d9e0e2";
Cesium.Ion.defaultAccessToken = "";
async function main() {
setLoadingMessage("Loading scene", config.areaId || "");
const metadata = await fetchJson(config.metadataName);
const routeData = await fetchOptionalJson(config.routeName);
const placement = scenePlacement(metadata);
const viewer = createViewer();
setLoadingMessage("Loading model", config.glbName || "");
const assets = await loadSceneAssets(viewer, metadata, placement);
const cruise = addVehicleCruises(viewer, routeData, config.vehicleModelName);
const cameras = createCameraPresets(viewer, metadata, placement, cruise);
buildAssetToggles(assets);
bindRuntimeControls(viewer, assets, cruise, cameras);
startDiagnostics(viewer, metadata, assets, cruise, placement);
cameras.overview();
baseStatus = summaryText(metadata, assets, cruise);
setStatus(baseStatus);
setLoadingMessage("Preparing view", "finalizing materials");
await waitForStableFrames(viewer);
document.body.classList.add("scene-ready");
// Handle for the browser console and for headless checks: everything else
// in here is closed over by the IIFE and unreachable from outside.
window.osmPreview = { viewer, metadata, placement, assets, cruise, cameras };
}
async function fetchJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error("Could not load " + url + ": " + response.status);
}
return response.json();
}
// The route file is an extra on top of the scene, not a precondition for it.
// A missing or unreadable route costs the cruise controls, not the preview.
async function fetchOptionalJson(url) {
try {
return await fetchJson(url);
} catch (error) {
console.warn(error);
return null;
}
}
function createViewer() {
const viewer = new Cesium.Viewer("cesiumContainer", {
animation: false,
timeline: false,
baseLayerPicker: false,
geocoder: false,
navigationHelpButton: false,
sceneModePicker: false,
homeButton: true,
fullscreenButton: true,
infoBox: false,
selectionIndicator: false,
baseLayer: false
});
viewer.scene.globe.show = false;
viewer.scene.globe.depthTestAgainstTerrain = false;
viewer.scene.backgroundColor = Cesium.Color.fromCssColorString(PREVIEW_BACKGROUND);
viewer.scene.skyAtmosphere.show = false;
viewer.scene.skyBox.show = false;
viewer.scene.sun.show = false;
viewer.scene.moon.show = false;
viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString(PREVIEW_BACKGROUND);
return viewer;
}
function setLoadingMessage(title, detail) {
if (!loadingOverlay) return;
const titleEl = loadingOverlay.querySelector("strong");
const detailEl = loadingOverlay.querySelector("span");
if (titleEl) titleEl.textContent = title;
if (detailEl) detailEl.textContent = detail || "";
}
function waitForStableFrames(viewer) {
return new Promise((resolve) => {
const started = performance.now();
let frames = 0;
let done = false;
let remove = function () {};
function finish() {
if (done) return;
done = true;
remove();
resolve();
}
remove = viewer.scene.postRender.addEventListener(() => {
frames += 1;
const elapsed = performance.now() - started;
if ((frames >= 14 && elapsed >= 650) || elapsed >= 2800) {
finish();
}
});
window.setTimeout(finish, 3200);
viewer.scene.requestRender();
});
}
function scenePlacement(metadata) {
const anchor = metadata.anchor || {};
const longitude = Number(anchor.longitude || 0);
const latitude = Number(anchor.latitude || 0);
const height = Number(anchor.height || 0);
const heading = Number(metadata.heading_correction_degrees || 0);
const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const correction = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(heading));
return {
longitude,
latitude,
height,
heading,
position,
modelMatrix: Cesium.Matrix4.multiplyByMatrix3(enu, correction, new Cesium.Matrix4())
};
}
function normalizedAssets(metadata) {
const assets = Array.isArray(metadata.assets) && metadata.assets.length
? metadata.assets
: [{
id: "main",
label: "Scene",
type: "model",
url: metadata.asset || config.glbName,
enabled: true
}];
return assets.filter((asset) => (asset.type || "model") === "model" && asset.url);
}
// One broken entry in metadata.assets should not blank the whole preview, so
// failures are collected and surfaced in the diagnostics panel instead.
async function loadSceneAssets(viewer, metadata, placement) {
const loaded = [];
for (const asset of normalizedAssets(metadata)) {
const id = asset.id || "asset-" + loaded.length;
const label = asset.label || asset.id || asset.url;
try {
const model = await Cesium.Model.fromGltfAsync({
url: asset.url,
modelMatrix: placement.modelMatrix,
scale: Number(asset.scale || 1.0)
});
model.show = asset.enabled !== false;
viewer.scene.primitives.add(model);
loaded.push({ id, label, url: asset.url, model, error: null });
} catch (error) {
console.error(error);
loaded.push({ id, label, url: asset.url, model: null, error });
}
}
if (!loaded.some((asset) => asset.model)) {
throw new Error("No scene model could be loaded (" + loaded.length + " declared)");
}
return loaded;
}
function liveAssets(assets) {
return assets.filter((asset) => asset.model);
}
// A single-asset scene keeps the plain "Scene" checkbox; a multi-asset one
// gets a child checkbox per model with "Scene" acting as the master.
function buildAssetToggles(assets) {
const live = liveAssets(assets);
if (live.length < 2) return;
for (const asset of live) {
const label = document.createElement("label");
const input = document.createElement("input");
input.type = "checkbox";
input.checked = asset.model.show;
input.dataset.assetId = asset.id;
input.addEventListener("change", () => {
asset.model.show = input.checked;
syncSceneMaster(assets);
setStatus(asset.label + (input.checked ? " visible" : " hidden"));
});
label.appendChild(input);
label.appendChild(document.createTextNode(" " + asset.label));
assetToggles.appendChild(label);
asset.toggle = input;
}
}
function syncSceneMaster(assets) {
const live = liveAssets(assets);
const shown = live.filter((asset) => asset.model.show).length;
toggleScene.checked = shown > 0;
toggleScene.indeterminate = shown > 0 && shown < live.length;
}
function bindRuntimeControls(viewer, assets, cruise, cameras) {
const hasVehicles = cruise.vehicles.length > 0;
toggleScene.addEventListener("change", () => {
for (const asset of liveAssets(assets)) {
asset.model.show = toggleScene.checked;
if (asset.toggle) asset.toggle.checked = toggleScene.checked;
}
toggleScene.indeterminate = false;
setStatus(toggleScene.checked ? "Scene visible" : "Scene hidden");
});
toggleRoutes.addEventListener("change", () => {
for (const vehicle of cruise.vehicles) vehicle.routeEntity.show = toggleRoutes.checked;
});
toggleVehicles.addEventListener("change", () => {
for (const vehicle of cruise.vehicles) vehicle.entity.show = toggleVehicles.checked;
});
toggleFps.addEventListener("change", () => {
viewer.scene.debugShowFramesPerSecond = toggleFps.checked;
});
toggleDiagnostics.addEventListener("change", () => {
diagnosticsEl.classList.toggle("hidden", !toggleDiagnostics.checked);
});
let stopFollow = function () {};
if (hasVehicles) {
stopFollow = bindCruiseControls(viewer, cruise);
} else {
// Nothing to drive: disable the cruise half of the panel rather than
// leaving controls that silently do nothing.
for (const el of [toggleCruise, toggleFollow, vehicleSelect, speedControl, toggleRoutes, toggleVehicles]) {
el.disabled = true;
}
toggleCruise.textContent = "Play";
}
for (const button of cameraButtons) {
const preset = cameras[button.dataset.camera];
if (!preset || (button.dataset.camera === "route" && !hasVehicles)) {
button.disabled = true;
continue;
}
button.addEventListener("click", () => {
// Chase-follow reclaims the camera on every clock tick, so a preset
// applied underneath it would be overwritten before the next frame.
stopFollow();
preset();
});
}
}
function bindCruiseControls(viewer, cruise) {
// The slider is authored with a static default; the route file decides the
// real cruise speed, so adopt it before the first input event.
speedControl.value = String(Cesium.Math.clamp(
Math.round(cruise.baseSpeed),
Number(speedControl.min),
Number(speedControl.max)
));
viewer.clock.multiplier = Number(speedControl.value) / cruise.baseSpeed;
speedLabel.textContent = speedControl.value + " m/s";
toggleCruise.addEventListener("click", () => {
viewer.clock.shouldAnimate = !viewer.clock.shouldAnimate;
toggleCruise.textContent = viewer.clock.shouldAnimate ? "Pause" : "Play";
});
speedControl.addEventListener("input", () => {
const value = Number(speedControl.value);
viewer.clock.multiplier = value / cruise.baseSpeed;
speedLabel.textContent = value + " m/s";
});
vehicleSelect.addEventListener("change", () => {
cruise.state.selectedIndex = Number(vehicleSelect.value || 0);
setStatus(selectedVehicle(cruise).label);
});
const follow = createChaseFollow(viewer, () => selectedVehicle(cruise).positions);
function stopFollow() {
if (!follow.enabled) return;
follow.stop();
toggleFollow.textContent = "Follow";
}
toggleFollow.addEventListener("click", () => {
if (follow.enabled) {
stopFollow();
setStatus(baseStatus);
} else {
follow.start();
toggleFollow.textContent = "Free";
setStatus("Following " + selectedVehicle(cruise).label);
}
});
return stopFollow;
}
function addVehicleCruises(viewer, routeData, vehicleModelName) {
const segments = ((routeData && routeData.segments) || [])
.filter((segment) => segment.coordinates && segment.coordinates.length >= 2)
.slice(0, 5);
const speed = Number((routeData && routeData.speedMetersPerSecond) || 8);
const start = Cesium.JulianDate.now();
viewer.clock.startTime = start.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
viewer.clock.multiplier = 1;
viewer.clock.shouldAnimate = segments.length > 0;
const vehicles = segments.map((segment, index) => {
const vehicle = addCruiseVehicle(viewer, segment, index, start, speed, vehicleModelName);
const option = document.createElement("option");
option.value = String(index);
option.textContent = "#" + (index + 1) + " " + segment.name + " " + Math.round(segment.lengthMeters) + "m";
vehicleSelect.appendChild(option);
return vehicle;
});
return {
vehicles,
baseSpeed: speed,
state: { selectedIndex: 0 }
};
}
function addCruiseVehicle(viewer, segment, index, start, speed, vehicleModelName) {
const route = prepareRoute(segment);
const positions = new Cesium.CallbackProperty((time, result) => {
return routePosition(route, start, time, speed, result);
}, false);
const flat = [];
for (const coord of segment.coordinates) {
flat.push(coord[0], coord[1], 1.05);
}
const routeColor = [
Cesium.Color.CYAN,
Cesium.Color.LIME,
Cesium.Color.YELLOW,
Cesium.Color.ORANGE,
Cesium.Color.DEEPSKYBLUE
][index % 5];
const routeEntity = viewer.entities.add({
name: "Cruise route " + (index + 1),
polyline: {
positions: Cesium.Cartesian3.fromDegreesArrayHeights(flat),
width: 2,
material: routeColor.withAlpha(0.75),
clampToGround: false
}
});
const vehicle = viewer.entities.add({
name: "Cruise vehicle " + (index + 1),
position: positions,
orientation: routeOrientation(route, start, speed, 0.0),
model: {
uri: vehicleModelName,
scale: 1.0,
minimumPixelSize: 24,
maximumScale: 80
}
});
return {
entity: vehicle,
routeEntity,
positions,
route,
segment,
label: "Vehicle #" + (index + 1) + " | route " + segment.id + " | " + Math.round(segment.lengthMeters) + "m"
};
}
function selectedVehicle(cruise) {
return cruise.vehicles[cruise.state.selectedIndex] || cruise.vehicles[0];
}
function prepareRoute(segment) {
const distances = [0.0];
for (let i = 1; i < segment.coordinates.length; i += 1) {
distances.push(distances[i - 1] + distanceMeters(segment.coordinates[i - 1], segment.coordinates[i]));
}
return {
coordinates: segment.coordinates,
distances,
length: Math.max(1.0, distances[distances.length - 1])
};
}
function routePosition(route, start, time, speed, result) {
const seconds = Math.max(0, Cesium.JulianDate.secondsDifference(time, start));
const distance = (seconds * speed) % route.length;
let index = 1;
while (index < route.distances.length - 1 && route.distances[index] < distance) {
index += 1;
}
const prevDist = route.distances[index - 1];
const nextDist = route.distances[index];
const t = nextDist > prevDist ? (distance - prevDist) / (nextDist - prevDist) : 0;
const a = route.coordinates[index - 1];
const b = route.coordinates[index];
const lon = a[0] + (b[0] - a[0]) * t;
const lat = a[1] + (b[1] - a[1]) * t;
return Cesium.Cartesian3.fromDegrees(lon, lat, 1.15, Cesium.Ellipsoid.WGS84, result);
}
function routeOrientation(route, start, speed, yawDegrees) {
const correction = Cesium.Quaternion.fromAxisAngle(
Cesium.Cartesian3.UNIT_Z,
Cesium.Math.toRadians(yawDegrees)
);
const current = new Cesium.Cartesian3();
const ahead = new Cesium.Cartesian3();
const direction = new Cesium.Cartesian3();
const up = new Cesium.Cartesian3();
const east = new Cesium.Cartesian3();
const north = new Cesium.Cartesian3();
return new Cesium.CallbackProperty((time, result) => {
routePosition(route, start, time, speed, current);
const aheadTime = Cesium.JulianDate.addSeconds(time, 0.8, new Cesium.JulianDate());
routePosition(route, start, aheadTime, speed, ahead);
Cesium.Cartesian3.subtract(ahead, current, direction);
if (Cesium.Cartesian3.magnitudeSquared(direction) < 0.0001) {
return result;
}
Cesium.Cartesian3.normalize(direction, direction);
Cesium.Cartesian3.normalize(current, up);
Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, up, east);
if (Cesium.Cartesian3.magnitudeSquared(east) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, east);
} else {
Cesium.Cartesian3.normalize(east, east);
}
Cesium.Cartesian3.cross(up, east, north);
Cesium.Cartesian3.normalize(north, north);
const eastComponent = Cesium.Cartesian3.dot(direction, east);
const northComponent = Cesium.Cartesian3.dot(direction, north);
const heading = Math.atan2(eastComponent, northComponent);
const base = Cesium.Transforms.headingPitchRollQuaternion(
current,
new Cesium.HeadingPitchRoll(heading, 0.0, 0.0)
);
return Cesium.Quaternion.multiply(base, correction, result || new Cesium.Quaternion());
}, false);
}
function createChaseFollow(viewer, positionsProvider) {
const scratchPosition = new Cesium.Cartesian3();
const scratchPrevious = new Cesium.Cartesian3();
const scratchDirection = new Cesium.Cartesian3();
const scratchEast = new Cesium.Cartesian3();
const scratchNorth = new Cesium.Cartesian3();
const scratchUp = new Cesium.Cartesian3();
const offset = new Cesium.Cartesian3();
const state = { enabled: false, distance: 36.0, height: 18.0 };
function update(clock) {
const time = clock.currentTime;
const positions = positionsProvider();
const position = positions.getValue(time, scratchPosition);
if (!position) return;
const previousTime = Cesium.JulianDate.addSeconds(time, -0.8, new Cesium.JulianDate());
const previous = positions.getValue(previousTime, scratchPrevious);
if (previous) {
Cesium.Cartesian3.subtract(position, previous, scratchDirection);
} else {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchDirection);
}
if (Cesium.Cartesian3.magnitudeSquared(scratchDirection) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchDirection);
}
Cesium.Cartesian3.normalize(scratchDirection, scratchDirection);
Cesium.Cartesian3.normalize(position, scratchUp);
Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, scratchUp, scratchEast);
if (Cesium.Cartesian3.magnitudeSquared(scratchEast) < 0.0001) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, scratchEast);
} else {
Cesium.Cartesian3.normalize(scratchEast, scratchEast);
}
Cesium.Cartesian3.cross(scratchUp, scratchEast, scratchNorth);
Cesium.Cartesian3.normalize(scratchNorth, scratchNorth);
const eastComponent = Cesium.Cartesian3.dot(scratchDirection, scratchEast);
const northComponent = Cesium.Cartesian3.dot(scratchDirection, scratchNorth);
const heading = Math.atan2(eastComponent, northComponent);
Cesium.Cartesian3.fromElements(0.0, -state.distance, state.height, offset);
const transform = Cesium.Transforms.headingPitchRollToFixedFrame(
position,
new Cesium.HeadingPitchRoll(heading, 0.0, 0.0)
);
viewer.camera.lookAtTransform(transform, offset);
}
function onWheel(event) {
if (!state.enabled) return;
event.preventDefault();
const zoom = event.deltaY > 0 ? 1.12 : 0.88;
state.distance = Cesium.Math.clamp(state.distance * zoom, 12.0, 160.0);
state.height = Cesium.Math.clamp(state.height * zoom, 6.0, 90.0);
update(viewer.clock);
}
return {
get enabled() {
return state.enabled;
},
start() {
if (state.enabled) return;
state.enabled = true;
viewer.trackedEntity = undefined;
viewer.canvas.addEventListener("wheel", onWheel, { passive: false });
viewer.clock.onTick.addEventListener(update);
update(viewer.clock);
},
stop() {
if (!state.enabled) return;
state.enabled = false;
viewer.clock.onTick.removeEventListener(update);
viewer.canvas.removeEventListener("wheel", onWheel);
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
};
}
function createCameraPresets(viewer, metadata, placement, cruise) {
const radius = Math.max(220.0, boundsRadiusMeters(metadata.bounds) || 900.0);
const center = placement.position;
function lookAt(range, headingDegrees, pitchDegrees) {
viewer.camera.lookAt(
center,
new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(headingDegrees),
Cesium.Math.toRadians(pitchDegrees),
range
)
);
// lookAt locks the camera into the target's reference frame; release it
// so orbit and pan keep working from the new vantage point.
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
return {
overview() {
viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(center, radius), {
duration: 0.0
});
},
oblique() {
lookAt(radius * 0.92, 135.0, -28.0);
},
detail() {
lookAt(radius * 0.32, 115.0, -18.0);
},
route() {
if (!cruise.vehicles.length) return;
const vehicle = selectedVehicle(cruise);
const coord = vehicle.segment.coordinates[Math.floor(vehicle.segment.coordinates.length / 2)];
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(coord[0], coord[1], 90.0),
orientation: {
heading: Cesium.Math.toRadians(0.0),
pitch: Cesium.Math.toRadians(-62.0),
roll: 0.0
},
duration: 0.0
});
}
};
}
// Camera-dependent readouts have to track the camera, so refresh off the
// render loop rather than a fixed timer, throttled to stay off the hot path.
function startDiagnostics(viewer, metadata, assets, cruise, placement) {
const center = placement.position;
const stats = metadata.scene_stats || {};
const failed = assets.filter((asset) => asset.error);
let lastUpdate = 0;
function render() {
const cartographic = viewer.camera.positionCartographic;
const distance = Cesium.Cartesian3.distance(viewer.camera.positionWC, center);
const lines = [
"Area: " + (config.areaId || "(unknown)"),
"Anchor: " + placement.longitude.toFixed(7) + ", " + placement.latitude.toFixed(7),
"Camera height: " + Math.round(cartographic.height) + " m",
"Camera range: " + Math.round(distance) + " m",
"Assets: " + liveAssets(assets).length + " model(s)",
"Vehicles: " + cruise.vehicles.length,
"Buildings: " + Number(stats.buildings || 0),
"Trees: " + Number(stats.trees || 0),
"Road layer source: " + (metadata.source_geojson ? "osm2streets" : "OSM fallback")
];
if (failed.length) {
lines.push("Failed assets: " + failed.map((asset) => asset.url).join(", "));
}
diagnosticsEl.textContent = lines.join("\n");
}
viewer.scene.postRender.addEventListener(() => {
const now = performance.now();
if (now - lastUpdate < 250) return;
lastUpdate = now;
render();
});
render();
}
function summaryText(metadata, assets, cruise) {
const stats = metadata.scene_stats || {};
return [
config.areaId,
liveAssets(assets).map((asset) => asset.url).join(", "),
cruise.vehicles.length ? "vehicles " + cruise.vehicles.length : "no drivable route",
"buildings " + Number(stats.buildings || 0),
"trees " + Number(stats.trees || 0)
].filter(Boolean).join(" | ");
}
function boundsRadiusMeters(bounds) {
if (!bounds) return null;
const minLon = Number(bounds.min_lon);
const minLat = Number(bounds.min_lat);
const maxLon = Number(bounds.max_lon);
const maxLat = Number(bounds.max_lat);
if (![minLon, minLat, maxLon, maxLat].every(Number.isFinite)) return null;
return Math.max(
80.0,
distanceMeters([minLon, minLat], [maxLon, maxLat]) * 0.58
);
}
function distanceMeters(a, b) {
const radius = 6371008.8;
const lat1 = Cesium.Math.toRadians(a[1]);
const lat2 = Cesium.Math.toRadians(b[1]);
const dLat = Cesium.Math.toRadians(b[1] - a[1]);
const dLon = Cesium.Math.toRadians(b[0] - a[0]);
const sinLat = Math.sin(dLat / 2);
const sinLon = Math.sin(dLon / 2);
const h = sinLat * sinLat + Math.cos(lat1) * Math.cos(lat2) * sinLon * sinLon;
return 2 * radius * Math.asin(Math.min(1, Math.sqrt(h)));
}
function setStatus(message) {
statusEl.textContent = message;
}
main().catch((error) => {
console.error(error);
setStatus("Failed to load Cesium preview: " + error.message);
document.body.classList.add("scene-error");
setLoadingMessage("Failed to load scene", error.message);
});
}());