Download utils/scene_generator.py from jacodd/SynthField: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/jacodd/SynthField/resolve/main/utils/scene_generator.py
- Command line
-
hf download hf://datasets/jacodd/SynthField/utils/scene_generator.py
-
curl -L -o scene_generator.py https://huggingface.co/datasets/jacodd/SynthField/resolve/main/utils/scene_generator.py
10.8 kB
| import omni | |
| import random | |
| import numpy as np | |
| from pxr import Usd, UsdGeom, Gf, Sdf, UsdShade | |
| from scipy.spatial.transform import Rotation | |
| # --- Asset and Scene Configuration --- | |
| CROP_ASSETS = { | |
| "soybean": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"], | |
| "sorghum": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"], | |
| "cotton": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"], | |
| "corn": ["_1", "_2", "_3", "_4", "_5", "_6", "_61", "_62", "_7", "_71", "_72", "_8", "_81", "_9", "_91", "_92"], | |
| "cane": ["_1", "_2"] | |
| } | |
| CROP_AGES = { | |
| "y": ["_1", "_2"], | |
| "y-m": ["_3", "_4", "_5"], | |
| "m-l": ["_5", "_6", "_7"], | |
| "l": ["_8", "_9"] | |
| } | |
| ROW_SPACING = { | |
| "corn": 0.45, | |
| "soybean": 0.45, | |
| "sorghum": 0.45, | |
| "cotton": 0.9, | |
| "cane": 1.0 | |
| } | |
| WEED_ASSETS = [ | |
| "/World/weed/broadleaf_1", | |
| "/World/weed/broadleaf_2", | |
| "/World/weed/grass_1", | |
| "/World/weed/grass_2" | |
| ] | |
| OBSTACLE_ASSETS = [ | |
| "/World/obstacle/cones/c1", | |
| "/World/obstacle/cones/c2", | |
| "/World/obstacle/cones/c3", | |
| "/World/obstacle/cones/c4", | |
| "/World/obstacle/female_adult_police_01_new", | |
| "/World/obstacle/male_adult_construction_01_new", | |
| # "/World/ood/Tractor" | |
| ] | |
| # Weed | |
| VOLUME_MAPPING = { | |
| "none": 0, | |
| "some": 50, # Number of assets to spawn | |
| "lot": 500 | |
| } | |
| OBSTACLE_VOLUME_MAPPING = { | |
| "none": 0, | |
| "some": 5, | |
| "lot": 15 | |
| } | |
| TIME_OF_DAY_MAPPING = { | |
| "early": 85, | |
| "noon": 0, | |
| "late": -75 | |
| } | |
| # | |
| GROUND_MATERIALS = [ | |
| "/FlatGrid/Looks/Dirt", | |
| "/FlatGrid/Looks/Mulch_Brown", | |
| "/FlatGrid/Looks/Mulch_Dry" | |
| ] | |
| # --- Helper Functions --- | |
| def change_ground_material(stage): | |
| """Changes the ground material using the MaterialBindingAPI.""" | |
| ground_path = "/FlatGrid/Environment" | |
| ground_prim = stage.GetPrimAtPath(ground_path) | |
| if not ground_prim: | |
| print(f"Ground prim not found at {ground_path}.") | |
| return | |
| material_path = random.choice(GROUND_MATERIALS) | |
| material_prim = stage.GetPrimAtPath(material_path) | |
| if not material_prim: | |
| print(f"Material prim not found at {material_path}.") | |
| return | |
| # Ensure the target prim is actually a Material | |
| material = UsdShade.Material(material_prim) | |
| if not material: | |
| print(f"Prim at {material_path} is not a valid UsdShadeMaterial.") | |
| return | |
| # Apply the MaterialBindingAPI to the ground prim | |
| binding_api = UsdShade.MaterialBindingAPI.Apply(ground_prim) | |
| # Bind the material. | |
| # UsdShade.Tokens.strongerThanDescendants ensures this material | |
| # overrides any materials assigned to child prims. | |
| binding_api.Bind(material, bindingStrength=UsdShade.Tokens.strongerThanDescendants) | |
| print(f"Successfully bound {ground_path} to {material_path}") | |
| def set_time_of_day(stage, time_of_day): | |
| """Sets the absolute time of day by finding or creating the rotation op.""" | |
| sun_path = "/World/CumulusLight/AxisNorth/AxisLatitude/AxisSHA" | |
| sun_prim = stage.GetPrimAtPath(sun_path) | |
| if not sun_prim: | |
| print(f"Warning: Sun prim not found at {sun_path}.") | |
| return | |
| angle = TIME_OF_DAY_MAPPING.get(time_of_day, 180) | |
| xform = UsdGeom.Xformable(sun_prim) | |
| # 1. Look for an existing RotateX operation in the stack | |
| rotate_op = None | |
| for op in xform.GetOrderedXformOps(): | |
| if op.GetOpType() == UsdGeom.XformOp.TypeRotateX: | |
| rotate_op = op | |
| break | |
| # 2. If it exists, set the absolute value. If not, create it. | |
| if rotate_op: | |
| rotate_op.Set(float(angle)) | |
| else: | |
| # This adds the op to the stack and sets the initial absolute value | |
| xform.AddRotateXOp(precision=UsdGeom.XformOp.PrecisionFloat).Set(float(angle)) | |
| def set_robust_transform(prim, translation=None, rotation_euler=None, scale=None): | |
| """ | |
| Robustly updates or adds transform operations to a prim. | |
| Handles existing Ops, different precisions, and Quaternion vs Euler rotations. | |
| """ | |
| xform = UsdGeom.Xformable(prim) | |
| # We use this to track which ops we've updated to avoid duplicates | |
| found_ops = {"translate": None, "rotate": None, "scale": None} | |
| for op in xform.GetOrderedXformOps(): | |
| op_type = op.GetOpType() | |
| if op_type in [UsdGeom.XformOp.TypeTranslate]: | |
| found_ops["translate"] = op | |
| elif op_type in [UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.TypeOrient]: | |
| found_ops["rotate"] = op | |
| elif op_type in [UsdGeom.XformOp.TypeScale]: | |
| found_ops["scale"] = op | |
| # --- Handle Translation --- | |
| if translation is not None: | |
| if found_ops["translate"]: | |
| found_ops["translate"].Set(translation) | |
| else: | |
| xform.AddTranslateOp().Set(translation) | |
| # --- Handle Rotation (Euler Z to XYZ or Quat) --- | |
| if rotation_euler is not None: | |
| z_deg = rotation_euler[2] # Assuming we mostly care about Z for plants | |
| if found_ops["rotate"]: | |
| op = found_ops["rotate"] | |
| attr_type = op.GetAttr().GetTypeName() | |
| if attr_type in (Sdf.ValueTypeNames.Quatf, Sdf.ValueTypeNames.Quatd): | |
| # Convert Euler to Quat | |
| r = Rotation.from_euler('z', z_deg, degrees=True) | |
| q = r.as_quat() # x, y, z, w | |
| quat_val = Gf.Quatd(q[3], q[0], q[1], q[2]) if attr_type == Sdf.ValueTypeNames.Quatd else Gf.Quatf(q[3], q[0], q[1], q[2]) | |
| op.Set(quat_val) | |
| else: | |
| # Standard Euler (Vec3f or Vec3d) | |
| current_rot = op.Get() or Gf.Vec3f(0) | |
| op.Set(Gf.Vec3f(current_rot[0], current_rot[1], z_deg)) | |
| else: | |
| xform.AddRotateXYZOp().Set(Gf.Vec3f(0, 0, z_deg)) | |
| # --- Handle Scale --- | |
| if scale is not None: | |
| if found_ops["scale"]: | |
| found_ops["scale"].Set(scale) | |
| else: | |
| xform.AddScaleOp().Set(scale) | |
| def scatter_assets(stage, asset_paths, num_assets, area_min, area_max, root_path): | |
| if num_assets == 0: return | |
| stage.DefinePrim(root_path, "Xform") | |
| for i in range(num_assets): | |
| asset_path = random.choice(asset_paths) | |
| new_path = f"{root_path}/item_{i}" | |
| omni.usd.duplicate_prim(stage, asset_path, new_path) | |
| prim = stage.GetPrimAtPath(new_path) | |
| pos = Gf.Vec3f(random.uniform(area_min[0], area_max[0]), | |
| random.uniform(area_min[1], area_max[1]), 0) | |
| rot = Gf.Vec3f(0, 0, random.uniform(0, 360)) | |
| set_robust_transform(prim, translation=pos, rotation_euler=rot, scale=Gf.Vec3f(1.0)) | |
| def get_crop_paths (crop_type, crop_age): | |
| """Get valid prim paths for the selected crop type and age.""" | |
| base_path = f"/World/base/{crop_type}" | |
| age_suffixes = CROP_AGES.get(crop_age, []) | |
| available_suffixes = CROP_ASSETS.get(crop_type, []) | |
| valid_suffixes = [s for s in age_suffixes if s in available_suffixes] | |
| if not valid_suffixes: | |
| raise ValueError(f"No assets found for crop {crop_type} with age {crop_age}'.") | |
| return [f"{base_path}/{suffix}" for suffix in valid_suffixes] | |
| def generate_scene(config): | |
| stage = omni.usd.get_context().get_stage() | |
| # ... [Config parsing logic] ... | |
| # --- Field Generation --- | |
| root_crop_path = Sdf.Path(f"/root/{config['crop_type']}_{config['crop_age']}_field") | |
| if stage.GetPrimAtPath(root_crop_path): stage.RemovePrim(root_crop_path) | |
| stage.DefinePrim(root_crop_path, "Xform") | |
| curve_effect = np.sin(np.linspace(0, 6 * np.pi, config["num_plants_in_row"])) * 0.35 if config["curve"] else np.zeros(config["num_plants_in_row"]) | |
| print(f"Generating {config['num_rows']} rows with {config['num_plants_in_row']} plants each (Curve: {config['curve']})") | |
| for i in range(config["num_rows"]): | |
| for j in range(config["num_plants_in_row"]): | |
| if random.random() < 0.1: continue | |
| new_prim_path = f"{root_crop_path}/row_{i}_plant_{j}" | |
| omni.usd.duplicate_prim(stage, random.choice(get_crop_paths(config["crop_type"], config["crop_age"])), new_prim_path) | |
| prim = stage.GetPrimAtPath(new_prim_path) | |
| # Position logic | |
| offset = random.uniform(-0.02, 0.02) | |
| x_pos = i * ROW_SPACING.get(config["crop_type"], 0.45) + offset + curve_effect[j] | |
| y_pos = j * 0.1 + offset | |
| # Scale logic | |
| s = 1.0 + random.uniform(-0.05, 0.05) | |
| set_robust_transform( | |
| prim, | |
| translation=Gf.Vec3f(x_pos, y_pos, 0), | |
| rotation_euler=Gf.Vec3f(0, 0, random.uniform(0, 360)), | |
| scale=Gf.Vec3f(s, s, s) | |
| ) | |
| # Scatter Weeds/Obstacles | |
| field_w = config["num_rows"] * ROW_SPACING.get(config["crop_type"], 0.45) | |
| field_l = config["num_plants_in_row"] * 0.1 | |
| print(f"Scattering weeds and obstacles (Weeds: {config['weed_volume']}, Obstacles: {config['obstacle_volume']})") | |
| scatter_assets(stage, WEED_ASSETS, VOLUME_MAPPING[config["weed_volume"]], (0,0), (field_w, field_l), Sdf.Path("/root/Weeds")) | |
| print(f"Scattering obstacles (Volume: {config['obstacle_volume']})") | |
| scatter_assets(stage, OBSTACLE_ASSETS, OBSTACLE_VOLUME_MAPPING[config["obstacle_volume"]], (0,0), (field_w, field_l), Sdf.Path("/root/Obstacles")) | |
| # print(f"Setting time of day to {config['time_of_day']}") | |
| # set_time_of_day(stage, config["time_of_day"]) | |
| # print("Changing ground material") | |
| # change_ground_material(stage) | |
| print("Scene generation complete!") | |
| # --- USER CONFIGURATION --- | |
| # Modify the values in this dictionary to change the generated scene. | |
| CONFIG = { | |
| "crop_type": "cane", # Options: "soybean", "sorghum", "cotton", "corn" | |
| "crop_age": "y", # Options: "y", "y-m", "m-l", "l" | |
| "curve": False, # Options: True or False | |
| "num_plants_in_row": 250, # Number of plants in each row | |
| "num_rows": 20, # Number of rows in the field | |
| "weed_volume": "none", # Options: "none", "some", "lot" | |
| "obstacle_volume": "none", # Options: "none", "some", "lot" | |
| "time_of_day": "noon" # Options: "early", "noon", "late" | |
| } | |
| # --- END USER CONFIGURATION --- | |
| # Execute the scene generation | |
| generate_scene(CONFIG) | |
| # for crop_type in ["soybean", "sorghum", "cotton", "corn"]: | |
| # for crop_age in ["y", "y-m", "m-l", "l"]: | |
| # CONFIG = { | |
| # "crop_type": crop_type, | |
| # "crop_age": crop_age, | |
| # "curve": False, | |
| # "num_plants_in_row": 250, | |
| # "num_rows": 20, | |
| # "weed_volume": "some", | |
| # "obstacle_volume": "some", | |
| # "time_of_day": "noon" | |
| # } | |
| # generate_scene(CONFIG) |