Трекинг 3д модели
20.11.2025, 21:44. Показов 636. Ответов 0
всем привет, столкнулся с проблемой, не получается настроить трекинг головы, использую mediapipe и 3д модель, устанавливаю маркеры на 3д модели, относительно точек mediapipe с помощью кода
| JavaScript | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
| const MARKER_PRESETS = [
{ key: 'RIGHT_EYE_OUTER', name: 'Внешний угол правого глаза модели' },
{ key: 'LEFT_EYE_OUTER', name: 'Внешний угол левого глаза модели' },
{ key: 'CHIN', name: 'Подбородок' },
]
export const MarkerManager = () => {
const {
camera,
gl: { domElement },
} = useThree()
const raycaster = useRef(new THREE.Raycaster())
const mouse = useRef(new THREE.Vector2())
const markerGroups = useRef<Record<string, THREE.Group>>({})
const [markerSelection, setMarkerSelection] = useState<{ hit: THREE.Intersection; modelId: string } | null>(
null,
)
const { isMarkerMode, selectedModelId, addMarkerToModel } = useAppStore()
const setIsMarkerMode = useAppStore((state) => state.setIsMarkerMode)
const models = useAppStore((state) => state.models)
const handleClick = useCallback(
(event: MouseEvent) => {
if (!isMarkerMode || !selectedModelId) return
const model = models.find((m) => m.id === selectedModelId)
if (!model || !model.mesh) return
const rect = domElement.getBoundingClientRect()
mouse.current.x = ((event.clientX - rect.left) / rect.width) * 2 - 1
mouse.current.y = -((event.clientY - rect.top) / rect.height) * 2 + 1
raycaster.current.setFromCamera(mouse.current, camera)
const meshes: THREE.Mesh[] = []
model.mesh.traverse((child) => {
if (child instanceof THREE.Mesh) meshes.push(child)
})
if (meshes.length === 0) return
const intersects = raycaster.current.intersectObjects(meshes, true)
if (intersects.length === 0) return
// Показываем выбор маркера через Html
setMarkerSelection({ hit: intersects[0], modelId: model.id })
},
[camera, domElement, isMarkerMode, selectedModelId, models],
)
useEffect(() => {
if (!domElement || !isMarkerMode) return
domElement.addEventListener('click', handleClick)
return () => domElement.removeEventListener('click', handleClick)
}, [domElement, handleClick, isMarkerMode])
const placeMarker = (preset: (typeof MARKER_PRESETS)[0]) => {
if (!markerSelection) return
const { hit, modelId } = markerSelection
const model = models.find((m) => m.id === modelId)
if (!model || !model.mesh) return
const parentObject = model.mesh.children.find(
(child) => child.type === 'Group' || child instanceof THREE.Object3D,
)
if (!parentObject) return
if (!markerGroups.current[model.id]) {
const group = new THREE.Group()
group.name = 'MarkerGroup'
parentObject.add(group)
markerGroups.current[model.id] = group
}
const markerGroup = markerGroups.current[model.id]
const localPoint = markerGroup.worldToLocal(hit.point.clone())
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(2, 16, 16),
new THREE.MeshBasicMaterial({ depthTest: false }),
)
sphere.position.copy(localPoint)
markerGroup.add(sphere)
addMarkerToModel(model.id, {
name: preset.name,
key: preset.key,
position: localPoint,
nodeUuid: hit.object.uuid,
})
setMarkerSelection(null)
setIsMarkerMode(false)
}
return (
<>
{markerSelection &&
(() => {
const model = models.find((m) => m.id === markerSelection.modelId)
if (!model) return null
// Получаем ключи уже установленных маркеров для этой модели
const existingKeys = new Set(model.markers?.map((m) => m.key) || [])
return (
<Html position={markerSelection.hit.point} center style={{ pointerEvents: 'auto' }}>
<div
style={{
display: 'flex',
gap: '8px',
background: 'rgba(0,0,0,0.85)',
padding: '8px 12px',
borderRadius: '8px',
boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
flexDirection: 'column',
alignItems: 'center',
minWidth: '300px',
}}
onPointerDownCapture={(e) => e.stopPropagation()}
onPointerUpCapture={(e) => e.stopPropagation()}
onPointerMoveCapture={(e) => e.stopPropagation()}
>
{/* Крестик */}
<button
onClick={(e) => {
e.stopPropagation()
setMarkerSelection(null) // или твоя функция закрытия
}}
style={{
position: 'absolute',
top: '4px',
right: '6px',
cursor: 'pointer',
}}
onMouseEnter={(e) => (e.currentTarget.style.color = '#f55')}
onMouseLeave={(e) => (e.currentTarget.style.color = '#fff')}
>
<X />
</button>
<div>Примечание: Точки располагаются зеркально</div>
{MARKER_PRESETS.filter((p) => !existingKeys.has(p.key)).map((preset) => (
<button
key={preset.key}
onClick={(e) => {
e.stopPropagation()
placeMarker(preset)
}}
style={{
background: '#1e1e1e',
color: 'white',
border: 'none',
borderRadius: '6px',
padding: '6px 12px',
cursor: 'pointer',
fontSize: '14px',
width: '100%',
transition: 'all 0.2s',
}}
onMouseEnter={(e) => (e.currentTarget.style.background = '#333')}
onMouseLeave={(e) => (e.currentTarget.style.background = '#1e1e1e')}
>
{preset.name} [{preset.key}]
</button>
))}
</div>
</Html>
)
})()}
</>
)
} |
|
скрин
и с помощью функции трекинга пытаюсь
| JavaScript | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
| export const FaceTracking = ({ clonedModels }: PreviewFaceTrackingProps) => {
// Получаем videoAspect из стора
const { faceLandmarks, isFaceTrackingActive, videoAspect } = useAppStore()
const previousHeadPose = useRef(null)
const smoothedLandmarks = useRef<Record<number, { x: number; y: number; z: number }>>({})
const smoothingAlpha = 0.7 // Сглаживание для точек, оставляем
// Флаг для плавной инициализации перед "жесткой" привязкой
const isInitialized = useRef<Record<string, boolean>>({})
const getHeadPoseFromMarkers = useCallback(
(model: any) => {
if (!faceLandmarks || faceLandmarks.length === 0 || !model.markers || model.markers.length < 3) {
return null
}
try {
const LANDMARKS = {
LEFT_EYE_OUTER: 359,
RIGHT_EYE_OUTER: 226,
CHIN: 152,
}
// Сглаживание точек (EMA)
Object.keys(LANDMARKS).forEach((key) => {
const index = LANDMARKS[key]
const current = faceLandmarks[index]
if (current) {
const prev = smoothedLandmarks.current[index] || current
smoothedLandmarks.current[index] = {
x: prev.x * (1 - smoothingAlpha) + current.x * smoothingAlpha,
y: prev.y * (1 - smoothingAlpha) + current.y * smoothingAlpha,
z: prev.z * (1 - smoothingAlpha) + current.z * smoothingAlpha,
}
}
})
const getSmoothedPoint = (index: number) => smoothedLandmarks.current[index] || faceLandmarks[index]
// Преобразование координат
const getPoint = (index: number) => {
const lm = getSmoothedPoint(index)
if (!lm) return new THREE.Vector3(0, 0, 0)
const x = (lm.x - 0.5) * 2
const y = (0.5 - lm.y) * (2 / videoAspect)
const z = -lm.z * 2
return new THREE.Vector3(x, y, z)
}
const facePoints = {
leftEyeOuter: getPoint(LANDMARKS.LEFT_EYE_OUTER),
rightEyeOuter: getPoint(LANDMARKS.RIGHT_EYE_OUTER),
chin: getPoint(LANDMARKS.CHIN),
}
const modelMarkers = model.markers.reduce((acc: any, marker: any) => {
acc[marker.key] = marker.position.clone()
return acc
}, {})
if (!modelMarkers['LEFT_EYE_OUTER'] || !modelMarkers['RIGHT_EYE_OUTER'] || !modelMarkers['CHIN']) {
return null
}
// --- Расчет позы (без изменений) ---
const modelChinToLeft = new THREE.Vector3().subVectors(
modelMarkers['LEFT_EYE_OUTER'],
modelMarkers['CHIN'],
)
const modelChinToRight = new THREE.Vector3().subVectors(
modelMarkers['RIGHT_EYE_OUTER'],
modelMarkers['CHIN'],
)
const faceChinToLeft = new THREE.Vector3().subVectors(facePoints.leftEyeOuter, facePoints.chin)
const faceChinToRight = new THREE.Vector3().subVectors(facePoints.rightEyeOuter, facePoints.chin)
const distChinLeftModel = modelChinToLeft.length()
const distChinRightModel = modelChinToRight.length()
const distLeftRightModel = modelMarkers['LEFT_EYE_OUTER'].distanceTo(modelMarkers['RIGHT_EYE_OUTER'])
const distChinLeftFace = faceChinToLeft.length()
const distChinRightFace = faceChinToRight.length()
const distLeftRightFace = facePoints.leftEyeOuter.distanceTo(facePoints.rightEyeOuter)
const scale =
(distChinLeftFace / distChinLeftModel +
distChinRightFace / distChinRightModel +
distLeftRightFace / distLeftRightModel) /
3
const modelRight = new THREE.Vector3().crossVectors(modelChinToLeft, modelChinToRight).normalize()
const modelUp = new THREE.Vector3().addVectors(modelChinToLeft, modelChinToRight).normalize()
const modelForward = new THREE.Vector3().crossVectors(modelRight, modelUp).normalize()
const faceRight = new THREE.Vector3().crossVectors(faceChinToLeft, faceChinToRight).normalize()
const faceUp = new THREE.Vector3().addVectors(faceChinToLeft, faceChinToRight).normalize()
const faceForward = new THREE.Vector3().crossVectors(faceRight, faceUp).normalize()
const modelBasis = new THREE.Matrix4().makeBasis(modelRight, modelUp, modelForward)
const faceBasis = new THREE.Matrix4().makeBasis(faceRight, faceUp, faceForward)
const rotationMatrix = new THREE.Matrix4().multiplyMatrices(faceBasis, modelBasis.clone().invert())
const rotation = new THREE.Quaternion().setFromRotationMatrix(rotationMatrix)
const faceCenter = new THREE.Vector3()
.addVectors(facePoints.chin, facePoints.leftEyeOuter)
.add(facePoints.rightEyeOuter)
.multiplyScalar(1 / 3)
// --- ГЛАВНОЕ ИЗМЕНЕНИЕ: Корректный расчет позиции ---
// 1. Находим реальный геометрический центр 3D-модели.
// ВАЖНО: Для производительности это следует вычислить один раз при загрузке модели и сохранить.
const modelBox = new THREE.Box3().setFromObject(model.mesh)
const modelGeometryCenter = modelBox.getCenter(new THREE.Vector3())
// 2. Применяем вычисленные поворот и масштаб к геометрическому центру.
// Это показывает нам, куда сместится центр модели после трансформации.
const transformedGeometryCenter = modelGeometryCenter
.clone()
.applyQuaternion(rotation)
.multiplyScalar(scale)
// 3. Вычисляем финальную позицию для origin'а модели.
// Мы хотим, чтобы преобразованный геометрический центр модели совпал с центром лица.
const position = new THREE.Vector3().subVectors(faceCenter, transformedGeometryCenter)
return { position, rotation, scale }
} catch (error) {
console.error('Error calculating head pose from markers:', error)
return null
}
},
[faceLandmarks, videoAspect],
)
// --- useFrame и useEffect остаются без изменений ---
useFrame(() => {
if (!isFaceTrackingActive || !faceLandmarks?.length) {
return
}
clonedModels.forEach((model) => {
if (model.isTracking && model.mesh) {
const headPose = getHeadPoseFromMarkers(model)
if (!headPose) return
if (isInitialized.current[model.id] === undefined) {
isInitialized.current[model.id] = false
}
if (!isInitialized.current[model.id]) {
model.mesh.position.lerp(headPose.position, 0.1)
model.mesh.quaternion.slerp(headPose.rotation, 0.1)
model.mesh.scale.lerp(new THREE.Vector3(headPose.scale, headPose.scale, headPose.scale), 0.1)
const posDiff = model.mesh.position.distanceToSquared(headPose.position)
const rotDiff = model.mesh.quaternion.angleTo(headPose.rotation)
const scaleDiff = Math.abs(model.mesh.scale.x - headPose.scale)
if (posDiff < 0.0001 && rotDiff < 0.01 && scaleDiff < 0.01) {
isInitialized.current[model.id] = true
console.log(`FaceTracking: Model ${model.id} initialized, switching to hard lock.`)
}
} else {
model.mesh.position.copy(headPose.position)
model.mesh.quaternion.copy(headPose.rotation)
model.mesh.scale.setScalar(headPose.scale)
}
}
})
})
useEffect(() => {
if (!isFaceTrackingActive) {
previousHeadPose.current = null
smoothedLandmarks.current = {}
isInitialized.current = {}
console.log('FaceTracking: Reset state')
}
}, [isFaceTrackingActive])
return null
} |
|
и модель у меня выходит за пределы головы
то есть, не сохраняется анатомическая структура, и отсюда возникает вопросы, как мне сделать так, чтобы модель была внутри головы
Буду очень сильно признателен за помощь
0
|