def add_asset(self, asset: 'Any'): if isinstance(asset, chrono.ChBody): self._system._system.AddBody(asset) return if isinstance(asset, WABody): if not hasattr(asset, 'size') or not hasattr(asset, 'position'): raise AttributeError( "Body must have 'size', and 'position' fields") position = asset.position yaw = 0 if not hasattr(asset, 'yaw') else asset.yaw size = asset.size body_type = 'box' if hasattr(asset, 'body_type'): body_type = asset.body_type if body_type == 'sphere': body = chrono.ChBodyEasySphere(size.length, 1000, True, False) body.SetBodyFixed(True) elif body_type == 'box': body = chrono.ChBodyEasyBox( size.x, size.y, size.z, 1000, True, False) body.SetBodyFixed(True) else: raise ValueError( f"'{asset.body_type}' not a supported body type.") body.SetPos(WAVector_to_ChVector(position)) body.SetRot(chrono.Q_from_AngZ(-yaw + WA_PI / 2)) if hasattr(asset, 'color'): color = asset.color body.AddAsset(chrono.ChColorAsset( chrono.ChColor(color.x, color.y, color.z))) texture = chrono.ChVisualMaterial() texture.SetDiffuseColor( chrono.ChVectorF(color.x, color.y, color.z)) chrono.CastToChVisualization( body.GetAssets()[0]).material_list.append(texture) if hasattr(asset, 'texture'): texture = chrono.ChVisualMaterial() texture.SetKdTexture(get_wa_data_file(asset.texture)) chrono.CastToChVisualization( body.GetAssets()[0]).material_list.append(texture) self._system._system.AddBody(body) asset.chrono_body = body super().add_asset(asset)
def create_sphere_in_chrono( system: 'WAChronoSystem', rgb=(1, 0, 0)) -> chrono.ChBodyEasySphere: """Create and add a sphere to the chrono world Args: system (WASystem): the system that manages the simulation rgb (tuple, optional): (red, green, blue). Defaults to (1, 0, 0) or red. Returns: chrono.ChBodyEasySphere: the sphere that was created """ sphere = chrono.ChBodyEasySphere(0.25, 1000, True, False) sphere.SetBodyFixed(True) sphere.AddAsset(chrono.ChColorAsset(*rgb)) texture = chrono.ChVisualMaterial() texture.SetDiffuseColor(chrono.ChVectorF(*rgb)) chrono.CastToChVisualization( sphere.GetAssets()[0]).material_list.append(texture) system._system.Add(sphere) return sphere
def reset(self): n = 2 * np.random.randint(0, 4) b1 = 0 b2 = 0 r1 = n r2 = n r3 = n r4 = n r5 = n t1 = 0 t2 = 0 t3 = 0 c = 0 self.assets = AssetList(b1, b2, r1, r2, r3, r4, r5, t1, t2, t3, c) # Create systems self.system = chrono.ChSystemNSC() self.system.Set_G_acc(chrono.ChVectorD(0, 0, -9.81)) self.system.SetSolverType(chrono.ChSolver.Type_BARZILAIBORWEIN) self.system.SetSolverMaxIterations(150) self.system.SetMaxPenetrationRecoverySpeed(4.0) # Create the terrain rigid_terrain = True self.terrain = veh.RigidTerrain(self.system) if rigid_terrain: patch_mat = chrono.ChMaterialSurfaceNSC() patch_mat.SetFriction(0.9) patch_mat.SetRestitution(0.01) patch = self.terrain.AddPatch(patch_mat, chrono.ChVectorD(0, 0, 0), chrono.ChVectorD(0, 0, 1), self.terrain_length * 1.5, self.terrain_width * 1.5) else: self.bitmap_file = os.path.dirname( os.path.realpath(__file__)) + "/../utils/height_map.bmp" self.bitmap_file_backup = os.path.dirname( os.path.realpath(__file__)) + "/../utils/height_map_backup.bmp" shape = (252, 252) generate_random_bitmap(shape=shape, resolutions=[(2, 2)], mappings=[(-1.5, 1.5)], file_name=self.bitmap_file) try: patch = self.terrain.AddPatch( chrono.CSYSNORM, # position self.bitmap_file, # heightmap file (.bmp) "test", # mesh name self.terrain_length * 1.5, # sizeX self.terrain_width * 1.5, # sizeY self.min_terrain_height, # hMin self.max_terrain_height) # hMax except Exception: print('Corrupt Bitmap File') patch = self.terrain.AddPatch( chrono.CSYSNORM, # position self.bitmap_file_backup, # heightmap file (.bmp) "test", # mesh name self.terrain_length * 1.5, # sizeX self.terrain_width * 1.5, # sizeY self.min_terrain_height, # hMin self.max_terrain_height) # hMax patch.SetTexture(veh.GetDataFile("terrain/textures/grass.jpg"), 200, 200) patch.SetColor(chrono.ChColor(0.8, 0.8, 0.5)) self.terrain.Initialize() ground_body = patch.GetGroundBody() ground_asset = ground_body.GetAssets()[0] visual_asset = chrono.CastToChVisualization(ground_asset) visual_asset.SetStatic(True) vis_mat = chrono.ChVisualMaterial() vis_mat.SetKdTexture(veh.GetDataFile("terrain/textures/grass.jpg")) visual_asset.material_list.append(vis_mat) theta = random.random() * 2 * np.pi x, y = self.terrain_length * 0.5 * np.cos( theta), self.terrain_width * 0.5 * np.sin(theta) z = self.terrain.GetHeight(chrono.ChVectorD(x, y, 0)) + 0.25 ang = np.pi + theta self.initLoc = chrono.ChVectorD(x, y, z) self.initRot = chrono.Q_from_AngZ(ang) self.vehicle = veh.Gator(self.system) self.vehicle.SetContactMethod(chrono.ChContactMethod_NSC) self.vehicle.SetChassisCollisionType(veh.ChassisCollisionType_NONE) self.vehicle.SetChassisFixed(False) self.m_inputs = veh.Inputs() self.vehicle.SetInitPosition( chrono.ChCoordsysD(self.initLoc, self.initRot)) self.vehicle.SetTireType(veh.TireModelType_TMEASY) self.vehicle.SetTireStepSize(self.timestep) self.vehicle.Initialize() if self.play_mode: self.vehicle.SetChassisVisualizationType( veh.VisualizationType_MESH) self.vehicle.SetWheelVisualizationType(veh.VisualizationType_MESH) self.vehicle.SetTireVisualizationType(veh.VisualizationType_MESH) else: self.vehicle.SetChassisVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetWheelVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetTireVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetSuspensionVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetSteeringVisualizationType( veh.VisualizationType_PRIMITIVES) self.chassis_body = self.vehicle.GetChassisBody() # self.chassis_body.GetCollisionModel().ClearModel() # size = chrono.ChVectorD(3,2,0.2) # self.chassis_body.GetCollisionModel().AddBox(0.5 * size.x, 0.5 * size.y, 0.5 * size.z) # self.chassis_body.GetCollisionModel().BuildModel() self.chassis_collision_box = chrono.ChVectorD(3, 2, 0.2) # Driver self.driver = veh.ChDriver(self.vehicle.GetVehicle()) # create goal # pi/4 ang displ delta_theta = (random.random() - 0.5) * 1.0 * np.pi gx, gy = self.terrain_length * 0.5 * np.cos( theta + np.pi + delta_theta), self.terrain_width * 0.5 * np.sin(theta + np.pi + delta_theta) self.goal = chrono.ChVectorD( gx, gy, self.terrain.GetHeight(chrono.ChVectorD(gx, gy, 0)) + 1.0) i = 0 while (self.goal - self.initLoc).Length() < 15: gx = random.random() * self.terrain_length - self.terrain_length / 2 gy = random.random() * self.terrain_width - self.terrain_width / 2 self.goal = chrono.ChVectorD(gx, gy, self.max_terrain_height + 1) if i > 100: print('Break') break i += 1 # self.goal = chrono.ChVectorD(75, 0, 0) # Origin in Madison WI self.origin = chrono.ChVectorD(43.073268, -89.400636, 260.0) self.goal_coord = chrono.ChVectorD(self.goal) sens.Cartesian2GPS(self.goal_coord, self.origin) self.goal_sphere = chrono.ChBodyEasySphere(.55, 1000, True, False) self.goal_sphere.SetBodyFixed(True) sphere_asset = self.goal_sphere.GetAssets()[0] visual_asset = chrono.CastToChVisualization(sphere_asset) vis_mat = chrono.ChVisualMaterial() vis_mat.SetAmbientColor(chrono.ChVectorF(0, 0, 0)) vis_mat.SetDiffuseColor(chrono.ChVectorF(.2, .2, .9)) vis_mat.SetSpecularColor(chrono.ChVectorF(.9, .9, .9)) visual_asset.material_list.append(vis_mat) visual_asset.SetStatic(True) self.goal_sphere.SetPos(self.goal) if self.play_mode: self.system.Add(self.goal_sphere) # create obstacles # start = t.time() self.assets.Clear() self.assets.RandomlyPositionAssets(self.system, self.initLoc, self.goal, self.terrain, self.terrain_length * 1.5, self.terrain_width * 1.5, should_scale=False) # Set the time response for steering and throttle inputs. # NOTE: this is not exact, since we do not render quite at the specified FPS. steering_time = 0.75 # time to go from 0 to +1 (or from 0 to -1) throttle_time = .5 # time to go from 0 to +1 braking_time = 0.3 # time to go from 0 to +1 self.SteeringDelta = (self.timestep / steering_time) self.ThrottleDelta = (self.timestep / throttle_time) self.BrakingDelta = (self.timestep / braking_time) self.manager = sens.ChSensorManager(self.system) self.manager.scene.AddPointLight(chrono.ChVectorF(100, 100, 100), chrono.ChVectorF(1, 1, 1), 5000.0) self.manager.scene.AddPointLight(chrono.ChVectorF(-100, -100, 100), chrono.ChVectorF(1, 1, 1), 5000.0) # Let's not, for the moment, give a different scenario during test """ if self.play_mode: self.manager.scene.GetBackground().has_texture = True; self.manager.scene.GetBackground().env_tex = "sensor/textures/qwantani_8k.hdr" self.manager.scene.GetBackground().has_changed = True; """ # ----------------------------------------------------- # Create a self.camera and add it to the sensor manager # ----------------------------------------------------- #chrono.ChFrameD(chrono.ChVectorD(1.5, 0, .875), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))), self.camera = sens.ChCameraSensor( self.chassis_body, # body camera is attached to 20, # scanning rate in Hz chrono.ChFrameD( chrono.ChVectorD(.65, 0, .75), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))), # offset pose self.camera_width, # number of horizontal samples self.camera_height, # number of vertical channels chrono.CH_C_PI / 2, # horizontal field of view 6 # supersampling factor ) self.camera.SetName("Camera Sensor") self.camera.PushFilter(sens.ChFilterRGBA8Access()) if self.play_mode: self.camera.PushFilter( sens.ChFilterVisualize(self.camera_width, self.camera_height, "RGB Camera")) self.manager.AddSensor(self.camera) # ----------------------------------------------------- # Create a self.gps and add it to the sensor manager # ----------------------------------------------------- gps_noise_none = sens.ChGPSNoiseNone() self.gps = sens.ChGPSSensor( self.chassis_body, 15, chrono.ChFrameD( chrono.ChVectorD(0, 0, 0), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))), self.origin, gps_noise_none) self.gps.SetName("GPS Sensor") self.gps.PushFilter(sens.ChFilterGPSAccess()) self.manager.AddSensor(self.gps) # have to reconstruct scene because sensor loads in meshes separately (ask Asher) # start = t.time() if self.assets.GetNum() > 0: # self.assets.TransformAgain() # start = t.time() for asset in self.assets.assets: if len(asset.frames) > 0: self.manager.AddInstancedStaticSceneMeshes( asset.frames, asset.mesh.shape) # self.manager.ReconstructScenes() # self.manager.AddInstancedStaticSceneMeshes(self.assets.frames, self.assets.shapes) # self.manager.Update() # print('Reconstruction :: ', t.time() - start) self.old_dist = (self.goal - self.initLoc).Length() self.step_number = 0 self.c_f = 0 self.isdone = False self.render_setup = False self.dist0 = (self.goal - self.chassis_body.GetPos()).Length() if self.play_mode: self.render() # print(self.get_ob()[1]) return self.get_ob()
def __init__(self, step_size, sys, controller, irrlicht=False, vehicle_type='json', initLoc=chrono.ChVectorD(0,0,0), initRot=chrono.ChQuaternionD(1,0,0,0), vis_balls=False, render_step_size=1.0/60): # Chrono parameters self.step_size = step_size self.irrlicht = irrlicht self.step_number = 0 # Vehicle controller self.controller = controller # Initial vehicle position self.initLoc = initLoc # Initial vehicle orientation self.initRot = initRot # Point on chassis tracked by the camera (Irrlicht only) self.trackPoint = chrono.ChVectorD(0.0, 0.0, 1.75) if vehicle_type == 'json': # JSON file for vehicle model self.vehicle_file = veh.GetDataPath() + os.path.join('hmmwv', 'vehicle', 'HMMWV_Vehicle.json') checkFile(self.vehicle_file) # JSON file for powertrain (simple) self.simplepowertrain_file = veh.GetDataPath() + os.path.join('generic', 'powertrain', 'SimplePowertrain.json') checkFile(self.simplepowertrain_file) # JSON files tire models (rigid) self.rigidtire_file = veh.GetDataPath() + os.path.join('hmmwv', 'tire', 'HMMWV_RigidTire.json') checkFile(self.rigidtire_file) # -------------------------- # Create the various modules # -------------------------- if sys == None: self.wheeled_vehicle = veh.WheeledVehicle(self.vehicle_file) else: self.wheeled_vehicle = veh.WheeledVehicle(sys, self.vehicle_file) self.wheeled_vehicle.Initialize(chrono.ChCoordsysD(self.initLoc, self.initRot)) self.wheeled_vehicle.SetChassisVisualizationType(veh.VisualizationType_PRIMITIVES) self.wheeled_vehicle.SetSuspensionVisualizationType(veh.VisualizationType_PRIMITIVES) self.wheeled_vehicle.SetSteeringVisualizationType(veh.VisualizationType_PRIMITIVES) self.wheeled_vehicle.SetWheelVisualizationType(veh.VisualizationType_NONE) # Create and initialize the powertrain system self.powertrain = veh.SimplePowertrain(self.simplepowertrain_file) self.wheeled_vehicle.InitializePowertrain(self.powertrain) # Create and initialize the tires for axle in self.wheeled_vehicle.GetAxles(): tireL = veh.RigidTire(self.rigidtire_file) self.wheeled_vehicle.InitializeTire(tireL, axle.m_wheels[0], veh.VisualizationType_MESH) tireR = veh.RigidTire(self.rigidtire_file) self.wheeled_vehicle.InitializeTire(tireR, axle.m_wheels[1], veh.VisualizationType_MESH) self.vehicle = self.wheeled_vehicle self.sys = self.wheeled_vehicle.GetSystem() elif vehicle_type == 'rccar': if sys == None: self.rc_vehicle = veh.RCCar() self.rc_vehicle.SetContactMethod(chrono.ChMaterialSurface.SMC) self.rc_vehicle.SetChassisCollisionType(veh.ChassisCollisionType_NONE) else: self.rc_vehicle = veh.RCCar(sys) self.rc_vehicle.SetChassisFixed(False) self.rc_vehicle.SetInitPosition(chrono.ChCoordsysD(initLoc, initRot)) self.rc_vehicle.SetTireType(veh.TireModelType_RIGID) self.rc_vehicle.SetTireStepSize(step_size) self.rc_vehicle.Initialize() self.rc_vehicle.SetChassisVisualizationType(veh.VisualizationType_PRIMITIVES) self.rc_vehicle.SetSuspensionVisualizationType(veh.VisualizationType_PRIMITIVES) self.rc_vehicle.SetSteeringVisualizationType(veh.VisualizationType_PRIMITIVES) self.rc_vehicle.SetWheelVisualizationType(veh.VisualizationType_PRIMITIVES) self.rc_vehicle.SetTireVisualizationType(veh.VisualizationType_PRIMITIVES) self.vehicle = self.rc_vehicle.GetVehicle() self.sys = self.vehicle.GetSystem() self.trackPoint = chrono.ChVectorD(4, 0.0, .15) elif vehicle_type == 'sedan': if sys == None: self.sedan = veh.Sedan() self.sedan.SetContactMethod(chrono.ChMaterialSurface.NSC) self.sedan.SetChassisCollisionType(veh.ChassisCollisionType_NONE) else: self.sedan = veh.Sedan(sys) self.sedan.SetChassisFixed(False) self.sedan.SetInitPosition(chrono.ChCoordsysD(initLoc, initRot)) self.sedan.SetTireType(veh.TireModelType_RIGID) self.sedan.SetTireStepSize(step_size) self.sedan.Initialize() self.sedan.SetChassisVisualizationType(veh.VisualizationType_PRIMITIVES) self.sedan.SetSuspensionVisualizationType(veh.VisualizationType_PRIMITIVES) self.sedan.SetSteeringVisualizationType(veh.VisualizationType_PRIMITIVES) self.sedan.SetWheelVisualizationType(veh.VisualizationType_PRIMITIVES) self.sedan.SetTireVisualizationType(veh.VisualizationType_PRIMITIVES) self.vehicle = self.sedan.GetVehicle() self.sys = self.vehicle.GetVehicle().GetSystem() # ------------- # Create driver # ------------- self.driver = Driver(self.vehicle) self.driver.SetStepSize(step_size) # Set the time response for steering and throttle inputs. # NOTE: this is not exact, since we do not render quite at the specified FPS. steering_time = 1.0 # time to go from 0 to +1 (or from 0 to -1) throttle_time = 1.0 # time to go from 0 to +1 braking_time = 0.3 # time to go from 0 to +1 self.driver.SetSteeringDelta(render_step_size / steering_time) self.driver.SetThrottleDelta(render_step_size / throttle_time) self.driver.SetBrakingDelta(render_step_size / braking_time) self.vis_balls = vis_balls if self.vis_balls: self.sentinel_sphere = chrono.ChBodyEasySphere(.25, 1000, False, True) self.sentinel_sphere.SetBodyFixed(True) self.sentinel_sphere.AddAsset(chrono.ChColorAsset(1,0,0)) self.sys.Add(self.sentinel_sphere) self.sentinel_target = chrono.ChBodyEasySphere(.25, 1000, False, True) self.sentinel_target.SetBodyFixed(True) self.sentinel_target.AddAsset(chrono.ChColorAsset(0,1,0)); self.sys.Add(self.sentinel_target) # Vehicle parameters for matplotlib self.length = self.vehicle.GetWheelbase() + 2.0 # [m] self.width = self.vehicle.GetWheeltrack(0) # [m] self.backtowheel = 1.0 # [m] self.wheel_len = self.vehicle.GetWheel(0, 1).GetWidth() * 2 # [m] self.wheel_width = self.vehicle.GetWheel(0, 1).GetWidth() # [m] self.tread = self.vehicle.GetWheeltrack(0) / 2 # [m] self.wb = self.vehicle.GetWheelbase() # [m] self.offset = [-4.0,0] # [m]
# brick_material.SetCompliance (0.0000001) # brick_material.SetComplianceT(0.0000001) # brick_material.SetRollingFriction(rollfrict_param) # brick_material.SetSpinningFriction(0) # brick_material.SetComplianceRolling(0.0000001) # brick_material.SetComplianceSpinning(0.0000001) S0 = chrono.ChVectorD(0, 0, 0) Sr = chrono.ChVectorD(rad_sph * math.sin(alpha), -rad_sph * math.cos(alpha), 0) Sl = chrono.ChVectorD(-rad_sph * math.sin(beta), rad_sph * math.cos(beta), 0) Dr = chrono.ChVectorD(math.cos(alpha), math.sin(alpha), 0) Dl = chrono.ChVectorD(math.cos(beta), math.sin(beta), 0) Dz = chrono.ChVectorD(0, 0, thick) if False: mbodyS = chrono.ChBodyEasySphere(0.1, 1000, True, True) mbodyS.SetPos(S0) mbodyS.SetMaterialSurface(brick_material) mysystem.Add(mbodyS) else: S1 = Sl + Dl * 0.2 S2 = Sl - Dl * 0.2 S3 = Sr + Dr * 0.2 S4 = Sr - Dr * 0.2 Dzz = chrono.ChVectorD(0, 0, (thick * 0.6)) pointsS = chrono.vector_ChVectorD([ S1 + Dzz, S2 + Dzz, S3 + Dzz, S4 + Dzz, S1 - Dzz, S2 - Dzz, S3 - Dzz, S4 - Dzz ]) mbodyS = chrono.ChBodyEasyConvexHullAuxRef(pointsS, 1000, True, True)
brick_material.SetDampingF(0.00000) brick_material.SetCompliance(1e-9) brick_material.SetComplianceT(1e-9) L_material = chrono.ChMaterialSurfaceNSC() L_material.SetFriction(0) S0 = chrono.ChVectorD(0, 0, 0) Sr = chrono.ChVectorD(rad_sph * math.sin(alpha), -rad_sph * math.cos(alpha), 0) Sl = chrono.ChVectorD(-rad_sph * math.sin(beta), rad_sph * math.cos(beta), 0) Dr = chrono.ChVectorD(math.cos(alpha), math.sin(alpha), 0) Dl = chrono.ChVectorD(math.cos(beta), math.sin(beta), 0) Dz = chrono.ChVectorD(0, 0, thick) if False: mbodyS = chrono.ChBodyEasySphere(0.1, 1000, True, True, brick_material) mbodyS.SetPos(S0) mysystem.Add(mbodyS) else: S1 = Sl + Dl * 0.2 S2 = Sl - Dl * 0.2 S3 = Sr + Dr * 0.2 S4 = Sr - Dr * 0.2 Dzz = chrono.ChVectorD(0, 0, (thick * 0.6)) pointsS = chrono.vector_ChVectorD([ S1 + Dzz, S2 + Dzz, S3 + Dzz, S4 + Dzz, S1 - Dzz, S2 - Dzz, S3 - Dzz, S4 - Dzz ]) mbodyS = chrono.ChBodyEasyConvexHullAuxRef(pointsS, 1000, True, True, brick_material)
mfloor = chrono.ChBodyEasyBox(2, 0.1, 2, 2700, True, True, mysurfmaterial) mfloor.SetBodyFixed(True) my_system.Add(mfloor) masset_texture = chrono.ChTexture() masset_texture.SetTextureFilename( chrono.GetChronoDataFile("textures/concrete.jpg")) mfloor.AddAsset(masset_texture) # two falling objects: mcube = chrono.ChBodyEasyBox(0.1, 0.1, 0.1, 2700, True, True, mysurfmaterial) mcube.SetPos(chrono.ChVectorD(0.6, 0.5, 0.6)) my_system.Add(mcube) msphere = chrono.ChBodyEasySphere(0.1, 2700, True, True, mysurfmaterial) msphere.SetPos(chrono.ChVectorD(0.8, 0.5, 0.6)) my_system.Add(msphere) # # Example 1: tetrahedrons, with collisions # # Create a mesh. We will use it for tetrahedrons. my_mesh = fea.ChMesh() # 1) a FEA tetrahedron(s): # Create a material, that must be assigned to each solid element in the mesh, # and set its parameters