diff --git a/README.md b/README.md
index d6b66df6f2cfab53f1be126d8bc2be88d2fd5397..c5bd26ded59e93c3799bdbc82c8c0846a32dd926 100644
--- a/README.md
+++ b/README.md
@@ -1,92 +1,7 @@
 # Synthe_DriPE
 
 
-
-## Getting started
-
-To make it easy for you to get started with GitLab, here's a list of recommended next steps.
-
-Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
-
-## Add your files
-
-- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
-- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
-
-```
-cd existing_repo
-git remote add origin https://gitlab.liris.cnrs.fr/rguesdon/synthe_dripe.git
-git branch -M main
-git push -uf origin main
-```
-
-## Integrate with your tools
-
-- [ ] [Set up project integrations](https://gitlab.liris.cnrs.fr/rguesdon/synthe_dripe/-/settings/integrations)
-
-## Collaborate with your team
-
-- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
-- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
-- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
-- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
-- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
-
-## Test and Deploy
-
-Use the built-in continuous integration in GitLab.
-
-- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
-- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
-- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
-- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
-- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
-
-***
-
-# Editing this README
-
-When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!).  Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
-
-## Suggestions for a good README
-Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
-
-## Name
-Choose a self-explaining name for your project.
-
-## Description
-Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
-
-## Badges
-On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
-
-## Visuals
-Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
-
-## Installation
-Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
-
-## Usage
-Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
-
-## Support
-Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
-
-## Roadmap
-If you have ideas for releases in the future, it is a good idea to list them in the README.
-
-## Contributing
-State if you are open to contributions and what your requirements are for accepting them.
-
-For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
-
-You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
-
-## Authors and acknowledgment
-Show your appreciation to those who have contributed to the project.
-
-## License
-For open source projects, say how it is licensed.
-
-## Project status
-If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+### Addons Blender:
+MHX2 : http://download.tuxfamily.org/makehuman/plugins/mhx-blender-latest.zip
+Import images as planes
+Lighting : Sun position
\ No newline at end of file
diff --git a/base.blend b/base.blend
index 5c3a27ee5eb9f3e07b8355a583f6982780f72106..4505bfe11ded5ec9aee7c8e504b0416814fc9dc9 100644
Binary files a/base.blend and b/base.blend differ
diff --git a/global_script.py b/global_script.py
index 7a0e2129d453185b1178c289e730e1170fece170..62edad87533ce6a16ed29ac7d23622a24d256b3e 100644
--- a/global_script.py
+++ b/global_script.py
@@ -67,295 +67,318 @@ for bpy_data_iter in (
 for ob in D.objects:
     C.scene.collection.objects.unlink(ob)
 
-# Import car
-car_collection = D.collections.new("Cars")
-C.scene.collection.children.link(car_collection)
-
-cars = []
-
-for src_path, name in {
-    r"car_models\suv_car\car.blend": 'SUV',
-    r"car_models\red_car\red.blend": 'Red',
-    r"car_models\pickup_car\pickup.blend": 'PickUp',
-    r"car_models\family_car\family_car.blend": 'Family',
-    r"car_models\coupe_car\coupe_car.blend": 'Coupe',
-    r"car_models\truck\truck_open.blend": 'Truck',
-
-}.items():
-    with D.libraries.load(abs_path(src_path)) as (data_from, data_to):
-        data_to.objects = data_from.objects
-
-    for obj in data_to.objects:
-        car_collection.objects.link(obj)
-
-    D.objects['Car'].name = name
-    cars.append(D.objects[name])
-car_picker = utils.Randomizer(cars)
-
-# import humans
-human_loader = HumanLoader('mh_models/exports')
-
-# Creation scene
-# add camera
-C.scene.render.engine = 'BLENDER_EEVEE'
-
-camera_data = D.cameras.new(name='Camera')
-camera_data.type = 'PERSP'
-camera_data.lens_unit = 'FOV'
-camera_data.angle = utils.r(68)
-
-C.scene.render.resolution_x = 256
-C.scene.render.resolution_y = int(480 / 640 * 256)
-
-camera_object = D.objects.new('Camera', camera_data)
-C.scene.collection.objects.link(camera_object)
-
-camera_object.location = [-.97, -0.24, 0.68]
-# camera_object.location = [-.97, -0.11, 0.68]
-camera_rotation_0 = utils.r(Vector([72, 8, -75]))
-camera_object.rotation_euler = camera_rotation_0
-# camera_object.rotation_euler = utils.r([72, 8, -82])
-
-# set background
-back_folder = abs_path("backgrounds")
-back_imgs = {}
-for key in ['night', 'day']:
-    list_imgs = glob.glob(os.path.join(back_folder, f'{key}_*'))
-    back_imgs[key] = []
-    for img in list_imgs:
-        img_name = os.path.basename(img)
-        bpy.ops.image.open(filepath=img, directory=back_folder,
-                           files=[{"name": img_name}], relative_path=False, show_multiview=False)
-        back_imgs[key].append(img_name)
-
-# Create image holder
-bpy.ops.import_image.to_plane(
-    directory=back_folder,
-    files=[{"name": "default_green.png"}],
-    shader='SHADELESS',
-    use_transparency=False,
-    offset=False,
-    height=round(10 / 2.25, 1),
-    align_axis="X-"
-)
-
-image_holder = C.active_object
-image_holder.name = 'Image_holder'
-image_holder.location = (4, 1.5, 1.3)
-image_holder.rotation_euler.z = utils.r(-95)
-image_holder.active_material.shadow_method = 'NONE'
-
-# add light
-sun_collection = D.collections.new("Sun")
-C.scene.collection.children.link(sun_collection)
-
-light_params = {
-    'day': {
-        'energy_bounds': (10, 35),
-        'back_color_bounds': (0.4, 0.65),
-        'sun_color': (1, 1, 1)
-    },
-    'night': {
-        'energy_bounds': (5, 15),
-        'back_color_bounds': (0.1, 0.15),
-        'sun_color': (1, 0.5, 0.2)
-    }
-
-}
-
-light_data = D.lights.new(name="Sun", type='SUN')
-light_data.energy = 20
-light_object = D.objects.new(name="Sun", object_data=light_data)
-
-sun_collection.objects.link(light_object)
-light_object.location = (5, 0, 3)
-
-# Sun position
-C.scene.sun_pos_properties.usage_mode = 'NORMAL'
-C.scene.sun_pos_properties.sun_object = light_object
-C.scene.sun_pos_properties.object_collection = sun_collection
-C.scene.sun_pos_properties.object_collection_type = 'DIURNAL'
-C.scene.sun_pos_properties.co_parser = "41°22′14″N 2°09′00″E"
-C.scene.sun_pos_properties.sun_distance = 3
-C.scene.sun_pos_properties.use_day_of_year = True
-C.scene.sun_pos_properties.year = 2022
-C.scene.sun_pos_properties.day_of_year = 182
-
-fp = abs_path(r"output_temp")
-fp_img = os.path.join(fp, 'images')
-fp_ann_2D = os.path.join(fp, 'annots_2D')
-fp_ann_3D = os.path.join(fp, 'annots_3D')
-
-info_path = os.path.join(fp, 'infos.json')
-cam_path = os.path.join(fp, 'cameras.json')
-scenes_ids = OrderedDict()
-if not CONTINUE or not os.path.isfile(info_path):
-    if os.path.isdir(fp):
-        shutil.rmtree(fp)
-    os.mkdir(fp)
-
-    os.mkdir(fp_img)
-    os.mkdir(fp_ann_2D)
-    os.mkdir(fp_ann_3D)
-
-frame_rate = 25
-nb_scene = 1
-nb_pose = 1
-human_loader.max_len = min(human_loader.max_len, nb_scene)
-ratio_conf_man = int(nb_scene / len(human_loader.human_paths))
-if CONTINUE:
-    with open(info_path) as f_info:
-        scenes_ids = json.load(f_info, object_pairs_hook=OrderedDict)['id_max_scenes']
-
-    human_loader.human_paths = [hp for hp in human_loader.human_paths if hp not in scenes_ids]
-
-man = None
-for sc in range(ratio_conf_man * len(scenes_ids), nb_scene):
-    # Random car
-    car = car_picker()
-    car_targets = {side: [ch for ch in car.children if f'Target_{side.upper()}' in ch.name] for side in 'lr'}
-    nb_targets = len(car_targets['l']) * len(car_targets['r'])
-    print(nb_targets)
-    # Random personne
-    if ratio_conf_man < 1:
-        if not sc % 10:
-            human_loader.load_next()
-        man = human_loader(car=car)
-    else:
-        if not sc % ratio_conf_man:
-            man = human_loader.next(car=car)
-        else:
-            human.set_bounds(man, car)
 
-    human_path = human_loader.paths[man]
-    scenes_ids.setdefault(human_path, -1)
-    scenes_ids[human_path] += 1
-
-    # Random time
-    C.scene.sun_pos_properties.north_offset = utils.r(random.randint(-179, 180))
-    time_day = random.randint(0, 23)
-    if 6 <= time_day <= 21:
-        day_night = 'day'
-        C.scene.sun_pos_properties.time = time_day
-    else:
-        day_night = 'night'
-        C.scene.sun_pos_properties.time = (time_day + 12) % 24
-
-    light_param = light_params[day_night]
-    light_data.energy = random.randint(*light_param['energy_bounds'])
-    light_data.color = light_param['sun_color']
-    back_val = random.uniform(*light_param['back_color_bounds'])
-    bpy.data.worlds["World"].node_tree.nodes["Background.001"].inputs[0].default_value = \
-        (back_val, back_val, back_val, 1)
-
-    # Random background
-    back_img = random.choice(back_imgs[day_night])
-    image_holder.active_material.node_tree.nodes['Image Texture'].image = D.images[back_img]
-    image_holder.location.y = 1.5 + random.uniform(-0.3, 0.3)
-
-    # Camera movement
-    camera_object.rotation_euler = camera_rotation_0 + utils.r(Vector([random.randint(-2, 2), 0, 0]))
-
-    C.scene.render.filepath = fp
-    C.scene.render.image_settings.file_format = 'PNG'
-    C.scene.camera = camera_object
-
-    P, K, RT = camera_proj.get_3x4_P_matrix_from_blender(camera_object)
-
-    file_root_name = f'{list(scenes_ids).index(human_path)}_{scenes_ids[human_path]}'
-
-    if os.path.isfile(cam_path):
-        with open(cam_path, 'r') as f_cam:
-            previous_cameras = f_cam.read()
-            if previous_cameras:
-                previous_cameras = json.loads(previous_cameras)
-            else:
-                previous_cameras = {}
-    else:
-        previous_cameras = {}
-    with open(cam_path, 'w') as f_cam:
-        previous_cameras[file_root_name] = {
-            'P': utils.mat_to_list(P),
-            'K': utils.mat_to_list(K),
-            'RT': utils.mat_to_list(RT),
+def main():
+    # Import car
+    car_collection = D.collections.new("Cars")
+    C.scene.collection.children.link(car_collection)
+
+    cars = []
+
+    for src_path, name in {
+        r"car_models\suv_car\car.blend": 'SUV',
+        r"car_models\red_car\red.blend": 'Red',
+        r"car_models\pickup_car\pickup.blend": 'PickUp',
+        r"car_models\family_car\family_car.blend": 'Family',
+        r"car_models\coupe_car\coupe_car.blend": 'Coupe',
+        r"car_models\truck\truck_open.blend": 'Truck',
+
+    }.items():
+        with D.libraries.load(abs_path(src_path)) as (data_from, data_to):
+            data_to.objects = data_from.objects
+
+        for obj in data_to.objects:
+            car_collection.objects.link(obj)
+
+        D.objects['Car'].name = name
+        cars.append(D.objects[name])
+    car_picker = utils.Randomizer(cars)
+
+    # import humans
+    human_loader = HumanLoader('mh_models/exports')
+
+    # Creation scene
+    # add camera
+    C.scene.render.engine = 'BLENDER_EEVEE'
+
+    camera_data = D.cameras.new(name='Camera')
+    camera_data.type = 'PERSP'
+    camera_data.lens_unit = 'FOV'
+    camera_data.angle = utils.r(68)
+
+    C.scene.render.resolution_x = 256
+    C.scene.render.resolution_y = int(480 / 640 * 256)
+
+    camera_object = D.objects.new('Camera', camera_data)
+    C.scene.collection.objects.link(camera_object)
+
+    # camera_object.location = [-.97, -0.24, 0.68]
+    camera_object.location = [-.97, -0.1, 0.68]
+    # camera_rotation_0 = utils.r(Vector([72, 8, -75]))
+    camera_rotation_0 = utils.r(Vector([73, 8, -82]))
+    camera_object.rotation_euler = camera_rotation_0
+
+    # set background
+    back_folder = abs_path("backgrounds")
+    back_imgs = {}
+    for key in ['night', 'day']:
+        list_imgs = glob.glob(os.path.join(back_folder, f'{key}_*'))
+        back_imgs[key] = []
+        for img in list_imgs:
+            img_name = os.path.basename(img)
+            bpy.ops.image.open(filepath=img, directory=back_folder,
+                               files=[{"name": img_name}], relative_path=False, show_multiview=False)
+            back_imgs[key].append(img_name)
+
+    # Create image holder
+    bpy.ops.import_image.to_plane(
+        directory=back_folder,
+        files=[{"name": "default_green.png"}],
+        shader='SHADELESS',
+        use_transparency=False,
+        offset=False,
+        height=round(10 / 2.25, 1),
+        align_axis="X-"
+    )
+
+    image_holder = C.active_object
+    image_holder.name = 'Image_holder'
+    image_holder.location = (4, 1.5, 1.3)
+    image_holder.rotation_euler.z = utils.r(-95)
+    image_holder.active_material.shadow_method = 'NONE'
+
+    # add light
+    sun_collection = D.collections.new("Sun")
+    C.scene.collection.children.link(sun_collection)
+
+    light_params = {
+        'day': {
+            'energy_bounds': (10, 35),
+            'back_color_bounds': (0.4, 0.65),
+            'sun_color': (1, 1, 1)
+        },
+        'night': {
+            'energy_bounds': (5, 15),
+            'back_color_bounds': (0.15, 0.25),
+            'sun_color': (1, 0.5, 0.2)
         }
-        json.dump(previous_cameras, f_cam, indent=4)
-
-    man.animation_data_clear()
-
-    # Exemple: 150k / 200 / 2 = 1500 poses
-    with open(os.path.join(fp_ann_2D, f'annotations_{file_root_name}.csv'), 'w') as annot_file_2D, \
-            open(os.path.join(fp_ann_3D, f'annotations_{file_root_name}.csv'), 'w') as annot_file_3D:
-        bone_lbls = list(man.pose.bones.keys())
-        face_lbls = ['nose', 'eye_l', 'eye_r', 'hear_l', 'hear_r']
-        annot_file_2D.write(';'.join([lbl for bone in bone_lbls + face_lbls for lbl in [bone + k for k in ['_x', '_y']]]) + '\n')
-        annot_file_3D.write(
-            ';'.join([lbl for bone in bone_lbls + face_lbls for lbl in [bone + k for k in ['_X', '_Y', '_Z']]]) + '\n')
-
-        for po in range(nb_pose):
-            C.scene.frame_set(po * frame_rate)
-            use_targets = nb_pose - po - 1 < nb_targets
-            # use_targets = False
-            human.switch_constraints(man, enable=not use_targets)
-            if nb_pose < nb_targets or not use_targets:
-                id_targets = None
-            else:
-                print(po, nb_pose - po - 1)
-                id_targets = {'l': (nb_pose - po - 1) % len(car_targets['l']),
-                              'r': (nb_pose - po - 1) // len(car_targets['l'])}
-                print(id_targets)
-            random_pose.random_pose_ik(man, targets=car_targets if use_targets else None, id_targets=id_targets)
-
-            bpy.ops.object.mode_set(mode='OBJECT')
-
-            man.keyframe_insert(data_path="location", index=-1)
-            man.keyframe_insert(data_path="rotation_euler", index=-1)
-
-            bpy.ops.object.mode_set(mode='POSE')
-
-            for bone in man.pose.bones:
-                bone.keyframe_insert(data_path="rotation_euler", index=-1)
-                if bone.name[-3:] == '_IK':
-                    bone.keyframe_insert(data_path="location", index=-1)
-
-            bpy.ops.object.mode_set(mode='OBJECT')
 
-            # set output path so render won't get overwritten
-            C.scene.render.filepath = os.path.join(fp_img,
-                                                   f"{file_root_name}_{po}" + (f'_drive' if use_targets else ''))
-            bpy.ops.render.render(write_still=True)  # render still
-
-            annotations_2D = []
-            annotations_3D = []
-            for lbl in bone_lbls:
-                bone_3d = utils.get_head_pose(lbl, man)
-                annotations_3D.append(f"{bone_3d[0]:.3f};{bone_3d[1]:.3f};{bone_3d[2]:.3f}")
-
-                bone_2d = P @ bone_3d
-                bone_2d /= bone_2d[-1]
-                annotations_2D.append(f"{bone_2d[0]:.2f};{bone_2d[1]:.2f}")
-
-            for lbl, bone_3d in human.get_face(man).items():
-                annotations_3D.append(f"{bone_3d[0]:.3f};{bone_3d[1]:.3f};{bone_3d[2]:.3f}")
-
-                bone_2d = P @ bone_3d
-                bone_2d /= bone_2d[-1]
-                annotations_2D.append(f"{bone_2d[0]:.2f};{bone_2d[1]:.2f}")
-
-            annot_file_2D.write(';'.join(annotations_2D) + '\n')
-            annot_file_3D.write(';'.join(annotations_3D) + '\n')
-
-    with open(info_path, 'w') as f_infos:
-        json.dump({
-            'models': list(scenes_ids),
-            'id_max_scenes': scenes_ids
-        }, f_infos, indent=4)
+    }
 
-    if sc % 20 == 19:
-        time.sleep(150)
+    light_data = D.lights.new(name="Sun", type='SUN')
+    light_data.energy = 20
+    light_object = D.objects.new(name="Sun", object_data=light_data)
+
+    sun_collection.objects.link(light_object)
+    light_object.location = (5, 0, 3)
+
+    bpy.data.worlds["World"].node_tree.nodes["Background.001"].inputs[1].default_value = 1.2
+
+    # Sun position
+    C.scene.sun_pos_properties.usage_mode = 'NORMAL'
+    C.scene.sun_pos_properties.sun_object = light_object
+    C.scene.sun_pos_properties.object_collection = sun_collection
+    C.scene.sun_pos_properties.object_collection_type = 'DIURNAL'
+    C.scene.sun_pos_properties.co_parser = "41°22′14″N 2°09′00″E"
+    C.scene.sun_pos_properties.sun_distance = 3
+    C.scene.sun_pos_properties.use_day_of_year = True
+    C.scene.sun_pos_properties.year = 2022
+    C.scene.sun_pos_properties.day_of_year = 182
+
+    fp = abs_path(r"output_temp")
+    fp_img = os.path.join(fp, 'images')
+    fp_ann_2D = os.path.join(fp, 'annots_2D')
+    fp_ann_3D = os.path.join(fp, 'annots_3D')
+
+    info_path = os.path.join(fp, 'infos.json')
+    cam_path = os.path.join(fp, 'cameras.json')
+    scenes_ids = OrderedDict()
+    if not CONTINUE or not os.path.isfile(info_path):
+        if os.path.isdir(fp):
+            shutil.rmtree(fp)
+        os.mkdir(fp)
+
+        os.mkdir(fp_img)
+        os.mkdir(fp_ann_2D)
+        os.mkdir(fp_ann_3D)
+
+    frame_rate = 25
+    nb_scene = 1
+    nb_pose = 1
+    human_loader.max_len = min(human_loader.max_len, nb_scene)
+    ratio_conf_man = int(nb_scene / len(human_loader.human_paths))
+
+    if CONTINUE:
+        try:
+            with open(info_path) as f_info:
+                scenes_ids = json.load(f_info, object_pairs_hook=OrderedDict)['id_max_scenes']
+
+            human_loader.human_paths = [hp for hp in human_loader.human_paths if hp not in scenes_ids]
+        except FileNotFoundError:
+            pass
+
+    man = None
+    for sc in range(ratio_conf_man * len(scenes_ids), nb_scene):
+        # Random car
+        car = car_picker()
+        car_targets = {side: [ch for ch in car.children if f'Target_{side.upper()}' in ch.name] for side in 'lr'}
+        nb_targets = len(car_targets['l']) * len(car_targets['r'])
+        print(nb_targets)
+        # Random personne
+        if ratio_conf_man < 1:
+            if not sc % 10:
+                human_loader.load_next()
+            man = human_loader(car=car)
+        else:
+            if not sc % ratio_conf_man:
+                man = human_loader.next(car=car)
+            else:
+                human.set_bounds(man, car)
 
-C.scene.frame_end = int(frame_rate * (nb_pose - 0.5))
-utils.select_only(man)
-bpy.ops.object.mode_set(mode='POSE')
+        human_path = human_loader.paths[man]
+        scenes_ids.setdefault(human_path, -1)
+        scenes_ids[human_path] += 1
 
-print('Done', '#' * 25)
+        # Random time
+        C.scene.sun_pos_properties.north_offset = utils.r(random.randint(-179, 180))
+        time_day = random.randint(8, 18)
+        C.scene.sun_pos_properties.time = time_day
+        if random.random() < 4 / 5:
+            day_night = 'day'
+        else:
+            day_night = 'night'
+
+        light_param = light_params[day_night]
+        light_data.energy = random.randint(*light_param['energy_bounds'])
+        light_data.color = light_param['sun_color']
+        back_val = random.uniform(*light_param['back_color_bounds'])
+        bpy.data.worlds["World"].node_tree.nodes["Background.001"].inputs[0].default_value = \
+            (back_val, back_val, back_val, 1)
+
+        # Random background
+        back_img = random.choice(back_imgs[day_night])
+        image_holder.active_material.node_tree.nodes['Image Texture'].image = D.images[back_img]
+        image_holder.location.y = 1.5 + random.uniform(-0.3, 0.3)
+
+        # Camera movement
+        camera_object.rotation_euler = camera_rotation_0 + utils.r(Vector([random.randint(-2, 2), 0, 0]))
+
+        C.scene.render.filepath = fp
+        C.scene.render.image_settings.file_format = 'PNG'
+        C.scene.camera = camera_object
+
+        P, K, RT = camera_proj.get_3x4_P_matrix_from_blender(camera_object)
+
+        file_root_name = f'{list(scenes_ids).index(human_path)}_{scenes_ids[human_path]}'
+
+        if os.path.isfile(cam_path):
+            with open(cam_path, 'r') as f_cam:
+                previous_cameras = f_cam.read()
+                if previous_cameras:
+                    previous_cameras = json.loads(previous_cameras)
+                else:
+                    previous_cameras = {}
+        else:
+            previous_cameras = {}
+        with open(cam_path, 'w') as f_cam:
+            previous_cameras[file_root_name] = {
+                'P': utils.mat_to_list(P),
+                'K': utils.mat_to_list(K),
+                'RT': utils.mat_to_list(RT),
+            }
+            json.dump(previous_cameras, f_cam, indent=4)
+
+        man.animation_data_clear()
+
+        # Exemple: 150k / 200 / 2 = 1500 poses
+        with open(os.path.join(fp_ann_2D, f'annotations_{file_root_name}.csv'), 'w') as annot_file_2D, \
+                open(os.path.join(fp_ann_3D, f'annotations_{file_root_name}.csv'), 'w') as annot_file_3D:
+            bone_lbls = list(man.pose.bones.keys())
+            bone_lbls = [lbl for bone in bone_lbls for lbl in [bone + k for k in ['_head', '_tail']]]
+            face_lbls = ['nose', 'eye_l', 'eye_r', 'ear_l', 'ear_r']
+            # full_lbls = [lbl for lbl in bone_lbls if lbl not in face_lbls] + face_lbls
+            full_lbls = bone_lbls + face_lbls
+            annot_file_2D.write(
+                ';'.join([lbl for bone in full_lbls for lbl in [bone + k for k in ['_x', '_y']]]) + '\n')
+            annot_file_3D.write(
+                ';'.join(
+                    [lbl for bone in full_lbls for lbl in [bone + k for k in ['_X', '_Y', '_Z']]]) + '\n')
+
+            for po in range(nb_pose):
+                C.scene.frame_set(po * frame_rate)
+                use_targets = nb_pose - po - 1 < nb_targets
+
+                # use_targets = False
+                human.switch_constraints(man, enable=not use_targets)
+                if nb_pose < nb_targets or not use_targets:
+                    id_targets = None
+                else:
+                    print(po, nb_pose - po - 1)
+                    id_targets = {'l': (nb_pose - po - 1) % len(car_targets['l']),
+                                  'r': (nb_pose - po - 1) // len(car_targets['l'])}
+                    print(id_targets)
+                random_pose.random_pose_ik(man, targets=car_targets if use_targets else None, id_targets=id_targets)
+
+                bpy.ops.object.mode_set(mode='OBJECT')
+
+                man.keyframe_insert(data_path="location", index=-1)
+                man.keyframe_insert(data_path="rotation_euler", index=-1)
+
+                bpy.ops.object.mode_set(mode='POSE')
+
+                for bone in man.pose.bones:
+                    bone.keyframe_insert(data_path="rotation_euler", index=-1)
+                    if bone.name[-3:] == '_IK':
+                        bone.keyframe_insert(data_path="location", index=-1)
+
+                bpy.ops.object.mode_set(mode='OBJECT')
+
+                # set output path so render won't get overwritten
+                C.scene.render.filepath = os.path.join(fp_img,
+                                                       f"{file_root_name}_{po}" + (f'_drive' if use_targets else ''))
+                bpy.ops.render.render(write_still=True)  # render still
+
+                annotations_2D = []
+                annotations_3D = []
+                for lbl in bone_lbls:
+                    if '_tail' in lbl:
+                        bone_3d = utils.get_tail_pose(lbl[:-5], man)
+                    else:
+                        bone_3d = utils.get_head_pose(lbl[:-5], man)
+                    annotations_3D.append(f"{bone_3d[0]:.3f};{bone_3d[1]:.3f};{bone_3d[2]:.3f}")
+
+                    bone_2d = P @ bone_3d
+                    bone_2d /= bone_2d[-1]
+                    annotations_2D.append(f"{bone_2d[0]:.2f};{bone_2d[1]:.2f}")
+
+                for lbl, bone_3d in human.get_face(man).items():
+                    annotations_3D.append(f"{bone_3d[0]:.3f};{bone_3d[1]:.3f};{bone_3d[2]:.3f}")
+
+                    bone_2d = P @ bone_3d
+                    bone_2d /= bone_2d[-1]
+                    annotations_2D.append(f"{bone_2d[0]:.2f};{bone_2d[1]:.2f}")
+
+                annot_file_2D.write(';'.join(annotations_2D) + '\n')
+                annot_file_3D.write(';'.join(annotations_3D) + '\n')
+
+        with open(info_path, 'w') as f_infos:
+            json.dump({
+                'models': list(scenes_ids),
+                'id_max_scenes': scenes_ids
+            }, f_infos, indent=4)
+
+        if sc * nb_pose % 4000 == 3999:
+            time.sleep(150)
+
+    C.scene.frame_end = int(frame_rate * (nb_pose - 0.5))
+    utils.select_only(man)
+    bpy.ops.object.mode_set(mode='POSE')
+
+    print('Done', '#' * 25)
+
+
+if __name__ == '__main__':
+    try:
+        main()
+    except utils.StopError:
+        pass
diff --git a/scripts/human.py b/scripts/human.py
index b94903ee02e17a43f433ed4742d293e415399c53..2bff41347aefa0d99f28d9f7a243c9a4bd15e3e8 100644
--- a/scripts/human.py
+++ b/scripts/human.py
@@ -145,8 +145,8 @@ class Human:
 
             hand = self.model.pose.bones[f'hand_{s}']
             hand.constraints.new("COPY_ROTATION")
-            hand.constraints['Copy Rotation'].target = self.model
             hand.constraints['Copy Rotation'].enabled = False
+            hand.constraints['Copy Rotation'].target = self.model
             hand.constraints['Copy Rotation'].subtarget = f'hand_{s}_IK'
 
             for name, consts in ik_constraints.items():
@@ -161,7 +161,8 @@ class Human:
                         setattr(bone, f'ik_max_{axe}', utils.r(const[1]))
 
             # self.model.pose.bones[f'hand_{s}_IK'].location = Vector((-15, 10, 0))
-            self.model.pose.bones[f'hand_{s}_IK'].location = Vector((0, 5, -10))
+            # self.model.pose.bones[f'hand_{s}_IK'].location = Vector((0, 5, -10))
+            self.model.pose.bones[f'hand_{s}_IK'].location = Vector((0, 1.2, 0.25))
 
         for i in '123':
             self.model.pose.bones[f'spine_0{i}'].lock_ik_x = False
@@ -173,6 +174,10 @@ class Human:
 
     def init_textures(self):
         for o in self.model.children:
+            if not o.type == 'MESH':
+                continue
+            if 'Mesh' not in o.name:
+                o.name = o.name.split(':')[-1].lower() + "Mesh"
             if "eye" in o.name or "high" in o.name:
                 continue
             try:
@@ -209,18 +214,14 @@ def get_face(model):
     previous_mode = bpy.context.mode
     bpy.ops.object.mode_set(mode='OBJECT')
     matrix_world = model.matrix_world.copy()
-    head = model.pose.bones["head"]
 
-    locations = {
-        'nose': (0, -0.2, 12.1),
-        'eye_l': (3.1, 3.5, 9),
-        'eye_r': (-3.1, 3.5, 9),
-        'hear_l': (7.6, 1.8, 0.5),
-        'hear_r': (-7.6, 1.8, 0.5),
-    }
-
-    locations = {k: Vector(v) / 10 for k, v in locations.items()}
-    face_3D = {k: matrix_world @ head.matrix @ v for k, v in locations.items()}
+    face_3D = {}
+    for marker in ['nose', 'eye_l', 'eye_r', 'ear_l', 'ear_r']:
+        if 'eye' in marker:
+            marker_loc = model.pose.bones[marker].head * 0.75 + model.pose.bones[marker].tail * 0.25
+        else:
+            marker_loc = model.pose.bones[marker].tail
+        face_3D[marker] = matrix_world @ marker_loc
 
     bpy.ops.object.mode_set(mode=previous_mode)
     return face_3D
@@ -310,7 +311,7 @@ def set_shrinkwraps(model, car=None):
 
 class HumanLoader:
     def __init__(self, dir_path, max_len=10):
-        self.human_paths = glob.glob(os.path.join(dir_path, '*.fbx'))
+        self.human_paths = glob.glob(os.path.join(dir_path, '*.mhx2'))
         random.shuffle(self.human_paths)
         self.paths = {}
         self.humans = {}
@@ -346,11 +347,15 @@ class HumanLoader:
         for human_path in human_paths:
             if human_path in already_loaded:
                 continue
-            bpy.ops.import_scene.fbx(filepath=human_path)
+            bpy.ops.import_scene.makehuman_mhx2(filepath=os.path.abspath(human_path))
 
             model = C.active_object
             self.paths[model] = human_path
             self.move_human(model)
+            armature = D.armatures[model.name]
+            armature.show_axes = True
+            armature.display_type = "OCTAHEDRAL"
+            model.show_in_front = False
             self.humans[human_path] = Human(model)
 
         self.picker = utils.Randomizer(list(self.humans.values()))
@@ -367,9 +372,13 @@ class HumanLoader:
         for ch in obj.children:
             self.move_human(ch)
 
-        if obj.name in C.collection.objects:
+        if obj.name not in self.collection.objects:
+            for col in obj.users_collection:
+                if col not in [C.collection, self.collection.objects]:
+                    D.collections.remove(col)
             self.collection.objects.link(obj)
-            C.collection.objects.unlink(obj)
+
+        utils.select_only(obj)
 
     def __call__(self, *args, **kwargs):
         return self.picker(*args, **kwargs)
diff --git a/scripts/random_pose.py b/scripts/random_pose.py
index 8c3987506e82d0ecd324032e708d1cbbb77021fb..384a48570ab6654bfff5ccc511cb6f45fed6c06a 100644
--- a/scripts/random_pose.py
+++ b/scripts/random_pose.py
@@ -15,6 +15,8 @@ from scripts.utils import *
 
 def default_rots():
     return {
+        'hand_r': (0, 0, 0),
+        'hand_l': (0, 0, 0),
         'thigh_r': (r(-70), r(-5 - random.random() * 15), 0),
         'thigh_l': (r(-70), r(5 + random.random() * 15), 0),
         'calf_r': (r(20 + random.random() * 50), r(30), 0),
@@ -81,11 +83,16 @@ def reset_subject(subject):
     scale = round(subject.scale[0] * (1.6 + 0.3 * random.random()) / (subject.dimensions.y), 3)
     # subject.scale = [scale] * 3
 
-    subject.scale = [0.1] * 3
-    height = subject.dimensions.y
+    # subject.scale = [0.1] * 3
+    # height = subject.dimensions.y
     # subject.location = [0, -0.16, -0.5 * 1.66]
-    subject.location = [0, -0.16, -0.5 * height]
-    subject.rotation_euler = r([65, 0, 0])
+    # subject.location = [0, -0.16, -0.5 * height]
+    # subject.rotation_euler = r([65, 0, 0])
+    subject.scale = [1.] * 3
+    height = subject.dimensions.z
+    print(height)
+    subject.location = [0, -0.05, -0.5 * height + 0.03]
+    subject.rotation_euler = r([-15, 0, 0])
 
 
 def hand_pose(pose, side, grasp=None):
@@ -217,7 +224,7 @@ def random_pose_ik(subject, auto_ik=False, targets=None, id_targets=None):
                     target = targets[s][id_targets[s]]
                 except IndexError as err:
                     print(targets[s], id_targets, s)
-                    raise(err)
+                    raise (err)
             pose.bones[f'hand_{s}_IK'].rotation_euler = Vector((0, 0, 0))
             pose.bones[f'hand_{s}_IK'].rotation_euler = (
                 ((matrix_world @ pose.bones[f'hand_{s}_IK'].matrix).inverted() @ target.matrix_world).to_euler())
diff --git a/scripts/utils.py b/scripts/utils.py
index b905f50a9734f4a4416af1580f1314a9c33b83c0..24521248de1383c1abe1b24dc492902c171f7733 100644
--- a/scripts/utils.py
+++ b/scripts/utils.py
@@ -94,7 +94,7 @@ def select_only_edit_bone(armature, bone=None):
     armature.edit_bones.active = bone
 
 
-def get_head_pose(bone, struct='Subject'):
+def get_bone_pose(bone, struct, side):
     if isinstance(struct, str):
         struct = get_object(struct)
 
@@ -102,7 +102,20 @@ def get_head_pose(bone, struct='Subject'):
     bpy.ops.object.mode_set(mode='OBJECT')
     matrix_world = struct.matrix_world
     bpy.ops.object.mode_set(mode=current_mode)
-    return (matrix_world @ struct.pose.bones[bone].head.to_4d()).to_3d()
+    if side == "tail":
+        side_3d = struct.pose.bones[bone].tail
+    else:
+        side_3d = struct.pose.bones[bone].head
+
+    return (matrix_world @ side_3d.to_4d()).to_3d()
+
+
+def get_head_pose(bone, struct='Subject'):
+    return get_bone_pose(bone, struct, side='head')
+
+
+def get_tail_pose(bone, struct='Subject'):
+    return get_bone_pose(bone, struct, side='tail')
 
 
 # Other utils
@@ -145,3 +158,7 @@ class Randomizer:
 
         if obj is not None:
             hide_object(obj, hide=False)
+
+
+class StopError(Exception):
+    pass