同步 sgs-frontend-mobile 源码
Some checks failed
CI / verify (push) Has been cancelled

This commit is contained in:
lyf
2026-07-27 11:26:01 +08:00
parent 575dca430f
commit 9ea1bfab71
181 changed files with 24395 additions and 5212 deletions

View File

@@ -0,0 +1,490 @@
export interface GuideFloorBasemapViewBounds {
minX: number
maxX: number
minZ: number
maxZ: number
screenXAxis: '+X' | '-X'
screenYAxis: '+Z' | '-Z'
}
export interface GuideFloorBasemapCameraProjection {
type: 'perspective'
position: { x: number; y: number; z: number }
target: { x: number; y: number; z: number }
up: { x: number; y: number; z: number }
fov: number
near: number
far: number
aspect: number
}
export interface GuideFloorBasemapOrthographicProjection {
type: 'orthographic-xz'
minX: number
maxX: number
minZ: number
maxZ: number
planeY: number
center: { x: number; z: number }
width: number
height: number
screenRight: { x: number; z: number }
screenDown: { x: number; z: number }
}
export interface GuideFloorBasemapInitialViewport {
centerX: number
centerZ: number
visibleWorldSpan: number
maxVisibleWorldSpan: number
}
export interface GuideFloorBasemapEntry {
floorId: string
floorCode: string
modelVersion: string
projection?: GuideFloorBasemapOrthographicProjection
initialViewport?: GuideFloorBasemapInitialViewport
viewBounds?: GuideFloorBasemapViewBounds
cameraProjection?: GuideFloorBasemapCameraProjection
image: {
path: string
width: number
height: number
format: 'webp'
}
}
export interface GuideCompositeBasemapEntry extends GuideFloorBasemapEntry {
role: 'SAME_GROUND_COMPOSITE'
assetId: string
modelUrl: string
coverageFloorCodes: string[]
coverageFloorIds: string[]
}
export interface GuideFloorBasemapManifest {
schemaVersion: number
render?: {
projection?: string
projectionVersion?: string
}
floors: GuideFloorBasemapEntry[]
routeAssets: GuideCompositeBasemapEntry[]
}
export interface GuideFloorBasemapPoint {
x: number
y?: number
z: number
}
export interface GuideFloorBasemapProjectionFrame {
width: number
height: number
offsetX: number
offsetY: number
}
export const GUIDE_FLOOR_BASEMAP_MANIFEST_URL = '/static/guide-floor-basemaps/manifest.json'
export const GUIDE_FLOOR_BASEMAP_PROJECTION = 'orthographic-xz'
export const GUIDE_FLOOR_BASEMAP_PROJECTION_VERSION = 'ortho-yaw54-v2'
export const GUIDE_FLOOR_BASEMAP_SCHEMA_VERSION = 4
let manifestPromise: Promise<GuideFloorBasemapManifest | null> | null = null
const isFiniteNumber = (value: unknown): value is number => (
typeof value === 'number' && Number.isFinite(value)
)
const isValidViewBounds = (value: Partial<GuideFloorBasemapViewBounds> | null | undefined) => (
Boolean(value)
&& isFiniteNumber(value?.minX)
&& isFiniteNumber(value?.maxX)
&& isFiniteNumber(value?.minZ)
&& isFiniteNumber(value?.maxZ)
&& value!.maxX > value!.minX
&& value!.maxZ > value!.minZ
&& (value!.screenXAxis === '+X' || value!.screenXAxis === '-X')
&& (value!.screenYAxis === '+Z' || value!.screenYAxis === '-Z')
)
const isFiniteVector3 = (value: { x?: unknown; y?: unknown; z?: unknown } | null | undefined) => (
isFiniteNumber(value?.x)
&& isFiniteNumber(value?.y)
&& isFiniteNumber(value?.z)
)
const isValidCameraProjection = (
value: Partial<GuideFloorBasemapCameraProjection> | null | undefined
) => (
value?.type === 'perspective'
&& isFiniteVector3(value.position)
&& isFiniteVector3(value.target)
&& isFiniteVector3(value.up)
&& isFiniteNumber(value.fov)
&& value.fov > 0
&& value.fov < 180
&& isFiniteNumber(value.aspect)
&& value.aspect > 0
)
export const isValidGuideFloorOrthographicProjection = (
value: Partial<GuideFloorBasemapOrthographicProjection> | null | undefined
) => {
if (
value?.type !== 'orthographic-xz'
|| !isFiniteNumber(value.minX)
|| !isFiniteNumber(value.maxX)
|| !isFiniteNumber(value.minZ)
|| !isFiniteNumber(value.maxZ)
|| value.maxX <= value.minX
|| value.maxZ <= value.minZ
|| !isFiniteNumber(value.planeY)
|| !isFiniteNumber(value.center?.x)
|| !isFiniteNumber(value.center?.z)
|| !isFiniteNumber(value.width)
|| value.width <= 0
|| !isFiniteNumber(value.height)
|| value.height <= 0
|| !isFiniteNumber(value.screenRight?.x)
|| !isFiniteNumber(value.screenRight?.z)
|| !isFiniteNumber(value.screenDown?.x)
|| !isFiniteNumber(value.screenDown?.z)
) return false
const rightLength = Math.hypot(value.screenRight.x, value.screenRight.z)
const downLength = Math.hypot(value.screenDown.x, value.screenDown.z)
const dot = value.screenRight.x * value.screenDown.x
+ value.screenRight.z * value.screenDown.z
return Math.abs(rightLength - 1) < 1e-6
&& Math.abs(downLength - 1) < 1e-6
&& Math.abs(dot) < 1e-6
}
export const isValidGuideFloorBasemapInitialViewport = (
value: Partial<GuideFloorBasemapInitialViewport> | null | undefined
) => Boolean(
value
&& isFiniteNumber(value.centerX)
&& isFiniteNumber(value.centerZ)
&& isFiniteNumber(value.visibleWorldSpan)
&& value.visibleWorldSpan > 0
&& isFiniteNumber(value.maxVisibleWorldSpan)
&& value.maxVisibleWorldSpan >= value.visibleWorldSpan
)
export const isCompatibleGuideFloorBasemapManifest = (
manifest: GuideFloorBasemapManifest | null | undefined
) => {
if (!manifest || !Array.isArray(manifest.floors) || !Array.isArray(manifest.routeAssets)) return false
return manifest.schemaVersion === GUIDE_FLOOR_BASEMAP_SCHEMA_VERSION
&& manifest.render?.projection === GUIDE_FLOOR_BASEMAP_PROJECTION
&& manifest.render?.projectionVersion === GUIDE_FLOOR_BASEMAP_PROJECTION_VERSION
}
const isValidGuideBasemapEntry = (entry: GuideFloorBasemapEntry | null | undefined) => Boolean(
entry
&& isValidGuideFloorOrthographicProjection(entry.projection)
&& isValidGuideFloorBasemapInitialViewport(entry.initialViewport)
&& Math.abs(
entry.projection!.width / entry.projection!.height
- entry.image.width / entry.image.height
) < 1e-6
&& Boolean(entry.image?.path)
&& isFiniteNumber(entry.image?.width)
&& isFiniteNumber(entry.image?.height)
&& entry.image.width > 0
&& entry.image.height > 0
)
const normalizeFloorReference = (value: unknown) => String(value || '').trim().toUpperCase()
const getCompositeCoverageIdentities = (entry: GuideCompositeBasemapEntry) => {
if (
entry.role !== 'SAME_GROUND_COMPOSITE'
|| !entry.assetId
|| !entry.modelUrl
|| !entry.modelVersion
|| !entry.floorCode
|| !Array.isArray(entry.coverageFloorCodes)
|| !Array.isArray(entry.coverageFloorIds)
|| entry.coverageFloorCodes.length <= 1
|| entry.coverageFloorCodes.length !== entry.coverageFloorIds.length
|| !isValidGuideBasemapEntry(entry)
) return null
const identities = entry.coverageFloorCodes.map((floorCode, index) => new Set([
normalizeFloorReference(floorCode),
normalizeFloorReference(entry.coverageFloorIds[index])
].filter(Boolean)))
return identities.every((identity) => identity.size > 0) ? identities : null
}
export const getGuideFloorBasemapWorldBounds = (
basemap: GuideFloorBasemapEntry | null | undefined
) => {
if (isValidGuideFloorOrthographicProjection(basemap?.projection)) {
const projection = basemap!.projection!
return {
minX: projection.minX,
maxX: projection.maxX,
minZ: projection.minZ,
maxZ: projection.maxZ,
screenRight: projection.screenRight,
screenDown: projection.screenDown,
projectionCenterX: projection.center.x,
projectionCenterZ: projection.center.z,
projectionWidth: projection.width,
projectionHeight: projection.height,
initialVisibleWorldSpan: basemap?.initialViewport?.visibleWorldSpan,
maxVisibleWorldSpan: basemap?.initialViewport?.maxVisibleWorldSpan
}
}
return isValidViewBounds(basemap?.viewBounds) ? basemap!.viewBounds! : null
}
export const findGuideFloorBasemap = (
manifest: GuideFloorBasemapManifest | null | undefined,
floorId: string,
modelVersion?: string
) => {
if (!isCompatibleGuideFloorBasemapManifest(manifest)) return null
const normalizedFloorId = String(floorId || '')
const normalizedVersion = String(modelVersion || '')
return manifest?.floors.find((floor) => (
(String(floor.floorId) === normalizedFloorId || floor.floorCode === normalizedFloorId)
&& (!normalizedVersion || floor.modelVersion === normalizedVersion)
&& isValidGuideBasemapEntry(floor)
)) || null
}
export const findGuideCompositeBasemap = (
manifest: GuideFloorBasemapManifest | null | undefined,
coverageFloorReferences: string[]
) => {
if (!isCompatibleGuideFloorBasemapManifest(manifest)) return null
const routeFloorReferences = Array.from(new Set(
coverageFloorReferences.map(normalizeFloorReference).filter(Boolean)
))
if (routeFloorReferences.length <= 1) return null
return manifest!.routeAssets.find((entry) => {
const identities = getCompositeCoverageIdentities(entry)
if (!identities || identities.length !== routeFloorReferences.length) return false
return routeFloorReferences.every((reference) => (
identities.some((identity) => identity.has(reference))
)) && identities.every((identity) => (
routeFloorReferences.some((reference) => identity.has(reference))
))
}) || null
}
export const getGuideFloorBasemapFrame = (
containerWidth: number,
containerHeight: number,
imageWidth: number,
imageHeight: number,
fit: 'contain' | 'cover' = 'contain'
): GuideFloorBasemapProjectionFrame => {
const safeContainerWidth = Math.max(containerWidth, 1)
const safeContainerHeight = Math.max(containerHeight, 1)
const widthScale = safeContainerWidth / Math.max(imageWidth, 1)
const heightScale = safeContainerHeight / Math.max(imageHeight, 1)
const scale = fit === 'cover'
? Math.max(widthScale, heightScale)
: Math.min(widthScale, heightScale)
const width = imageWidth * scale
const height = imageHeight * scale
return {
width,
height,
offsetX: (safeContainerWidth - width) / 2,
offsetY: (safeContainerHeight - height) / 2
}
}
export const projectPointToGuideFloorBasemap = (
point: GuideFloorBasemapPoint,
basemap: GuideFloorBasemapEntry,
frame: GuideFloorBasemapProjectionFrame
) => {
const projection = basemap.projection
if (isValidGuideFloorOrthographicProjection(projection)) {
const deltaX = point.x - projection!.center.x
const deltaZ = point.z - projection!.center.z
const screenXRatio = 0.5 + (
deltaX * projection!.screenRight.x + deltaZ * projection!.screenRight.z
) / projection!.width
const screenYRatio = 0.5 + (
deltaX * projection!.screenDown.x + deltaZ * projection!.screenDown.z
) / projection!.height
return {
x: frame.offsetX + screenXRatio * frame.width,
y: frame.offsetY + screenYRatio * frame.height
}
}
const camera = basemap.cameraProjection
if (camera && isValidCameraProjection(camera)) {
const position = camera.position
const forward = {
x: camera.target.x - position.x,
y: camera.target.y - position.y,
z: camera.target.z - position.z
}
const forwardLength = Math.hypot(forward.x, forward.y, forward.z) || 1
forward.x /= forwardLength
forward.y /= forwardLength
forward.z /= forwardLength
const right = {
x: forward.y * camera.up.z - forward.z * camera.up.y,
y: forward.z * camera.up.x - forward.x * camera.up.z,
z: forward.x * camera.up.y - forward.y * camera.up.x
}
const rightLength = Math.hypot(right.x, right.y, right.z) || 1
right.x /= rightLength
right.y /= rightLength
right.z /= rightLength
const screenUp = {
x: right.y * forward.z - right.z * forward.y,
y: right.z * forward.x - right.x * forward.z,
z: right.x * forward.y - right.y * forward.x
}
const pointY = point.y || 0
const relative = {
x: point.x - position.x,
y: pointY - position.y,
z: point.z - position.z
}
const depth = relative.x * forward.x + relative.y * forward.y + relative.z * forward.z
const safeDepth = Math.max(depth, 0.001)
const tangent = Math.tan((camera.fov * Math.PI) / 360)
const ndcX = (relative.x * right.x + relative.y * right.y + relative.z * right.z)
/ (safeDepth * tangent * camera.aspect)
const ndcY = (relative.x * screenUp.x + relative.y * screenUp.y + relative.z * screenUp.z)
/ (safeDepth * tangent)
return {
x: frame.offsetX + ((ndcX + 1) / 2) * frame.width,
y: frame.offsetY + ((1 - ndcY) / 2) * frame.height
}
}
const bounds = basemap.viewBounds
if (!bounds) {
return {
x: frame.offsetX + frame.width / 2,
y: frame.offsetY + frame.height / 2
}
}
const xRatio = (point.x - bounds.minX) / (bounds.maxX - bounds.minX)
const zRatio = (point.z - bounds.minZ) / (bounds.maxZ - bounds.minZ)
const screenXRatio = bounds.screenXAxis === '+X' ? xRatio : 1 - xRatio
const screenYRatio = bounds.screenYAxis === '-Z' ? 1 - zRatio : zRatio
return {
x: frame.offsetX + screenXRatio * frame.width,
y: frame.offsetY + screenYRatio * frame.height
}
}
export const unprojectGuideFloorBasemapPoint = (
point: { x: number; y: number },
basemap: GuideFloorBasemapEntry,
frame: GuideFloorBasemapProjectionFrame
) => {
const projection = basemap.projection
if (isValidGuideFloorOrthographicProjection(projection)) {
const screenXRatio = (point.x - frame.offsetX) / Math.max(frame.width, 1)
const screenYRatio = (point.y - frame.offsetY) / Math.max(frame.height, 1)
const right = (screenXRatio - 0.5) * projection!.width
const down = (screenYRatio - 0.5) * projection!.height
return {
x: projection!.center.x
+ right * projection!.screenRight.x
+ down * projection!.screenDown.x,
z: projection!.center.z
+ right * projection!.screenRight.z
+ down * projection!.screenDown.z
}
}
const camera = basemap.cameraProjection
if (camera && isValidCameraProjection(camera)) {
const forward = {
x: camera.target.x - camera.position.x,
y: camera.target.y - camera.position.y,
z: camera.target.z - camera.position.z
}
const forwardLength = Math.hypot(forward.x, forward.y, forward.z) || 1
forward.x /= forwardLength
forward.y /= forwardLength
forward.z /= forwardLength
const right = {
x: forward.y * camera.up.z - forward.z * camera.up.y,
y: forward.z * camera.up.x - forward.x * camera.up.z,
z: forward.x * camera.up.y - forward.y * camera.up.x
}
const rightLength = Math.hypot(right.x, right.y, right.z) || 1
right.x /= rightLength
right.y /= rightLength
right.z /= rightLength
const screenUp = {
x: right.y * forward.z - right.z * forward.y,
y: right.z * forward.x - right.x * forward.z,
z: right.x * forward.y - right.y * forward.x
}
const ndcX = ((point.x - frame.offsetX) / Math.max(frame.width, 1)) * 2 - 1
const ndcY = 1 - ((point.y - frame.offsetY) / Math.max(frame.height, 1)) * 2
const tangent = Math.tan((camera.fov * Math.PI) / 360)
const direction = {
x: forward.x + right.x * ndcX * tangent * camera.aspect + screenUp.x * ndcY * tangent,
y: forward.y + right.y * ndcX * tangent * camera.aspect + screenUp.y * ndcY * tangent,
z: forward.z + right.z * ndcX * tangent * camera.aspect + screenUp.z * ndcY * tangent
}
const directionLength = Math.hypot(direction.x, direction.y, direction.z) || 1
direction.x /= directionLength
direction.y /= directionLength
direction.z /= directionLength
const planeY = camera.target.y
const distance = Math.abs(direction.y) > 1e-6
? (planeY - camera.position.y) / direction.y
: 0
return {
x: camera.position.x + direction.x * distance,
z: camera.position.z + direction.z * distance
}
}
const bounds = basemap.viewBounds
if (!bounds) return { x: 0, z: 0 }
const screenXRatio = (point.x - frame.offsetX) / Math.max(frame.width, 1)
const screenYRatio = (point.y - frame.offsetY) / Math.max(frame.height, 1)
const xRatio = bounds.screenXAxis === '+X' ? screenXRatio : 1 - screenXRatio
const zRatio = bounds.screenYAxis === '-Z' ? 1 - screenYRatio : screenYRatio
return {
x: bounds.minX + xRatio * (bounds.maxX - bounds.minX),
z: bounds.minZ + zRatio * (bounds.maxZ - bounds.minZ)
}
}
export const loadGuideFloorBasemapManifest = async () => {
if (manifestPromise) return manifestPromise
if (typeof fetch !== 'function') return null
const request = fetch(GUIDE_FLOOR_BASEMAP_MANIFEST_URL, { cache: 'no-cache' })
.then(async (response) => {
if (!response.ok) return null
const manifest = await response.json() as GuideFloorBasemapManifest
return isCompatibleGuideFloorBasemapManifest(manifest) ? manifest : null
})
.catch(() => null)
manifestPromise = request
const manifest = await request
if (!manifest && manifestPromise === request) manifestPromise = null
return manifest
}
export const resetGuideFloorBasemapManifestCacheForTests = () => {
manifestPromise = null
}

