diff --git a/config/s52/cm95_s52_style_compiler_v1.json b/config/s52/cm95_s52_style_compiler_v1.json new file mode 100644 index 0000000..eaec23f --- /dev/null +++ b/config/s52/cm95_s52_style_compiler_v1.json @@ -0,0 +1,59 @@ +{ + "schema": "navsea.cm95.s52-style-compiler-config/v1", + "name": "CM95 S-52 Fukuoka compiled style v1", + "palette": "DAY_BRIGHT", + "sprite": "http://192.168.200.184:8877/s52-sprite-lc-ap-v3", + "background_color": "DEPDW", + "fallback_color": "NODTA", + "area_fill_opacity": 0.92, + "area_pattern_opacity": 0.85, + "line_width_fallback": 1.0, + "complex_line_width_px": 5.0, + "display_categories": ["Displaybase", "Standard", "Other"], + "source": { + "id": "cm95", + "type": "vector", + "tiles": ["http://192.168.200.184:8877/tiles-presentation-v10/{z}/{x}/{y}.pbf"], + "bounds": [130.341796875, 33.57801474614399, 130.4296875, 33.65120829920498], + "minzoom": 12, + "maxzoom": 12 + }, + "resources": { + "colors": "build/s52_poc_patterns_v1/s52_colors.json", + "symbol_metadata": "build/s52_poc_patterns_v1/s52_symbol_metadata.json", + "bitmap_pattern_metadata": "build/s52_poc_patterns_v1/s52_pattern_metadata.json", + "vector_pattern_metadata": "build/s52_ap_v3/s52-sprite-lc-ap-pattern-metadata.json", + "line_metadata": "build/s52_lc_v1/s52-sprite-lc-line-metadata.json", + "sprite_index": "build/s52_ap_v3/s52-sprite-lc-ap.json", + "lookup_ir": "build/s52_presentation_ir/lookup_rule_ir.json" + }, + "source_layers": [ + {"name": "anchor_caution_hazard_area", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "anchor_caution_hazard_point", "capabilities": ["symbol", "text"]}, + {"name": "anchorage_area", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "baseline_area", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "baseline_line", "capabilities": ["line", "symbol", "text"]}, + {"name": "bridge_structure", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "clearance_limit_line", "capabilities": ["line", "symbol", "text"]}, + {"name": "clearance_limit_point", "capabilities": ["symbol", "text"]}, + {"name": "cm95_unmapped", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "depth_contour", "capabilities": ["line", "text"]}, + {"name": "facility_boundary_area", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "facility_boundary_outline", "capabilities": ["line", "symbol", "text"]}, + {"name": "facility_boundary_point", "capabilities": ["symbol", "text"]}, + {"name": "land_area", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "navigation_hazard_area", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "navigation_hazard_outline", "capabilities": ["line", "symbol", "text"]}, + {"name": "navigation_hazard_point", "capabilities": ["symbol", "text"]}, + {"name": "navigation_marks", "capabilities": ["symbol", "text"]}, + {"name": "onshore_structure_area", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "onshore_structure_point", "capabilities": ["symbol", "text"]}, + {"name": "pilot_station_point", "capabilities": ["symbol", "text"]}, + {"name": "place_label_land", "capabilities": ["symbol", "text"]}, + {"name": "s52_areas", "capabilities": ["fill", "line", "symbol", "text"]}, + {"name": "s52_lines", "capabilities": ["line", "symbol", "text"]}, + {"name": "s52_points", "capabilities": ["symbol", "text"]}, + {"name": "seabed_line", "capabilities": ["line", "symbol", "text"]}, + {"name": "seabed_text_point", "capabilities": ["symbol", "text"]} + ] +} diff --git a/tools/cm95_s52_style_compiler.py b/tools/cm95_s52_style_compiler.py new file mode 100755 index 0000000..b3076e6 --- /dev/null +++ b/tools/cm95_s52_style_compiler.py @@ -0,0 +1,1010 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path +import re +from typing import Any, Iterable + + +DISPLAY_PRIORITY_ORDER = ( + "No data", + "Group 1", + "Area 1", + "Area 2", + "Point Symbol", + "Line Symbol", + "Area Symbol", + "Routing", + "Hazards", + "Mariners", +) +STATIC_OPCODES = ("SY", "AC", "AP", "LS", "LC", "TX", "TE") + + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text(encoding="utf-8")) + + +def _resolve_path(root: Path, value: str | Path) -> Path: + path = Path(value) + return path if path.is_absolute() else root / path + + +def _rgb_hex(value: dict[str, Any]) -> str: + return "#{:02x}{:02x}{:02x}".format( + int(value["r"]), int(value["g"]), int(value["b"]) + ) + + +def _safe_id(value: str) -> str: + return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-") or "layer" + + +def _color_expression( + field: str, colors: dict[str, dict[str, Any]], fallback: str +) -> list[Any]: + expression: list[Any] = ["match", ["get", field]] + for name in sorted(colors): + expression.extend([name, _rgb_hex(colors[name])]) + expression.append(fallback) + return expression + + +def _mapped_expression(field: str, mapping: dict[str, str], fallback: str) -> list[Any]: + expression: list[Any] = ["match", ["get", field]] + for name in sorted(mapping): + expression.extend([name, mapping[name]]) + expression.append(fallback) + return expression + + +def _supported_filter(field: str, values: Iterable[str]) -> list[Any]: + choices = sorted(set(values)) + return ["match", ["get", field], choices, True, False] + + +def _base_filter( + *, + priority: str, + categories: list[str], + required_field: str, + supported_values: list[str] | None = None, + forbidden_field: str | None = None, +) -> list[Any]: + clauses: list[Any] = [ + ["==", ["get", "s52_display_priority"], priority], + ["match", ["get", "s52_display_category"], categories, True, False], + ["has", required_field], + ] + if supported_values is not None: + clauses.append(_supported_filter(required_field, supported_values)) + if forbidden_field is not None: + clauses.append(["!", ["has", forbidden_field]]) + return ["all", *clauses] + + +def _symbol_offset_expression(field: str, metadata: dict[str, dict[str, Any]]) -> list[Any]: + expression: list[Any] = ["match", ["get", field]] + for name in sorted(metadata): + offset = metadata[name].get("maplibre_icon_offset", [0, 0]) + expression.extend([name, ["literal", offset]]) + expression.append(["literal", [0, 0]]) + return expression + + +def _text_offset_pairs(lookup_ir: list[dict[str, Any]]) -> list[tuple[str, str]]: + pairs: set[tuple[str, str]] = set() + for row in lookup_ir: + for rule in row.get("rules") or []: + args = rule.get("args") or [] + if rule.get("opcode") == "TX" and len(args) >= 9: + layout = args[1:9] + elif rule.get("opcode") == "TE" and len(args) >= 10: + layout = args[2:10] + else: + continue + xoff, yoff = str(layout[4]).strip(), str(layout[5]).strip() + try: + float(xoff) + float(yoff) + except ValueError: + continue + pairs.add((xoff, yoff)) + return sorted(pairs, key=lambda pair: (float(pair[0]), float(pair[1]))) + + +def _text_offset_expression(slot: int, pairs: list[tuple[str, str]]) -> list[Any]: + key = [ + "concat", + ["to-string", ["get", f"s52_text{slot}_xoff"]], + ",", + ["to-string", ["get", f"s52_text{slot}_yoff"]], + ] + expression: list[Any] = ["match", key] + for xoff, yoff in pairs: + expression.extend( + [f"{xoff},{yoff}", ["literal", [float(xoff), float(yoff)]]] + ) + expression.append(["literal", [0.0, 0.0]]) + return expression + + + + +def _text_anchor_expression(slot: int) -> list[Any]: + key = [ + "concat", + ["to-string", ["get", f"s52_text{slot}_hjust"]], + ["to-string", ["get", f"s52_text{slot}_vjust"]], + ] + return [ + "match", key, + "11", "bottom", + "12", "center", + "13", "top", + "21", "bottom-right", + "22", "right", + "23", "top-right", + "31", "bottom-left", + "32", "left", + "33", "top-left", + "left", + ] + +def _layer_contract(config: dict[str, Any]) -> list[dict[str, Any]]: + rows = list(config.get("source_layers") or []) + if not rows: + raise SystemExit("config.source_layers must not be empty") + for row in rows: + if not row.get("name"): + raise SystemExit(f"source layer missing name: {row!r}") + return rows + + +USAGE_VALUE_FIELDS = ( + "s52_symbol_code", + "s52_light_symbol_code", + "s52_area_color", + "s52_area_pattern_code", + "s52_line_color", + "s52_line_complex_code", + "s52_text1_color", + "s52_text2_color", + "s52_text3_color", +) +USAGE_PRESENCE_FIELDS = ( + *USAGE_VALUE_FIELDS, + "s52_text_literal", + "s52_light_label_text", + "s52_light_rotation_deg", + "s52_text1_value", + "s52_text2_value", + "s52_text3_value", +) + + +def _scan_pbf_usage(path: Path) -> dict[str, Any]: + try: + import mapbox_vector_tile + except ImportError as exc: + raise SystemExit( + "--usage-pbf requires mapbox_vector_tile; run with the project .venv Python" + ) from exc + + decoded = mapbox_vector_tile.decode(path.read_bytes()) + global_values: dict[str, set[str]] = {field: set() for field in USAGE_VALUE_FIELDS} + render_kind_counts: dict[str, Counter[tuple[str, str, str]]] = { + key: Counter() + for key in ("AC", "AP", "LS", "LC", "SY", "LIGHT_SY", "TXTE", "LIGHT_TX", "RUNTIME_SOUNDG", "RUNTIME_CA") + } + geometry_ignored: Counter[tuple[str, str, str]] = Counter() + layers: dict[str, Any] = {} + for layer_name, layer in decoded.items(): + field_values: dict[str, set[str]] = {field: set() for field in USAGE_VALUE_FIELDS} + field_priorities: dict[str, set[str]] = {field: set() for field in USAGE_PRESENCE_FIELDS} + present: set[str] = set() + features = list(layer.get("features") or []) + for feature in features: + props = dict(feature.get("properties") or {}) + priority = str(props.get("s52_display_priority") or "") + category = str(props.get("s52_display_category") or "") + placement = (layer_name, priority, category) + geometry_type = str((feature.get("geometry") or {}).get("type") or "") + area_geometry = geometry_type in {"Polygon", "MultiPolygon"} + line_geometry = geometry_type in {"LineString", "MultiLineString", "Polygon", "MultiPolygon"} + if "s52_area_color" in props: + if area_geometry: + render_kind_counts["AC"][placement] += 1 + else: + geometry_ignored[("AC", layer_name, geometry_type)] += 1 + if "s52_area_pattern_code" in props: + if area_geometry: + render_kind_counts["AP"][placement] += 1 + else: + geometry_ignored[("AP", layer_name, geometry_type)] += 1 + if "s52_line_color" in props: + if line_geometry: + render_kind_counts["LS"][placement] += 1 + else: + geometry_ignored[("LS", layer_name, geometry_type)] += 1 + if "s52_line_complex_code" in props: + if line_geometry: + render_kind_counts["LC"][placement] += 1 + else: + geometry_ignored[("LC", layer_name, geometry_type)] += 1 + if "s52_symbol_code" in props: + if props.get("s52_sounding_symbol_sequence"): + render_kind_counts["RUNTIME_SOUNDG"][placement] += 1 + else: + render_kind_counts["SY"][placement] += 1 + if "s52_light_symbol_code" in props: + render_kind_counts["LIGHT_SY"][placement] += 1 + if any(f"s52_text{slot}_value" in props for slot in (1, 2, 3)): + render_kind_counts["TXTE"][placement] += 1 + if props.get("s52_csp_resolved") == "LIGHTS05" and "s52_text_literal" in props: + render_kind_counts["LIGHT_TX"][placement] += 1 + if "s52_arc_color" in props: + render_kind_counts["RUNTIME_CA"][placement] += 1 + for field in USAGE_PRESENCE_FIELDS: + if field not in props: + continue + present.add(field) + field_priorities[field].add(priority) + if field in field_values: + value = str(props[field]) + field_values[field].add(value) + global_values[field].add(value) + layers[layer_name] = { + "feature_count": len(features), + "fields_present": sorted(present), + "field_values": {k: sorted(v) for k, v in field_values.items() if v}, + "field_priorities": {k: sorted(v) for k, v in field_priorities.items() if v}, + } + return { + "pbf": str(path), + "layers": layers, + "global_values": {k: sorted(v) for k, v in global_values.items() if v}, + "geometry_ignored": [ + {"kind": kind, "source_layer": layer, "geometry_type": geometry, "feature_count": count} + for (kind, layer, geometry), count in sorted(geometry_ignored.items()) + ], + "render_kind_counts": { + kind: [ + {"source_layer": layer, "priority": priority, "category": category, "feature_count": count} + for (layer, priority, category), count in sorted(counter.items()) + ] + for kind, counter in render_kind_counts.items() + if counter + }, + } + + +def _field_used( + usage: dict[str, Any] | None, layer_name: str, field: str, priority: str +) -> bool: + if usage is None: + return True + layer = (usage.get("layers") or {}).get(layer_name) + if not layer or field not in set(layer.get("fields_present") or []): + return False + return priority in set((layer.get("field_priorities") or {}).get(field) or []) + + +def _add_layer( + layers: list[dict[str, Any]], + counts: Counter[str], + opcode: str, + layer: dict[str, Any], +) -> None: + layers.append(layer) + counts[opcode] += 1 + + +def _compile_style( + *, + config: dict[str, Any], + colors: dict[str, dict[str, Any]], + symbol_metadata: dict[str, dict[str, Any]], + bitmap_pattern_metadata: dict[str, dict[str, Any]], + vector_pattern_metadata: dict[str, dict[str, Any]], + line_metadata: dict[str, dict[str, Any]], + sprite_index: dict[str, Any], + lookup_ir: list[dict[str, Any]], + usage: dict[str, Any] | None = None, +) -> tuple[dict[str, Any], dict[str, Any]]: + source = dict(config["source"]) + source_id = str(source.pop("id")) + sprite_url = str(config["sprite"]) + categories = [str(x) for x in config.get("display_categories", [])] + if not categories: + categories = ["Displaybase", "Standard", "Other"] + fallback_name = str(config.get("fallback_color", "NODTA")) + fallback = _rgb_hex(colors.get(fallback_name, {"r": 163, "g": 180, "b": 183})) + background_name = str(config.get("background_color", "DEPDW")) + background = _rgb_hex(colors.get(background_name, {"r": 212, "g": 234, "b": 238})) + usage_values = dict((usage or {}).get("global_values") or {}) + + available_symbol_names = sorted(set(symbol_metadata) & set(sprite_index)) + symbol_names = list(available_symbol_names) + if usage is not None: + symbol_names = sorted(set(symbol_names) & set(usage_values.get("s52_symbol_code") or [])) + symbol_offsets = {name: symbol_metadata[name] for name in symbol_names} + light_symbol_names = list(available_symbol_names) + if usage is not None: + light_symbol_names = sorted( + set(light_symbol_names) & set(usage_values.get("s52_light_symbol_code") or []) + ) + light_symbol_offsets = {name: symbol_metadata[name] for name in light_symbol_names} + + ap_mapping: dict[str, str] = {} + for name in bitmap_pattern_metadata: + if name in sprite_index: + ap_mapping[name] = name + for name, meta in vector_pattern_metadata.items(): + sprite_key = str(meta.get("sprite_key") or "") + if sprite_key and sprite_key in sprite_index: + ap_mapping[name] = sprite_key + available_ap_mapping = dict(ap_mapping) + if usage is not None: + used = set(usage_values.get("s52_area_pattern_code") or []) + ap_mapping = {name: value for name, value in ap_mapping.items() if name in used} + + lc_mapping: dict[str, str] = {} + for name, meta in line_metadata.items(): + sprite_key = str(meta.get("sprite_key") or "") + if sprite_key and sprite_key in sprite_index: + lc_mapping[name] = sprite_key + available_lc_mapping = dict(lc_mapping) + if usage is not None: + used = set(usage_values.get("s52_line_complex_code") or []) + lc_mapping = {name: value for name, value in lc_mapping.items() if name in used} + + text_offsets = _text_offset_pairs(lookup_ir) + lookup_opcode_priorities: dict[str, set[str]] = { + key: set() for key in (*STATIC_OPCODES, "TX/TE") + } + for row in lookup_ir: + priority = str(row.get("display_priority") or "") + for rule in row.get("rules") or []: + opcode = str(rule.get("opcode") or "") + if opcode in {"TX", "TE"}: + lookup_opcode_priorities["TX/TE"].add(priority) + elif opcode in lookup_opcode_priorities: + lookup_opcode_priorities[opcode].add(priority) + + materialized_priority_fields = { + "AC": ("s52_area_color",), + "AP": ("s52_area_pattern_code",), + "LS": ("s52_line_color",), + "LC": ("s52_line_complex_code",), + "SY": ("s52_symbol_code",), + "TX/TE": ("s52_text1_value", "s52_text2_value", "s52_text3_value"), + } + materialized_opcode_priorities: dict[str, set[str]] = { + key: set() for key in lookup_opcode_priorities + } + if usage is not None: + for layer in (usage.get("layers") or {}).values(): + field_priorities = layer.get("field_priorities") or {} + for opcode, fields in materialized_priority_fields.items(): + for field in fields: + materialized_opcode_priorities[opcode].update( + str(value) for value in (field_priorities.get(field) or []) if value + ) + opcode_priorities = { + key: set(lookup_opcode_priorities[key]) | set(materialized_opcode_priorities[key]) + for key in lookup_opcode_priorities + } + source_layers = _layer_contract(config) + layers: list[dict[str, Any]] = [ + { + "id": "s52-background", + "type": "background", + "paint": {"background-color": background}, + } + ] + compiled_counts: Counter[str] = Counter() + compiled_placements: dict[str, set[tuple[str, str]]] = { + key: set() for key in ("AC", "AP", "LS", "LC", "SY", "LIGHT_SY", "TXTE", "LIGHT_TX") + } + active_colors = colors + if usage is not None: + used_color_names = set() + for field in ( + "s52_area_color", + "s52_line_color", + "s52_text1_color", + "s52_text2_color", + "s52_text3_color", + ): + used_color_names.update(usage_values.get(field) or []) + active_colors = {name: colors[name] for name in used_color_names if name in colors} + if not active_colors: + active_colors = colors + color_area = _color_expression("s52_area_color", active_colors, fallback) + color_line = _color_expression("s52_line_color", active_colors, fallback) + + for priority_index, priority in enumerate(DISPLAY_PRIORITY_ORDER): + prefix = f"s52-p{priority_index:02d}" + for contract in source_layers: + layer_name = str(contract["name"]) + caps = set(contract.get("capabilities") or []) + layer_id = _safe_id(layer_name) + + if ( + "fill" in caps + and priority in opcode_priorities["AC"] + and _field_used(usage, layer_name, "s52_area_color", priority) + ): + _add_layer( + layers, + compiled_counts, + "AC", + { + "id": f"{prefix}-ac-{layer_id}", + "type": "fill", + "source": source_id, + "source-layer": layer_name, + "filter": _base_filter( + priority=priority, + categories=categories, + required_field="s52_area_color", + ), + "paint": { + "fill-color": color_area, + "fill-opacity": float(config.get("area_fill_opacity", 0.92)), + }, + }, + ) + compiled_placements["AC"].add((layer_name, priority)) + if ( + "fill" in caps + and ap_mapping + and priority in opcode_priorities["AP"] + and _field_used(usage, layer_name, "s52_area_pattern_code", priority) + ): + _add_layer( + layers, + compiled_counts, + "AP", + { + "id": f"{prefix}-ap-{layer_id}", + "type": "fill", + "source": source_id, + "source-layer": layer_name, + "filter": _base_filter( + priority=priority, + categories=categories, + required_field="s52_area_pattern_code", + supported_values=list(ap_mapping), + ), + "paint": { + "fill-pattern": _mapped_expression( + "s52_area_pattern_code", ap_mapping, next(iter(ap_mapping.values())) + ), + "fill-opacity": float(config.get("area_pattern_opacity", 0.85)), + }, + }, + ) + compiled_placements["AP"].add((layer_name, priority)) + + if ( + "line" in caps + and priority in opcode_priorities["LS"] + and _field_used(usage, layer_name, "s52_line_color", priority) + ): + _add_layer( + layers, + compiled_counts, + "LS", + { + "id": f"{prefix}-ls-{layer_id}", + "type": "line", + "source": source_id, + "source-layer": layer_name, + "filter": _base_filter( + priority=priority, + categories=categories, + required_field="s52_line_color", + ), + "paint": { + "line-color": color_line, + "line-width": [ + "to-number", + ["get", "s52_line_width"], + float(config.get("line_width_fallback", 1.0)), + ], + "line-dasharray": [ + "case", + ["==", ["get", "s52_line_style"], "DASH"], + ["literal", [4, 2]], + ["literal", [1, 0]], + ], + }, + }, + ) + compiled_placements["LS"].add((layer_name, priority)) + if ( + "line" in caps + and lc_mapping + and priority in opcode_priorities["LC"] + and _field_used(usage, layer_name, "s52_line_complex_code", priority) + ): + _add_layer( + layers, + compiled_counts, + "LC", + { + "id": f"{prefix}-lc-{layer_id}", + "type": "line", + "source": source_id, + "source-layer": layer_name, + "filter": _base_filter( + priority=priority, + categories=categories, + required_field="s52_line_complex_code", + supported_values=list(lc_mapping), + ), + "paint": { + "line-pattern": _mapped_expression( + "s52_line_complex_code", lc_mapping, next(iter(lc_mapping.values())) + ), + "line-width": float(config.get("complex_line_width_px", 5.0)), + }, + }, + ) + compiled_placements["LC"].add((layer_name, priority)) + + if ( + "symbol" in caps + and symbol_names + and priority in opcode_priorities["SY"] + and _field_used(usage, layer_name, "s52_symbol_code", priority) + ): + _add_layer( + layers, + compiled_counts, + "SY", + { + "id": f"{prefix}-sy-{layer_id}", + "type": "symbol", + "source": source_id, + "source-layer": layer_name, + "filter": _base_filter( + priority=priority, + categories=categories, + required_field="s52_symbol_code", + supported_values=symbol_names, + forbidden_field="s52_sounding_symbol_sequence", + ), + "layout": { + "icon-image": ["get", "s52_symbol_code"], + "icon-anchor": "center", + "icon-offset": _symbol_offset_expression("s52_symbol_code", symbol_offsets), + "icon-size": 1, + "icon-allow-overlap": True, + "icon-ignore-placement": True, + }, + }, + ) + compiled_placements["SY"].add((layer_name, priority)) + + if ( + "symbol" in caps + and light_symbol_names + and _field_used(usage, layer_name, "s52_light_symbol_code", priority) + ): + _add_layer( + layers, + compiled_counts, + "LIGHTS05-SY", + { + "id": f"{prefix}-lights05-sy-{layer_id}", + "type": "symbol", + "source": source_id, + "source-layer": layer_name, + "filter": _base_filter( + priority=priority, + categories=categories, + required_field="s52_light_symbol_code", + supported_values=light_symbol_names, + ), + "layout": { + "icon-image": ["get", "s52_light_symbol_code"], + "icon-anchor": "center", + "icon-offset": _symbol_offset_expression( + "s52_light_symbol_code", light_symbol_offsets + ), + "icon-size": 1, + "icon-rotate": [ + "to-number", ["get", "s52_light_rotation_deg"], 0 + ], + "icon-rotation-alignment": "map", + "icon-allow-overlap": True, + "icon-ignore-placement": True, + }, + }, + ) + compiled_placements["LIGHT_SY"].add((layer_name, priority)) + + if ( + "text" in caps + and _field_used(usage, layer_name, "s52_text_literal", priority) + ): + _add_layer( + layers, + compiled_counts, + "LIGHTS05-TX", + { + "id": f"{prefix}-lights05-tx-{layer_id}", + "type": "symbol", + "source": source_id, + "source-layer": layer_name, + "filter": [ + "all", + *_base_filter( + priority=priority, + categories=categories, + required_field="s52_text_literal", + )[1:], + ["==", ["get", "s52_csp_resolved"], "LIGHTS05"], + ], + "layout": { + "text-field": ["get", "s52_text_literal"], + "text-size": 10, + "text-offset": [1.2, 0.0], + "text-anchor": "left", + "text-allow-overlap": False, + "text-optional": True, + }, + "paint": { + "text-color": _rgb_hex( + colors.get("CHBLK", {"r": 7, "g": 7, "b": 7}) + ), + "text-halo-color": "rgba(255,255,255,0.65)", + "text-halo-width": 0.5, + }, + }, + ) + compiled_placements["LIGHT_TX"].add((layer_name, priority)) + + if "text" in caps and priority in opcode_priorities["TX/TE"]: + for slot in (1, 2, 3): + field = f"s52_text{slot}_value" + if not _field_used(usage, layer_name, field, priority): + continue + _add_layer( + layers, + compiled_counts, + "TX/TE", + { + "id": f"{prefix}-text{slot}-{layer_id}", + "type": "symbol", + "source": source_id, + "source-layer": layer_name, + "filter": _base_filter( + priority=priority, + categories=categories, + required_field=field, + ), + "layout": { + "text-field": ["get", field], + "text-size": [ + "to-number", + ["get", f"s52_text{slot}_size"], + 10, + ], + "text-offset": _text_offset_expression(slot, text_offsets), + "text-anchor": _text_anchor_expression(slot), + "text-allow-overlap": False, + "text-optional": True, + }, + "paint": { + "text-color": _color_expression( + f"s52_text{slot}_color", active_colors, _rgb_hex(colors.get("CHBLK", {"r": 7, "g": 7, "b": 7})) + ), + "text-halo-color": "rgba(255,255,255,0.65)", + "text-halo-width": 0.5, + }, + }, + ) + compiled_placements["TXTE"].add((layer_name, priority)) + + opcode_usage = Counter( + rule.get("opcode") + for row in lookup_ir + for rule in (row.get("rules") or []) + if rule.get("opcode") + ) + referenced_sy = { + str(rule["args"][0]).strip("'\"")[:8] + for row in lookup_ir + for rule in (row.get("rules") or []) + if rule.get("opcode") == "SY" and rule.get("args") + } + referenced_ap = { + str(rule["args"][0]).strip("'\"")[:8] + for row in lookup_ir + for rule in (row.get("rules") or []) + if rule.get("opcode") == "AP" and rule.get("args") + } + referenced_lc = { + str(rule["args"][0]).strip("'\"")[:8] + for row in lookup_ir + for rule in (row.get("rules") or []) + if rule.get("opcode") == "LC" and rule.get("args") + } + + style = { + "version": 8, + "name": str(config.get("name", "CM95 S-52 compiled style")), + "sprite": sprite_url, + "metadata": { + "cm95:s52-style-compiler": "v1", + "cm95:palette": config.get("palette", "DAY_BRIGHT"), + "cm95:static-opcodes": list(STATIC_OPCODES), + "cm95:runtime-opcodes": ["CA", "SOUNDG composition"], + }, + "sources": {source_id: source}, + "layers": layers, + } + hard_gate_failures: list[dict[str, Any]] = [] + if usage is not None: + contract_names = {str(row["name"]) for row in source_layers} + actual_names = set((usage.get("layers") or {}).keys()) + unknown_layers = sorted(actual_names - contract_names) + if unknown_layers: + hard_gate_failures.append({ + "code": "SOURCE_LAYER_CONTRACT_GAP", + "values": unknown_layers, + }) + + used_symbols = set(usage_values.get("s52_symbol_code") or []) + missing_used_symbols = sorted(used_symbols - set(available_symbol_names)) + if missing_used_symbols: + hard_gate_failures.append({ + "code": "USED_SYMBOL_RESOURCE_GAP", + "values": missing_used_symbols, + }) + + used_light_symbols = set(usage_values.get("s52_light_symbol_code") or []) + missing_used_light_symbols = sorted( + used_light_symbols - set(available_symbol_names) + ) + if missing_used_light_symbols: + hard_gate_failures.append({ + "code": "USED_LIGHT_SYMBOL_RESOURCE_GAP", + "values": missing_used_light_symbols, + }) + + used_patterns = set(usage_values.get("s52_area_pattern_code") or []) + missing_used_patterns = sorted(used_patterns - set(available_ap_mapping)) + if missing_used_patterns: + hard_gate_failures.append({ + "code": "USED_PATTERN_RESOURCE_GAP", + "values": missing_used_patterns, + }) + + used_complex_lines = set(usage_values.get("s52_line_complex_code") or []) + missing_used_complex_lines = sorted(used_complex_lines - set(available_lc_mapping)) + if missing_used_complex_lines: + hard_gate_failures.append({ + "code": "USED_COMPLEX_LINE_RESOURCE_GAP", + "values": missing_used_complex_lines, + }) + + used_colors: set[str] = set() + for field in ( + "s52_area_color", + "s52_line_color", + "s52_text1_color", + "s52_text2_color", + "s52_text3_color", + ): + used_colors.update(usage_values.get(field) or []) + missing_used_colors = sorted(used_colors - set(colors)) + if missing_used_colors: + hard_gate_failures.append({ + "code": "USED_COLOR_RESOURCE_GAP", + "values": missing_used_colors, + }) + + light_text_count = sum( + int(row.get("feature_count") or 0) + for row in (usage.get("render_kind_counts") or {}).get("LIGHT_TX", []) + ) + if light_text_count and "CHBLK" not in colors: + hard_gate_failures.append({ + "code": "LIGHT_TEXT_COLOR_GAP", + "values": ["CHBLK"], + }) + + static_coverage: dict[str, Any] = {} + runtime_coverage: dict[str, Any] = {} + if usage is not None: + render_counts = usage.get("render_kind_counts") or {} + for kind in ("AC", "AP", "LS", "LC", "SY", "LIGHT_SY", "TXTE", "LIGHT_TX"): + rows = list(render_counts.get(kind) or []) + total = sum(int(row.get("feature_count") or 0) for row in rows) + covered = 0 + gaps: list[dict[str, Any]] = [] + for row in rows: + layer_name = str(row.get("source_layer") or "") + priority = str(row.get("priority") or "") + category = str(row.get("category") or "") + count = int(row.get("feature_count") or 0) + if (layer_name, priority) in compiled_placements[kind] and category in categories: + covered += count + else: + gaps.append({ + "source_layer": layer_name, + "priority": priority, + "category": category, + "feature_count": count, + }) + static_coverage[kind] = { + "feature_count": total, + "covered_feature_count": covered, + "gap_feature_count": total - covered, + "placement_count": len(rows), + "gaps": gaps, + } + if gaps: + hard_gate_failures.append({ + "code": "MATERIALIZED_STATIC_COVERAGE_GAP", + "kind": kind, + "values": gaps, + }) + + for kind in ("RUNTIME_SOUNDG", "RUNTIME_CA"): + rows = list(render_counts.get(kind) or []) + runtime_coverage[kind] = { + "feature_count": sum(int(row.get("feature_count") or 0) for row in rows), + "placement_count": len(rows), + "placements": rows, + } + + audit = { + "schema": "navsea.cm95.s52-style-compiler-audit/v1", + "hard_gate_failures": hard_gate_failures, + "palette": config.get("palette", "DAY_BRIGHT"), + "source_id": source_id, + "source_layer_count": len(source_layers), + "display_categories": categories, + "display_priority_order": list(DISPLAY_PRIORITY_ORDER), + "lookup_ir_count": len(lookup_ir), + "presentation_library_opcode_usage": dict(sorted(opcode_usage.items())), + "lookup_priority_usage": { + key: sorted(values) + for key, values in sorted(lookup_opcode_priorities.items()) + if values + }, + "materialized_priority_usage": { + key: sorted(values) + for key, values in sorted(materialized_opcode_priorities.items()) + if values + }, + "compiled_priority_usage": { + key: sorted( + values, + key=lambda value: ( + DISPLAY_PRIORITY_ORDER.index(value) + if value in DISPLAY_PRIORITY_ORDER + else 999 + ), + ) + for key, values in sorted(opcode_priorities.items()) + if values + }, + "compiled_layer_count": len(layers), + "compiled_layer_count_by_opcode": dict(sorted(compiled_counts.items())), + "sprite_symbol_count": len(symbol_names), + "light_symbol_count": len(light_symbol_names), + "area_pattern_count": len(ap_mapping), + "complex_line_count": len(lc_mapping), + "text_offset_pair_count": len(text_offsets), + "materialized_static_coverage": static_coverage, + "geometry_incompatible_materialized": (usage or {}).get("geometry_ignored") or [], + "runtime_coverage": runtime_coverage, + "usage_scope": ( + None + if usage is None + else { + "pbf": usage.get("pbf"), + "source_layer_count": len(usage.get("layers") or {}), + "feature_count": sum( + int(row.get("feature_count") or 0) + for row in (usage.get("layers") or {}).values() + ), + "global_values": usage.get("global_values") or {}, + } + ), + "presentation_library_reference_gaps": { + "note": "Full 3057-row Presentation Library inventory; not a Dataset 1 usage hard gate.", + "symbols": sorted(referenced_sy - set(available_symbol_names)), + "patterns": sorted(referenced_ap - set(available_ap_mapping)), + "complex_lines": sorted(referenced_lc - set(available_lc_mapping)), + }, + "runtime_boundary": { + "CA": "runtime overlay; screen-mm geometry is not compiled into static style", + "SOUNDG": "runtime glyph composition; static style does not split symbol sequences", + }, + } + return style, audit + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Compile CM95 materialized S-52 properties/resources into a MapLibre style." + ) + parser.add_argument("--config", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--audit-output", type=Path) + parser.add_argument( + "--usage-pbf", + type=Path, + help="Optionally scope generated layers/resources to fields actually present in one PBF tile.", + ) + args = parser.parse_args() + + project_root = Path(__file__).resolve().parents[1] + config = _load_json(args.config) + resources = dict(config.get("resources") or {}) + required = ( + "colors", + "symbol_metadata", + "bitmap_pattern_metadata", + "vector_pattern_metadata", + "line_metadata", + "sprite_index", + "lookup_ir", + ) + missing = [name for name in required if not resources.get(name)] + if missing: + raise SystemExit(f"config.resources missing: {missing}") + + color_tables = _load_json(_resolve_path(project_root, resources["colors"])) + palette = str(config.get("palette", "DAY_BRIGHT")) + if palette not in color_tables: + raise SystemExit(f"unknown palette {palette}; choices={sorted(color_tables)}") + colors = dict(color_tables[palette].get("colors") or {}) + if not colors: + raise SystemExit(f"palette {palette} has no colors") + usage = ( + _scan_pbf_usage(_resolve_path(project_root, args.usage_pbf)) + if args.usage_pbf is not None + else None + ) + + style, audit = _compile_style( + config=config, + colors=colors, + symbol_metadata=_load_json(_resolve_path(project_root, resources["symbol_metadata"])), + bitmap_pattern_metadata=_load_json(_resolve_path(project_root, resources["bitmap_pattern_metadata"])), + vector_pattern_metadata=_load_json(_resolve_path(project_root, resources["vector_pattern_metadata"])), + line_metadata=_load_json(_resolve_path(project_root, resources["line_metadata"])), + sprite_index=_load_json(_resolve_path(project_root, resources["sprite_index"])), + lookup_ir=_load_json(_resolve_path(project_root, resources["lookup_ir"])), + usage=usage, + ) + + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text( + json.dumps(style, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + audit_output = args.audit_output or args.output.with_suffix(".audit.json") + audit_output.parent.mkdir(parents=True, exist_ok=True) + audit_output.write_text( + json.dumps(audit, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(audit, ensure_ascii=False, indent=2)) + if audit.get("hard_gate_failures"): + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cm95_s52_vector_pattern_sprite.py b/tools/cm95_s52_vector_pattern_sprite.py index b9dcdc3..653f4a0 100644 --- a/tools/cm95_s52_vector_pattern_sprite.py +++ b/tools/cm95_s52_vector_pattern_sprite.py @@ -94,7 +94,20 @@ def _svg_for_pattern(node: ET.Element, palette: dict[str, str], dpi: float) -> t if pts: current = pts[-1] elif cmd == "PD": - for target in _points(arg): + targets = _points(arg) + if not targets and current is not None: + # OpenCPN RenderFromHPGL draws an argument-less PD as a + # one-screen-pixel horizontal segment, then advances the + # current point to that segment end. DRGARE01 relies on it. + x1, y1 = cv(current) + color = pen_colors.get(pen, next(iter(pen_colors.values()))) + stroke = max(1.0, pen_width * nominal) + elements.append( + f'' + ) + current = (current[0] + (1.0 / unit), current[1]) + for target in targets: if current is None: current = target continue @@ -143,6 +156,11 @@ def main() -> int: ap.add_argument("--base-sprite-png", required=True, type=Path) ap.add_argument("--base-sprite-json", required=True, type=Path) ap.add_argument("--usage-audit", required=True, type=Path) + ap.add_argument( + "--usage-pbf", + type=Path, + help="Optionally union materialized s52_area_pattern_code values from a PBF tile.", + ) ap.add_argument("--output-prefix", required=True, type=Path) ap.add_argument("--palette", default="DAY_BRIGHT") ap.add_argument("--dpi", default=96.0, type=float) @@ -157,7 +175,22 @@ def main() -> int: raise SystemExit("missing patterns") by_name = {_text(n, "name"): n for n in patterns.findall("pattern")} usage = json.loads(args.usage_audit.read_text(encoding="utf-8")) - used = [str(row[0]) for row in usage.get("pattern_resource_counts", [])] + lookup_used = {str(row[0]) for row in usage.get("pattern_resource_counts", [])} + pbf_used: set[str] = set() + if args.usage_pbf is not None: + try: + import mapbox_vector_tile + except ImportError as exc: + raise SystemExit( + "--usage-pbf requires mapbox_vector_tile; run with the project .venv Python" + ) from exc + decoded = mapbox_vector_tile.decode(args.usage_pbf.read_bytes()) + for layer in decoded.values(): + for feature in layer.get("features") or []: + value = (feature.get("properties") or {}).get("s52_area_pattern_code") + if value not in (None, ""): + pbf_used.add(str(value)) + used = sorted(lookup_used | pbf_used) names = [ name for name in used if name in by_name @@ -183,6 +216,15 @@ def main() -> int: pp = tmp / f"{idx:03d}-{name}.png" sp.write_text(svg, encoding="utf-8") subprocess.run(["convert", "-background", "none", str(sp), str(pp)], check=True) + alpha_probe = subprocess.run( + [ + "convert", str(pp), "-alpha", "extract", + "-format", "%[fx:maxima]", "info:", + ], + check=True, capture_output=True, text=True, + ).stdout.strip() + if not alpha_probe or float(alpha_probe) <= 0.0: + raise RuntimeError(f"pattern {name} rendered fully transparent") w, h = _png_size(pp) key = f"ap-{name}" sprite[key] = {"x": 0, "y": y, "width": w, "height": h, "pixelRatio": 1} @@ -206,6 +248,10 @@ def main() -> int: print(json.dumps({ "schema": "navsea.cm95.s52-vector-pattern-sprite/v1", "palette": args.palette, + "lookup_usage_pattern_count": len(lookup_used), + "pbf_usage_pattern_count": len(pbf_used), + "pbf_usage_patterns": sorted(pbf_used), + "effective_usage_pattern_count": len(used), "vector_pattern_count": len(names), "vector_patterns": names, "base_sprite": {"width": base_w, "height": base_h},