feat(studio-3d): 限速、真实耗时统计、无位移复用资产几何,以及保护包密钥注入(阶段 9 上半)
- What:
1. **显示限速真的生效**(R5):`ThreeDCoordinator.tick()` 用注入的单调时钟与
`display_period_s() = 1/max_fps` 限制**合成启动**频率(窗口定时器仍是 16 ms,但"显示帧率"是给操作者的
承诺,不是定时器的描述);声明边界(activate/begin_session/show_rest/隐藏)把预算清零,所以按下开始后的
第一帧立刻合成。生产者侧改为**按需**跳过:`Scene3DView.submit_packet()` 在
`coordinator.has_pending_frame()`(mailbox 里已有一帧等待)时不再构造快照——那是 O(H×W) 的拷贝,
而 mailbox 只保留最新一帧,两次拷贝里必然丢一个;被跳过的数量计入新的 `skipped_producer`,
与"显示跳帧"分开。**不丢任何本该显示的帧**(等待中的那一帧仍在)。
2. **真实统计**:`RenderFrame.compose_ms`(composer 在构造帧之前测量并写入,不再读会被下一任务改写的
`last_stats`);`GLRenderer` 的绘制计数改名为 `paint_calls`,`RenderStats.displayed_frames` 由
**widget 按帧身份**统计(相机旋转/色标改动只是重画,不再是"多显示了一帧");`render_totals()` 增
`compose_ms`/`latency_ms`(合成开始→被接受的单调耗时)/`paint_calls`/`skipped_producer`,并且
`shown`/`compose_ms` 改从 widget 读(无 GL 的机器也能报告,之前只有画过才有数)。
3. **无位移时复用资产几何**(R5 建议):`SceneComposer` 缓存 `asset_hash → (positions, normals)`;
变形时照旧从形变后的位置重算法线,不变形时直接用资产自己的(只读、零拷贝)数组。20k 顶点实测:
compose p50 **6.15 ms → 1.03 ms**(法线段 4.9 ms → 0.0001 ms,剩余是采样 1.01 ms);
真实发布包(1032 顶点)compose p50 **0.50 ms → 0.17 ms**。
4. **保护包密钥注入**(R4):新增 `scene3d/keys.py`——从 preference 读取
`scene3d_verify_key`(验签公钥 PEM)/`scene3d_content_key_file` + `scene3d_content_key_id`
(内容密钥,经 `protect.load_key_file`)/`scene3d_require_signature`(发布模式,拒绝无签名包),
组装成 `SceneKeys` 交给 `SceneAssetLoader` → `load_package` → `PackagedAssetLoader.load(keys=…,
verify_key_pem=…)`;`AppWindow._sync_3d_source()` 解析它并 `Mesh3dPanel.set_keys()`。
缺失/不可读的密钥是**状态而不是崩溃**(`describe()` 里带原因),密钥材料永不进日志;
`Mesh3dPanel.describe()` 的 scene 块记录 `keys`(布尔 + 路径)。
- Why: 审查报告 R5(`max_fps` 只被存储与显示、`draw()` 硬编码 `compose_ms=0.0`、`_displayed_frames` 把
重画也算新帧、`SceneComposer.last_stats` 被显示链路完全未读)与 R4(底层支持签名/加密包,Studio 加载
入口却从不传验签公钥与 KeyProvider,合法保护包打不开,只能发明文包或关掉校验)。R5 的另一半是
"当前只有曲面着色、没有 displacement 时,composer 仍每帧重算法线并重新打包位置"——缓存后 20k 顶点
降低到六分之一。
- Verification:
· `test_scene3d_coordinator.py` +6:15 fps 的假时钟下 1.32 s 内只启动约 20 次合成(60 fps 对照 ≥55 次)、
`display_period_s()` 跟随设置、结果延迟是真实单调差值、`has_pending_frame()` 随 mailbox 变化;
`test_scene3d_live.py` +3:无位移时发布帧直接**就是**资产自己的(只读)数组、force_deform 但仍无位移时
给出 `field_unavailable` 诊断、有标定位移时仍重算、`compose_ms` 属于该帧且不被下一次合成改写;
`test_scene3d_view.py` +2:等待中的帧让生产者跳过第二个快照且取出后立即恢复、`render_totals()` 的
compose 成本与延迟是真实值;新增 `test_scene3d_protected_package.py` 7 项:Studio 入口打开签名包、
用 preference 里的内容密钥打开加密包、缺验签公钥 → `asset_auth_failed`、密钥文件缺失/无 key id →
状态而非崩溃、发布模式拒绝无签名包而开发模式接受、`SceneAssetLoader` 把密钥交给 worker、面板携带密钥。
· 全量:shared+apps 同一次运行 **588 项 0 失败 15 跳过**;真 GL 冒烟(`QT_QPA_PLATFORM=windows`)
**14 项 0 失败**;ui_check 587 项 0 失败;locale_check 0 缺失。
· 顺带修掉两个**既有的顺序依赖**真 GL 用例(不是本次引入:在上一提交上单跑同样失败):
`test_the_producer_side_never_waits_for_the_gpu` 的收尾没有排空 mailbox(留下的一帧会被下一个测试
上传),`test_an_automatic_colour_scale_follows_the_frame` 在渲染之前就断言"范围来自本帧",
且用"不同颜色数"当自动量程的代理(对可见面积敏感)。现在前者排空并断言排空完成,后者先渲染再断言,
判据改为**平均亮度**(固定 0..1000 把 3..7 压进 LUT 最暗的一小段,自动量程铺满整条色带)。
· 性能报告(`.repro/perf-cpu-*-after-9.json`,`bench_scene.py --cpu-only`):合成 p50
合成 poc 0.016 ms / 20k 顶点 1.03 ms / 真实包 0.17 ms;对比已提交的 `perf-report-windows-dev.json`
(20k 6.15 ms、真实包 0.50 ms)。
- Not in this change: **画布布局第二批**(2D/3D 页签容器、参数抽屉、窄窗口回退、诊断抽屉)与曲线量程开关
仍未做;阶段 9 的门禁部分(`soak_scene.py --minutes 120` GUI 模式、Jetson Orin Nano 与 QCS6490 上的
`probe_gl/bench_scene/soak_scene` 报告)需要长时间运行与板卡,本轮未跑,结论不写"通过";
签名私钥仍只在构建机(本提交只引入"读"的一半)。
This commit is contained in:
@@ -2191,7 +2191,14 @@ class StudioMainWindow(QMainWindow):
|
||||
that on its worker thread. Without it the pane could only compare the asset with
|
||||
itself, which is how a scene built on a different mapping would still look
|
||||
matched.
|
||||
|
||||
The release keys travel the same way (from the preferences, paths only): a signed
|
||||
or sealed package is refused by the container without them, which left a
|
||||
legitimate protected release unopenable from the application.
|
||||
"""
|
||||
from orisys_studio.scene3d.keys import resolve_scene_keys
|
||||
|
||||
self.mesh3d_panel.set_keys(resolve_scene_keys(self.prefs))
|
||||
self.mesh3d_panel.set_sensor(
|
||||
self.sensor_picker.sensor_type(),
|
||||
expected_provider=self._device_geometry_provider(),
|
||||
|
||||
@@ -43,6 +43,7 @@ from orisys_app_shared.scene3d.contracts import (
|
||||
diagnostic,
|
||||
error,
|
||||
)
|
||||
from orisys_studio.scene3d.keys import SceneKeys, check_release_requirement
|
||||
|
||||
if TYPE_CHECKING: # the description is a value object; the callable returns one
|
||||
from orisys_app_shared.acquisition.geometry import DeviceGeometry
|
||||
@@ -124,20 +125,37 @@ def no_asset_diagnostic(sensor_type: str, *, override: str | Path | None = None)
|
||||
|
||||
|
||||
def load_package(
|
||||
source: SceneSource, expected: Optional[ExpectedGeometry] = None
|
||||
source: SceneSource,
|
||||
expected: Optional[ExpectedGeometry] = None,
|
||||
keys: "Optional[SceneKeys]" = None,
|
||||
) -> SceneAssets:
|
||||
"""Read and validate a package. Runs on a worker thread; raises ``ThreeDError``."""
|
||||
"""Read and validate a package. Runs on a worker thread; raises ``ThreeDError``.
|
||||
|
||||
``keys`` carries the release key material (a verification key and/or a content-key
|
||||
provider) and the release-mode flag. Without it a *signed* package is refused by the
|
||||
container itself ("a verification key is required"), which left the application with
|
||||
no way to open a legitimate protected release at all.
|
||||
"""
|
||||
from orisys_app_shared.scene3d.package import PackagedAssetLoader
|
||||
|
||||
if not source.path.is_file():
|
||||
raise error("asset_rejected", f"the scene package is missing: {source.path}")
|
||||
return PackagedAssetLoader().load(source.path, expected)
|
||||
requirement = check_release_requirement(source.path, keys)
|
||||
if requirement is not None:
|
||||
raise error(requirement.code, requirement.message, **dict(requirement.details))
|
||||
return PackagedAssetLoader().load(
|
||||
source.path,
|
||||
expected,
|
||||
keys=getattr(keys, "provider", None),
|
||||
verify_key_pem=getattr(keys, "verify_key_pem", None),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_and_load(
|
||||
source: SceneSource,
|
||||
expected: Optional[ExpectedGeometry],
|
||||
provider: "Optional[Callable[[], DeviceGeometry]]",
|
||||
keys: "Optional[SceneKeys]" = None,
|
||||
) -> tuple[SceneAssets, "Optional[DeviceGeometry]"]:
|
||||
"""Worker-thread half: build the *device's* description, then read the package.
|
||||
|
||||
@@ -150,7 +168,7 @@ def _resolve_and_load(
|
||||
if expected is None and provider is not None:
|
||||
device = provider()
|
||||
expected = device.expected
|
||||
return load_package(source, expected), device
|
||||
return load_package(source, expected, keys), device
|
||||
|
||||
|
||||
class SceneAssetLoader(QObject):
|
||||
@@ -179,10 +197,11 @@ class SceneAssetLoader(QObject):
|
||||
expected: Optional[ExpectedGeometry] = None,
|
||||
*,
|
||||
expected_provider: "Optional[Callable[[], DeviceGeometry]]" = None,
|
||||
keys: "Optional[SceneKeys]" = None,
|
||||
) -> int:
|
||||
"""Ask for a scene; returns the request id this call was given."""
|
||||
self._request_id += 1
|
||||
request = (source, expected, expected_provider, self._request_id)
|
||||
request = (source, expected, expected_provider, self._request_id, keys)
|
||||
if self._inflight:
|
||||
self._pending = request
|
||||
return self._request_id
|
||||
@@ -190,13 +209,15 @@ class SceneAssetLoader(QObject):
|
||||
return self._request_id
|
||||
|
||||
def _start(self, request) -> None:
|
||||
source, expected, provider, request_id = request
|
||||
source, expected, provider, request_id, keys = request
|
||||
if self._executor is None:
|
||||
self._executor = ThreadPoolExecutor(
|
||||
max_workers=1, thread_name_prefix="scene3d-assets"
|
||||
)
|
||||
self._inflight = True
|
||||
future = self._executor.submit(_resolve_and_load, source, expected, provider)
|
||||
future = self._executor.submit(
|
||||
_resolve_and_load, source, expected, provider, keys
|
||||
)
|
||||
future.add_done_callback(
|
||||
lambda done: self._finished(done, source, request_id)
|
||||
)
|
||||
|
||||
@@ -131,6 +131,11 @@ class ThreeDCoordinator:
|
||||
#: Without this the pane re-uploaded the same rest frame on every 16 ms tick
|
||||
#: while it waited for the first measurement.
|
||||
self._rest_presented = False
|
||||
#: A monotonic budget for *starting* composes: the window ticks at 16 ms, and
|
||||
#: "display rate" is a promise to the operator, not a description of the timer.
|
||||
self._last_compose_start = float("-inf")
|
||||
#: How long the last accepted result took (compose + queue), in milliseconds.
|
||||
self._last_result_latency_ms = 0.0
|
||||
#: The field frame currently on screen, so a gain change can redraw exactly
|
||||
#: it rather than a newer instant.
|
||||
self._last_field_frame: Optional[SurfaceFieldFrame] = None
|
||||
@@ -154,6 +159,23 @@ class ThreeDCoordinator:
|
||||
"""What is on screen, and the monotonic time it was handed to the widget."""
|
||||
return self._last_presented
|
||||
|
||||
def last_result_latency_ms(self) -> float:
|
||||
"""How long the last accepted compose took, from start to acceptance."""
|
||||
return self._last_result_latency_ms
|
||||
|
||||
def display_period_s(self) -> float:
|
||||
"""The shortest interval between two compose starts, from ``max_fps``."""
|
||||
return 1.0 / max(1, int(self._settings.max_fps))
|
||||
|
||||
def has_pending_frame(self) -> bool:
|
||||
"""Whether a produced frame is already waiting for the timer.
|
||||
|
||||
The producer asks this before *building* a snapshot: the mailbox keeps only the
|
||||
newest frame, so the O(H×W) copy that would be dropped is work nobody displays.
|
||||
A frame is never lost that would have been shown — it is only not made twice.
|
||||
"""
|
||||
return self._incoming.peek() is not None
|
||||
|
||||
@property
|
||||
def superseded_frames(self) -> int:
|
||||
"""Frames the display never showed. Never a recording drop."""
|
||||
@@ -203,6 +225,11 @@ class ThreeDCoordinator:
|
||||
self._settings_dirty = False
|
||||
self._stale_since = None
|
||||
self._rest_presented = False
|
||||
# The next frame after a claim boundary composes at once: the operator just
|
||||
# asked for something, and making them wait out the display period adds delay to
|
||||
# no purpose.
|
||||
self._last_compose_start = float("-inf")
|
||||
self._last_result_latency_ms = 0.0
|
||||
item = self._inflight
|
||||
if item is not None:
|
||||
item.future.cancel()
|
||||
@@ -382,17 +409,23 @@ class ThreeDCoordinator:
|
||||
return
|
||||
self._collect_inflight()
|
||||
self._expire_stale()
|
||||
if self._inflight is None:
|
||||
# One compose per display period. The window's timer is 16 ms whatever the panel
|
||||
# says, so without this "15 fps" was a stored number nobody obeyed.
|
||||
period = self.display_period_s()
|
||||
now = self._clock()
|
||||
if self._inflight is None and (now - self._last_compose_start) >= period:
|
||||
if self._settings_dirty and self._last_field_frame is not None:
|
||||
# A gain change re-draws the field that is already on screen; taking
|
||||
# a newer one would show a different instant than the one the
|
||||
# operator just changed the exaggeration of.
|
||||
self._settings_dirty = False
|
||||
self._last_compose_start = now
|
||||
self._start_compose(self._last_field_frame)
|
||||
else:
|
||||
self._settings_dirty = False
|
||||
frame = self._incoming.take()
|
||||
if frame is not None:
|
||||
self._last_compose_start = now
|
||||
self._start_compose(frame)
|
||||
composed = self._composed.take()
|
||||
if composed is not None:
|
||||
@@ -580,4 +613,7 @@ class ThreeDCoordinator:
|
||||
# screen for something that is no longer being measured.
|
||||
self._stale_frames += 1
|
||||
return
|
||||
# From the compose's own start to here: the cost plus however long it waited for
|
||||
# a tick. A number the operator can compare with the frame period.
|
||||
self._last_result_latency_ms = (self._clock() - item.started) * 1000.0
|
||||
self._composed.offer(composed)
|
||||
|
||||
@@ -512,7 +512,7 @@ class GLRenderer:
|
||||
self._sensing_part_id: str = ""
|
||||
self._estimated_gpu_bytes: int = 0
|
||||
self._initialized = False
|
||||
self._displayed_frames = 0
|
||||
self._paint_calls = 0
|
||||
self._last_upload_ms = 0.0
|
||||
|
||||
# ------------------------------------------------------------------ lifetime
|
||||
@@ -660,9 +660,12 @@ class GLRenderer:
|
||||
)
|
||||
GL.glBindVertexArray(0)
|
||||
GL.glUseProgram(0)
|
||||
self._displayed_frames += 1
|
||||
self._paint_calls += 1
|
||||
return RenderStats(
|
||||
displayed_frames=self._displayed_frames,
|
||||
# The renderer counts *draws*; the widget counts unique frames. Keeping the
|
||||
# two apart is what lets a slow camera move be told from a slow pipeline.
|
||||
displayed_frames=0,
|
||||
paint_calls=self._paint_calls,
|
||||
# The real cost of the frame's compose is carried on the frame itself
|
||||
# (``RenderFrame.compose_ms``): the shared composer counter is rewritten by
|
||||
# the next task, and reading it here reported the wrong frame's cost.
|
||||
@@ -703,7 +706,7 @@ class GLRenderer:
|
||||
self._scalar_range = None
|
||||
self._last_scale = None
|
||||
self._last_scale_mode = ""
|
||||
self._displayed_frames = 0
|
||||
self._paint_calls = 0
|
||||
|
||||
def release_parts(self) -> None:
|
||||
from OpenGL import GL
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Where the application's release keys come from.
|
||||
|
||||
A scene package can be signed (provenance) and sealed (a content key): the container
|
||||
format supports both, and the loader accepts a ``KeyProvider`` and a verification key.
|
||||
The application, however, never passed either — so a legitimate release package was
|
||||
refused with "this package is signed; a verification key is required", and the only way
|
||||
to run it was to ship a plain package or turn the check off. That is precisely the
|
||||
decision this module keeps out of the engineer's hands.
|
||||
|
||||
The keys are therefore *configuration*: paths in the preferences file, resolved here into
|
||||
the two things the loader wants, plus a release-mode flag that refuses an unsigned
|
||||
package. Nothing here logs or returns key material; :meth:`SceneKeys.describe` reports
|
||||
paths and booleans so a recording can say how a package was authenticated.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
from orisys_app_shared.scene3d.contracts import Diagnostic, diagnostic
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Preferences keys. Paths only — never key material, and never a private key: signing
|
||||
#: happens on the build machine (see ``tools/scene_assets/compile_scene.py``).
|
||||
PREF_VERIFY_KEY = "scene3d_verify_key"
|
||||
PREF_CONTENT_KEY_FILE = "scene3d_content_key_file"
|
||||
PREF_CONTENT_KEY_ID = "scene3d_content_key_id"
|
||||
PREF_REQUIRE_SIGNATURE = "scene3d_require_signature"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SceneKeys:
|
||||
"""What the loader needs to authenticate a package — and how strict to be."""
|
||||
|
||||
verify_key_pem: Optional[bytes] = None
|
||||
provider: Any = None
|
||||
require_signature: bool = False
|
||||
#: Paths/ids only, for logs and for the recording: never material.
|
||||
sources: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
def authenticated_by_key(self) -> bool:
|
||||
return self.verify_key_pem is not None
|
||||
|
||||
def describe(self) -> dict:
|
||||
"""What is configured, in a form safe to log and to record.
|
||||
|
||||
Booleans for "is this piece present" and the *paths* it came from; never key
|
||||
material, and never the private half of anything.
|
||||
"""
|
||||
return {
|
||||
"verify_key": bool(self.verify_key_pem),
|
||||
"content_key": bool(self.provider is not None),
|
||||
"require_signature": bool(self.require_signature),
|
||||
**{str(key): str(value) for key, value in self.sources.items()},
|
||||
}
|
||||
|
||||
|
||||
def resolve_scene_keys(prefs: Optional[Mapping[str, Any]]) -> SceneKeys:
|
||||
"""Build the key material the preferences describe. Never raises for absence.
|
||||
|
||||
A missing or unreadable file is a *diagnostic-bearing state*, not a crash: the 2D
|
||||
application must start and run, and only the 3D pane is affected. The reason is kept
|
||||
so the pane can say why a protected package was refused instead of looking broken.
|
||||
"""
|
||||
prefs = dict(prefs or {})
|
||||
sources: dict[str, str] = {}
|
||||
verify_pem: Optional[bytes] = None
|
||||
provider = None
|
||||
|
||||
verify_path = str(prefs.get(PREF_VERIFY_KEY) or "").strip()
|
||||
if verify_path:
|
||||
path = Path(verify_path).expanduser()
|
||||
sources["verify_key_path"] = str(path)
|
||||
if path.is_file():
|
||||
try:
|
||||
verify_pem = path.read_bytes()
|
||||
except OSError:
|
||||
logger.warning("the 3D verification key is unreadable: %s", path)
|
||||
sources["verify_key_error"] = "unreadable"
|
||||
else:
|
||||
logger.warning("the configured 3D verification key is missing: %s", path)
|
||||
sources["verify_key_error"] = "missing"
|
||||
|
||||
key_file = str(prefs.get(PREF_CONTENT_KEY_FILE) or "").strip()
|
||||
if key_file:
|
||||
path = Path(key_file).expanduser()
|
||||
key_id = str(prefs.get(PREF_CONTENT_KEY_ID) or "").strip()
|
||||
sources["content_key_file"] = str(path)
|
||||
if key_id:
|
||||
sources["content_key_id"] = key_id
|
||||
if path.is_file() and key_id:
|
||||
try:
|
||||
from orisys_app_shared.scene3d import protect
|
||||
|
||||
provider = protect.load_key_file(path, key_id=key_id)
|
||||
except Exception as exc: # noqa: BLE001 - reported, never fatal here
|
||||
logger.warning("the 3D content key file was refused: %s", type(exc).__name__)
|
||||
sources["content_key_error"] = str(getattr(exc, "diagnostic", exc))
|
||||
elif not key_id:
|
||||
sources["content_key_error"] = "no key id configured"
|
||||
else:
|
||||
sources["content_key_error"] = "missing"
|
||||
|
||||
return SceneKeys(
|
||||
verify_key_pem=verify_pem,
|
||||
provider=provider,
|
||||
require_signature=bool(prefs.get(PREF_REQUIRE_SIGNATURE, False)),
|
||||
sources=sources,
|
||||
)
|
||||
|
||||
|
||||
def check_release_requirement(path: Path, keys: Optional[SceneKeys]) -> Optional[Diagnostic]:
|
||||
"""Refuse an unsigned package when the application is in release mode.
|
||||
|
||||
Development builds accept a plain package (the shipped engineering one is exactly
|
||||
that); a release build is asked to say so explicitly rather than rely on whoever
|
||||
compiled the package remembering to sign it.
|
||||
"""
|
||||
if keys is None or not keys.require_signature:
|
||||
return None
|
||||
from orisys_app_shared.scene3d.package import describe_envelope
|
||||
|
||||
try:
|
||||
summary = describe_envelope(Path(path))
|
||||
except Exception as exc: # noqa: BLE001 - the loader will report the real problem
|
||||
logger.debug("could not read the envelope of %s: %s", path, exc)
|
||||
return None
|
||||
if not summary.get("signed"):
|
||||
return diagnostic(
|
||||
"asset_auth_failed",
|
||||
"this build requires signed scene packages and this one is not signed",
|
||||
package=Path(path).name,
|
||||
)
|
||||
return None
|
||||
@@ -115,6 +115,8 @@ class Scene3DView(QWidget):
|
||||
self._reported_diagnostic: Optional[Diagnostic] = None
|
||||
#: Whether the loaded asset was compared against the device's own description.
|
||||
self._device_verified = False
|
||||
#: Frames the producer did not even build (a frame was already waiting).
|
||||
self._skipped_snapshots = 0
|
||||
|
||||
self._layout = QVBoxLayout(self)
|
||||
self._layout.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -294,6 +296,12 @@ class Scene3DView(QWidget):
|
||||
identity = self.identity_for(packet)
|
||||
if identity is None:
|
||||
return
|
||||
if coordinator.has_pending_frame():
|
||||
# A produced frame is still waiting for the timer: building another one
|
||||
# would be an O(H×W) copy the mailbox drops. It is not a dropped frame —
|
||||
# the frame it would have replaced is still there to be shown.
|
||||
self._skipped_snapshots += 1
|
||||
return
|
||||
frame = snapshot(packet, identity)
|
||||
if frame is not None:
|
||||
coordinator.submit(frame)
|
||||
@@ -590,16 +598,40 @@ class Scene3DView(QWidget):
|
||||
}
|
||||
|
||||
def render_totals(self) -> dict:
|
||||
"""Display-side counters: shown frames and display drops, never recording ones."""
|
||||
"""Display-side counters: shown frames and display drops, never recording ones.
|
||||
|
||||
"Shown" and the compose cost come from the *widget*, which counts what was
|
||||
presented — not from the last ``RenderStats``, which only exists after a paint (a
|
||||
headless or offscreen pane never paints, and it still received every frame).
|
||||
"""
|
||||
coordinator = self._coordinator
|
||||
widget = self._widget
|
||||
stats = self._last_stats
|
||||
shown = (
|
||||
int(widget.displayed_frames())
|
||||
if widget is not None
|
||||
else int(getattr(stats, "displayed_frames", 0) or 0)
|
||||
)
|
||||
compose_ms = (
|
||||
float(widget.last_compose_ms())
|
||||
if widget is not None
|
||||
else float(getattr(stats, "compose_ms", 0.0) or 0.0)
|
||||
)
|
||||
return {
|
||||
"shown": int(getattr(stats, "displayed_frames", 0) or 0),
|
||||
"shown": shown,
|
||||
"dropped_display": int(
|
||||
coordinator.superseded_frames if coordinator is not None else 0
|
||||
),
|
||||
"stale": int(getattr(coordinator, "stale_frames", 0) or 0),
|
||||
"invalid": int(getattr(coordinator, "invalid_frames", 0) or 0),
|
||||
# Work the producer deliberately did not do because a frame was waiting.
|
||||
"skipped_producer": int(self._skipped_snapshots),
|
||||
# A *real* cost, per frame, plus how long the result took to be accepted.
|
||||
"compose_ms": compose_ms,
|
||||
"latency_ms": float(
|
||||
coordinator.last_result_latency_ms() if coordinator is not None else 0.0
|
||||
),
|
||||
"paint_calls": int(getattr(stats, "paint_calls", 0) or 0),
|
||||
}
|
||||
|
||||
def close(self) -> None:
|
||||
|
||||
@@ -76,6 +76,10 @@ class Sensor3DWidget(QOpenGLWidget):
|
||||
self._needs_scene_upload = False
|
||||
self._needs_surface_upload = False
|
||||
self._last_stats_at = 0.0
|
||||
#: What reached the screen, counted by identity, and what it cost to compose.
|
||||
self._unique_frames = 0
|
||||
self._last_frame_identity: Optional[FrameIdentity] = None
|
||||
self._last_compose_ms = 0.0
|
||||
self._last_press: Optional[tuple[float, float]] = None
|
||||
self._unavailable = False
|
||||
#: Frames the display never showed, set by the coordinator. Never a
|
||||
@@ -97,6 +101,12 @@ class Sensor3DWidget(QOpenGLWidget):
|
||||
"""Keep the newest CPU frame and ask for a repaint. Never requires a context."""
|
||||
self._frame = frame
|
||||
self._needs_surface_upload = True
|
||||
# Count *data*, not drawing: a camera move or a colour-scale change repaints the
|
||||
# same measurement, and the old counter incremented on every paintGL.
|
||||
if frame.identity != self._last_frame_identity:
|
||||
self._last_frame_identity = frame.identity
|
||||
self._unique_frames += 1
|
||||
self._last_compose_ms = float(getattr(frame, "compose_ms", 0.0) or 0.0)
|
||||
self.descriptorChanged.emit(frame.scalar_descriptor)
|
||||
self.update()
|
||||
|
||||
@@ -110,6 +120,14 @@ class Sensor3DWidget(QOpenGLWidget):
|
||||
def capabilities(self) -> Optional[GLCapabilities]:
|
||||
return self._capabilities
|
||||
|
||||
def displayed_frames(self) -> int:
|
||||
"""Unique frames handed to this widget (a repaint is not a new frame)."""
|
||||
return int(self._unique_frames)
|
||||
|
||||
def last_compose_ms(self) -> float:
|
||||
"""What the frame on screen cost to compose, measured where it was composed."""
|
||||
return float(self._last_compose_ms)
|
||||
|
||||
def diagnostic(self) -> Optional[Diagnostic]:
|
||||
return self._diagnostic
|
||||
|
||||
@@ -220,9 +238,12 @@ class Sensor3DWidget(QOpenGLWidget):
|
||||
self._last_stats_at = now
|
||||
self.renderStatsChanged.emit(
|
||||
RenderStats(
|
||||
displayed_frames=stats.displayed_frames,
|
||||
# Frames that reached the screen, by identity; ``paint_calls`` is the
|
||||
# renderer's own count of how often it was asked to draw.
|
||||
displayed_frames=self._unique_frames,
|
||||
superseded_frames=self._superseded,
|
||||
compose_ms=stats.compose_ms,
|
||||
paint_calls=stats.paint_calls,
|
||||
compose_ms=self._last_compose_ms,
|
||||
upload_ms=stats.upload_ms,
|
||||
paint_ms=(now - started) * 1000.0,
|
||||
estimated_gpu_bytes=stats.estimated_gpu_bytes,
|
||||
|
||||
@@ -87,6 +87,8 @@ class Mesh3dPanel(QFrame):
|
||||
#: request describes a selection the operator has already moved away from.
|
||||
self._load_request = 0
|
||||
self._device = None
|
||||
#: Release key material from the preferences (``scene3d.keys.SceneKeys``).
|
||||
self._keys = None
|
||||
#: The package whose scene is in the view, so switching sensor away and back
|
||||
#: does not reload it (and does not pretend to be loading it either).
|
||||
self._loaded_path: Optional[Path] = None
|
||||
@@ -209,9 +211,19 @@ class Mesh3dPanel(QFrame):
|
||||
self._loader.loaded.connect(self._on_loaded)
|
||||
self._loader.failed.connect(self._on_load_failed)
|
||||
self._load_request = self._loader.load(
|
||||
self._source, self._expected, expected_provider=self._expected_provider
|
||||
self._source,
|
||||
self._expected,
|
||||
expected_provider=self._expected_provider,
|
||||
keys=self._keys,
|
||||
)
|
||||
|
||||
def set_keys(self, keys) -> None:
|
||||
"""The release key material (see ``scene3d.keys``). Paths, never material."""
|
||||
self._keys = keys
|
||||
|
||||
def keys(self):
|
||||
return self._keys
|
||||
|
||||
# -------------------------------------------------------------- settings
|
||||
def set_display_settings(self, settings) -> None:
|
||||
"""Persisted display settings, applied now if the view exists.
|
||||
@@ -257,6 +269,9 @@ class Mesh3dPanel(QFrame):
|
||||
"reason": reason,
|
||||
"scene": {
|
||||
"path": str(self._source.path) if self._source is not None else "",
|
||||
# How the package was authenticated, when it was: paths and booleans
|
||||
# only, never key material (see ``scene3d.keys``).
|
||||
"keys": self._keys.describe() if self._keys is not None else {},
|
||||
**dict(described.get("scene") or {}),
|
||||
},
|
||||
"gl": dict(described.get("gl") or {}),
|
||||
|
||||
Reference in New Issue
Block a user