View File

@@ -1,5 +1,9 @@
import * as THREE from 'three'
import type { GLTF } from 'three/addons/loaders/GLTFLoader.js'
import {
recordGuidePerformance,
startGuidePerformance
} from '@/services/performance/guidePerformance'
export interface GuideModelResourceSet {
geometries: Set<THREE.BufferGeometry>
@@ -357,6 +361,14 @@ export class GuideModelLoadManager {
if (cached) {
cached.lastUsedAt = Date.now()
this.diagnostics.hits += 1
recordGuidePerformance({
kind: 'model',
name: options.label,
startedAt: getNow(),
durationMs: 0,
outcome: 'cache-hit',
detail: { url, key }
})
logModelDiagnostic('cache-hit', {
label: options.label,
url,
@@ -376,8 +388,17 @@ export class GuideModelLoadManager {
let inFlight = this.inFlightCache.get(key)
const startedAt = getNow()
let finishPerformance: ReturnType<typeof startGuidePerformance> | null = null
if (inFlight) {
this.diagnostics.inFlightHits += 1
recordGuidePerformance({
kind: 'model',
name: options.label,
startedAt,
durationMs: 0,
outcome: 'cache-hit',
detail: { url, key, layer: 'in-flight' }
})
logModelDiagnostic('in-flight-hit', {
label: options.label,
url,
@@ -385,6 +406,7 @@ export class GuideModelLoadManager {
diagnostics: this.getDiagnostics()
})
} else {
finishPerformance = startGuidePerformance('model', options.label, { url, key })
logModelDiagnostic('load-start', {
label: options.label,
url,
@@ -398,6 +420,9 @@ export class GuideModelLoadManager {
try {
gltf = await inFlight
} catch (error) {
finishPerformance?.('failure', {
error: error instanceof Error ? error.message : String(error)
})
logModelDiagnostic('load-failed', {
label: options.label,
url,
@@ -420,6 +445,9 @@ export class GuideModelLoadManager {
}
this.sourceCache.set(key, entry)
this.trim()
finishPerformance?.('success', {
sourceEntries: this.sourceCache.size
})
logModelDiagnostic('load-complete', {
label: options.label,
url,

View File

@@ -0,0 +1,147 @@
const CACHE_NAME = 'sgs-guide-model-v1'
const INDEX_STORAGE_KEY = 'sgs.guide.model-cache-index.v1'
const MAX_ENTRIES = 6
interface CacheIndexEntry {
key: string
touchedAt: number
}
export interface PersistentModelAsset {
url: string
release: () => void
}
const getCacheStorage = () => (
typeof globalThis !== 'undefined' && 'caches' in globalThis
? globalThis.caches
: null
)
const getStorage = () => (
typeof localStorage !== 'undefined' ? localStorage : null
)
const buildCacheKey = (url: string, version?: string) => {
const normalizedUrl = url.trim()
const normalizedVersion = version?.trim() || normalizedUrl
const separator = normalizedUrl.includes('?') ? '&' : '?'
return `${normalizedUrl}${separator}__sgs_model_version=${encodeURIComponent(normalizedVersion)}`
}
const readIndex = (): CacheIndexEntry[] => {
try {
const raw = getStorage()?.getItem(INDEX_STORAGE_KEY)
const parsed = raw ? JSON.parse(raw) : []
return Array.isArray(parsed)
? parsed.filter((entry): entry is CacheIndexEntry => (
Boolean(entry)
&& typeof entry.key === 'string'
&& typeof entry.touchedAt === 'number'
))
: []
} catch {
return []
}
}
const writeIndex = (entries: CacheIndexEntry[]) => {
try {
getStorage()?.setItem(INDEX_STORAGE_KEY, JSON.stringify(entries))
} catch {
// Persistent cache is an optimization. Storage quota failures must not block map loading.
}
}
const touchIndex = (key: string) => {
const now = Date.now()
const next = readIndex()
.filter((entry) => entry.key !== key)
next.push({ key, touchedAt: now })
writeIndex(next)
return next
}
const removeFromIndex = (key: string) => {
writeIndex(readIndex().filter((entry) => entry.key !== key))
}
export class GuideModelPersistentCache {
async get(url: string, version?: string): Promise<PersistentModelAsset | null> {
const cacheStorage = getCacheStorage()
if (!cacheStorage || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') return null
const key = buildCacheKey(url, version)
try {
const cache = await cacheStorage.open(CACHE_NAME)
const response = await cache.match(key)
if (!response) return null
const blob = await response.blob()
if (!blob.size) {
await cache.delete(key)
removeFromIndex(key)
return null
}
touchIndex(key)
const objectUrl = URL.createObjectURL(blob)
return {
url: objectUrl,
release: () => URL.revokeObjectURL(objectUrl)
}
} catch {
return null
}
}
async store(url: string, version?: string): Promise<void> {
const cacheStorage = getCacheStorage()
if (!cacheStorage || typeof fetch !== 'function') return
const key = buildCacheKey(url, version)
try {
const cache = await cacheStorage.open(CACHE_NAME)
if (await cache.match(key)) {
await this.prune(cache, touchIndex(key))
return
}
// The preceding GLTF request is normally still in the browser HTTP cache, so this does
// not redownload a successful asset on standard H5 browsers.
const response = await fetch(url, { cache: 'force-cache' })
if (!response.ok || !response.body) return
await cache.put(key, response)
await this.prune(cache, touchIndex(key))
} catch {
// Cache writes are deliberately best-effort.
}
}
async remove(url: string, version?: string): Promise<void> {
const cacheStorage = getCacheStorage()
if (!cacheStorage) return
const key = buildCacheKey(url, version)
try {
const cache = await cacheStorage.open(CACHE_NAME)
await cache.delete(key)
} catch {
// Ignore cache cleanup failures and continue with a normal network request.
}
removeFromIndex(key)
}
private async prune(cache: Cache, entries: CacheIndexEntry[]) {
const staleEntries = [...entries]
.sort((left, right) => left.touchedAt - right.touchedAt)
.slice(0, Math.max(0, entries.length - MAX_ENTRIES))
if (!staleEntries.length) return
await Promise.all(staleEntries.map((entry) => cache.delete(entry.key)))
const staleKeys = new Set(staleEntries.map((entry) => entry.key))
writeIndex(entries.filter((entry) => !staleKeys.has(entry.key)))
}
}
export const guideModelPersistentCache = new GuideModelPersistentCache()