feat: prepare STEP-114 guarded fast smoke validation
Some checks failed
validate-scripts / validate-scripts (push) Has been cancelled

This commit is contained in:
tei
2026-10-11 10:01:10 +09:00
parent b02e54de3d
commit 21a1081643
11 changed files with 1032 additions and 6 deletions

View File

@@ -67,6 +67,10 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
private var step113DiagnosticsMaxLines = 6
private var step113Scene: Step113PbfGateScene? = null
private var step113Scenario: Step113PbfGateScene.Scenario? = null
private var step114Scene: Step114FastSmokeScene? = null
private var step114Scenario: Step114FastSmokeScene.Scenario? = null
private var step114DiagnosticsHeight: Int? = null
private var step114DiagnosticsMaxLines = 6
private var step102Scenario: Step102PlacementFixture.Scenario? = null
private var step102Tick = 0L
private val step102Handler = Handler(Looper.getMainLooper())
@@ -356,6 +360,11 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
} else intent.getStringExtra("step113_scenario")
step113Scenario = savedStep113
?.let { value -> Step113PbfGateScene.Scenario.values().firstOrNull { it.name == value } }
val savedStep114 = if (savedInstanceState?.containsKey("step114_scenario") == true) {
savedInstanceState.getString("step114_scenario")
} else intent.getStringExtra("step114_scenario")
step114Scenario = savedStep114
?.let { value -> Step114FastSmokeScene.Scenario.values().firstOrNull { it.name == value } }
super.onCreate(savedInstanceState)
Log.i(
TAG,
@@ -369,6 +378,7 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
diagnostics = findViewById(R.id.validationDiagnostics)
mapView.addOnDidFailLoadingMapListener { errorMessage ->
step113Scene?.onStyleLoadFailed(errorMessage)
step114Scene?.onStyleLoadFailed(errorMessage)
if (navSeaPbfMode || purePbfMode) {
Log.e(TAG, "NAVSEA_PBF_STYLE_ERROR reason=$errorMessage")
} else if (realWeatherMode) {
@@ -389,7 +399,8 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
updateNavSeaPbfButtonState()
updatePbfModeButtonState()
updateRetainedCacheButtonState()
if (step113Scenario != null) startStep113Scene(step113Scenario!!)
if (step114Scenario != null) startStep114Scene(step114Scenario!!)
else if (step113Scenario != null) startStep113Scene(step113Scenario!!)
else if (step102Scenario != null) loadStep102Style()
else if (step101Scenario != null) loadStep101Style()
else if (step097Topology != null) loadStep097StencilStyle()
@@ -700,6 +711,7 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
menu.add(0, 18, 18, "STEP-101 TEARDOWN")
menu.add(0, 19, 19, "STEP-102 PLACEMENT LOCALITY")
menu.add(0, 20, 20, "STEP-113 FZG1-PBF GATE")
menu.add(0, 21, 21, "STEP-114 独立 FAST_SMOKE(非正式 PBF)")
setOnMenuItemClickListener { item ->
when (item.itemId) {
in Step093Topology.values().indices -> applyStep093Scene(Step093Topology.values()[item.itemId])
@@ -714,6 +726,7 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
18 -> showStep101Menu(anchor)
19 -> showStep102Menu(anchor)
20 -> showStep113Menu(anchor)
21 -> showStep114Menu(anchor)
}
true
}
@@ -777,7 +790,7 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
private fun showStep113Menu(anchor: android.view.View) {
PopupMenu(this, anchor).apply {
Step113PbfGateScene.Scenario.values().forEachIndexed { index, scenario ->
menu.add(0, index, index, "STEP-113 ${scenario.name}")
menu.add(0, index, index, "STEP-113 正式 PBF · ${scenario.name}")
}
menu.add(0, 10, 10, "EXPORT LAST SNAPSHOT")
menu.add(0, 11, 11, "MUTATE PROBE SOURCE ONCE")
@@ -826,6 +839,9 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
}
private fun stopStep113Scene() {
// Existing style-switch entry points all call this method; also stop the
// independent smoke before another scene takes ownership of this Map.
stopStep114Scene()
step113Scene?.stop()
step113DiagnosticsHeight?.let { originalHeight ->
diagnostics.maxLines = step113DiagnosticsMaxLines
@@ -836,6 +852,72 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
step113Scenario = null
}
private fun showStep114Menu(anchor: android.view.View) {
PopupMenu(this, anchor).apply {
Step114FastSmokeScene.Scenario.values().forEachIndexed { index, scenario ->
menu.add(0, index, index, "独立 smoke · ${scenario.name}")
}
listOf("导出当前 Native 快照", "单次更新 R GeoJSON", "Pan/Zoom 往返", "Reload 当前场景",
"单次 Image 变更", "禁用/恢复缓存", "单次更新真实 Annotation", "退出独立 smoke")
.forEachIndexed { index, title -> menu.add(0, 10 + index, 10 + index, title) }
setOnMenuItemClickListener { item ->
when (item.itemId) {
in Step114FastSmokeScene.Scenario.values().indices ->
startStep114Scene(Step114FastSmokeScene.Scenario.values()[item.itemId])
10 -> step114Scene?.export()
11 -> step114Scene?.mutateSource()
12 -> step114Scene?.panZoom()
13 -> step114Scene?.reload()
14 -> step114Scene?.mutateImage()
15 -> step114Scene?.toggleCache()
16 -> step114Scene?.mutateAnnotation()
17 -> { stopStep113Scene(); loadValidationStyle(active, enabled, "STEP114_EXIT") }
}
true
}
show()
}
}
private fun startStep114Scene(scenario: Step114FastSmokeScene.Scenario) {
stopStep113Scene()
stopStep102Scenario()
stopStep099Scenario()
stopStep093DiagnosticsPolling()
step101Handler.removeCallbacksAndMessages(null)
step101Scenario = null
step097Topology = null
step093Mode = false
pureParticleMode = false
purePbfMode = false
navSeaPbfMode = false
realWeatherMode = false
weatherRuntime?.dispose()
weatherRuntime = null
styleReady = false
++styleLoadEpoch
step114Scenario = scenario
retainedCacheEnabled = true
updateRetainedCacheButtonState()
step114DiagnosticsHeight = diagnostics.layoutParams.height
step114DiagnosticsMaxLines = diagnostics.maxLines
diagnostics.maxLines = 10
diagnostics.layoutParams = diagnostics.layoutParams.apply { height = (156 * resources.displayMetrics.density).toInt() }
status.text = "STEP-114 独立 smoke · $scenario · 待真实 Native 验收"
step114Scene = Step114FastSmokeScene(this, maplibreMap) { diagnostics.text = it }.also { it.start(scenario) }
}
private fun stopStep114Scene() {
step114Scene?.stop()
step114DiagnosticsHeight?.let { originalHeight ->
diagnostics.maxLines = step114DiagnosticsMaxLines
diagnostics.layoutParams = diagnostics.layoutParams.apply { height = originalHeight }
}
step114DiagnosticsHeight = null
step114Scene = null
step114Scenario = null
}
private fun showStep102Menu(anchor: android.view.View) {
PopupMenu(this, anchor).apply {
Step102PlacementFixture.Scenario.values().forEachIndexed { index, scenario ->
@@ -2481,8 +2563,8 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
}
} else if (step093Mode || step097Topology != null) startStep093DiagnosticsPolling()
}
override fun onResume() { super.onResume(); mapView.onResume(); step113Scene?.resume() }
override fun onPause() { step113Scene?.pause(); mapView.onPause(); super.onPause() }
override fun onResume() { super.onResume(); mapView.onResume(); step113Scene?.resume(); step114Scene?.resume() }
override fun onPause() { step113Scene?.pause(); step114Scene?.pause(); mapView.onPause(); super.onPause() }
override fun onStop() {
step101Handler.removeCallbacksAndMessages(null)
step093Handler.removeCallbacks(step093DiagnosticsPoll)
@@ -2508,6 +2590,7 @@ class ParticleCoreLayerValidationActivity : AppCompatActivity() {
override fun onSaveInstanceState(outState: Bundle) {
outState.putString("step113_scenario", step113Scenario?.name)
outState.putString("step114_scenario", step114Scenario?.name)
outState.putBoolean(STATE_ACTIVE, active)
outState.putBoolean(STATE_ENABLED, enabled)
outState.putInt(STATE_MASK_MODE, maskMode)

View File

@@ -0,0 +1,329 @@
package org.maplibre.android.testapp.activity.particle
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import org.maplibre.android.annotations.Marker
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.maps.WeatherRuntime
import org.maplibre.android.style.layers.PropertyFactory.iconImage
import org.maplibre.android.style.layers.SymbolLayer
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.testapp.BuildConfig
import org.maplibre.geojson.Feature
import org.maplibre.geojson.Point
import java.io.File
/** 独立离线最小场景;不代表正式 PBF/NavSea。所有帧与缓存计数仅来自 Native。 */
internal class Step114FastSmokeScene(
private val context: Context,
private val map: MapLibreMap,
private val display: (String) -> Unit
) {
enum class Scenario { FAST_SMOKE, CIRCLE_C_BLOCKED, ANNOTATION_BLOCKED, SYMBOL_R_BLOCKED }
private val handler = Handler(Looper.getMainLooper())
private var generation = 0
private var running = false
private var paused = false
private var ready = false
private var blocked: String? = null
private var scenario = Scenario.FAST_SMOKE
private var runtime: WeatherRuntime? = null
private var marker: Marker? = null
private var savedGestures: List<Boolean>? = null
private var commands = JSONObject()
private var mutation = 0
private var cameraAlternate = false
private var actionSequence = 0L
private var lastLogMs = 0L
private val poll = object : Runnable {
override fun run() {
if (!running || paused) return
try {
val native = JSONObject(map.getRenderSegmentDiagnostics())
val trace = native.optJSONObject("fastGateTrace")
val segments = native.optJSONArray("segments") ?: JSONArray()
display(buildString {
append("STEP-114 $scenario · 独立 smoke · ${if (ready) "READY/待验收" else blocked ?: "LOADING"}\n")
append("Native Full=${trace?.optLong("fullRendered")} Fast=${trace?.optLong("fastRendered")} ")
append("windowFast=${trace?.optLong("windowFastRendered")} mismatch=${trace?.optLong("decisionMismatch")}\n")
for (i in 0 until segments.length()) {
val s = segments.getJSONObject(i)
val c = s.optJSONObject("cache")
append("${s.optString("strategy")}[${s.optInt("beginIndex")},${s.optInt("endExclusive")}) ")
append("B=${c?.optLong("build") ?: 0} Reuse=${c?.optLong("reuse") ?: 0} ")
append("${s.optString("actualExecution")} ${c?.optString("lastFallbackReason") ?: ""}\n")
}
append("固定预报/相机;操作前后快照保存在 files/step114-*.json")
})
val now = SystemClock.elapsedRealtime()
if (now - lastLogMs >= 30000L) {
lastLogMs = now
Log.i(TAG, "scenario=$scenario ready=$ready full=${trace?.optLong("fullRendered")} " +
"fast=${trace?.optLong("fastRendered")} mismatch=${trace?.optLong("decisionMismatch")}")
}
} catch (error: Exception) { fail(error) }
handler.postDelayed(this, 3000L)
}
}
fun start(next: Scenario = Scenario.FAST_SMOKE) {
stop()
running = true
scenario = next
ready = false
blocked = null
commands = JSONObject()
mutation = 0
cameraAlternate = false
lastLogMs = 0L
val epoch = ++generation
display("STEP-114 $scenario · 独立离线场景加载中;正式 PBF 五场景另在 STEP-113")
val ui = map.uiSettings
savedGestures = listOf(ui.isScrollGesturesEnabled(), ui.isRotateGesturesEnabled(),
ui.isTiltGesturesEnabled(), ui.isZoomGesturesEnabled(),
ui.isDoubleTapGesturesEnabled(), ui.isQuickZoomGesturesEnabled())
ui.setAllGesturesEnabled(false)
map.cancelTransitions()
map.setRetainedUnderlayEnabled(true)
val plan = JSONObject().put("schemaVersion", 1).put("segments", JSONArray()
.put(JSONObject().put("strategy", "RETAINED"))
.put(JSONObject().put("strategy", "CONTINUOUS").put("startLayerId", COLOR_LAYER)))
commands.put("requestedPlan", plan).put("planAccepted", map.setRenderSegmentPlan(plan.toString()))
if (!paused) handler.post(poll)
map.setStyle(Style.Builder().fromJson(styleJson())) loaded@ { style ->
if (!running || epoch != generation) return@loaded
try {
check(commands.getBoolean("planAccepted")) { "RenderSegmentPlan 未接受" }
check(map.annotations.isEmpty()) { "存在非本场景 Annotation,禁止移除其层" }
if (scenario != Scenario.ANNOTATION_BLOCKED) {
// 只在这个没有 Annotation 实例的独立场景移除空内建层。
// 保留内建 source;生产场景和 Native Annotation 行为均不修改。
check(style.getLayer(ANNOTATION_LAYER) != null && style.removeLayer(ANNOTATION_LAYER)) {
"空内建 Annotation 层未能移除,保留 fail-closed 现场"
}
commands.put("emptyBuiltinAnnotationLayerRemoved", true)
} else {
check(style.getLayer(ANNOTATION_LAYER) != null) { "内建 Annotation 层缺失" }
marker = map.addMarker(MarkerOptions().position(LatLng(33.45, 129.97)))
commands.put("realAnnotationAdded", true)
}
if (scenario == Scenario.SYMBOL_R_BLOCKED) {
style.addImage(IMAGE, image(Color.YELLOW))
style.addLayerBelow(SymbolLayer(SYMBOL_LAYER, PROBE_SOURCE)
.withProperties(iconImage(IMAGE)), COLOR_LAYER)
commands.put("structuralSymbolInR", true)
}
map.cameraPosition = camera(false)
initializeFields()
ready = true
handler.removeCallbacksAndMessages(null)
if (!paused) handler.post(poll)
} catch (error: Exception) { fail(error) }
}
}
private fun styleJson(): String {
val layers = JSONArray()
.put(JSONObject().put("id", "step114-background").put("type", "background")
.put("paint", JSONObject().put("background-color", "#172c40")))
.put(JSONObject().put("id", "step114-r-circle").put("type", "circle").put("source", PROBE_SOURCE)
.put("paint", JSONObject().put("circle-radius", 12).put("circle-color", "#ff8800")))
.put(JSONObject().put("id", COLOR_LAYER).put("type", "weather-color").put("source", FIELD_SOURCE)
.put("paint", JSONObject().put("weather-color-opacity", 0.62)))
.put(JSONObject().put("id", PARTICLE_LAYER).put("type", "raster-particle").put("source", FIELD_SOURCE)
.put("paint", JSONObject().put("raster-particle-active", true)
.put("raster-particle-particle-count", 1024)))
if (scenario == Scenario.CIRCLE_C_BLOCKED) {
layers.put(JSONObject().put("id", "step114-c-circle").put("type", "circle").put("source", PROBE_SOURCE)
.put("paint", JSONObject().put("circle-radius", 5).put("circle-color", "#00ffff")))
}
return JSONObject().put("version", 8).put("name", "STEP-114 independent offline smoke")
.put("sources", JSONObject()
.put(PROBE_SOURCE, JSONObject().put("type", "geojson")
.put("data", JSONObject(Feature.fromGeometry(Point.fromLngLat(129.97, 33.45)).toJson())))
.put(FIELD_SOURCE, JSONObject().put("type", "raster-array").put("host-field-submission", true)))
.put("layers", layers).toString()
}
private fun initializeFields() {
val host = WeatherRuntime(map, WeatherRuntime.Config(FIELD_SOURCE, COLOR_LAYER, PARTICLE_LAYER))
runtime = host
val submitted = JSONArray()
for (cycle in listOf("2026080700", "2026080706")) {
val path = "integration/particle-weatherv2/ecmwf-hres-wind-20260807/$cycle"
val meta = context.assets.open("$path/metadata.json").bufferedReader().use { it.readText() }
val data = context.assets.open("$path/field.f32").use { it.readBytes() }
val result = host.submitWindField(meta, data)
submitted.put(result.name)
check(result.accepted()) { "离线 Field 提交失败: $cycle $result" }
}
commands.put("fieldSubmit", submitted)
.put("forecastSeek", host.setForecastTime(FORECAST_MS).name)
.put("forecastPause", host.setPlaybackState(WeatherRuntime.PlaybackState.PAUSE).name)
.put("particleVisibility", host.setParticleVisible(true).name)
.put("targetFps", host.setTargetFps(WeatherRuntime.TargetFps.FPS_30).name)
check(host.state == WeatherRuntime.State.READY && listOf("forecastSeek", "forecastPause",
"particleVisibility", "targetFps").all { commands.getString(it) == "ACCEPTED" }) {
"固定预报/粒子控制未全部接受: $commands"
}
}
// 操作前、提交后与短延迟分别保存真实 Native 窗口;不等待、不强制 Full、不构造 Gate 输入。
private fun action(name: String, change: () -> Unit) {
if (!running || !ready || paused) return
val epoch = generation
val id = ++actionSequence
try {
capture("$id-$name-before")
change()
commands.put("lastAction", name).put("actionSequence", id)
capture("$id-$name-submitted")
for (delay in listOf(100L, 500L, 1500L)) {
handler.postDelayed({
if (running && !paused && epoch == generation) {
try { capture("$id-$name-after-${delay}ms") } catch (error: Exception) { fail(error) }
}
}, delay)
}
} catch (error: Exception) { fail(error) }
}
fun mutateSource() = action("source") {
val source = checkNotNull(map.style?.getSourceAs<GeoJsonSource>(PROBE_SOURCE))
++mutation
source.setGeoJson(Feature.fromGeometry(Point.fromLngLat(129.97 + (mutation % 2) * 0.01, 33.45)))
commands.put("sourceMutationCount", mutation)
}
fun panZoom() = action("pan-zoom") {
cameraAlternate = !cameraAlternate
map.cameraPosition = camera(cameraAlternate)
commands.put("cameraAlternate", cameraAlternate)
}
fun mutateImage() = action("image") {
val count = commands.optInt("imageMutationCount") + 1
checkNotNull(map.style).addImage(IMAGE, image(if (count % 2 == 1) Color.RED else Color.YELLOW))
commands.put("imageMutationCount", count)
}
fun toggleCache() = action("cache-toggle") {
val enabled = !commands.optBoolean("cacheDisabled", false)
map.setRetainedUnderlayEnabled(!enabled)
commands.put("cacheDisabled", enabled)
}
fun mutateAnnotation() = action("annotation") {
val annotation = checkNotNull(marker) { "请先选择 ANNOTATION_BLOCKED" }
++mutation
annotation.position = LatLng(33.45, 129.97 + (mutation % 2) * 0.01)
commands.put("annotationMutationCount", mutation)
}
fun reload() {
if (!running) return
try { capture("reload-before") } catch (error: Exception) { fail(error); return }
start(scenario)
}
private fun envelope(native: JSONObject, phase: String) = JSONObject()
.put("schema", "step114-fast-smoke").put("schemaVersion", 1).put("appVersion", BuildConfig.VERSION_NAME)
.put("scenario", scenario.name).put("sceneGeneration", generation).put("sceneReady", ready)
.put("blockedReason", blocked ?: JSONObject.NULL).put("sampleElapsedMs", SystemClock.elapsedRealtime())
.put("phase", phase).put("evidence", "INDEPENDENT-SMOKE; 非PBF/非113层等价")
.put("commands", JSONObject(commands.toString())).put("forecastRequestedMs", FORECAST_MS)
.put("actualForecastTimeObservedMs", JSONObject.NULL)
.put("fieldBasis", "既有离线 ECMWF canonical 双帧;非NavSea当前QBIN")
.put("cameraObservedFromSdk", JSONObject().put("latitude", map.cameraPosition.target?.latitude)
.put("longitude", map.cameraPosition.target?.longitude).put("zoom", map.cameraPosition.zoom)
.put("bearing", map.cameraPosition.bearing).put("pitch", map.cameraPosition.tilt))
.put("native", native)
private fun capture(phase: String) {
val record = envelope(JSONObject(map.getRenderSegmentDiagnostics()), phase)
write(record, phase)
}
private fun write(record: JSONObject, phase: String) {
val file = File(context.filesDir, "step114-${scenario.name}-${generation}-${SystemClock.elapsedRealtime()}-$phase.json")
file.writeText(record.toString(), Charsets.UTF_8)
Log.i(TAG, "snapshot=${file.name} scenario=$scenario generation=$generation phase=$phase")
}
fun export() {
if (!running) return
try { capture("manual") } catch (error: Exception) { fail(error) }
}
fun onStyleLoadFailed(message: String) { if (running) fail(IllegalStateException(message)) }
private fun fail(error: Exception) {
ready = false
blocked = "BLOCKED: ${error.message}"
display("STEP-114 $scenario $blocked")
Log.e(TAG, "scene-blocked", error)
}
fun pause() {
if (running) try { capture("pause-before") } catch (error: Exception) { fail(error) }
paused = true
handler.removeCallbacksAndMessages(null)
}
fun resume() {
paused = false
handler.removeCallbacksAndMessages(null)
if (running) handler.post(poll)
}
fun stop() {
if (running) try { capture("teardown-before") } catch (error: Exception) { Log.e(TAG, "capture-failed", error) }
running = false
++generation
handler.removeCallbacksAndMessages(null)
runtime?.dispose()
runtime = null
marker?.let { map.removeMarker(it) }
marker = null
savedGestures?.let { flags ->
val ui = map.uiSettings
ui.setScrollGesturesEnabled(flags[0]); ui.setRotateGesturesEnabled(flags[1])
ui.setTiltGesturesEnabled(flags[2]); ui.setZoomGesturesEnabled(flags[3])
ui.setDoubleTapGesturesEnabled(flags[4]); ui.setQuickZoomGesturesEnabled(flags[5])
}
savedGestures = null
ready = false
Log.i(TAG, "scene-stop generation=$generation;MapView 销毁验收由 Activity/设备日志确认")
}
companion object {
const val TAG = "STEP114Gate"
private const val ANNOTATION_LAYER = "org.maplibre.annotations.points"
private const val PROBE_SOURCE = "step114-r-geojson"
private const val FIELD_SOURCE = "step114-fields"
private const val COLOR_LAYER = "step114-color"
private const val PARTICLE_LAYER = "step114-particles"
private const val SYMBOL_LAYER = "step114-r-symbol"
private const val IMAGE = "step114-image"
private const val FORECAST_MS = 1786060800000L
private fun camera(alternate: Boolean) = CameraPosition.Builder()
.target(LatLng(33.45, if (alternate) 130.0 else 129.97))
.zoom(if (alternate) 11.0 else 10.5).bearing(0.0).tilt(0.0).build()
private fun image(color: Int): Bitmap = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)
.apply { eraseColor(color) }
}
}