mmd-mpl 0.3.4

MPL is a rule-based Domain-Specific Language for creating MMD poses and animations using natural semantic syntax
Documentation
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::{
    mpl::MPLBoneFrame,
    utils::{Quaternion, Vector3},
    with_bone_db, ActionRule,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MPLPoseStatement {
    pub bone: String,
    pub action: String,
    pub direction: String,
    pub amount: f32,
}

impl MPLPoseStatement {
    pub fn from_str(text: &str) -> Result<Self, String> {
        if text.is_empty() {
            return Err("Empty statement".to_string());
        }
        let parts = text.split_whitespace().collect::<Vec<&str>>();
        if parts.len() != 4 {
            if parts.len() == 2 && parts[1] == "reset" {
                return Ok(Self {
                    bone: parts[0].to_string(),
                    action: "reset".to_string(),
                    direction: "".to_string(),
                    amount: 0.0,
                });
            }
            return Err("Invalid statement".to_string());
        }

        let bone = parts[0].to_string();
        let action = parts[1].to_string();
        let direction = parts[2].to_string();
        let amount: f32 = parts[3]
            .trim()
            .parse()
            .map_err(|_| "Invalid degrees number".to_string())?;

        with_bone_db(|db| db.validate(&bone, &action, &direction, amount))?;

        Ok(Self {
            bone,
            action,
            direction,
            amount,
        })
    }

    pub fn to_string(&self) -> String {
        if self.action == "reset" {
            return format!("{} reset;", self.bone);
        }

        format!(
            "{} {} {} {:.0};",
            self.bone,
            self.action,
            self.direction,
            self.amount.round()
        )
    }

    pub fn to_vector(&self) -> Vector3 {
        let rule = with_bone_db(|db| {
            db.get_rule(&self.bone, &self.action, &self.direction)
                .cloned()
        });

        let rule = match rule {
            Some(r) => r,
            None => return Vector3::new(0.0, 0.0, 0.0),
        };

        let normalized_axis = rule.axis.normalize();
        normalized_axis.multiply_by_scalar(self.amount)
    }

    pub fn from_vector(bone: &str, target_vector: Vector3) -> Vec<Self> {
        let bone = bone.to_string();
        let mut statements = vec![];

        // Map vector components to move directions
        let direction_mappings = [
            (target_vector.x, "right", "left"),
            (target_vector.y, "up", "down"),
            (target_vector.z, "backward", "forward"),
        ];

        for (component, pos_dir, neg_dir) in direction_mappings {
            if component.abs() > 0.01 {
                let direction = if component > 0.0 { pos_dir } else { neg_dir };
                let amount = component.abs();

                // Check if this bone supports this move direction
                let has_rule = with_bone_db(|db| db.get_rule(&bone, "move", direction).is_some());
                if has_rule {
                    statements.push(Self {
                        bone: bone.clone(),
                        action: "move".to_string(),
                        direction: direction.to_string(),
                        amount,
                    });
                }
            }
        }
        statements
    }

    pub fn to_quaternion(&self) -> Quaternion {
        if self.action == "reset" {
            return Quaternion::identity();
        }

        let rule = with_bone_db(|db| {
            db.get_rule(&self.bone, &self.action, &self.direction)
                .cloned()
        });

        let rule = match rule {
            Some(r) => r,
            None => return Quaternion::identity(),
        };

        let normalized_axis = rule.axis.normalize();

        let radians = self.amount * (std::f32::consts::PI / 180.0);
        let half_angle = radians / 2.0;
        let sin = half_angle.sin();
        let cos = half_angle.cos();

        Quaternion::new(
            normalized_axis.x * sin,
            normalized_axis.y * sin,
            normalized_axis.z * sin,
            cos,
        )
    }

    pub fn from_quaternion(bone: &str, target_quat: Quaternion) -> Vec<Self> {
        let bone = bone.to_string();

        // Gather all possible (action, direction) rules for this bone
        let possible_actions: Vec<(String, String, ActionRule)> = with_bone_db(|db| {
            let mut vec = Vec::new();
            if let Some(actions) = db.actions(&bone) {
                for action in actions {
                    if action == "move" {
                        continue;
                    }
                    if let Some(directions) = db.directions(&bone, action) {
                        for direction in directions {
                            if let Some(rule) = db.get_rule(&bone, action, direction) {
                                vec.push((action.to_string(), direction.to_string(), rule.clone()));
                            }
                        }
                    }
                }
            }
            vec
        });
        if possible_actions.is_empty() {
            return vec![];
        }

        // Special case: if target quaternion is identity (0,0,0,1),
        // return bone reset
        if target_quat.x == 0.0
            && target_quat.y == 0.0
            && target_quat.z == 0.0
            && target_quat.w == 1.0
        {
            let mut statements = Vec::new();
            statements.push(Self {
                bone: bone.clone(),
                action: "reset".to_string(),
                direction: "".to_string(),
                amount: 0.0,
            });
            return statements;
        }

        // Ensure deterministic order independent of HashMap iteration
        let mut possible_actions = possible_actions;
        possible_actions.sort_by(|a, b| {
            let key_a = format!("{}-{}", a.0, a.1);
            let key_b = format!("{}-{}", b.0, b.1);
            key_a.cmp(&key_b)
        });

        // Evaluate fitness of a degree combination
        let evaluate_combination = |degrees: &[f32]| -> f32 {
            if degrees.len() != possible_actions.len() {
                return f32::INFINITY;
            }

            let mut combined_quaternion = Quaternion::identity();

            for (i, deg) in degrees.iter().enumerate() {
                let clamped_deg = deg.max(0.0).min(possible_actions[i].2.limit);
                if clamped_deg > 0.01 {
                    // Only apply significant rotations
                    let q = Quaternion::from_axis_angle(possible_actions[i].2.axis, clamped_deg);
                    combined_quaternion = combined_quaternion.multiply(&q);
                }
            }

            target_quat.angular_distance(&combined_quaternion)
        };

        // Nelder-Mead simplex optimization algorithm
        let nelder_mead = |initial_guess: &[f32], max_iterations: usize| -> (Vec<f32>, f32) {
            let n = initial_guess.len();
            let alpha = 1.0; // reflection coefficient
            let gamma = 2.0; // expansion coefficient
            let rho = 0.5; // contraction coefficient
            let sigma = 0.5; // shrinkage coefficient

            // Initialize simplex with n+1 points
            let mut simplex: Vec<(Vec<f32>, f32)> = Vec::new();

            simplex.push((initial_guess.to_vec(), evaluate_combination(initial_guess)));

            // Create additional points by perturbing initial guess
            for i in 0..n {
                let mut point = initial_guess.to_vec();
                let range = possible_actions[i].2.limit;
                point[i] += range * 0.1;
                let value = evaluate_combination(&point);
                simplex.push((point, value));
            }

            // Main optimization loop
            for _ in 0..max_iterations {
                simplex.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());

                let best_value = simplex[0].1;
                let worst_value = simplex[n].1;
                let second_worst_value = simplex[n - 1].1;

                // Check convergence
                if worst_value - best_value < 0.0001 {
                    break;
                }

                // Calculate centroid (excluding worst point)
                let mut centroid = vec![0.0f32; n];
                for i in 0..n {
                    for j in 0..n {
                        centroid[j] += simplex[i].0[j];
                    }
                }
                for j in 0..n {
                    centroid[j] /= n as f32;
                }

                // Reflection step
                let reflected: Vec<f32> = centroid
                    .iter()
                    .zip(&simplex[n].0)
                    .map(|(c, w)| c + alpha * (c - w))
                    .collect();
                let reflected_value = evaluate_combination(&reflected);

                if reflected_value >= best_value && reflected_value < second_worst_value {
                    simplex[n] = (reflected, reflected_value);
                    continue;
                }

                // Expansion step
                if reflected_value < best_value {
                    let expanded: Vec<f32> = centroid
                        .iter()
                        .zip(&reflected)
                        .map(|(c, r)| c + gamma * (r - c))
                        .collect();
                    let expanded_value = evaluate_combination(&expanded);

                    if expanded_value < reflected_value {
                        simplex[n] = (expanded, expanded_value);
                    } else {
                        simplex[n] = (reflected, reflected_value);
                    }
                    continue;
                }

                // Contraction step
                let contracted: Vec<f32> = centroid
                    .iter()
                    .zip(&simplex[n].0)
                    .map(|(c, w)| c + rho * (w - c))
                    .collect();
                let contracted_value = evaluate_combination(&contracted);

                if contracted_value < worst_value {
                    simplex[n] = (contracted, contracted_value);
                    continue;
                }

                // Shrinkage step
                let best_point = simplex[0].0.clone();
                for i in 1..=n {
                    for j in 0..n {
                        simplex[i].0[j] = best_point[j] + sigma * (simplex[i].0[j] - best_point[j]);
                    }
                    simplex[i].1 = evaluate_combination(&simplex[i].0);
                }
            }

            simplex.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
            (simplex[0].0.clone(), simplex[0].1)
        };

        let mut best_result = (Vec::new(), f32::INFINITY);

        // Try optimization from multiple starting points for global search
        let starting_points = vec![
            vec![0.0; possible_actions.len()], // Zero start
            possible_actions
                .iter()
                .enumerate()
                .map(|(i, action)| {
                    let limit = action.2.limit.min(30.0);
                    // Use deterministic "random" values based on index
                    let pseudo_random = ((i * 12345) % 1000) as f32 / 1000.0;
                    (limit * pseudo_random).min(limit)
                })
                .collect(), // Pseudo-random start
            possible_actions
                .iter()
                .map(|action| action.2.limit * 0.5)
                .collect(), // Mid-range start
            possible_actions
                .iter()
                .enumerate()
                .map(|(i, action)| {
                    if i % 2 == 0 {
                        action.2.limit * 0.3
                    } else {
                        action.2.limit * 0.7
                    }
                })
                .collect(), // Mixed start
        ];

        for start in starting_points {
            let result = nelder_mead(&start, 1000);
            if result.1 < best_result.1 {
                best_result = result;
            }
        }

        // Convert optimal degrees to MPL statements and simplify opposing actions
        let mut action_map: HashMap<String, HashMap<String, f32>> = HashMap::new();

        // Group degrees by action and direction
        for (i, deg) in best_result.0.iter().enumerate() {
            if *deg > 0.01 {
                let action = &possible_actions[i];
                let clamped_deg = deg.max(0.0).min(action.2.limit);

                action_map
                    .entry(action.0.clone())
                    .or_default()
                    .insert(action.1.clone(), clamped_deg);
            }
        }

        // Simplify opposing directions within each action
        let mut statements = Vec::new();
        for (action, directions) in action_map.into_iter() {
            // Handle opposing pairs
            let opposing_pairs = [("forward", "backward"), ("left", "right")];
            let mut processed_directions = std::collections::HashSet::new();

            for (dir1, dir2) in opposing_pairs.iter() {
                if directions.contains_key(*dir1)
                    && directions.contains_key(*dir2)
                    && !processed_directions.contains(*dir1)
                    && !processed_directions.contains(*dir2)
                {
                    let deg1 = directions.get(*dir1).unwrap();
                    let deg2 = directions.get(*dir2).unwrap();
                    let net_degrees = (deg1 - deg2).abs();

                    if net_degrees > 0.01 {
                        let net_direction = if deg1 > deg2 { dir1 } else { dir2 };
                        statements.push(Self {
                            bone: bone.clone(),
                            action: action.clone(),
                            direction: net_direction.to_string(),
                            amount: net_degrees,
                        });
                    }

                    processed_directions.insert(*dir1);
                    processed_directions.insert(*dir2);
                }
            }

            // Handle remaining directions that don't have opposing pairs
            for (direction, degrees) in directions.iter() {
                if !processed_directions.contains(direction.as_str()) && *degrees > 0.01 {
                    statements.push(Self {
                        bone: bone.clone(),
                        action: action.clone(),
                        direction: direction.clone(),
                        amount: *degrees,
                    });
                }
            }
        }

        // Format statements to match TypeScript output format
        let s = statements
            .into_iter()
            .map(|stmt| MPLPoseStatement {
                amount: (stmt.amount / 5.0).round() * 5.0,
                ..stmt
            })
            .filter(|stmt| stmt.amount.abs() >= 0.0)
            .collect();
        return s;
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MPLPose {
    pub name: String,
    pub statements: Vec<MPLPoseStatement>,
}

impl MPLPose {
    pub fn new(name: String, statements: Vec<MPLPoseStatement>) -> Self {
        Self { name, statements }
    }

    pub fn to_string(&self) -> String {
        // Group statements by bone
        let mut bone_groups: HashMap<String, Vec<&MPLPoseStatement>> = HashMap::new();
        for statement in &self.statements {
            bone_groups
                .entry(statement.bone.clone())
                .or_insert_with(Vec::new)
                .push(statement);
        }

        // Sort bones according to BONES array order for consistent output
        let mut sorted_bones: Vec<_> = bone_groups.into_iter().collect();
        sorted_bones.sort_by(|(a, _), (b, _)| {
            let a_idx = crate::bone::BONES
                .iter()
                .position(|&x| x == a)
                .unwrap_or(999);
            let b_idx = crate::bone::BONES
                .iter()
                .position(|&x| x == b)
                .unwrap_or(999);
            a_idx.cmp(&b_idx)
        });

        // Convert each bone's statements to compound format
        let mut compound_statements = Vec::new();
        for (bone, statements) in sorted_bones {
            if statements.len() == 1 {
                // Single statement - use as-is
                compound_statements.push(format!("    {}", statements[0].to_string()));
            } else {
                // Multiple statements - combine into compound format
                let compound_parts: Vec<String> = statements
                    .iter()
                    .map(|stmt| {
                        if stmt.action == "reset" {
                            "reset".to_string()
                        } else {
                            format!("{} {} {}", stmt.action, stmt.direction, stmt.amount.round())
                        }
                    })
                    .collect();
                compound_statements.push(format!("    {} {};", bone, compound_parts.join(", ")));
            }
        }

        format!("{{\n{}\n}}", compound_statements.join("\n"))
    }

    pub fn to_script(&self) -> String {
        // Filter out reset statements and zero-degree actions for static pose
        let filtered_statements: Vec<MPLPoseStatement> = self
            .statements
            .iter()
            .filter(|stmt| stmt.action != "reset" && stmt.amount.abs() > 0.01)
            .cloned()
            .collect();

        let filtered_pose = MPLPose::new(self.name.clone(), filtered_statements);

        format!(
            "@pose {} {}\n\nmain {{\n    {};\n}}",
            self.name,
            filtered_pose.to_string(),
            self.name
        )
    }

    pub fn to_block(&self) -> String {
        format!("@pose {} {}\n", self.name, self.to_string())
    }

    pub fn to_bone_frames(&self) -> Vec<MPLBoneFrame> {
        let mut frames = vec![];

        // Expand grouped finger statements into individual joint statements
        let mut expanded_statements = Vec::new();
        for statement in &self.statements {
            if Self::is_grouped_finger_bone(&statement.bone) {
                expanded_statements.extend(Self::expand_grouped_finger_statement(statement));
            } else {
                expanded_statements.push(statement.clone());
            }
        }

        // Process all statements (expanded and original)
        let mut bone_groups: HashMap<String, Vec<&MPLPoseStatement>> = HashMap::new();
        for statement in &expanded_statements {
            bone_groups
                .entry(statement.bone.clone())
                .or_insert_with(Vec::new)
                .push(statement);
        }

        for (bone, bone_statements) in bone_groups {
            let mut combined_position = Vector3::new(0.0, 0.0, 0.0);
            let mut combined_quaternion = Quaternion::identity();

            for statement in bone_statements {
                if statement.action == "move" {
                    let vector = statement.to_vector();
                    combined_position = combined_position.add(&vector);
                } else if statement.action == "reset" {
                    combined_quaternion = Quaternion::identity();
                } else {
                    let quaternion = statement.to_quaternion();
                    combined_quaternion = combined_quaternion.multiply(&quaternion);
                }
            }

            let bone_name_jp =
                with_bone_db(|db| db.japanese_name(&bone).unwrap_or(&bone).to_string());

            frames.push(MPLBoneFrame::new(
                bone,
                bone_name_jp,
                combined_position,
                combined_quaternion,
            ));
        }

        frames
    }

    pub fn from_bone_frames(name: &str, frames: Vec<MPLBoneFrame>) -> Self {
        let mut statements = vec![];
        for frame in frames.iter() {
            statements.extend(MPLPoseStatement::from_vector(
                &frame.name_en(),
                frame.position(),
            ));
            statements.extend(MPLPoseStatement::from_quaternion(
                &frame.name_en(),
                frame.rotation(),
            ));
        }

        // Consolidate individual finger joint statements into grouped finger statements
        let consolidated_statements = Self::consolidate_finger_statements(&statements);

        Self::new(name.to_string(), consolidated_statements)
    }

    fn expand_grouped_finger_statement(
        stmt: &crate::pose::MPLPoseStatement,
    ) -> Vec<crate::pose::MPLPoseStatement> {
        let mut expanded_statements = Vec::new();

        // Define finger joint mappings with ratios
        // Based on natural finger movement: MCP (1.0) > PIP (0.85-0.95) > DIP (0.5-0.7)
        let finger_mappings = match stmt.bone.as_str() {
            "thumb_l" => vec![("thumb_0_l", 1.0), ("thumb_1_l", 0.85)], // Thumb has different joint structure
            "index_l" => vec![("index_0_l", 1.0), ("index_1_l", 0.9), ("index_2_l", 0.65)],
            "middle_l" => vec![
                ("middle_0_l", 1.0),
                ("middle_1_l", 0.9),
                ("middle_2_l", 0.65),
            ],
            "ring_l" => vec![("ring_0_l", 1.0), ("ring_1_l", 0.88), ("ring_2_l", 0.6)], // Ring finger bends slightly less
            "pinky_l" => vec![("pinky_0_l", 1.0), ("pinky_1_l", 0.85), ("pinky_2_l", 0.55)], // Pinky bends the least
            "thumb_r" => vec![("thumb_1_r", 1.0), ("thumb_2_r", 0.85)],
            "index_r" => vec![("index_0_r", 1.0), ("index_1_r", 0.9), ("index_2_r", 0.65)],
            "middle_r" => vec![
                ("middle_0_r", 1.0),
                ("middle_1_r", 0.9),
                ("middle_2_r", 0.65),
            ],
            "ring_r" => vec![("ring_0_r", 1.0), ("ring_1_r", 0.88), ("ring_2_r", 0.6)],
            "pinky_r" => vec![("pinky_0_r", 1.0), ("pinky_1_r", 0.85), ("pinky_2_r", 0.55)],
            _ => return vec![stmt.clone()], // Not a grouped finger bone, return original
        };

        // Create expanded statements for each joint
        for (joint_bone, ratio) in finger_mappings {
            let adjusted_amount = (stmt.amount * ratio).round();
            if adjusted_amount.abs() >= 1.0 {
                // Only add if amount is significant
                expanded_statements.push(crate::pose::MPLPoseStatement {
                    bone: joint_bone.to_string(),
                    action: stmt.action.clone(),
                    direction: stmt.direction.clone(),
                    amount: adjusted_amount,
                });
            }
        }

        expanded_statements
    }

    fn is_grouped_finger_bone(bone: &str) -> bool {
        bone == "thumb_l"
            || bone == "index_l"
            || bone == "middle_l"
            || bone == "ring_l"
            || bone == "pinky_l"
            || bone == "thumb_r"
            || bone == "index_r"
            || bone == "middle_r"
            || bone == "ring_r"
            || bone == "pinky_r"
    }

    fn consolidate_finger_statements(statements: &[MPLPoseStatement]) -> Vec<MPLPoseStatement> {
        let mut consolidated = Vec::new();

        for stmt in statements {
            // Only keep _0 joints and rename them to grouped form, ignore all others
            if stmt.bone.ends_with("_0_l") || stmt.bone.ends_with("_0_r") {
                let grouped_bone = if stmt.bone.ends_with("_0_l") {
                    stmt.bone.replace("_0_l", "_l")
                } else {
                    stmt.bone.replace("_0_r", "_r")
                };
                consolidated.push(MPLPoseStatement {
                    bone: grouped_bone,
                    action: stmt.action.clone(),
                    direction: stmt.direction.clone(),
                    amount: stmt.amount,
                });
            } else if !stmt.bone.ends_with("_1_l")
                && !stmt.bone.ends_with("_2_l")
                && !stmt.bone.ends_with("_1_r")
                && !stmt.bone.ends_with("_2_r")
            {
                // Keep non-finger joint statements as they are
                consolidated.push(stmt.clone());
            }
            // Ignore all other individual joints (_1_l, _2_l, etc.)
        }

        consolidated
    }
}