did I fix the meshing now?
[antikythera] / src / machine.cc
index 913b0b0..d6bb338 100644 (file)
@@ -88,7 +88,7 @@ void Machine::calc_meshing()
                                float inner_rad_sum = outer_rad_sum - gears[i]->teeth_length - gears[j]->teeth_length;
 
                                if(dsq <= outer_rad_sum * outer_rad_sum && dsq >= inner_rad_sum * inner_rad_sum) {
-                                       printf("connecting co-planar gears %d - %d\n", i, j);
+                                       //printf("connecting co-planar gears %d - %d\n", i, j);
                                        meshing[i][j] = meshing[j][i] = true;
                                }
 
@@ -105,32 +105,31 @@ void Machine::calc_meshing()
        // fix the initial angles so that teeth mesh as best as possible
        // should work in one pass as long as the gear train is not impossible
        for(int i=0; i<ngears; i++) {
-               gears[i]->init_angle = 0;
+               float rnd = gears[i]->angle + gears[i]->get_angular_pitch() / 2.0;
+               float snap = rnd - fmod(rnd, gears[i]->get_angular_pitch());
+               gears[i]->set_angle(snap);
+               gears[i]->set_angular_offset(0);
        }
 
        for(int i=0; i<ngears; i++) {
-               for(int j=1; j<ngears; j++) {
+               for(int j=i; j<ngears; j++) {
                        if(meshing[i][j]) {
                                assert(i != j);
 
                                Vec2 dir = normalize(ppos[j].xy() - ppos[i].xy());
                                float rel_angle = atan2(dir.y, dir.x);
 
-                               float frac_i = fmod(gears[i]->init_angle / gears[i]->get_angular_pitch() + 1.0, 1.0);
-                               float frac_j = fmod((gears[j]->init_angle + rel_angle) / gears[j]->get_angular_pitch() + 1.0, 1.0);
+                               float frac_i = fmod((gears[i]->init_angle + rel_angle) / gears[i]->get_angular_pitch() + 100.0, 1.0);
+                               float frac_j = fmod((gears[j]->init_angle - rel_angle) / gears[j]->get_angular_pitch() + 100.0, 1.0);
+                               assert(frac_i >= 0.0 && frac_j >= 0.0);
                                float delta = frac_j - frac_i;
 
                                float correction = 0.5 - delta;
-                               gears[j]->init_angle += correction * gears[j]->get_angular_pitch();
+                               float prev_offs = gears[j]->get_angular_offset();
+                               gears[j]->set_angular_offset(prev_offs + correction * gears[j]->get_angular_pitch());
                        }
                }
        }
-
-       /*
-       for(int i=0; i<ngears; i++) {
-               printf("init %d: %f\n", i, gears[i]->init_angle);
-       }
-       */
 }
 
 void Machine::update_gear(int idx, float angle)