feat: add aperture mouth candidate and early foreground permissions
Route runtime04 curve values to five source-frame lip geometries with level0 body bypass and spatial opacity1 for all other levels. Preserve the continuous decoded body clock and clean home. Request normal permissions after foreground host layout independently of network; support offline manual consent without capture or connection. Add strict 97x5 parsing, renderer and permission regressions, offline EGL shader pixel goldens and exact debug-candidate packaging. Naturalness, visible talk, device colors and perceived response remain pending.
This commit is contained in:
+11
-3
@@ -16,6 +16,10 @@ def mediaPipeVersion = expressionVersions.getProperty('mediapipe.version')
|
||||
def avatarEngineering = providers.gradleProperty('avatarEngineering').orNull == 'true'
|
||||
def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true'
|
||||
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
|
||||
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
|
||||
if (avatarMouthCandidate && (!avatarNatural || avatarUiCandidate)) {
|
||||
throw new GradleException('Mouth candidate requires natural runtime and a distinct version from UI-only')
|
||||
}
|
||||
if (avatarUiCandidate && !avatarNatural) {
|
||||
throw new GradleException('UI candidate requires the pinned natural debug runtime')
|
||||
}
|
||||
@@ -54,6 +58,7 @@ def packagedAssets = layout.buildDirectory.dir('generated/packagedAssets')
|
||||
def stagePackagedAssets = tasks.register('stagePackagedAssets', Sync) {
|
||||
from('src/main/assets')
|
||||
exclude 'avatar/a01-v1/**', 'avatar/a01-standing-v2/**'
|
||||
if (!avatarMouthCandidate) exclude 'avatar/a01-neutral-graph-v1/runtime-04/**'
|
||||
into(packagedAssets)
|
||||
}
|
||||
|
||||
@@ -65,8 +70,8 @@ android {
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
|
||||
versionCode avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)
|
||||
versionName avatarUiCandidate ? '0.6.2' : '0.6.1'
|
||||
versionCode avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12))
|
||||
versionName = (avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
@@ -74,16 +79,19 @@ android {
|
||||
buildFeatures { compose true; buildConfig true }
|
||||
buildTypes {
|
||||
debug {
|
||||
if (avatarUiCandidate) versionNameSuffix '-ui-dev'
|
||||
if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
|
||||
else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
|
||||
else if (avatarNatural) versionNameSuffix '-natural-dev'
|
||||
else if (avatarEngineering) versionNameSuffix '-dev'
|
||||
buildConfigField 'boolean', 'AVATAR_ENGINEERING', (avatarEngineering || avatarNatural) ? 'true' : 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_NATURAL', avatarNatural ? 'true' : 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', avatarMouthCandidate ? 'true' : 'false'
|
||||
buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '"' + (avatarNatural ? naturalManifestSha : '') + '"'
|
||||
}
|
||||
release {
|
||||
buildConfigField 'boolean', 'AVATAR_ENGINEERING', 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_NATURAL', 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', 'false'
|
||||
buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '""'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,9 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
|
||||
check(checkNotNull(gear()).performAction(AccessibilityNodeInfo.ACTION_CLICK))
|
||||
await { nodes().any { it.text?.toString()=="关闭" } }
|
||||
check(nodes().any { it.text?.toString()?.contains("离线 avatar")==true })
|
||||
check(nodes().any { it.text?.toString()?.contains("嘴层沿用 runtime03")==true })
|
||||
val version=targetContext.packageManager.getPackageInfo(targetContext.packageName,0).versionName
|
||||
val candidate=if(version=="0.6.2-mouth-dev") "嘴部工程候选" else "嘴层沿用 runtime03"
|
||||
check(nodes().any { it.text?.toString()?.contains(candidate)==true })
|
||||
check(nodes().first { it.text?.toString()=="关闭" }.performAction(AccessibilityNodeInfo.ACTION_CLICK))
|
||||
await { nodes().none { it.text?.toString()=="关闭" } && gear()!=null }
|
||||
assertClean()
|
||||
|
||||
@@ -48,6 +48,9 @@ class MainActivity : ComponentActivity() {
|
||||
private var permissionMessage by mutableStateOf<String?>(null)
|
||||
private var micSettings by mutableStateOf(false)
|
||||
private var cameraSettings by mutableStateOf(false)
|
||||
private var micGranted by mutableStateOf(false)
|
||||
private var cameraGranted by mutableStateOf(false)
|
||||
private var permissionPending by mutableStateOf<EntryPermission?>(null)
|
||||
private val main = android.os.Handler(android.os.Looper.getMainLooper())
|
||||
private val pump = Runnable { advanceEntry() }
|
||||
private val retryTimer = Runnable { advanceEntry() }
|
||||
@@ -65,11 +68,11 @@ class MainActivity : ComponentActivity() {
|
||||
private fun granted(permission: String) = checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
||||
private fun preferences() = getSharedPreferences("entry-permissions", MODE_PRIVATE)
|
||||
private fun permissionResult(permission: EntryPermission, granted: Boolean) {
|
||||
if (!::entry.isInitialized || isDestroyed) return
|
||||
if (!::entry.isInitialized || isDestroyed || entry.permissionPending!=permission) return
|
||||
DebugLogUpload.log("audio", "permission=${permission.name.lowercase()} granted=$granted foreground=$inForeground")
|
||||
entry.permissionResult(permission, granted)
|
||||
if (permission == EntryPermission.CAMERA && !granted) preferences().edit().putBoolean("cameraWanted", false).apply()
|
||||
if (!granted) {
|
||||
if (!granted && !offlineAvatarPreview) {
|
||||
if (permission == EntryPermission.MICROPHONE) session.permissionDenied()
|
||||
else expressions.permissionDenied()
|
||||
}
|
||||
@@ -81,12 +84,21 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
private fun advanceEntry() {
|
||||
if (!::entry.isInitialized || isDestroyed) return
|
||||
// First consent is after the foreground Compose host has a stable layout,
|
||||
// independent of health/WS/HELLO. No request originates from recomposition.
|
||||
if(inForeground && (!window.decorView.isAttachedToWindow || !window.decorView.isLaidOut)) {
|
||||
window.decorView.postOnAnimation { if(inForeground && !isDestroyed) scheduleEntry() }
|
||||
return
|
||||
}
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
micGranted=granted(Manifest.permission.RECORD_AUDIO)
|
||||
cameraGranted=granted(Manifest.permission.CAMERA)
|
||||
micSettings = !granted(Manifest.permission.RECORD_AUDIO) && preferences().getBoolean("micAsked", false) &&
|
||||
!shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)
|
||||
cameraSettings = !granted(Manifest.permission.CAMERA) && preferences().getBoolean("camAsked", false) &&
|
||||
!shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)
|
||||
val actions = entry.drive(granted(Manifest.permission.RECORD_AUDIO), granted(Manifest.permission.CAMERA), state.voiceActive, now)
|
||||
permissionPending=entry.permissionPending
|
||||
entryPhase = entry.phase
|
||||
permissionMessage = when {
|
||||
!granted(Manifest.permission.RECORD_AUDIO) -> "需要麦克风权限才能对话" + if (micSettings) " · 请在应用设置中开启" else ""
|
||||
@@ -96,9 +108,9 @@ class MainActivity : ComponentActivity() {
|
||||
main.removeCallbacks(retryTimer)
|
||||
entry.retryAtMs?.takeIf { inForeground }?.let { main.postDelayed(retryTimer, (it - now).coerceAtLeast(1)) }
|
||||
for (action in actions) when (action) {
|
||||
EntryEffect.Connect -> session.dial()
|
||||
EntryEffect.StartVoice -> session.startVoice(microphoneMuted = preferences().getBoolean("microphoneMuted", false))
|
||||
EntryEffect.StartCamera -> if (inForeground && granted(Manifest.permission.CAMERA)) expressions.start()
|
||||
EntryEffect.Connect -> if(!offlineAvatarPreview && inForeground) session.dial()
|
||||
EntryEffect.StartVoice -> if(!offlineAvatarPreview && inForeground && micGranted && state.connection==ConnectionStatus.CONNECTED) session.startVoice(microphoneMuted = preferences().getBoolean("microphoneMuted", false))
|
||||
EntryEffect.StartCamera -> if (!offlineAvatarPreview && inForeground && cameraGranted) expressions.start()
|
||||
is EntryEffect.RequestPermission -> {
|
||||
val mic = action.permission == EntryPermission.MICROPHONE
|
||||
preferences().edit().putBoolean(if (mic) "micAsked" else "camAsked", true).apply()
|
||||
@@ -112,10 +124,15 @@ class MainActivity : ComponentActivity() {
|
||||
android.net.Uri.parse("package:$packageName")))
|
||||
}
|
||||
private fun authorizeMicrophone() {
|
||||
if (!inForeground || state.connection != ConnectionStatus.CONNECTED || entry.permissionPending != null) return
|
||||
if (!inForeground || granted(Manifest.permission.RECORD_AUDIO) || entry.permissionPending != null) return
|
||||
if (micSettings) openSettings()
|
||||
else if (entry.requestPermission(EntryPermission.MICROPHONE, false)) scheduleEntry()
|
||||
}
|
||||
private fun authorizeCamera() {
|
||||
if(!inForeground || granted(Manifest.permission.CAMERA) || entry.permissionPending!=null) return
|
||||
if(cameraSettings) openSettings()
|
||||
else if(entry.requestPermission(EntryPermission.CAMERA,false)) scheduleEntry()
|
||||
}
|
||||
private fun retryConnection() {
|
||||
if (entry.retry(android.os.SystemClock.elapsedRealtime())) {
|
||||
session.resetConnection()
|
||||
@@ -134,8 +151,11 @@ class MainActivity : ComponentActivity() {
|
||||
offlineAvatarPreview = BuildConfig.DEBUG && BuildConfig.AVATAR_ENGINEERING && intent.getBooleanExtra(OfflineAvatarTrace.EXTRA,false)
|
||||
if (offlineAvatarPreview) {
|
||||
avatarPack = AvatarPack.load(this)
|
||||
setContent { EngineeringPreviewScreen(avatarPack) }
|
||||
return // No VoiceSession, audio focus, permission launchers or camera controller.
|
||||
entry=AutoConversation(preferences().getBoolean("micAsked",false),preferences().getBoolean("camAsked",false),
|
||||
conversationEnabled=false,automaticPermissions=false)
|
||||
setContent { EngineeringPreviewScreen(avatarPack,micGranted,cameraGranted,micSettings,cameraSettings,
|
||||
permissionPending,::authorizeMicrophone,::authorizeCamera) }
|
||||
return // No VoiceSession/audio focus/camera controller; manual permission consent only.
|
||||
}
|
||||
audioOutput = AudioOutputGate(this) { session.outputUnavailable("播放被系统音频占用打断,请重新开始") }
|
||||
DebugLogUpload.appLaunch(
|
||||
@@ -172,6 +192,7 @@ class MainActivity : ComponentActivity() {
|
||||
session.setMicrophoneMuted(muted) }, ::toggleExpressions,
|
||||
expressionState, shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
|
||||
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt,
|
||||
micGranted,cameraGranted,permissionPending,::authorizeCamera,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -212,7 +233,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun toggleExpressions() {
|
||||
if (!inForeground || state.connection != ConnectionStatus.CONNECTED || entry.permissionPending != null) return
|
||||
if (!inForeground || entry.permissionPending != null) return
|
||||
val running = expressionState.status in setOf(ExpressionStatus.STARTING, ExpressionStatus.ACTIVE)
|
||||
if (running) { preferences().edit().putBoolean("cameraWanted", false).apply(); entry.cameraOff(); closeCamera() }
|
||||
else if (granted(Manifest.permission.CAMERA)) { preferences().edit().putBoolean("cameraWanted", true).apply(); entry.cameraOn(); scheduleEntry() }
|
||||
@@ -230,18 +251,17 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (offlineAvatarPreview) return
|
||||
inForeground = true
|
||||
entry.enter()
|
||||
// The pure coordinator owns bounded connection attempts. No automatic listen here.
|
||||
session.foreground(connectAutomatically = false)
|
||||
if(!offlineAvatarPreview) session.foreground(connectAutomatically = false)
|
||||
scheduleEntry()
|
||||
}
|
||||
override fun onPause() {
|
||||
if (offlineAvatarPreview) { super.onPause(); return }
|
||||
inForeground = false
|
||||
entry.leave()
|
||||
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
|
||||
if (offlineAvatarPreview) { super.onPause(); return }
|
||||
closeCamera()
|
||||
// Permission windows can pause/stop the Activity. No sensors survive this pause;
|
||||
// retain only the fenced connection continuation, bounded by VoiceSession's timeout.
|
||||
@@ -257,8 +277,8 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (offlineAvatarPreview) { super.onDestroy(); return }
|
||||
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
|
||||
if (offlineAvatarPreview) { super.onDestroy(); return }
|
||||
DebugLogUpload.log("audio", "camera stop reason=release")
|
||||
expressions.release()
|
||||
DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations")
|
||||
|
||||
@@ -11,7 +11,8 @@ sealed interface EntryEffect {
|
||||
data object StartCamera : EntryEffect
|
||||
}
|
||||
class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean = false,
|
||||
cameraInitiallyWanted: Boolean = true, private val retryDelaysMs: List<Long> = listOf(1_000, 3_000)) {
|
||||
cameraInitiallyWanted: Boolean = true, private val retryDelaysMs: List<Long> = listOf(1_000, 3_000),
|
||||
private val conversationEnabled: Boolean = true, automaticPermissions: Boolean = true) {
|
||||
init { require(retryDelaysMs.size <= 4 && retryDelaysMs.all { it in 500..30_000 }) }
|
||||
var phase = EntryPhase.CONNECTING; private set
|
||||
var permissionPending: EntryPermission? = null; private set
|
||||
@@ -26,8 +27,8 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
|
||||
private var startIssued = false
|
||||
private var cameraIssued = false
|
||||
private var cycleStarted = false
|
||||
private var autoMicAllowed = !microphoneAsked
|
||||
private var autoCamAllowed = !cameraAsked
|
||||
private var autoMicAllowed = automaticPermissions && !microphoneAsked
|
||||
private var autoCamAllowed = automaticPermissions && !cameraAsked
|
||||
private var manualPermission: EntryPermission? = null
|
||||
|
||||
fun enter() {
|
||||
@@ -52,13 +53,13 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
|
||||
if (inProgress) phase = EntryPhase.CONNECTING
|
||||
}
|
||||
fun retry(nowMs: Long): Boolean {
|
||||
if (!foreground || permissionPending != null || connecting || retryAtMs?.let { nowMs < it } == true) return false
|
||||
if (!conversationEnabled || !foreground || permissionPending != null || connecting || retryAtMs?.let { nowMs < it } == true) return false
|
||||
attempts = 0; retryAtMs = null; connected = false; cycleStarted = true
|
||||
startIssued = false; cameraIssued = false
|
||||
return true
|
||||
}
|
||||
fun requestPermission(permission: EntryPermission, permanentlyDenied: Boolean): Boolean {
|
||||
if (!foreground || !connected || permissionPending != null || permanentlyDenied) return false
|
||||
if (!foreground || permissionPending != null || manualPermission != null || permanentlyDenied) return false
|
||||
manualPermission = permission
|
||||
if (permission == EntryPermission.CAMERA) cameraWanted = true
|
||||
return true
|
||||
@@ -74,21 +75,8 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
|
||||
fun drive(microphoneGranted: Boolean, cameraGranted: Boolean, voiceActive: Boolean,
|
||||
nowMs: Long): List<EntryEffect> {
|
||||
if (!foreground) return emptyList()
|
||||
if (!connected) {
|
||||
if (connecting) { phase = EntryPhase.CONNECTING; return emptyList() }
|
||||
val due = attempts == 0 || retryAtMs?.let { nowMs >= it } == true
|
||||
if (!due) { phase = EntryPhase.ERROR; return emptyList() }
|
||||
attempts++; retryAtMs = null; connecting = true; phase = EntryPhase.CONNECTING
|
||||
return listOf(EntryEffect.Connect)
|
||||
}
|
||||
val actions = mutableListOf<EntryEffect>()
|
||||
// Voice starts as soon as MIC is granted; video and CAMERA readiness are independent.
|
||||
if (microphoneGranted && !voiceActive && !startIssued) {
|
||||
startIssued = true; actions += EntryEffect.StartVoice
|
||||
}
|
||||
if (cameraGranted && cameraWanted && !cameraIssued) {
|
||||
cameraIssued = true; actions += EntryEffect.StartCamera
|
||||
}
|
||||
// Permission consent is foreground/UI driven, independent of network/HELLO.
|
||||
if (permissionPending == null) {
|
||||
val ask = manualPermission ?: when {
|
||||
!microphoneGranted && autoMicAllowed -> EntryPermission.MICROPHONE
|
||||
@@ -96,13 +84,38 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
|
||||
else -> null
|
||||
}
|
||||
manualPermission = null
|
||||
if (ask != null) {
|
||||
val alreadyGranted=when(ask) {
|
||||
EntryPermission.MICROPHONE -> microphoneGranted
|
||||
EntryPermission.CAMERA -> cameraGranted
|
||||
null -> true
|
||||
}
|
||||
if (ask != null && !alreadyGranted) {
|
||||
permissionPending = ask
|
||||
if (ask == EntryPermission.MICROPHONE) { micAsked = true; autoMicAllowed = false }
|
||||
else { camAsked = true; autoCamAllowed = false }
|
||||
actions += EntryEffect.RequestPermission(ask)
|
||||
}
|
||||
}
|
||||
// Offline preview permits explicit consent only, never transport or sensors.
|
||||
if (!conversationEnabled) {
|
||||
phase=if(permissionPending!=null) EntryPhase.AWAITING_PERMISSION else EntryPhase.ACTIVE
|
||||
return actions
|
||||
}
|
||||
if (permissionPending==null && cameraGranted && cameraWanted && !cameraIssued) {
|
||||
cameraIssued=true;actions+=EntryEffect.StartCamera
|
||||
}
|
||||
if (!connected) {
|
||||
if (connecting) { phase=EntryPhase.CONNECTING;return actions }
|
||||
val due=attempts==0 || retryAtMs?.let { nowMs>=it }==true
|
||||
if (!due) { phase=EntryPhase.ERROR;return actions }
|
||||
attempts++;retryAtMs=null;connecting=true;phase=EntryPhase.CONNECTING
|
||||
actions+=EntryEffect.Connect
|
||||
return actions
|
||||
}
|
||||
// Consent does not start uplink: MIC, real HELLO and actual foreground are required.
|
||||
if (permissionPending==null && microphoneGranted && !voiceActive && !startIssued) {
|
||||
startIssued=true;actions+=EntryEffect.StartVoice
|
||||
}
|
||||
phase = when {
|
||||
!microphoneGranted -> EntryPhase.AWAITING_PERMISSION
|
||||
voiceActive -> EntryPhase.ACTIVE
|
||||
|
||||
@@ -22,15 +22,17 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
|
||||
catch (_: Exception) { return null }
|
||||
val static = AvatarPack(fallback=fallback)
|
||||
if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try {
|
||||
val root=MOTION_ROOT+"runtime-03/"
|
||||
val root=MOTION_ROOT+(if(BuildConfig.AVATAR_MOUTH_CANDIDATE) "runtime-04/" else "runtime-03/")
|
||||
val raw=read(context,root+"manifest.json",512_000)
|
||||
val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(raw,Charsets.UTF_8))),sha(raw),
|
||||
BuildConfig.NATURAL_MANIFEST_SHA,true,root))
|
||||
check(runtime.apertureMode==BuildConfig.AVATAR_MOUTH_CANDIDATE)
|
||||
check(sha(read(context,root+runtime.body.path,16_000_000))==runtime.body.sha256)
|
||||
for (patch in runtime.patches) {
|
||||
check(sha(read(context,root+patch.path,256_000))==patch.sha256)
|
||||
for ((index,image) in runtime.textureImages.withIndex()) {
|
||||
val patch=runtime.patches[index/(if(runtime.apertureMode) 5 else 1)]
|
||||
check(sha(read(context,root+image.path,256_000))==image.sha256)
|
||||
val options=android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds=true }
|
||||
val bytes=read(context,root+patch.path,256_000)
|
||||
val bytes=read(context,root+image.path,256_000)
|
||||
android.graphics.BitmapFactory.decodeByteArray(bytes,0,bytes.size,options)
|
||||
check(options.outWidth==patch.width && options.outHeight==patch.height)
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
||||
pack: AvatarPack?,onRetry: ()->Unit,onAuthorizeMic: ()->Unit,onMute: ()->Unit,onCamera: ()->Unit,
|
||||
expression: ExpressionUiState,shareFace: Boolean,onShare: (Boolean)->Unit,
|
||||
logs: List<String>,onReport: ()->Unit,reportSending: Boolean,reportResult: String?,onInterrupt: ()->Unit,
|
||||
micGranted: Boolean,cameraGranted: Boolean,permissionPending: EntryPermission?,onAuthorizeCamera: ()->Unit,
|
||||
) {
|
||||
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity)
|
||||
val latestAvatar by rememberUpdatedState(avatar)
|
||||
@@ -107,13 +108,13 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
||||
Text("麦克风:${if(state.voiceActive && !state.microphoneMuted && state.phase==VoicePhase.LISTENING) "正在收音" else "未收音"} · 相机:${when(expression.status) { ExpressionStatus.ACTIVE -> "开启";ExpressionStatus.STARTING -> "启动中";ExpressionStatus.UNAVAILABLE -> "不可用";else -> "关闭" }}",fontSize=13.sp)
|
||||
TextButton(onClick=onRetry) { Text("重试连接") }
|
||||
permissionMessage?.let { Text(it,fontSize=13.sp) }
|
||||
if(entry==EntryPhase.AWAITING_PERMISSION) TextButton(onClick=onAuthorizeMic) { Text(if(micSettings) "打开麦克风权限设置" else "允许麦克风") }
|
||||
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
|
||||
state.guidance?.let { Text(it,fontSize=13.sp) }
|
||||
Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.spacedBy(12.dp)) {
|
||||
Button(onClick=onMute,enabled=state.voiceActive,modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
|
||||
Text(if(state.microphoneMuted) "恢复收音" else "暂停收音")
|
||||
}
|
||||
OutlinedButton(onClick=onCamera,enabled=state.connection==com.gorios.lanvoice.net.ConnectionStatus.CONNECTED,
|
||||
OutlinedButton(onClick=onCamera,
|
||||
modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
|
||||
Text(if(expression.status in setOf(ExpressionStatus.ACTIVE,ExpressionStatus.STARTING)) "关闭相机" else if(cameraSettings) "相机权限设置" else "开启相机")
|
||||
}
|
||||
@@ -135,10 +136,25 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
||||
})
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PermissionSettings(micGranted: Boolean,cameraGranted: Boolean,micSettings: Boolean,cameraSettings: Boolean,
|
||||
pending: EntryPermission?,onMic: ()->Unit,onCamera: ()->Unit) {
|
||||
Text("麦克风权限:${if(micGranted) "已授权" else "未授权"} · 摄像头权限:${if(cameraGranted) "已授权" else "未授权"}",fontSize=13.sp)
|
||||
if(pending!=null) Text("正在申请${if(pending==EntryPermission.MICROPHONE) "麦克风" else "摄像头"}权限",fontSize=12.sp)
|
||||
if(micSettings || cameraSettings) Text("权限已关闭或不再询问,可打开应用系统权限设置后手动开启",fontSize=12.sp)
|
||||
TextButton(onClick=onMic,enabled=!micGranted && pending==null) {
|
||||
Text(if(micGranted) "麦克风已授权" else if(micSettings) "打开麦克风系统权限设置" else "申请麦克风权限")
|
||||
}
|
||||
TextButton(onClick=onCamera,enabled=!cameraGranted && pending==null) {
|
||||
Text(if(cameraGranted) "摄像头已授权" else if(cameraSettings) "打开摄像头系统权限设置" else "申请摄像头权限")
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AvatarDiagnostics(pack: AvatarPack?,video: VideoPresentation) {
|
||||
if(BuildConfig.AVATAR_ENGINEERING) Text("工程候选:自然度待验",color=Color(0xFF94652D),fontSize=13.sp)
|
||||
if(BuildConfig.VERSION_NAME=="0.6.2-ui-dev") Text("本版仅修复界面;嘴层沿用 runtime03,变形问题尚未修复",fontSize=13.sp)
|
||||
if(BuildConfig.VERSION_NAME=="0.6.2-mouth-dev") Text("嘴部工程候选:源帧自身嘴形五档微动;阶梯感、可见性及变形改善待真机验证",fontSize=13.sp)
|
||||
Text("画面:${video.clipId} / ${video.reason}",fontSize=12.sp)
|
||||
Text("相位等待 ${video.waitMs}ms · 首帧 ${video.firstFrameMs ?: "未知"}ms",fontSize=12.sp)
|
||||
Text("口部活动延后 ${video.mouthActiveLagMs ?: "未知"}ms · 稳定闭嘴延后 ${video.closingLagMs ?: "未知"}ms",fontSize=12.sp)
|
||||
@@ -148,7 +164,8 @@ private fun AvatarDiagnostics(pack: AvatarPack?,video: VideoPresentation) {
|
||||
|
||||
/** Sensor-free synthetic intents, same real renderer and same clean home. */
|
||||
@Composable
|
||||
fun EngineeringPreviewScreen(pack: AvatarPack?) {
|
||||
fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted: Boolean,micSettings: Boolean,cameraSettings: Boolean,
|
||||
permissionPending: EntryPermission?,onAuthorizeMic: ()->Unit,onAuthorizeCamera: ()->Unit) {
|
||||
val activity=LocalContext.current as ComponentActivity
|
||||
var resumed by remember { mutableStateOf(activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) }
|
||||
var trace by remember { mutableStateOf(OfflineAvatarTrace.at(0)) }
|
||||
@@ -172,7 +189,9 @@ fun EngineeringPreviewScreen(pack: AvatarPack?) {
|
||||
CleanAvatarScaffold(avatar={
|
||||
AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize()) { video=it }
|
||||
},settings={
|
||||
Text("离线 avatar · 无连接 / 无麦克风 / 无相机",fontSize=13.sp)
|
||||
Text("离线 avatar · 无连接 / 不录音 / 不采集相机",fontSize=13.sp)
|
||||
Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp)
|
||||
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
|
||||
Text("合成意图:${override?.name ?: trace.label}",fontSize=12.sp)
|
||||
AvatarDiagnostics(pack,video)
|
||||
Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
|
||||
data class MouthPatchLevel(val levelIndex: Int,val aperture: Float,val path: String,val sha256: String)
|
||||
data class RegisteredMouthPatch(val frameIndex: Int,val ptsUs: Long,val path: String,val sha256: String,
|
||||
val x: Float,val y: Float,val width: Int,val height: Int)
|
||||
val x: Float,val y: Float,val width: Int,val height: Int,val levels: List<MouthPatchLevel> = emptyList())
|
||||
data class ContinuousBodyAsset(val path: String,val sha256: String,val width: Int,val height: Int,
|
||||
val frameCount: Int,val durationUs: Long)
|
||||
data class ContinuousAvatarPack(val body: ContinuousBodyAsset,val patches: List<RegisteredMouthPatch>,
|
||||
val curves: Map<String,MouthCurve>,val root: String,val manifestSha: String)
|
||||
val curves: Map<String,MouthCurve>,val root: String,val manifestSha: String,val apertureMode: Boolean=false) {
|
||||
val textureImages: List<MouthPatchLevel> = patches.flatMap { p ->
|
||||
if(apertureMode) p.levels else listOf(MouthPatchLevel(0,1f,p.path,p.sha256))
|
||||
}
|
||||
}
|
||||
|
||||
/** This parser admits only coordinator-selected debug runtime data; no production graph. */
|
||||
object ContinuousAvatarManifest {
|
||||
@@ -18,7 +23,9 @@ object ContinuousAvatarManifest {
|
||||
fun smallInt(v: Any?): Int { val n=integer(v);require(n in 0..1_000_000);return n.toInt() }
|
||||
fun finite(v: Any?): Float { val f=(v as Number).toFloat(); require(f.isFinite()); return f }
|
||||
fun hash(v: Any?)=(v as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) }
|
||||
require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" && root["packId"]=="a01-neutral-graph-v1-runtime-03")
|
||||
val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04"
|
||||
require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" &&
|
||||
(apertureMode || root["packId"]=="a01-neutral-graph-v1-runtime-03"))
|
||||
require(root["publishApproval"]==false && root["runtimeReady"]==true)
|
||||
val b=obj(root["body"])
|
||||
val body=ContinuousBodyAsset(b["path"] as String,hash(b["sha256"]),smallInt(b["width"]),smallInt(b["height"]),
|
||||
@@ -29,6 +36,10 @@ object ContinuousAvatarManifest {
|
||||
require(integer(b["frameDurationUsNumerator"])==1_000_000L && integer(b["frameDurationUsDenominator"])==24L)
|
||||
val patchFormat=obj(root["patchFormat"])
|
||||
require(patchFormat["alphaEncoding"]=="straight_unassociated" && patchFormat["format"]=="PNG RGBA 8bit")
|
||||
if(apertureMode) {
|
||||
require((patchFormat["apertureLevels"] as List<*>).map(::finite)==listOf(0f,.25f,.5f,.75f,1f))
|
||||
require(patchFormat["requiresRendererExtension"]==true)
|
||||
}
|
||||
val rows=root["patches"] as List<Map<String,Any?>>; require(rows.size==97)
|
||||
val patches=rows.mapIndexed { index,p ->
|
||||
val patch=RegisteredMouthPatch(smallInt(p["frameIndex"]),integer(p["ptsUs"]),p["path"] as String,hash(p["sha256"]),
|
||||
@@ -37,9 +48,23 @@ object ContinuousAvatarManifest {
|
||||
require(patch.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png")))
|
||||
require(patch.width in 1..128 && patch.height in 1..128 && patch.x>=0 && patch.y>=0 &&
|
||||
patch.x+patch.width<=480 && patch.y+patch.height<=848)
|
||||
if(apertureMode) {
|
||||
val levels=(p["levels"] as List<Map<String,Any?>>).mapIndexed { level,row ->
|
||||
require(level in 0..4 && smallInt(row["levelIndex"])==level && finite(row["aperture"])==level/4f)
|
||||
MouthPatchLevel(level,level/4f,row["path"] as String,hash(row["sha256"])).also {
|
||||
require(it.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png")))
|
||||
}
|
||||
}
|
||||
require(levels.size==5 && patch.path==levels[4].path && patch.sha256==levels[4].sha256)
|
||||
patch.copy(levels=levels)
|
||||
} else {
|
||||
require(p["levels"]==null) // Never silently treat aperture data as opacity.
|
||||
patch
|
||||
}
|
||||
require(patches.map { it.path }.distinct().size==97 && patches.sumOf { it.width*it.height*4L }<=8_000_000)
|
||||
}
|
||||
val paths=patches.flatMap { if(apertureMode) it.levels.map { l -> l.path } else listOf(it.path) }
|
||||
require(paths.distinct().size==if(apertureMode) 485 else 97)
|
||||
require(patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) }<=8_000_000)
|
||||
val states=root["mouthStates"] as List<Map<String,Any?>>
|
||||
require(states.size==5)
|
||||
val c=states.associateBy { it["id"] as String }
|
||||
@@ -69,7 +94,7 @@ object ContinuousAvatarManifest {
|
||||
required.forEach { (id,targets) ->
|
||||
val list=routing[id] as List<*>;require(list.size==targets.size && list.toSet()==targets)
|
||||
}
|
||||
ContinuousAvatarPack(body,patches,curves,pathRoot,sha)
|
||||
ContinuousAvatarPack(body,patches,curves,pathRoot,sha,apertureMode)
|
||||
} catch(_: Exception) { null }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,12 +57,12 @@ class ContinuousAvatarView(context: Context,private val pack: AvatarPack?,privat
|
||||
texture.alpha=1f;still.alpha=0f
|
||||
if(firstFrameMs==null) firstFrameMs=elapsed
|
||||
val p=VideoPresentation(actual=frame.mouth.phase,reason="natural_candidate_atomic_layer",
|
||||
waitMs=frame.mouth.phaseWaitMs,firstFrameMs=firstFrameMs,clipId="body_f${frame.key.index}_loop${frame.key.loopOrdinal}")
|
||||
waitMs=frame.mouth.phaseWaitMs,firstFrameMs=firstFrameMs,clipId="body_f${frame.key.index}_loop${frame.key.loopOrdinal}_level${frame.selection.levelIndex ?: "opacity"}")
|
||||
report(p)
|
||||
val now=android.os.SystemClock.elapsedRealtime()
|
||||
if(now-lastLog>=1_000) {
|
||||
lastLog=now
|
||||
DiagnosticLog.record("avatar_layer","phase=${frame.mouth.phase} frame=${frame.key.index} loop=${frame.key.loopOrdinal} pts_us=${frame.key.ptsUs} generation=${frame.mouth.generation} phase_wait_ms=${frame.mouth.phaseWaitMs.coerceAtMost(60000)} first_ms=$firstFrameMs perceived_lag=unknown")
|
||||
DiagnosticLog.record("avatar_layer","phase=${frame.mouth.phase} frame=${frame.key.index} loop=${frame.key.loopOrdinal} level=${frame.selection.levelIndex ?: -1} opacity=${frame.selection.opacity} pts_us=${frame.key.ptsUs} generation=${frame.mouth.generation} phase_wait_ms=${frame.mouth.phaseWaitMs.coerceAtMost(60000)} first_ms=$firstFrameMs perceived_lag=unknown")
|
||||
}
|
||||
}
|
||||
},failure={reason -> if(fence==epoch) { failed=true;stop();report(VideoPresentation(reason=reason)) } })
|
||||
|
||||
@@ -47,14 +47,14 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
||||
private var first=true
|
||||
private var program=0
|
||||
private var bodyTexture=0
|
||||
private val patchTextures=IntArray(pack.patches.size)
|
||||
private val patchTextures=IntArray(pack.textureImages.size)
|
||||
private val textureMatrix=FloatArray(16)
|
||||
private val positions=ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer()
|
||||
private val uv=ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer().apply {
|
||||
put(floatArrayOf(0f,0f,1f,0f,0f,1f,1f,1f));position(0)
|
||||
}
|
||||
private var aPosition=0; private var aUv=0; private var uTextureMatrix=0
|
||||
private var uBody=0; private var uPatch=0; private var uRect=0; private var uAlpha=0
|
||||
private var uBody=0; private var uPatch=0; private var uRect=0; private var uOpacity=0
|
||||
private var startedMs=SystemClock.elapsedRealtime()
|
||||
private var progressMs=startedMs
|
||||
private val timeout=Runnable { fail("frame_timeout") }
|
||||
@@ -77,14 +77,15 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
||||
aPosition=GLES20.glGetAttribLocation(program,"aPosition");aUv=GLES20.glGetAttribLocation(program,"aUv")
|
||||
uTextureMatrix=GLES20.glGetUniformLocation(program,"uTextureMatrix")
|
||||
uBody=GLES20.glGetUniformLocation(program,"uBody");uPatch=GLES20.glGetUniformLocation(program,"uPatch")
|
||||
uRect=GLES20.glGetUniformLocation(program,"uRect");uAlpha=GLES20.glGetUniformLocation(program,"uAlpha")
|
||||
check(listOf(aPosition,aUv,uTextureMatrix,uBody,uPatch,uRect,uAlpha).all { it>=0 })
|
||||
uRect=GLES20.glGetUniformLocation(program,"uRect");uOpacity=GLES20.glGetUniformLocation(program,"uOpacity")
|
||||
check(listOf(aPosition,aUv,uTextureMatrix,uBody,uPatch,uRect,uOpacity).all { it>=0 })
|
||||
val texture=IntArray(1);GLES20.glGenTextures(1,texture,0);bodyTexture=texture[0]
|
||||
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture)
|
||||
configureTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES)
|
||||
GLES20.glGenTextures(patchTextures.size,patchTextures,0)
|
||||
pack.patches.forEachIndexed { index,p ->
|
||||
val bitmap=context.assets.open(pack.root+p.path).use { BitmapFactory.decodeStream(it) } ?: error("patch_decode")
|
||||
pack.textureImages.forEachIndexed { index,image ->
|
||||
val p=pack.patches[index/(if(pack.apertureMode) 5 else 1)]
|
||||
val bitmap=context.assets.open(pack.root+image.path).use { BitmapFactory.decodeStream(it) } ?: error("patch_decode")
|
||||
try {
|
||||
check(bitmap.width==p.width && bitmap.height==p.height)
|
||||
val pixels=IntArray(p.width*p.height);bitmap.getPixels(pixels,0,p.width,0,0,p.width,p.height)
|
||||
@@ -124,31 +125,8 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
||||
if(status[0]!=GLES20.GL_TRUE) { GLES20.glDeleteShader(id);error("shader_compile") }
|
||||
return id
|
||||
}
|
||||
val vertex=shader(GLES20.GL_VERTEX_SHADER,"""
|
||||
attribute vec2 aPosition; attribute vec2 aUv;
|
||||
uniform mat4 uTextureMatrix; varying vec2 vBody; varying vec2 vLogical;
|
||||
void main() { gl_Position=vec4(aPosition,0.0,1.0); vLogical=aUv;
|
||||
vBody=(uTextureMatrix*vec4(aUv,0.0,1.0)).xy; }
|
||||
""")
|
||||
val fragment=shader(GLES20.GL_FRAGMENT_SHADER,"""
|
||||
#extension GL_OES_EGL_image_external : require
|
||||
precision highp float;
|
||||
uniform samplerExternalOES uBody; uniform sampler2D uPatch;
|
||||
uniform vec4 uRect; uniform float uAlpha;
|
||||
varying vec2 vBody; varying vec2 vLogical;
|
||||
void main() {
|
||||
vec4 body=texture2D(uBody,vBody);
|
||||
vec2 pixel=vec2(vLogical.x*480.0,(1.0-vLogical.y)*848.0);
|
||||
vec2 local=(pixel-uRect.xy)/uRect.zw;
|
||||
if(uAlpha<=0.0 || local.x<0.0 || local.y<0.0 || local.x>=1.0 || local.y>=1.0) {
|
||||
gl_FragColor=vec4(body.rgb,1.0);
|
||||
} else {
|
||||
vec4 patch=texture2D(uPatch,local);
|
||||
float mask=uAlpha*patch.a;
|
||||
gl_FragColor=vec4(mix(body.rgb,patch.rgb,mask),1.0);
|
||||
}
|
||||
}
|
||||
""")
|
||||
val vertex=shader(GLES20.GL_VERTEX_SHADER,AvatarLayerShader.VERTEX)
|
||||
val fragment=shader(GLES20.GL_FRAGMENT_SHADER,AvatarLayerShader.FRAGMENT)
|
||||
val result=GLES20.glCreateProgram();GLES20.glAttachShader(result,vertex);GLES20.glAttachShader(result,fragment)
|
||||
GLES20.glLinkProgram(result);GLES20.glDeleteShader(vertex);GLES20.glDeleteShader(fragment)
|
||||
val status=IntArray(1);GLES20.glGetProgramiv(result,GLES20.GL_LINK_STATUS,status,0)
|
||||
@@ -204,8 +182,8 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
||||
GLES20.glVertexAttribPointer(aUv,2,GLES20.GL_FLOAT,false,0,uv);GLES20.glEnableVertexAttribArray(aUv)
|
||||
GLES20.glUniformMatrix4fv(uTextureMatrix,1,false,textureMatrix,0)
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture);GLES20.glUniform1i(uBody,0)
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE1);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,patchTextures[frame.key.index]);GLES20.glUniform1i(uPatch,1)
|
||||
val p=frame.patch;GLES20.glUniform4f(uRect,p.x,p.y,p.width.toFloat(),p.height.toFloat());GLES20.glUniform1f(uAlpha,frame.mouth.alpha)
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE1);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,patchTextures[frame.selection.textureSlot]);GLES20.glUniform1i(uPatch,1)
|
||||
val p=frame.patch;GLES20.glUniform4f(uRect,p.x,p.y,p.width.toFloat(),p.height.toFloat());GLES20.glUniform1f(uOpacity,frame.selection.opacity)
|
||||
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP,0,4)
|
||||
check(GLES20.glGetError()==GLES20.GL_NO_ERROR && EGL14.eglSwapBuffers(display,window))
|
||||
}
|
||||
@@ -238,3 +216,32 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Shared literal shader source is exercised by the offline EGL pixel golden check. */
|
||||
internal object AvatarLayerShader {
|
||||
const val VERTEX="""
|
||||
attribute vec2 aPosition; attribute vec2 aUv;
|
||||
uniform mat4 uTextureMatrix; varying vec2 vBody; varying vec2 vLogical;
|
||||
void main() { gl_Position=vec4(aPosition,0.0,1.0); vLogical=aUv;
|
||||
vBody=(uTextureMatrix*vec4(aUv,0.0,1.0)).xy; }
|
||||
"""
|
||||
const val FRAGMENT="""
|
||||
#extension GL_OES_EGL_image_external : require
|
||||
precision highp float;
|
||||
uniform samplerExternalOES uBody; uniform sampler2D uPatch;
|
||||
uniform vec4 uRect; uniform float uOpacity;
|
||||
varying vec2 vBody; varying vec2 vLogical;
|
||||
void main() {
|
||||
vec4 body=texture2D(uBody,vBody);
|
||||
vec2 pixel=vec2(vLogical.x*480.0,(1.0-vLogical.y)*848.0);
|
||||
vec2 local=(pixel-uRect.xy)/uRect.zw;
|
||||
if(uOpacity<=0.0 || local.x<0.0 || local.y<0.0 || local.x>=1.0 || local.y>=1.0) {
|
||||
gl_FragColor=vec4(body.rgb,1.0);
|
||||
} else {
|
||||
vec4 patch=texture2D(uPatch,local);
|
||||
float mask=uOpacity*patch.a;
|
||||
gl_FragColor=vec4(mix(body.rgb,patch.rgb,mask),1.0);
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
|
||||
data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPatch,val mouth: MouthLayerSample)
|
||||
data class MouthPatchSelection(val textureSlot: Int,val levelIndex: Int?,val opacity: Float)
|
||||
/** In runtime04 aperture chooses geometry, never its opacity. Ties choose the lower level. */
|
||||
fun selectMouthPatch(pack: ContinuousAvatarPack,frameIndex: Int,aperture: Float): MouthPatchSelection {
|
||||
require(frameIndex in pack.patches.indices && aperture.isFinite() && aperture in 0f..1f)
|
||||
if(!pack.apertureMode) return MouthPatchSelection(frameIndex,null,aperture)
|
||||
val level=(0..4).minBy { kotlin.math.abs(aperture-it/4f) }
|
||||
return MouthPatchSelection(frameIndex*5+level,level,if(level==0) 0f else 1f)
|
||||
}
|
||||
data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPatch,val mouth: MouthLayerSample,
|
||||
val selection: MouthPatchSelection)
|
||||
/** The real EGL renderer uses this gate immediately around updateTexImage + draw/swap.
|
||||
* No other thread can choose a patch or change body phase. close() fences stale output. */
|
||||
class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) {
|
||||
@@ -12,7 +21,8 @@ class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,choose: (I
|
||||
fun present(timestampNs: Long,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame? {
|
||||
if(!active) return null
|
||||
val key=clock.latched(timestampNs)
|
||||
val frame=ComposedBodyFrame(key,pack.patches[key.index],mouth.sample(nowMs))
|
||||
val sample=mouth.sample(nowMs)
|
||||
val frame=ComposedBodyFrame(key,pack.patches[key.index],sample,selectMouthPatch(pack,key.index,sample.alpha))
|
||||
drawAndSwap(frame) // Exactly one atomic composition; failed swap is not presented.
|
||||
return frame
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# 0.6.2-mouth-dev / code15 — runtime04 device candidate
|
||||
|
||||
Coordinator approved runtime04 for Android debug/device validation after reviewing fixed-frame comparisons and IMPORT. This is a mouth-method candidate, not final natural-quality approval or a claim that the user's deformation report is resolved. Code14 remains the separate UI-only/runtime03 baseline; its artifact is never overwritten. No new AI generation or fees, backend/provider/TTS/voice/model changes, system toolchain changes, sensor capture or automatic device installation.
|
||||
|
||||
## Exact material and admission scope
|
||||
|
||||
Private input: `.runtime/avatar-imports/a01-neutral-graph-v1/runtime-04/`.
|
||||
Manifest SHA256: `0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad`.
|
||||
Body SHA256: `177dbc0ab809e3c9c684899ffbd9cf3a2c357973c7037134f5d79e4e6cdfc762` (unchanged from runtime03),97frames,480×848,24fps,4041667us,H264/yuv420p/no audio.
|
||||
Owner preview `review/mouth-fix-20s-clean.mp4` SHA256: `a72d69d06b795db737b549f00f14f2b2dfff0670cd5320c1a0ab51e6a951236a`.
|
||||
|
||||
485 straight RGBA8 PNGs represent97body frames×5aperture levels. They use each source frame's own lip seam and a maximum0.9px local opening deformation. This replaces the runtime03 method that mixed a different open-lip image over the source lip. It does not warp the whole face or introduce another body phase. The source seam detection is an offline dark/red heuristic; it is not an affine/identity solution. Tiny opening may be inconspicuous at full-body scale. Body-loop seam and dynamic naturalness remain pending.
|
||||
|
||||
Exact SHA is admitted only by `-PavatarNatural=true -PavatarMouthCandidate=true -PnaturalManifestSha=<runtime04 SHA>` in debug. Existing manifest fields remain unchanged: publishApproval=false, naturalQualityStatus=pending_coordinator, deviceTestStatus=pending, safeTransitions pending, approvedEdges empty, rights unverified. Production flags are false and motion allowlist stays empty. Runtime03, controlled01, all source imports and earlier APKs retain their bytes. Code15 bundles runtime03 for baseline preservation but selects only runtime04; invalid runtime04 falls back to verified static reference rather than silently selecting another motion pack.
|
||||
|
||||
## Runtime contract
|
||||
|
||||
Parser distinguishes packId runtime03 from runtime04 and rejects cross-schema opacity/aperture substitution. Runtime04 patch rows have actual frameIndex/ptsUs,x/y/width/height and exactly five ordered `levels`: levelIndex0..4,aperture0/.25/.5/.75/1,path/sha256. Top-level row path/sha must match level4. All485paths are unique and bounded; width/height≤128,rect inside480×848,total decoded RGBA≤8MB. Every file hash and decoded PNG dimension is checked before rendering. There is no atlas; small textures are independently bounded and cached once, with no per-frame PNG decode, SSD or whole-body Bitmap allocation.
|
||||
|
||||
Latest actual PCM playback-head activity still supplies only mouth intent. The independent controller retains idle/opening/talk1/talk2/end-talk curves,250ms bridges and500ms legal talking units; old generation/revision and callbacks are fenced. Opening reversal completes the short bridge then closes; stop/abort finishes the current mouth unit then end-talk. Audio abort remains immediate and never waits for video.
|
||||
|
||||
Curve value g now selects the **nearest geometry aperture level**, not opacity. Exact halfway ties choose the lower level deterministically. For example g=.125→level0,g>.125→level1,g=.5→level2. Level0 bypasses the patch and outputs the original body sample. Any other selected level uses global opacity1 and only its spatial alpha a:
|
||||
|
||||
`out = body*(1-a) + selectedPatchRGB*a`
|
||||
|
||||
There is no second multiplication by g, interpolation between two level images, or crossfade of two lip anatomies. Nearest selection can reveal stepping; no larger aperture or temporal smoothing is added without visual evidence. Runtime03 retains its old g×a path only when explicitly building the old runtime03 variant.
|
||||
|
||||
`ContinuousFramePresenter` selects the level, texture slot and opacity from the same latched body key and mouth sample. One MediaCodec output is pending at a time; SurfaceTexture timestamp is checked against decoded PTS,patch frame index follows0..96 and loop ordinal increments only at full wrap. Body,patch and mouth selection draw in one EGL pass/swap,using one Fit quad. Mouth changes do not seek/restart body. Background releases decoder/EGL/GL textures and fences callbacks. Decoder/GL/hash/dimension failure returns to the verified still image and cannot block audio.
|
||||
|
||||
## UI and versions
|
||||
|
||||
Both versions have only full-screen white Fit avatar+one48dp bottom-right safe-inset gear at home. Settings holds all statuses,errors,permissions,privacy controls,face sharing,emotions,diagnostic report/player text and offline controls. Opening/closing the sheet does not key the renderer/session. Code15's settings explicitly label source-own-lip five-level micro-motion,stepping,visibility and deformation improvement as pending device validation. No engineering banner covers the face.
|
||||
|
||||
Code15 also fixes permission timing, superseding code13/code14's HELLO-before-consent policy. Normal first RESUMED entry waits for the attached Compose host to be laid out, then requests MIC and CAMERA sequentially without waiting for health/WS/HELLO. Asked flags persist before launching the dialog; repeated drive/recomposition/rotation/reconnect cannot prompt again automatically. Explicit permission buttons and permanent-denial application-settings entries are always in settings and work even when network connection fails. Already granted permission is a no-op. Stale/wrong callbacks cannot clear another pending request or alter preferences.
|
||||
|
||||
Consent is separate from collection: microphone capture/upload starts only in foreground after real HELLO; no connection means no uplink. Normal camera analysis may start when foreground, granted and cameraWanted, independently of network, after pending dialogs finish. Camera denial permits audio; mic denial prevents recording. Camera-off choices persist. Sharing remains independent/defaultoff and clears on camera-off/disconnect/background. System privacy indicators/dialogs stay visible. Permission onPause/onStop stops all sensors; only the bounded pending-permission connection continuation survives. A callback in background cannot start anything.
|
||||
|
||||
Explicit offline extra constructs no VoiceSession/AudioOutputGate/ExpressionController and automatically requests no permissions. Its settings show each actual granted/ungranted state and manual MIC/CAMERA permission buttons; a user can consent through the real system dialog or application settings without network. Granting in offline mode still never starts capture/analysis, and no adb pm grant is used. Opening a system dialog may pause/release the video according to Activity lifecycle; merely opening/closing the in-Activity settings sheet does not.
|
||||
|
||||
## Reproduction and validation
|
||||
|
||||
Portrait inputs remain private/ignored. Restore the accepted arms reference and controlled01/runtime03 baselines using the import commands in AVATAR_UI_062.md. Then:
|
||||
|
||||
```sh
|
||||
/home/ubuntu/miniconda3/bin/python3 scripts/package-avatar-mouth.py --import-only
|
||||
python3 scripts/check-reply-regressions.py --suite avatar --runtime-manifest .runtime/avatar-imports/a01-neutral-graph-v1/runtime-03/manifest.json > logs/avatar-mouth-062/actual-manifest-tests.txt 2>&1
|
||||
python3 scripts/check-reply-regressions.py --suite avatar --runtime-manifest .runtime/avatar-imports/a01-neutral-graph-v1/runtime-04/manifest.json >> logs/avatar-mouth-062/actual-manifest-tests.txt 2>&1
|
||||
./scripts/check-avatar-regressions.sh
|
||||
/home/ubuntu/miniconda3/envs/gori-speech/bin/python gateway/scripts/check-archive.py --vad-model /home/ubuntu/miniconda3/envs/gori-speech/lib/python3.12/site-packages/silero_vad/data/silero_vad.onnx > logs/avatar-safe-061/gateway-tests.txt 2>&1
|
||||
/home/ubuntu/miniconda3/bin/python3 scripts/check-avatar-shader.py --runtime .runtime/avatar-imports/a01-neutral-graph-v1/runtime-04 --output logs/avatar-mouth-062/shader-golden
|
||||
./scripts/build.sh compileDebugKotlin assembleDebugAndroidTest -PavatarNatural=true -PavatarMouthCandidate=true -PnaturalManifestSha=0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad > logs/avatar-mouth-062/android-test-compile.txt 2>&1
|
||||
/home/ubuntu/miniconda3/bin/python3 scripts/package-avatar-mouth.py
|
||||
```
|
||||
|
||||
Missing/drifted data stops packaging. Current permission tests additionally cover first-foreground requests before HELLO, sequential callbacks across onStop, one-shot denial/permanent/manual retry, network-independent/offline consent-only, granted no-op, MIC after HELLO, foreground camera without network, and genuine background guards. Packaging verifies strict97×5hash/dimension/bounds,the production Kotlin parser for both actual manifests,current source regression fingerprints,all74isolated gateway tests,completebodydecode/CFR,CPUlevel0bypass+selectedgeometryspatialmask math,compiled optional UI probe,SDK/ABI/same debug certificate,exact ZIPavatar bytes/MP4stored,and HTTPAPK/checksum. It preserves all existing artifacts and requires a new filename/versioncode for later revisions. To reproduce code14 exactly,use its source commit9ea5eb31c16f5a1360880c57370b590057090f0a in an isolated checkout;current code15 has extended renderer fingerprints.
|
||||
|
||||
New JVM checks cover97×5selection slots,nearest/tie boundaries,nonfinite values,level0opacity0/nonzeroopacity1,missing/duplicate/invalid levels,path/bounds/memory rejection,cross-schema rejection,and the actual renderer's chosen texture+opacity through wrap/abort/background/error/resource teardown under deterministic Android/EGL doubles. Existing9JVM entrypoints cover partial PCM/head activity,silence/underrun,oldturn/reversal,permissions/autoentry and all prior suites. UI source contracts run; optional sensor-free physical UI probe is compiled,not executed here.
|
||||
|
||||
The C/EGL golden harness executes the production shader strings on Mesa llvmpipe,substituting a2D body sampler for OES.40cases cover synthetic top-bottom/subpixel UV/portrait+landscape Fit,a nontrivial body texture transform,straightalpha spatial blending,exact alpha0 body identity,and actual runtime04 frames0/26/43/52/69/96 at all5levels. Observed maximum RGB discrepancy is1/255 against independent bilinear CPU golden. This is actual offline GLES execution,but does **not** validate Android Bitmap premul roundtrip,hardware OES/YUV conversion,SurfaceTexture transform delivered by the phone,physical display timing or perceived naturalness. No proven Android double-premul/root bug is claimed.
|
||||
|
||||
## Coordinator offline device acceptance
|
||||
|
||||
Artifact: `artifacts/lan-voice-v062-mouth-candidate-arm64-debug.apk` plus `.apk.sha256`,version0.6.2-mouth-dev/code15,arm64/min26/target34,same debug certificate. Device must be online before coordinator installation;this task does not reconfigure USB/wireless/network or clear data.
|
||||
|
||||
```sh
|
||||
adb -s 0123456789ABCDEF install -r lan-voice-v062-mouth-candidate-arm64-debug.apk
|
||||
adb -s 0123456789ABCDEF shell am force-stop com.gorios.lanvoice
|
||||
adb -s 0123456789ABCDEF shell am start -W -n com.gorios.lanvoice/.MainActivity --ez avatar_offline_preview true
|
||||
```
|
||||
|
||||
Open gear for Idle/Talk/Abort/Trace. Check visible small repeated talk without deforming lips or extra shadows,nearest-level stepping,stop/resume/reversal,body blink/sway continuity and wrap,settings open/close without body reset,portrait/landscape/tablet Fit,background release/resume and failure fallback. Actual perception,≤1s response,performance/temperature,hardware shader colors and final naturalness remain unknown. Nearly static mouth is not success;do not certify the fix solely from hashes,CPU equality or low pixel differences. Camera/face algorithm acceptance remains separate.
|
||||
@@ -1,10 +1,10 @@
|
||||
# Current avatar UX — clean home in 0.6.2 UI candidate
|
||||
# Current avatar UX — clean home and 0.6.2 mouth candidate
|
||||
|
||||
The user has resumed complete implementation, self-validation and final APK production. This supersedes both the released0.6.0 dial/hangup design and the intervening development pause. Final motion activation still requires coordinator review of actual material/edges and an exact manifest hash; no repeated per-step user permission is required. Current implementation, limitations and release gate: [AVATAR_SAFE_061.md](AVATAR_SAFE_061.md). Material owner interface: [AVATAR_NEUTRAL_GRAPH_INTERFACE.md](AVATAR_NEUTRAL_GRAPH_INTERFACE.md).
|
||||
|
||||
## Foreground conversation
|
||||
|
||||
RESUMED automatically attempts health→authenticated WS→real HELLO. Only after HELLO request microphone and camera sequentially, once unless explicitly retried. Already granted MIC can start voice immediately, independently of camera/video preparation. Denied camera permits audio; denied MIC starts no capture and exposes authorization/settings. Persist asked/denied/mute/camera-off preferences; no repeated automatic permission prompts.
|
||||
Code15 supersedes the code13/code14 permission timing: first RESUMED entry after host layout requests MIC/CAMERA sequentially without waiting for health/WS/HELLO. Foreground connection attempts still wait for real HELLO before MIC capture/upload. Granted wanted camera may analyze in foreground independently of network. Explicit permission/settings actions also work without network; offline preview only requests on explicit settings actions and never collects after grant. Denied camera permits audio; denied MIC starts no capture and exposes authorization/settings. Persist asked/denied/mute/camera-off preferences; no repeated automatic permission prompts.
|
||||
|
||||
CONNECTING / AWAITING_PERMISSION / ACTIVE / ERROR are the page states. Transport retry is finite (three attempts,1s/3s backoff), stops on busy and leaves visible manual Retry. It never requests duplicate LLM generation. No dial/hangup, fake ringing, real-person acceptance claim, account or router UI. Users close/background the app to exit.
|
||||
|
||||
@@ -26,4 +26,4 @@ PCM actual playback-head activity supplies latest mouth intent only. Reviewed so
|
||||
|
||||
## Release boundary
|
||||
|
||||
Current UI-only candidate targets0.6.2-ui-dev/code14, retaining runtime03 mouth rendering unchanged; mouth deformation is unresolved. See [AVATAR_UI_062.md](AVATAR_UI_062.md) for exact reproduction and test boundaries. Code12/code13 and retained0.6.0/code11 APK stay byte-identical. Current checks and staged material blockers are recorded in AVATAR_SAFE_061.md and ignored logs/avatar-safe-061/. Final material hash, signature/badging/HTTP checks, commit/push and coordinator Windows USB installation follow actual graph review. No device sensors/install or backend/provider/model/TTS change is performed by this agent.
|
||||
Retained UI-only candidate is0.6.2-ui-dev/code14 with unchanged runtime03 mouth. Current0.6.2-mouth-dev/code15 uses coordinator-admitted runtime04 five aperture levels for device validation; final mouth deformation/naturalness is not certified. See [AVATAR_MOUTH_062.md](AVATAR_MOUTH_062.md). See [AVATAR_UI_062.md](AVATAR_UI_062.md) for exact reproduction and test boundaries. Code12/code13 and retained0.6.0/code11 APK stay byte-identical. Current checks and staged material blockers are recorded in AVATAR_SAFE_061.md and ignored logs/avatar-safe-061/. Final material hash, signature/badging/HTTP checks, commit/push and coordinator Windows USB installation follow actual graph review. No automatic device sensors/install or backend/provider/model/TTS change is performed by this agent.
|
||||
|
||||
@@ -11,7 +11,8 @@ from pathlib import Path
|
||||
import hashlib,json
|
||||
root=Path.cwd()
|
||||
paths=list((root/'app/src/main/java').rglob('*.kt'))+list((root/'app/src/androidTest').rglob('*.kt'))+list((root/'tests').rglob('*.kt'))
|
||||
paths += [root/p for p in ('app/build.gradle','scripts/check-reply-regressions.py','scripts/check-expression-rules.sh','scripts/check-avatar-regressions.sh','scripts/check-avatar-ui.py','scripts/import-avatar-graph.py','scripts/package-avatar-safe-release.sh','scripts/package-avatar-safe-release.py','scripts/package-avatar-engineering.py','scripts/package-avatar-natural.py','scripts/package-avatar-ui.py')]
|
||||
paths += list((root/'tests/avatar-pixels').glob('*.c'))
|
||||
paths += [root/p for p in ('app/build.gradle','scripts/check-reply-regressions.py','scripts/check-expression-rules.sh','scripts/check-avatar-regressions.sh','scripts/check-avatar-ui.py','scripts/check-avatar-shader.py','scripts/import-avatar-graph.py','scripts/package-avatar-safe-release.sh','scripts/package-avatar-safe-release.py','scripts/package-avatar-engineering.py','scripts/package-avatar-natural.py','scripts/package-avatar-ui.py','scripts/package-avatar-mouth.py')]
|
||||
result={'status':'passed','jvm_entry_points':9,'uiSourceContracts':'passed','uiDeviceInstrumentation':'not_run','real_device':'pending',
|
||||
'hashes':{str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(paths)}}
|
||||
(root/'logs/avatar-safe-061/client-tests.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline real GLES2 shader pixel golden; surrogate body texture, no Android/device claim."""
|
||||
from pathlib import Path
|
||||
import argparse,hashlib,json,os,re,subprocess,tempfile
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
def bilinear(image,x,y):
|
||||
h,w=image.shape[:2];x=np.clip(x,0,w-1);y=np.clip(y,0,h-1)
|
||||
ix=np.floor(x).astype(int);iy=np.floor(y).astype(int);jx=np.minimum(ix+1,w-1);jy=np.minimum(iy+1,h-1)
|
||||
fx=(x-ix)[...,None];fy=(y-iy)[...,None]
|
||||
return (image[iy,ix]*(1-fx)+image[iy,jx]*fx)*(1-fy)+(image[jy,ix]*(1-fx)+image[jy,jx]*fx)*fy
|
||||
|
||||
def golden(body,patch,x,y,opacity,w,h,crop):
|
||||
scale=min(w/480,h/848);left=(w-480*scale)/2;top=(h-848*scale)/2
|
||||
yy,xx=np.mgrid[:h,:w];px=(xx+.5-left)/scale;py=(yy+.5-top)/scale
|
||||
inside=(px>=0)&(px<480)&(py>=0)&(py<848)
|
||||
bx=px*(.98 if crop else 1)+(4.8 if crop else 0)-.5
|
||||
by=py*(.98 if crop else 1)+(8.48 if crop else 0)-.5
|
||||
b=bilinear(body.astype(float),bx,by)
|
||||
localx=px-x;localy=py-y;ph,pw=patch.shape[:2]
|
||||
p=bilinear(patch.astype(float),localx-.5,localy-.5)
|
||||
mask=(opacity*p[:,:,3:4]/255)*((localx>=0)&(localy>=0)&(localx<pw)&(localy<ph))[...,None]
|
||||
out=b[:,:,:3]*(1-mask)+p[:,:,:3]*mask
|
||||
out[~inside]=255
|
||||
return np.clip(np.floor(out+.5),0,255).astype(np.uint8)
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--runtime',type=Path,required=True);parser.add_argument('--output',type=Path,required=True)
|
||||
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
||||
m=json.loads((args.runtime/'manifest.json').read_text());source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_text()
|
||||
vertex=re.search(r'const val VERTEX="""([\s\S]*?)"""',source)[1]
|
||||
fragment=re.search(r'const val FRAGMENT="""([\s\S]*?)"""',source)[1]
|
||||
fragment=fragment.replace('#extension GL_OES_EGL_image_external : require','').replace('samplerExternalOES','sampler2D')
|
||||
results=[]
|
||||
with tempfile.TemporaryDirectory(prefix='avatar-gles-golden-') as temporary:
|
||||
tmp=Path(temporary);(tmp/'vertex').write_text(vertex);(tmp/'fragment').write_text(fragment)
|
||||
subprocess.run(['cc','-O2',str(ROOT/'tests/avatar-pixels/gles-golden.c'),'-lEGL','-lGLESv2','-lm','-o',str(tmp/'golden')],check=True)
|
||||
env=dict(os.environ,EGL_PLATFORM='surfaceless',LIBGL_ALWAYS_SOFTWARE='1')
|
||||
def check(body,patch,x,y,opacity,w,h,label,crop=0):
|
||||
(tmp/'body.rgba').write_bytes(body.tobytes());(tmp/'patch.rgba').write_bytes(patch.tobytes())
|
||||
p=subprocess.run([str(tmp/'golden'),str(tmp/'vertex'),str(tmp/'fragment'),str(tmp/'body.rgba'),str(tmp/'patch.rgba'),str(tmp/'out.rgba'),str(patch.shape[1]),str(patch.shape[0]),str(x),str(y),str(opacity),str(w),str(h),str(crop)],env=env,capture_output=True,text=True)
|
||||
assert p.returncode==0,p.stderr
|
||||
actual=np.frombuffer((tmp/'out.rgba').read_bytes(),np.uint8).reshape(h,w,4)[::-1,:,:3]
|
||||
expected=golden(body,patch,x,y,opacity,w,h,crop);diff=np.abs(actual.astype(int)-expected.astype(int))
|
||||
row={'case':label,'maxAbsRGB':int(diff.max()),'meanAbsRGB':float(diff.mean()),'viewport':[w,h],'bodyTransformCrop':crop,'gl':p.stdout.strip()}
|
||||
results.append(row)
|
||||
assert diff.max()<=2,row
|
||||
if opacity==0 and w==480 and h==848 and not crop:assert np.array_equal(actual,body[:,:,:3]),'Level0 must be exact decoded body'
|
||||
if label=='frame43-level2':Image.fromarray(actual[94:150,193:263]).resize((560,448)).save(args.output/'gles-frame43-level2-mouth.png')
|
||||
yy,xx=np.mgrid[:848,:480];body=np.empty((848,480,4),np.uint8)
|
||||
body[:,:,0]=xx%256;body[:,:,1]=yy%256;body[:,:,2]=((xx//16+yy//16)%2)*255;body[:,:,3]=255
|
||||
patch=np.zeros((22,40,4),np.uint8);patch[:,:,:3]=[211,70,39];patch[:,:,3]=np.arange(40,dtype=np.uint8)[None,:]*6
|
||||
for w,h in [(480,848),(360,800),(800,480)]:
|
||||
for opacity in [0,.5,1]:check(body,patch,211.25,112.5,opacity,w,h,f'synthetic-{w}x{h}-opacity{opacity}')
|
||||
check(body,patch,211.25,112.5,1,480,848,'synthetic-transform-crop',1)
|
||||
pipe=subprocess.Popen(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(args.runtime/m['body']['path']),'-f','rawvideo','-pix_fmt','rgba','-'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
try:
|
||||
for i,row in enumerate(m['patches']):
|
||||
raw=pipe.stdout.read(480*848*4);assert len(raw)==480*848*4
|
||||
if i not in (0,26,43,52,69,96):continue
|
||||
body=np.frombuffer(raw,np.uint8).reshape(848,480,4)
|
||||
for level in (0,1,2,3,4):
|
||||
patch=np.asarray(Image.open(args.runtime/row['levels'][level]['path']).convert('RGBA'))
|
||||
check(body,patch,row['x'],row['y'],0 if level==0 else 1,480,848,f'frame{i}-level{level}')
|
||||
assert pipe.stdout.read(1)==b'';assert pipe.wait(timeout=10)==0
|
||||
finally:
|
||||
if pipe.poll() is None:pipe.kill();pipe.wait()
|
||||
report={'status':'passed','shaderSourceSha':hashlib.sha256(source.encode()).hexdigest(),
|
||||
'harnessSha':hashlib.sha256((ROOT/'tests/avatar-pixels/gles-golden.c').read_bytes()).hexdigest(),
|
||||
'scope':'Production shader strings; body OES sampler substituted by2D, decoded ffmpeg/PIL straight bytes. Does not test Android Bitmap/OES/YUV/physicaldisplay.','cases':results}
|
||||
(args.output/'shader-golden.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print('PASS:',len(results),'real offline EGL/GLES pixel golden cases: UV/top-bottom/Fit/nontrivial body transform/straight blend/alpha0/6fixedframes x5levels; Android device pending')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -44,6 +44,7 @@ for name in ('CallScreen','EngineeringPreviewScreen'):
|
||||
assert text(avatar).count('AvatarPortrait(')==1
|
||||
no_calls(avatar,['Text','AvatarDiagnostics','ExpressionControls','Button','TextButton'])
|
||||
assert 'AvatarDiagnostics(pack,video)' in text(settings)
|
||||
assert 'PermissionSettings(' in text(settings)
|
||||
assert 'settingsOpen' not in text(fn)
|
||||
if name=='CallScreen':
|
||||
for expected in ('正在连接','重试连接','permissionMessage','onAuthorizeMic','onMute','onCamera','ExpressionControls','请求表达','onReport'):
|
||||
@@ -59,5 +60,15 @@ activity=(ROOT/'app/src/main/java/com/gorios/lanvoice/MainActivity.kt').read_tex
|
||||
offline=activity[activity.index('if (offlineAvatarPreview) {'):activity.index('audioOutput = AudioOutputGate')]
|
||||
assert 'EngineeringPreviewScreen' in offline and 'return' in offline
|
||||
for forbidden in ('VoiceSession(', 'ExpressionController(', 'permission.launch(', '.dial('): assert forbidden not in offline
|
||||
assert 'conversationEnabled=false,automaticPermissions=false' in offline
|
||||
assert 'isLaidOut' in activity and 'isAttachedToWindow' in activity
|
||||
for method,next_method in (('authorizeMicrophone','authorizeCamera'),('authorizeCamera','retryConnection')):
|
||||
body=activity[activity.index('private fun '+method):activity.index('private fun '+next_method)]
|
||||
assert 'ConnectionStatus.CONNECTED' not in body,'Manual consent must not depend on HELLO'
|
||||
assert 'granted(Manifest.permission.' in body and 'openSettings()' in body
|
||||
assert 'entry.permissionPending!=permission' in activity
|
||||
permissions=text(block('fun PermissionSettings'))
|
||||
for label in ('已授权','未授权','申请麦克风权限','申请摄像头权限','系统权限设置'):
|
||||
assert label in permissions
|
||||
assert '本版仅修复界面;嘴层沿用 runtime03,变形问题尚未修复' in source
|
||||
print('PASS: clean home has persistent avatar + one 48dp safe-inset gear; normal/offline text and controls are sheet-only; sheet state never keys renderer/session; offline construction bypasses sensors/network. Source contracts only; real-device probe pending.')
|
||||
|
||||
@@ -40,21 +40,31 @@ for name, main, real in suites:
|
||||
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out:
|
||||
files = list((ROOT/'tests'/name).glob('*.kt')) + real
|
||||
if name == 'avatar' and args.runtime_manifest:
|
||||
definitions=[]
|
||||
def kotlin(value):
|
||||
if value is None: return 'null'
|
||||
if isinstance(value,bool): return str(value).lower()
|
||||
if isinstance(value,str): return json.dumps(value,ensure_ascii=False).replace('$','\\$')
|
||||
if isinstance(value,int): return str(value)+'L'
|
||||
if isinstance(value,float): return repr(value)
|
||||
if isinstance(value,list): return 'listOf<Any?>('+','.join(map(kotlin,value))+')'
|
||||
if isinstance(value,dict): return 'mapOf<String,Any?>('+','.join(kotlin(k)+' to '+kotlin(v) for k,v in value.items())+')'
|
||||
if isinstance(value,(list,dict)):
|
||||
result=('listOf<Any?>('+','.join(map(kotlin,value))+')' if isinstance(value,list) else
|
||||
'mapOf<String,Any?>('+','.join(kotlin(k)+' to '+kotlin(v) for k,v in value.items())+')')
|
||||
# Actual97x5 metadata exceeds a single JVM method. Preserve every
|
||||
# field while splitting literal construction into bounded helpers.
|
||||
method='metadata'+str(len(definitions))
|
||||
kind='List<Any?>' if isinstance(value,list) else 'Map<String,Any?>'
|
||||
definitions.append('private fun '+method+'(): '+kind+' = '+result+'\n')
|
||||
return method+'()'
|
||||
raise TypeError(type(value))
|
||||
import hashlib
|
||||
raw=args.runtime_manifest.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
||||
extra=Path(out)/'ActualRuntimeCheck.kt'
|
||||
extra.write_text('import com.gorios.lanvoice.avatar.*\nfun main() {\nval root='+kotlin(json.loads(raw))+'\n'+
|
||||
literal=kotlin(json.loads(raw))
|
||||
extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+'fun main() {\nval root='+literal+'\n'+
|
||||
'val pack=checkNotNull(ContinuousAvatarManifest.read(root,"'+digest+'","'+digest+'",true,"runtime/"))\n'+
|
||||
'check(pack.patches.size==97 && pack.body.frameCount==97 && pack.curves.size==5)\n'+
|
||||
('check(pack.apertureMode && pack.textureImages.size==485 && pack.patches.all { it.levels.size==5 })\n' if json.loads(raw)['packId'].endswith('runtime-04') else 'check(!pack.apertureMode && pack.textureImages.size==97)\n')+
|
||||
'println("PASS: actual exported runtime manifest parsed by production Kotlin, exact hash '+digest+'; 97 body/patch frames and five authored curves/routing")\n}\n')
|
||||
files.append(extra)
|
||||
subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib',
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pinned runtime04 aperture-level Android internal debug candidate; no final quality approval."""
|
||||
from pathlib import Path
|
||||
import argparse,hashlib,importlib.util,json,os,re,subprocess,tempfile,urllib.request,zipfile
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('natural_packaging',ROOT/'scripts/package-avatar-natural.py')
|
||||
natural=importlib.util.module_from_spec(spec);spec.loader.exec_module(natural)
|
||||
LOG=ROOT/'logs/avatar-mouth-062';natural.LOG=LOG
|
||||
SOURCE=ROOT/'.runtime/avatar-imports/a01-neutral-graph-v1/runtime-04'
|
||||
PACK=ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1/runtime-04'
|
||||
PIN='0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad'
|
||||
ARTIFACT=ROOT/'artifacts/lan-voice-v062-mouth-candidate-arm64-debug.apk'
|
||||
CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
|
||||
UI_SHA='8d18f4b4f46ad1a165901cd794d9407b4b61fc017cafb249a7addf9834d5e029'
|
||||
sha=lambda data:hashlib.sha256(data).hexdigest()
|
||||
|
||||
def import_runtime():
|
||||
raw=(SOURCE/'manifest.json').read_bytes();assert sha(raw)==PIN and len(raw)<=512000,'runtime04 manifest drift'
|
||||
m=json.loads(raw);assert m['schemaVersion']==1 and m['packId']=='a01-neutral-graph-v1-runtime-04' and m['identityId']=='a01'
|
||||
assert m['runtimeReady'] is True and m['publishApproval'] is False and m['deviceTestStatus']=='pending'
|
||||
assert m['naturalQualityStatus']=='pending_coordinator' and m['safeTransitions']['reviewStatus']=='pending' and m['approvedEdges']==[]
|
||||
assert m['patchFormat']['alphaEncoding']=='straight_unassociated' and m['patchFormat']['apertureLevels']==[0,.25,.5,.75,1]
|
||||
b=m['body'];assert b['sha256']=='177dbc0ab809e3c9c684899ffbd9cf3a2c357973c7037134f5d79e4e6cdfc762'
|
||||
assert (b['frameCount'],b['width'],b['height'],b['fpsNumerator'],b['fpsDenominator'],b['durationUs'],b['hasAudio'])==(97,480,848,24,1,4041667,False)
|
||||
files={'manifest.json':raw}
|
||||
def read(row,pattern,limit):
|
||||
name=row['path'];assert re.fullmatch(pattern,name) and name not in files
|
||||
p=(SOURCE/name).resolve(strict=True);assert p.is_relative_to(SOURCE.resolve()) and p.stat().st_size<=limit
|
||||
data=p.read_bytes();assert sha(data)==row['sha256'];files[name]=data
|
||||
read(b,r'body/[A-Za-z0-9_.-]+\.mp4',16000000)
|
||||
assert len(m['patches'])==97
|
||||
size=0
|
||||
for i,p in enumerate(m['patches']):
|
||||
assert p['frameIndex']==i and abs(p['ptsUs']-i*1000000//24)<=2
|
||||
x,y,w,h=(p[k] for k in ('x','y','width','height'))
|
||||
assert all(isinstance(v,int) for v in (x,y,w,h)) and 1<=w<=128 and 1<=h<=128 and 0<=x<=480-w and 0<=y<=848-h
|
||||
assert len(p['levels'])==5
|
||||
for level,l in enumerate(p['levels']):
|
||||
assert l['levelIndex']==level and l['aperture']==level/4
|
||||
read(l,r'patches/[A-Za-z0-9_.-]+\.png',256000)
|
||||
with Image.open(SOURCE/l['path']) as image:assert image.mode=='RGBA' and image.size==(w,h)
|
||||
size+=w*h*4
|
||||
assert p['path']==p['levels'][4]['path'] and p['sha256']==p['levels'][4]['sha256']
|
||||
assert size<=8000000 and len(files)==487
|
||||
for name,data in files.items():
|
||||
dest=PACK/name;assert not dest.exists() or dest.read_bytes()==data,'Unknown existing runtime04 byte: '+name
|
||||
for name,data in files.items():
|
||||
dest=PACK/name;dest.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
if dest.exists():continue
|
||||
fd,tmp=tempfile.mkstemp(prefix='.runtime04-',dir=dest.parent)
|
||||
try:
|
||||
with os.fdopen(fd,'wb') as f:f.write(data)
|
||||
os.chmod(tmp,0o600);os.replace(tmp,dest)
|
||||
finally:
|
||||
if os.path.exists(tmp):os.unlink(tmp)
|
||||
assert sha((SOURCE/'manifest.json').read_bytes())==PIN
|
||||
(LOG/'import.json').write_text(json.dumps({'manifestSha':PIN,'admissionScope':'coordinator_authorized_debug_device_candidate_only','fileCount':len(files),'rgbaBytes':size,'productionApproval':False},indent=2)+'\n')
|
||||
return m,files
|
||||
|
||||
def decode_math(m):
|
||||
body=PACK/m['body']['path']
|
||||
probe=json.loads(natural.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',body],'body-probe.json'))
|
||||
assert len(probe['streams'])==1 and len(probe['frames'])==97
|
||||
s=probe['streams'][0];assert (s['codec_name'],s['pix_fmt'],s['width'],s['height'],s['r_frame_rate'])==('h264','yuv420p',480,848,'24/1')
|
||||
assert all(abs(float(f['best_effort_timestamp_time'])-i/24)<1e-5 for i,f in enumerate(probe['frames']))
|
||||
natural.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',body,'-f','null','-'],'body-full-decode.txt')
|
||||
pipe=subprocess.Popen(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(body),'-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
metrics=[]
|
||||
try:
|
||||
for i,row in enumerate(m['patches']):
|
||||
data=pipe.stdout.read(480*848*3);assert len(data)==480*848*3
|
||||
base=np.frombuffer(data,np.uint8).reshape(848,480,3);x,y,w,h=[row[k] for k in ('x','y','width','height')]
|
||||
region=base[y:y+h,x:x+w].astype(float);previous=region
|
||||
for level,l in enumerate(row['levels']):
|
||||
rgba=np.asarray(Image.open(PACK/l['path']),float);a=rgba[:,:,3:4]/255
|
||||
out=region if level==0 else region*(1-a)+rgba[:,:,:3]*a
|
||||
if level==0:assert np.array_equal(out,region)
|
||||
delta=np.abs(out-previous)
|
||||
metrics.append({'frameIndex':i,'levelIndex':level,'opacity':0 if level==0 else 1,
|
||||
'adjacentLevelMaxRGB':float(delta.max()),'adjacentLevelMeanRGB':float(delta.mean()),
|
||||
'perceivedMotion':'unknown','zeroBypassExact':True if level==0 else None})
|
||||
previous=out
|
||||
assert pipe.stdout.read(1)==b'' and pipe.wait(timeout=10)==0
|
||||
finally:
|
||||
if pipe.poll() is None:pipe.kill();pipe.wait()
|
||||
(LOG/'level-math.json').write_text(json.dumps({'scope':'CPU selected geometry with spatial mask only; pixel deltas do not certify naturalness, visible talk or ≤1s','frames':metrics},indent=2)+'\n')
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--import-only',action='store_true');parser.add_argument('--verify-existing',action='store_true')
|
||||
args=parser.parse_args();LOG.mkdir(parents=True,exist_ok=True)
|
||||
m,files=import_runtime();_,oldfiles=natural.import_runtime()
|
||||
ui=ROOT/'artifacts/lan-voice-v062-ui-candidate-arm64-debug.apk';assert sha(ui.read_bytes())==UI_SHA
|
||||
if args.import_only:
|
||||
decode_math(m);print('PASS: runtime04 pinned debug candidate manifest/body/97x5RGBA, strict dimensions/bounds/hash, CFR/full decode, alpha0 bypass and selected geometry opacity1 math. runtime03/code14 retained.');return
|
||||
natural.tests_current()
|
||||
actual=(LOG/'actual-manifest-tests.txt').read_text();assert PIN in actual and 'PASS: actual exported runtime manifest parsed' in actual
|
||||
assert 'PASS: clean home' in (ROOT/'logs/avatar-safe-061/ui-contract-tests.txt').read_text()
|
||||
assert 'BUILD SUCCESSFUL' in (LOG/'android-test-compile.txt').read_text()
|
||||
golden=json.loads((LOG/'shader-golden/shader-golden.json').read_text());assert golden['status']=='passed' and len(golden['cases'])==40
|
||||
assert golden['shaderSourceSha']==sha((ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_bytes())
|
||||
if args.verify_existing:assert ARTIFACT.is_file();built=ARTIFACT
|
||||
else:
|
||||
assert not ARTIFACT.exists(),'Never overwrite a delivered code15 artifact'
|
||||
natural.run([ROOT/'scripts/build.sh','assembleDebug','-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+PIN],'assemble.txt')
|
||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk'
|
||||
extra={'assets/avatar/a01-neutral-graph-v1/runtime-04/'+n:data for n,data in files.items()}
|
||||
cert=natural.verify(built,oldfiles,15,'0.6.2-mouth-dev',extra);assert cert==CERT
|
||||
signature=natural.run([natural.TOOLS/'apksigner','verify','--print-certs',ui],'signature-code14.txt');assert CERT in signature
|
||||
with zipfile.ZipFile(built) as new,zipfile.ZipFile(ui) as old:
|
||||
for n in old.namelist():
|
||||
if n.startswith('assets/avatar/') and not n.endswith('/'):assert new.read(n)==old.read(n)
|
||||
if not args.verify_existing:
|
||||
with ARTIFACT.open('xb') as f:f.write(built.read_bytes())
|
||||
digest=sha(ARTIFACT.read_bytes());checksum=f'{digest} {ARTIFACT.name}\n'.encode();side=ARTIFACT.with_suffix('.apk.sha256')
|
||||
assert not side.exists() or side.read_bytes()==checksum;side.write_bytes(checksum)
|
||||
url='http://192.168.31.124:8080/'+ARTIFACT.name;opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(url,timeout=15) as response:
|
||||
data=response.read();assert response.status==200 and len(data)==ARTIFACT.stat().st_size and sha(data)==digest
|
||||
with opener.open(url+'.sha256',timeout=15) as response:assert response.status==200 and response.read()==checksum
|
||||
result={'scope':'coordinator_authorized_runtime04_debug_device_candidate_only','version':'0.6.2-mouth-dev','versionCode':15,
|
||||
'url':url,'apk':str(ARTIFACT),'sha256':digest,'bytes':ARTIFACT.stat().st_size,'sameCertificateSha256':cert,'manifestSha256':PIN,
|
||||
'httpBytesVerified':True,'permissionTiming':'foreground_host_layout_before_network','offlinePermissions':'manual_only_no_collection','mouthChanged':True,'mouthDeformationResolved':'not_certified','bodyChanged':False,
|
||||
'naturalQuality':'device_pending','visibleTalk':'device_pending','stairStepping':'device_pending','compliance1s':'not_certified',
|
||||
'productionApproval':False,'deviceInstall':'not_attempted','offlineExtra':'avatar_offline_preview'}
|
||||
(LOG/'delivery.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -104,7 +104,7 @@ def tests_current():
|
||||
assert sha((ROOT/'artifacts/lan-voice-v060-arm64-debug.apk').read_bytes())=='37f789820e86ac1656bda546f47ece3e4533ff8fc54614b171fd8a42accaa52e'
|
||||
assert 'APPROVED_MOTION_HASHES = emptySet<String>()' in (ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt').read_text()
|
||||
|
||||
def verify(apk,files,version_code=13,version_name='0.6.1-natural-dev'):
|
||||
def verify(apk,files,version_code=13,version_name='0.6.1-natural-dev',additional_assets=None):
|
||||
badge=run([TOOLS/'aapt','dump','badging',apk],'badging.txt')
|
||||
for value in ("name='com.gorios.lanvoice'",f"versionCode='{version_code}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||
assert value in badge,value
|
||||
@@ -126,6 +126,7 @@ def verify(apk,files,version_code=13,version_name='0.6.1-natural-dev'):
|
||||
expected['assets/avatar/a01-neutral-graph-v1/'+row['path']]=data
|
||||
still='assets/avatar/a01-standing-arms-reference/frames/reference.png';data=(ROOT/'app/src/main'/still).read_bytes()
|
||||
assert sha(data)=='36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2';expected[still]=data
|
||||
expected.update(additional_assets or {})
|
||||
with zipfile.ZipFile(apk) as z:
|
||||
actual={n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')}
|
||||
assert actual==set(expected),f'Unexpected/missing avatar files: {actual^set(expected)}'
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/* Executes the production vertex/fragment strings with a 2D body surrogate.
|
||||
* This tests shader UV/Fit/blend math, not Android OES decoder or Bitmap colors. */
|
||||
#include <EGL/egl.h>
|
||||
#include <EGL/eglext.h>
|
||||
#include <GLES2/gl2.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
#include <assert.h>
|
||||
static char *readfile(const char *path) {
|
||||
FILE *f=fopen(path,"rb");assert(f);fseek(f,0,SEEK_END);long n=ftell(f);rewind(f);
|
||||
char *p=calloc(n+1,1);assert(fread(p,1,n,f)==(size_t)n);fclose(f);return p;
|
||||
}
|
||||
static GLuint shader(GLenum type,const char *path) {
|
||||
char *source=readfile(path);GLuint s=glCreateShader(type);glShaderSource(s,1,(const char **)&source,NULL);glCompileShader(s);free(source);
|
||||
GLint ok;glGetShaderiv(s,GL_COMPILE_STATUS,&ok);if(!ok) {char log[4096];glGetShaderInfoLog(s,sizeof(log),NULL,log);fprintf(stderr,"%s\n",log);exit(2);}return s;
|
||||
}
|
||||
static void texture(GLuint id,int w,int h,const char *path) {
|
||||
unsigned char *data=(unsigned char*)readfile(path);glBindTexture(GL_TEXTURE_2D,id);
|
||||
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
|
||||
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,w,h,0,GL_RGBA,GL_UNSIGNED_BYTE,data);free(data);
|
||||
}
|
||||
int main(int argc,char **v) {
|
||||
assert(argc==14);
|
||||
int pw=atoi(v[6]),ph=atoi(v[7]),w=atoi(v[11]),h=atoi(v[12]);float x=atof(v[8]),y=atof(v[9]),opacity=atof(v[10]);
|
||||
PFNEGLGETPLATFORMDISPLAYEXTPROC platform=(void*)eglGetProcAddress("eglGetPlatformDisplayEXT");assert(platform);
|
||||
EGLDisplay d=platform(EGL_PLATFORM_SURFACELESS_MESA,EGL_DEFAULT_DISPLAY,NULL);assert(d!=EGL_NO_DISPLAY);
|
||||
EGLint major,minor;assert(eglInitialize(d,&major,&minor));assert(eglBindAPI(EGL_OPENGL_ES_API));
|
||||
EGLint attrs[]={EGL_SURFACE_TYPE,EGL_PBUFFER_BIT,EGL_RENDERABLE_TYPE,EGL_OPENGL_ES2_BIT,EGL_RED_SIZE,8,EGL_GREEN_SIZE,8,EGL_BLUE_SIZE,8,EGL_ALPHA_SIZE,8,EGL_NONE};
|
||||
EGLConfig config;EGLint count;assert(eglChooseConfig(d,attrs,&config,1,&count)&&count);
|
||||
EGLint ca[]={EGL_CONTEXT_CLIENT_VERSION,2,EGL_NONE};EGLContext c=eglCreateContext(d,config,EGL_NO_CONTEXT,ca);assert(c!=EGL_NO_CONTEXT);
|
||||
EGLint pa[]={EGL_WIDTH,w,EGL_HEIGHT,h,EGL_NONE};EGLSurface surface=eglCreatePbufferSurface(d,config,pa);assert(surface!=EGL_NO_SURFACE);
|
||||
assert(eglMakeCurrent(d,surface,surface,c));
|
||||
GLuint vertex=shader(GL_VERTEX_SHADER,v[1]),fragment=shader(GL_FRAGMENT_SHADER,v[2]);GLuint p=glCreateProgram();glAttachShader(p,vertex);glAttachShader(p,fragment);glLinkProgram(p);
|
||||
GLint linked;glGetProgramiv(p,GL_LINK_STATUS,&linked);assert(linked);glUseProgram(p);
|
||||
GLuint ids[2];glGenTextures(2,ids);glActiveTexture(GL_TEXTURE0);texture(ids[0],480,848,v[3]);glUniform1i(glGetUniformLocation(p,"uBody"),0);
|
||||
glActiveTexture(GL_TEXTURE1);texture(ids[1],pw,ph,v[4]);glUniform1i(glGetUniformLocation(p,"uPatch"),1);
|
||||
float scale=fminf(w/480.f,h/848.f),mw=480*scale,mh=848*scale,left=(w-mw)/2,top=(h-mh)/2;
|
||||
GLfloat pos[]={left/w*2-1,1-(top+mh)/h*2,(left+mw)/w*2-1,1-(top+mh)/h*2,left/w*2-1,1-top/h*2,(left+mw)/w*2-1,1-top/h*2};
|
||||
GLfloat uv[]={0,0,1,0,0,1,1,1};
|
||||
GLint a=glGetAttribLocation(p,"aPosition"),b=glGetAttribLocation(p,"aUv");glVertexAttribPointer(a,2,GL_FLOAT,GL_FALSE,0,pos);glEnableVertexAttribArray(a);glVertexAttribPointer(b,2,GL_FLOAT,GL_FALSE,0,uv);glEnableVertexAttribArray(b);
|
||||
/* OES surrogate data arrives top-down; flip body Y just as SurfaceTexture does.
|
||||
* A second case exercises a nontrivial crop transform; patch stays logical. */
|
||||
GLfloat m[]={1,0,0,0,0,-1,0,0,0,0,1,0,0,1,0,1};
|
||||
if(atoi(v[13])) {m[0]=.98f;m[5]=-.98f;m[12]=.01f;m[13]=.99f;}
|
||||
glUniformMatrix4fv(glGetUniformLocation(p,"uTextureMatrix"),1,GL_FALSE,m);
|
||||
glUniform4f(glGetUniformLocation(p,"uRect"),x,y,pw,ph);glUniform1f(glGetUniformLocation(p,"uOpacity"),opacity);
|
||||
glViewport(0,0,w,h);glClearColor(1,1,1,1);glClear(GL_COLOR_BUFFER_BIT);glDrawArrays(GL_TRIANGLE_STRIP,0,4);glFinish();assert(glGetError()==GL_NO_ERROR);
|
||||
unsigned char *out=malloc(w*h*4);glReadPixels(0,0,w,h,GL_RGBA,GL_UNSIGNED_BYTE,out);assert(glGetError()==GL_NO_ERROR);
|
||||
FILE *f=fopen(v[5],"wb");assert(f&&fwrite(out,1,w*h*4,f)==(size_t)w*h*4);fclose(f);free(out);
|
||||
printf("GLES vendor=%s renderer=%s\n",glGetString(GL_VENDOR),glGetString(GL_RENDERER));
|
||||
glDeleteTextures(2,ids);glDeleteProgram(p);glDeleteShader(vertex);glDeleteShader(fragment);
|
||||
eglMakeCurrent(d,EGL_NO_SURFACE,EGL_NO_SURFACE,EGL_NO_CONTEXT);eglDestroySurface(d,surface);eglDestroyContext(d,c);eglTerminate(d);return 0;
|
||||
}
|
||||
@@ -1,68 +1,91 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
fun checkAutoConversation() {
|
||||
val mic=EntryEffect.RequestPermission(EntryPermission.MICROPHONE)
|
||||
val cam=EntryEffect.RequestPermission(EntryPermission.CAMERA)
|
||||
fun requests(actions: List<EntryEffect>)=actions.filterIsInstance<EntryEffect.RequestPermission>()
|
||||
val flow=AutoConversation()
|
||||
check(flow.drive(false,false,false,0).isEmpty()) // not in actual foreground
|
||||
check(flow.drive(false,false,false,0).isEmpty())
|
||||
flow.enter()
|
||||
check(flow.drive(false,false,false,0) == listOf(EntryEffect.Connect))
|
||||
check(flow.drive(false,false,false,1).isEmpty()) // duplicate entry/pump never reconnects
|
||||
flow.connection(false,true,2)
|
||||
check(flow.drive(false,false,false,2).isEmpty()) // health/open socket isn't HELLO
|
||||
flow.connection(true,false,10)
|
||||
check(flow.drive(false,false,false,10) == listOf(EntryEffect.RequestPermission(EntryPermission.MICROPHONE)))
|
||||
check(flow.drive(false,false,false,11).isEmpty()) // one dialog at a time
|
||||
// First stable foreground requests permission before network/HELLO succeeds.
|
||||
check(flow.drive(false,false,false,0)==listOf(mic,EntryEffect.Connect))
|
||||
check(flow.drive(false,false,false,1).isEmpty())
|
||||
flow.connection(false,true,2);check(flow.drive(false,false,false,2).isEmpty())
|
||||
flow.leave();check(flow.permissionPending==EntryPermission.MICROPHONE)
|
||||
flow.permissionResult(EntryPermission.CAMERA,true) // wrong callback cannot clear MIC
|
||||
check(flow.permissionPending == EntryPermission.MICROPHONE)
|
||||
flow.permissionResult(EntryPermission.CAMERA,true);check(flow.permissionPending==EntryPermission.MICROPHONE)
|
||||
flow.permissionResult(EntryPermission.MICROPHONE,true)
|
||||
check(flow.drive(true,false,false,12).isEmpty()) // permission result in background starts no sensor
|
||||
flow.enter()
|
||||
check(flow.drive(true,false,false,13) == listOf(EntryEffect.StartVoice,EntryEffect.RequestPermission(EntryPermission.CAMERA)))
|
||||
flow.leave(); flow.permissionResult(EntryPermission.CAMERA,true)
|
||||
check(flow.drive(true,true,false,14).isEmpty())
|
||||
flow.enter()
|
||||
check(flow.drive(true,true,false,15) == listOf(EntryEffect.StartVoice,EntryEffect.StartCamera))
|
||||
check(flow.drive(true,true,true,16).isEmpty() && flow.phase == EntryPhase.ACTIVE)
|
||||
flow.cameraOff(); flow.leave(); flow.enter()
|
||||
check(flow.drive(true,true,false,20) == listOf(EntryEffect.StartVoice))
|
||||
// Denial survives reentry and never loops a system permission request.
|
||||
val denied=AutoConversation(); denied.enter(); denied.drive(false,false,false,0); denied.connection(true,false,1)
|
||||
denied.drive(false,false,false,1); denied.permissionResult(EntryPermission.MICROPHONE,false)
|
||||
check(denied.drive(false,false,false,2) == listOf(EntryEffect.RequestPermission(EntryPermission.CAMERA)))
|
||||
check(flow.drive(true,false,false,3).isEmpty()) // background callback cannot request/start
|
||||
flow.enter();check(flow.drive(true,false,false,4)==listOf(cam)) // no HELLO, sequential CAMERA
|
||||
flow.leave();flow.permissionResult(EntryPermission.CAMERA,false)
|
||||
check(flow.drive(true,false,false,5).isEmpty())
|
||||
flow.enter();check(flow.drive(true,false,false,6).isEmpty()) // permission alone cannot start voice
|
||||
flow.connection(true,false,7)
|
||||
check(flow.drive(true,false,false,7)==listOf(EntryEffect.StartVoice)) // denied camera still audio
|
||||
check(flow.drive(true,false,true,8).isEmpty() && flow.phase==EntryPhase.ACTIVE)
|
||||
flow.leave();check(flow.drive(true,true,true,9).isEmpty())
|
||||
|
||||
// Already granted camera may analyze in foreground before HELLO; MIC upload may not.
|
||||
val ready=AutoConversation(true,true);ready.enter()
|
||||
check(ready.drive(true,true,false,0)==listOf(EntryEffect.StartCamera,EntryEffect.Connect))
|
||||
check(ready.drive(true,true,false,1).isEmpty())
|
||||
ready.connection(true,false,2);check(ready.drive(true,true,false,2)==listOf(EntryEffect.StartVoice))
|
||||
repeat(20) { check(ready.drive(true,true,true,3L+it).isEmpty()) } // sheet/recomposition does not restart
|
||||
ready.cameraOff();ready.leave();ready.enter()
|
||||
check(ready.drive(true,true,false,30)==listOf(EntryEffect.StartVoice))
|
||||
|
||||
// Denied/asked choices are one-shot across foreground/reconnect; explicit manual
|
||||
// permission and permanent-denial settings action do not depend on network.
|
||||
val denied=AutoConversation();denied.enter();denied.drive(false,false,false,0)
|
||||
denied.permissionResult(EntryPermission.MICROPHONE,false)
|
||||
check(denied.drive(false,false,false,1)==listOf(cam))
|
||||
denied.permissionResult(EntryPermission.CAMERA,false)
|
||||
denied.leave(); denied.enter(); denied.connection(true,false,3)
|
||||
check(denied.drive(false,false,false,3).isEmpty() && denied.phase == EntryPhase.AWAITING_PERMISSION)
|
||||
check(!denied.requestPermission(EntryPermission.MICROPHONE,true)) // UI must open settings
|
||||
denied.connection(false,false,2);denied.leave();denied.enter()
|
||||
check(requests(denied.drive(false,false,false,3)).isEmpty())
|
||||
check(!denied.requestPermission(EntryPermission.MICROPHONE,true))
|
||||
check(denied.requestPermission(EntryPermission.MICROPHONE,false))
|
||||
check(denied.drive(false,false,false,4) == listOf(EntryEffect.RequestPermission(EntryPermission.MICROPHONE)))
|
||||
check(!denied.requestPermission(EntryPermission.CAMERA,false)) // queued/manual requests cannot overwrite
|
||||
check(requests(denied.drive(false,false,false,4))==listOf(mic))
|
||||
denied.permissionResult(EntryPermission.MICROPHONE,true)
|
||||
check(denied.drive(true,false,false,5) == listOf(EntryEffect.StartVoice)) // camera refusal does not block audio
|
||||
check(denied.drive(true,false,true,6).isEmpty() && denied.phase == EntryPhase.ACTIVE)
|
||||
// Three finite transport attempts: 1s and 3s backoff; no inference effects.
|
||||
val retry=AutoConversation(); retry.enter(); check(retry.drive(false,false,false,0).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,100); check(retry.phase == EntryPhase.ERROR && retry.retryAtMs == 1100L)
|
||||
check(!retry.retry(101))
|
||||
check(denied.drive(true,false,false,5).none { it==EntryEffect.StartVoice })
|
||||
denied.connection(true,false,6);check(denied.drive(true,false,false,6)==listOf(EntryEffect.StartVoice))
|
||||
|
||||
// Offline mode: never auto request/connect/capture, but manual consent works
|
||||
// regardless of connection, including callbacks before/after permission onStop.
|
||||
val offline=AutoConversation(conversationEnabled=false,automaticPermissions=false)
|
||||
offline.enter();check(offline.drive(false,false,false,0).isEmpty())
|
||||
check(offline.requestPermission(EntryPermission.MICROPHONE,false))
|
||||
check(offline.drive(false,false,false,1)==listOf(mic))
|
||||
check(!offline.requestPermission(EntryPermission.CAMERA,false))
|
||||
offline.permissionResult(EntryPermission.CAMERA,true);check(offline.permissionPending==EntryPermission.MICROPHONE)
|
||||
offline.leave();offline.permissionResult(EntryPermission.MICROPHONE,true)
|
||||
check(offline.drive(true,false,false,2).isEmpty())
|
||||
offline.enter();check(offline.drive(true,false,false,3).isEmpty())
|
||||
check(offline.requestPermission(EntryPermission.CAMERA,false))
|
||||
check(offline.drive(true,false,false,4)==listOf(cam))
|
||||
offline.permissionResult(EntryPermission.CAMERA,true) // callback before pause order
|
||||
offline.leave();check(offline.drive(true,true,false,5).isEmpty())
|
||||
offline.enter();check(offline.drive(true,true,false,6).isEmpty())
|
||||
check(offline.requestPermission(EntryPermission.MICROPHONE,false))
|
||||
check(offline.drive(true,true,false,7).isEmpty()) // already granted is a no-op
|
||||
check(!offline.requestPermission(EntryPermission.CAMERA,true))
|
||||
check(!offline.retry(8));offline.leave();check(!offline.requestPermission(EntryPermission.CAMERA,false))
|
||||
|
||||
val retry=AutoConversation(true,true,cameraInitiallyWanted=false)
|
||||
retry.enter();check(retry.drive(false,false,false,0)==listOf(EntryEffect.Connect))
|
||||
retry.connection(false,false,100);check(retry.retryAtMs==1100L && !retry.retry(101))
|
||||
check(retry.drive(false,false,false,1099).isEmpty())
|
||||
check(retry.drive(false,false,false,1100).single() == EntryEffect.Connect)
|
||||
check(retry.drive(false,false,false,1100)==listOf(EntryEffect.Connect))
|
||||
retry.connection(false,false,1200);check(retry.retryAtMs==4200L)
|
||||
check(retry.drive(false,false,false,4200).single() == EntryEffect.Connect)
|
||||
check(retry.drive(false,false,false,4200)==listOf(EntryEffect.Connect))
|
||||
retry.connection(false,false,4300);check(retry.retryAtMs==null && retry.attempts==3)
|
||||
check(retry.drive(false,false,false,900000).isEmpty())
|
||||
check(retry.retry(900001)); check(retry.drive(false,false,false,900001).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,900002,busy=true)
|
||||
check(retry.retryAtMs == null && retry.drive(false,false,false,910000).isEmpty())
|
||||
check(retry.retry(900001));retry.drive(false,false,false,900001)
|
||||
retry.connection(false,false,900002,busy=true);check(retry.retryAtMs==null)
|
||||
check(retry.drive(false,false,false,910000).isEmpty())
|
||||
retry.leave();check(retry.drive(true,true,false,1000000).isEmpty())
|
||||
val persisted=AutoConversation(true,true,cameraInitiallyWanted=false);persisted.enter()
|
||||
persisted.drive(true,true,false,0);persisted.connection(true,false,1)
|
||||
check(persisted.drive(true,true,false,1)==listOf(EntryEffect.StartVoice))
|
||||
check(persisted.drive(true,true,false,2).isEmpty() && persisted.phase == EntryPhase.ERROR) // failed audio start isn't retried forever
|
||||
// Opening/closing in-Activity settings has no enter/leave transition or effects.
|
||||
// Recomposition while ACTIVE must never reconnect, restart capture or request permission.
|
||||
val settings=AutoConversation(true,true);settings.enter()
|
||||
settings.drive(true,true,false,0);settings.connection(true,false,1)
|
||||
check(settings.drive(true,true,false,1)==listOf(EntryEffect.StartVoice,EntryEffect.StartCamera))
|
||||
repeat(20) { check(settings.drive(true,true,true,2L+it).isEmpty() && settings.phase==EntryPhase.ACTIVE) }
|
||||
settings.cameraOff();check(settings.drive(true,true,true,30).isEmpty())
|
||||
settings.leave();check(settings.drive(true,true,true,31).isEmpty())
|
||||
println("PASS: automatic foreground connection/real HELLO/sequential permission continuations, denial/settings/camera-off, audio independent of camera/video, finite retry and busy stop, failed audio-start bound; no device permission granted by tests")
|
||||
check(persisted.drive(true,true,false,2).isEmpty() && persisted.phase==EntryPhase.ERROR)
|
||||
println("PASS: first foreground permission requests independent of HELLO/network, one-shot/sequential callbacks/denial/permanent/manual retries, offline manual-only no connection/sensors, background guards, already-granted no-op, camera before HELLO and MIC only after HELLO, settings continuity, finite transport/audio-start retry; device dialogs pending")
|
||||
}
|
||||
|
||||
@@ -92,6 +92,7 @@ fun checkContinuous() {
|
||||
for(b in listOf(0f,.123f,1f)) for(a in listOf(0f,.5f,1f)) check(composeMouthChannel(b,.8f,a,0f)==b)
|
||||
check(kotlin.math.abs(composeMouthChannel(.2f,.8f,.5f,.5f)-.35f)<.00001)
|
||||
checkContinuousRenderer(pack)
|
||||
checkApertureRuntime()
|
||||
println("PASS: continuous runtime strict hash/bounds/97frame/routing/alpha parser; independent mouth state/latest generation/abort/reversal/random continuation; actual decoded-latched frame+loop indexing; Fit/patch mapping/alpha-zero; atomic presenter lifecycle and failure fences")
|
||||
}
|
||||
private fun checkContinuousRenderer(pack: ContinuousAvatarPack) {
|
||||
@@ -107,10 +108,11 @@ private fun checkContinuousRenderer(pack: ContinuousAvatarPack) {
|
||||
TestScheduler.advanceBy(2500)
|
||||
check(errors.isEmpty() && frames.size>97 && frames[97].key.index==0 && frames[97].key.loopOrdinal==1L)
|
||||
check(GLFixture.swaps==frames.size && GLFixture.draws==frames.size)
|
||||
check(frames.map { it.key.index+1 }==GLFixture.rendered.map { it.first })
|
||||
check(frames.map { it.selection.textureSlot+1 }==GLFixture.rendered.map { it.first })
|
||||
check(frames.map { it.selection.opacity }==GLFixture.rendered.map { it.second })
|
||||
check(frames.last().mouth.phase=="idle")
|
||||
val before=frames.size;renderer.close();TestScheduler.advanceBy(1000)
|
||||
check(frames.size==before && CodecFixture.releases==1 && GLFixture.deleted==98 && GLFixture.terminated==1)
|
||||
check(frames.size==before && CodecFixture.releases==1 && GLFixture.deleted==pack.textureImages.size+1 && GLFixture.terminated==1)
|
||||
reset();val (timestamp,_,timestampErrors)=rig();CodecFixture.onRender={pts->SurfaceTexture.lastCreated?.emit(pts*1000+100000)}
|
||||
TestScheduler.advanceBy(100);check(timestampErrors.size==1);timestamp.close()
|
||||
reset();GLFixture.swapFails=true;val (swap,swapFrames,swapErrors)=rig();TestScheduler.advanceBy(100)
|
||||
@@ -123,3 +125,40 @@ private fun checkContinuousRenderer(pack: ContinuousAvatarPack) {
|
||||
check(cancelFrames.isEmpty())
|
||||
println("PASS: real ContinuousBodyRenderer with deterministic Android MediaCodec/EGL doubles: one atomic draw/swap per decoded+latched body frame, 97frame wrap, patch selection, stop body continuity, timestamp/swap/size/timeout failures and resource teardown; actual GPU/device pending")
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun checkApertureRuntime() {
|
||||
val old=continuousFixture()
|
||||
val rows=(old["patches"] as List<Map<String,Any?>>).mapIndexed { index,p ->
|
||||
val levels=(0..4).map { level -> mapOf("levelIndex" to level,"aperture" to level/4f,
|
||||
"path" to "patches/$index-l$level.png","sha256" to runtimeSha) }
|
||||
p+mapOf("levels" to levels,"path" to levels[4]["path"])
|
||||
}
|
||||
val root=old+mapOf("packId" to "a01-neutral-graph-v1-runtime-04","patches" to rows,
|
||||
"patchFormat" to mapOf("format" to "PNG RGBA 8bit","alphaEncoding" to "straight_unassociated",
|
||||
"apertureLevels" to listOf(0f,.25f,.5f,.75f,1f),"requiresRendererExtension" to true))
|
||||
fun read(r: Map<String,Any?>)=ContinuousAvatarManifest.read(r,runtimeSha,runtimeSha,true,"runtime04/")
|
||||
val pack=checkNotNull(read(root));check(pack.apertureMode && pack.textureImages.size==485)
|
||||
for(frame in 0..96) for(level in 0..4) {
|
||||
val selection=selectMouthPatch(pack,frame,level/4f)
|
||||
check(selection.textureSlot==frame*5+level && selection.levelIndex==level)
|
||||
check(selection.opacity==if(level==0) 0f else 1f)
|
||||
check(pack.textureImages[selection.textureSlot].path=="patches/$frame-l$level.png")
|
||||
}
|
||||
for((g,level) in listOf(0f to 0,.1249f to 0,.125f to 0,.1251f to 1,.25f to 1,.375f to 1,.3751f to 2,.5f to 2,.75f to 3,1f to 4))
|
||||
check(selectMouthPatch(pack,0,g).levelIndex==level)
|
||||
for(g in listOf(Float.NaN,-.1f,1.1f)) check(runCatching { selectMouthPatch(pack,0,g) }.isFailure)
|
||||
check(runCatching { selectMouthPatch(pack,97,.5f) }.isFailure)
|
||||
val levels=rows[0]["levels"] as List<Map<String,Any?>>
|
||||
fun invalidFirst(row: Map<String,Any?>) { check(read(root+("patches" to listOf(row)+rows.drop(1)))==null) }
|
||||
invalidFirst(rows[0]+("levels" to levels.dropLast(1)))
|
||||
invalidFirst(rows[0]+("levels" to listOf(levels[0]+("levelIndex" to 3))+levels.drop(1)))
|
||||
invalidFirst(rows[0]+("levels" to listOf(levels[0]+("aperture" to .2f))+levels.drop(1)))
|
||||
invalidFirst(rows[0]+("levels" to listOf(levels[0]+("path" to "../x.png"))+levels.drop(1)))
|
||||
invalidFirst(rows[0]+("levels" to listOf(levels[0]+("path" to levels[1]["path"]))+levels.drop(1)))
|
||||
invalidFirst(rows[0]+("width" to 129));invalidFirst(rows[0]+("x" to 479))
|
||||
check(read(root+("patches" to rows.map { it+mapOf("width" to 128,"height" to 128) }))==null) // total RGBA cache cap
|
||||
check(read(root+("packId" to "a01-neutral-graph-v1-runtime-03"))==null)
|
||||
checkContinuousRenderer(pack) // real driver's chosen texture AND opacity at every present, through wrap/abort/teardown
|
||||
println("PASS: runtime04 strict97x5 levels/hash/path/bounds, nearest aperture ties, zero bypass/nonzero opacity1, cross-schema rejection, actual renderer selection/render opacity through97frame loop and lifecycle; no atlas used")
|
||||
}
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ object GLES20 {
|
||||
const val GL_FRAGMENT_SHADER=111;const val GL_COMPILE_STATUS=112;const val GL_TRUE=1;const val GL_LINK_STATUS=113
|
||||
const val GL_COLOR_BUFFER_BIT=114;const val GL_FLOAT=115;const val GL_TEXTURE0=116;const val GL_TEXTURE1=117;const val GL_TRIANGLE_STRIP=118
|
||||
fun glGetAttribLocation(p: Int,name: String)=if(name=="aPosition") 1 else 2
|
||||
fun glGetUniformLocation(p: Int,name: String)=when(name) { "uAlpha"->3;"uRect"->4;else->5 }
|
||||
fun glGetUniformLocation(p: Int,name: String)=when(name) { "uOpacity"->3;"uRect"->4;else->5 }
|
||||
fun glGenTextures(n: Int,ids: IntArray,o: Int) { repeat(n) { ids[o+it]=it+1 } }
|
||||
fun glBindTexture(target: Int,id: Int) { if(target==GL_TEXTURE_2D && GLFixture.activeUnit==GL_TEXTURE1) GLFixture.patchTexture=id }
|
||||
fun glTexParameteri(target: Int,name: Int,value: Int) {}
|
||||
|
||||
Reference in New Issue
Block a user