text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_SensorBase_hpp #define msr_airlib_SensorBase_hpp #include "common/Common.hpp" #include "common/UpdatableObject.hpp" #include "common/CommonStructs.hpp" #include "physics/Environment.hpp" #include "physics/Kinematics.hpp" namespace msr { namespace airlib { /* Derived classes should not do any work in constructor which requires ground truth. After construction of the derived class an initialize(...) must be made which would set the sensor in good-to-use state by call to reset. */ class SensorBase : public UpdatableObject { public: enum class SensorType : uint { Barometer = 1, Imu = 2, Gps = 3, Magnetometer = 4, Distance = 5, Lidar = 6 }; SensorBase(const std::string& sensor_name = "") : name_(sensor_name) { } protected: struct GroundTruth { const Kinematics::State* kinematics; const Environment* environment; }; public: virtual void initialize(const Kinematics::State* kinematics, const Environment* environment) { ground_truth_.kinematics = kinematics; ground_truth_.environment = environment; } const GroundTruth& getGroundTruth() const { return ground_truth_; } const std::string& getName() const { return name_; } virtual ~SensorBase() = default; private: //ground truth can be shared between many sensors GroundTruth ground_truth_ = { nullptr, nullptr }; std::string name_ = ""; }; } } //namespace #endif
AirSim/AirLib/include/sensors/SensorBase.hpp/0
{ "file_path": "AirSim/AirLib/include/sensors/SensorBase.hpp", "repo_id": "AirSim", "token_count": 780 }
9
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_Lidar_hpp #define msr_airlib_Lidar_hpp #include <random> #include "common/Common.hpp" #include "LidarSimpleParams.hpp" #include "LidarBase.hpp" #include "common/DelayLine.hpp" #include "common/FrequencyLimiter.hpp" namespace msr { namespace airlib { class LidarSimple : public LidarBase { public: LidarSimple(const AirSimSettings::LidarSetting& setting = AirSimSettings::LidarSetting()) : LidarBase(setting.sensor_name) { // initialize params params_.initializeFromSettings(setting); //initialize frequency limiter freq_limiter_.initialize(params_.update_frequency, params_.startup_delay); } //*** Start: UpdatableState implementation ***// virtual void resetImplementation() override { freq_limiter_.reset(); last_time_ = clock()->nowNanos(); updateOutput(); } virtual void update() override { LidarBase::update(); freq_limiter_.update(); if (freq_limiter_.isWaitComplete()) { updateOutput(); } } virtual void reportState(StateReporter& reporter) override { //call base LidarBase::reportState(reporter); reporter.writeValue("Lidar-NumChannels", params_.number_of_channels); reporter.writeValue("Lidar-Range", params_.range); reporter.writeValue("Lidar-FOV-Upper", params_.vertical_FOV_upper); reporter.writeValue("Lidar-FOV-Lower", params_.vertical_FOV_lower); } //*** End: UpdatableState implementation ***// virtual ~LidarSimple() = default; const LidarSimpleParams& getParams() const { return params_; } protected: virtual void getPointCloud(const Pose& lidar_pose, const Pose& vehicle_pose, TTimeDelta delta_time, vector<real_T>& point_cloud, vector<int>& segmentation_cloud) = 0; private: //methods void updateOutput() { TTimeDelta delta_time = clock()->updateSince(last_time_); point_cloud_.clear(); const GroundTruth& ground_truth = getGroundTruth(); // calculate the pose before obtaining the point-cloud. Before/after is a bit arbitrary // decision here. If the pose can change while obtaining the point-cloud (could happen for drones) // then the pose won't be very accurate either way. // // TODO: Seems like pose is in vehicle inertial-frame (NOT in Global NED frame). // That could be a bit unintuitive but seems consistent with the position/orientation returned as part of // ImageResponse for cameras and pose returned by getCameraInfo API. // Do we need to convert pose to Global NED frame before returning to clients? Pose lidar_pose = params_.relative_pose + ground_truth.kinematics->pose; getPointCloud(params_.relative_pose, // relative lidar pose ground_truth.kinematics->pose, // relative vehicle pose delta_time, point_cloud_, segmentation_cloud_); LidarData output; output.point_cloud = point_cloud_; output.time_stamp = clock()->nowNanos(); output.pose = lidar_pose; output.segmentation = segmentation_cloud_; last_time_ = output.time_stamp; setOutput(output); } private: LidarSimpleParams params_; vector<real_T> point_cloud_; vector<int> segmentation_cloud_; FrequencyLimiter freq_limiter_; TTimePoint last_time_; }; } } //namespace #endif
AirSim/AirLib/include/sensors/lidar/LidarSimple.hpp/0
{ "file_path": "AirSim/AirLib/include/sensors/lidar/LidarSimple.hpp", "repo_id": "AirSim", "token_count": 1770 }
10
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_RotorParams_hpp #define msr_airlib_RotorParams_hpp #include "common/Common.hpp" namespace msr { namespace airlib { //In NED system, +ve torque would generate clockwise rotation enum class RotorTurningDirection : int { RotorTurningDirectionCCW = -1, RotorTurningDirectionCW = 1 }; struct RotorParams { /* Ref: http://physics.stackexchange.com/a/32013/14061 force in Newton = C_T * \rho * n^2 * D^4 torque in N.m = C_P * \rho * n^2 * D^5 / (2*pi) where, \rho = air density (1.225 kg/m^3) n = revolutions per sec D = propeller diameter in meters C_T, C_P = dimensionless constants available at propeller performance database http://m-selig.ae.illinois.edu/props/propDB.html We use values for GWS 9X5 propeller for which, C_T = 0.109919, C_P = 0.040164 @ 6396.667 RPM */ real_T C_T = 0.109919f; // the thrust co-efficient @ 6396.667 RPM, measured by UIUC. real_T C_P = 0.040164f; // the torque co-efficient at @ 6396.667 RPM, measured by UIUC. real_T air_density = 1.225f; // kg/m^3 real_T max_rpm = 6396.667f; // revolutions per minute real_T propeller_diameter = 0.2286f; //diameter in meters, default is for DJI Phantom 2 real_T propeller_height = 1 / 100.0f; //height of cylindrical area when propeller rotates, 1 cm real_T control_signal_filter_tc = 0.005f; //time constant for low pass filter real_T revolutions_per_second; real_T max_speed; // in radians per second real_T max_speed_square; real_T max_thrust = 4.179446268f; //computed from above formula for the given constants real_T max_torque = 0.055562f; //computed from above formula // call this method to recalculate thrust if you want to use different numbers for C_T, C_P, max_rpm, etc. void calculateMaxThrust() { revolutions_per_second = max_rpm / 60; max_speed = revolutions_per_second * 2 * M_PIf; // radians / sec max_speed_square = pow(max_speed, 2.0f); real_T nsquared = revolutions_per_second * revolutions_per_second; max_thrust = C_T * air_density * nsquared * static_cast<real_T>(pow(propeller_diameter, 4)); max_torque = C_P * air_density * nsquared * static_cast<real_T>(pow(propeller_diameter, 5)) / (2 * M_PIf); } }; } } //namespace #endif
AirSim/AirLib/include/vehicles/multirotor/RotorParams.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/RotorParams.hpp", "repo_id": "AirSim", "token_count": 1173 }
11
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_SimpleFlightDroneController_hpp #define msr_airlib_SimpleFlightDroneController_hpp #include "vehicles/multirotor/api/MultirotorApiBase.hpp" #include "sensors/SensorCollection.hpp" #include "physics/Environment.hpp" #include "physics/Kinematics.hpp" #include "vehicles/multirotor/MultiRotorParams.hpp" #include "common/Common.hpp" #include "firmware/Firmware.hpp" #include "AirSimSimpleFlightBoard.hpp" #include "AirSimSimpleFlightCommLink.hpp" #include "AirSimSimpleFlightEstimator.hpp" #include "AirSimSimpleFlightCommon.hpp" #include "physics/PhysicsBody.hpp" #include "common/AirSimSettings.hpp" //TODO: we need to protect contention between physics thread and API server thread namespace msr { namespace airlib { class SimpleFlightApi : public MultirotorApiBase { public: SimpleFlightApi(const MultiRotorParams* vehicle_params, const AirSimSettings::VehicleSetting* vehicle_setting) : vehicle_params_(vehicle_params) { readSettings(*vehicle_setting); //TODO: set below properly for better high speed safety safety_params_.vel_to_breaking_dist = safety_params_.min_breaking_dist = 0; //create sim implementations of board and commlink board_.reset(new AirSimSimpleFlightBoard(&params_)); comm_link_.reset(new AirSimSimpleFlightCommLink()); estimator_.reset(new AirSimSimpleFlightEstimator()); //create firmware firmware_.reset(new simple_flight::Firmware(&params_, board_.get(), comm_link_.get(), estimator_.get())); } public: //VehicleApiBase implementation virtual void resetImplementation() override { MultirotorApiBase::resetImplementation(); firmware_->reset(); } virtual void update() override { MultirotorApiBase::update(); //update controller which will update actuator control signal firmware_->update(); } virtual bool isApiControlEnabled() const override { return firmware_->offboardApi().hasApiControl(); } virtual void enableApiControl(bool is_enabled) override { if (is_enabled) { //comm_link should print message so no extra handling for errors std::string message; firmware_->offboardApi().requestApiControl(message); } else firmware_->offboardApi().releaseApiControl(); } virtual bool armDisarm(bool arm) override { std::string message; if (arm) return firmware_->offboardApi().arm(message); else return firmware_->offboardApi().disarm(message); } virtual GeoPoint getHomeGeoPoint() const override { return AirSimSimpleFlightCommon::toGeoPoint(firmware_->offboardApi().getHomeGeoPoint()); } virtual void getStatusMessages(std::vector<std::string>& messages) override { comm_link_->getStatusMessages(messages); } virtual const SensorCollection& getSensors() const override { return vehicle_params_->getSensors(); } public: //MultirotorApiBase implementation virtual real_T getActuation(unsigned int rotor_index) const override { auto control_signal = board_->getMotorControlSignal(rotor_index); return control_signal; } virtual size_t getActuatorCount() const override { return vehicle_params_->getParams().rotor_count; } virtual void moveByRC(const RCData& rc_data) override { setRCData(rc_data); } virtual void setSimulatedGroundTruth(const Kinematics::State* kinematics, const Environment* environment) override { board_->setGroundTruthKinematics(kinematics); estimator_->setGroundTruthKinematics(kinematics, environment); } virtual bool setRCData(const RCData& rc_data) override { last_rcData_ = rc_data; if (rc_data.is_valid) { board_->setIsRcConnected(true); board_->setInputChannel(0, rc_data.roll); //X board_->setInputChannel(1, rc_data.yaw); //Y board_->setInputChannel(2, rc_data.throttle); //F board_->setInputChannel(3, -rc_data.pitch); //Z board_->setInputChannel(4, static_cast<float>(rc_data.getSwitch(0))); //angle rate or level board_->setInputChannel(5, static_cast<float>(rc_data.getSwitch(1))); //Allow API control board_->setInputChannel(6, static_cast<float>(rc_data.getSwitch(2))); board_->setInputChannel(7, static_cast<float>(rc_data.getSwitch(3))); board_->setInputChannel(8, static_cast<float>(rc_data.getSwitch(4))); board_->setInputChannel(9, static_cast<float>(rc_data.getSwitch(5))); board_->setInputChannel(10, static_cast<float>(rc_data.getSwitch(6))); board_->setInputChannel(11, static_cast<float>(rc_data.getSwitch(7))); } else { //else we don't have RC data board_->setIsRcConnected(false); } return true; } protected: virtual Kinematics::State getKinematicsEstimated() const override { return AirSimSimpleFlightCommon::toKinematicsState3r(firmware_->offboardApi().getStateEstimator().getKinematicsEstimated()); } virtual Vector3r getPosition() const override { const auto& val = firmware_->offboardApi().getStateEstimator().getPosition(); return AirSimSimpleFlightCommon::toVector3r(val); } virtual Vector3r getVelocity() const override { const auto& val = firmware_->offboardApi().getStateEstimator().getLinearVelocity(); return AirSimSimpleFlightCommon::toVector3r(val); } virtual Quaternionr getOrientation() const override { const auto& val = firmware_->offboardApi().getStateEstimator().getOrientation(); return AirSimSimpleFlightCommon::toQuaternion(val); } virtual LandedState getLandedState() const override { return firmware_->offboardApi().getLandedState() ? LandedState::Landed : LandedState::Flying; } virtual RCData getRCData() const override { //return what we received last time through setRCData return last_rcData_; } virtual GeoPoint getGpsLocation() const override { return AirSimSimpleFlightCommon::toGeoPoint(firmware_->offboardApi().getGeoPoint()); } virtual float getCommandPeriod() const override { return 1.0f / 50; //50hz } virtual float getTakeoffZ() const override { // pick a number, 3 meters is probably safe // enough to get out of the backwash turbulence. Negative due to NED coordinate system. return params_.takeoff.takeoff_z; } virtual float getDistanceAccuracy() const override { return 0.5f; //measured in simulator by firing commands "MoveToLocation -x 0 -y 0" multiple times and looking at distance traveled } virtual void commandMotorPWMs(float front_right_pwm, float rear_left_pwm, float front_left_pwm, float rear_right_pwm) override { //Utils::log(Utils::stringf("commandMotorPWMs %f, %f, %f, %f", front_right_pwm, rear_left_pwm, front_left_pwm, rear_right_pwm)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::Passthrough, GoalModeType::Passthrough, GoalModeType::Passthrough, GoalModeType::Passthrough); simple_flight::Axis4r goal(front_right_pwm, rear_left_pwm, front_left_pwm, rear_right_pwm); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandRollPitchYawZ(float roll, float pitch, float yaw, float z) override { //Utils::log(Utils::stringf("commandRollPitchYawZ %f, %f, %f, %f", pitch, roll, z, yaw)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::AngleLevel, GoalModeType::AngleLevel, GoalModeType::AngleLevel, GoalModeType::PositionWorld); simple_flight::Axis4r goal(roll, pitch, yaw, z); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandRollPitchYawThrottle(float roll, float pitch, float yaw, float throttle) override { //Utils::log(Utils::stringf("commandRollPitchYawThrottle %f, %f, %f, %f", roll, pitch, yaw, throttle)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::AngleLevel, GoalModeType::AngleLevel, GoalModeType::AngleLevel, GoalModeType::Passthrough); simple_flight::Axis4r goal(roll, pitch, yaw, throttle); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandRollPitchYawrateThrottle(float roll, float pitch, float yaw_rate, float throttle) override { //Utils::log(Utils::stringf("commandRollPitchYawThrottle %f, %f, %f, %f", roll, pitch, yaw, throttle)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::AngleLevel, GoalModeType::AngleLevel, GoalModeType::AngleRate, GoalModeType::Passthrough); simple_flight::Axis4r goal(roll, pitch, yaw_rate, throttle); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandRollPitchYawrateZ(float roll, float pitch, float yaw_rate, float z) override { //Utils::log(Utils::stringf("commandRollPitchYawThrottle %f, %f, %f, %f", roll, pitch, yaw_rate, throttle)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::AngleLevel, GoalModeType::AngleLevel, GoalModeType::AngleRate, GoalModeType::PositionWorld); simple_flight::Axis4r goal(roll, pitch, yaw_rate, z); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandAngleRatesZ(float roll_rate, float pitch_rate, float yaw_rate, float z) override { //Utils::log(Utils::stringf("commandRollPitchYawThrottle %f, %f, %f, %f", roll, pitch, yaw_rate, throttle)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::AngleRate, GoalModeType::AngleRate, GoalModeType::AngleRate, GoalModeType::PositionWorld); simple_flight::Axis4r goal(roll_rate, pitch_rate, yaw_rate, z); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandAngleRatesThrottle(float roll_rate, float pitch_rate, float yaw_rate, float throttle) override { //Utils::log(Utils::stringf("commandRollPitchYawThrottle %f, %f, %f, %f", roll, pitch, yaw_rate, throttle)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::AngleRate, GoalModeType::AngleRate, GoalModeType::AngleRate, GoalModeType::Passthrough); simple_flight::Axis4r goal(roll_rate, pitch_rate, yaw_rate, throttle); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandVelocity(float vx, float vy, float vz, const YawMode& yaw_mode) override { //Utils::log(Utils::stringf("commandVelocity %f, %f, %f, %f", vx, vy, vz, yaw_mode.yaw_or_rate)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::VelocityWorld, GoalModeType::VelocityWorld, yaw_mode.is_rate ? GoalModeType::AngleRate : GoalModeType::AngleLevel, GoalModeType::VelocityWorld); simple_flight::Axis4r goal(vy, vx, Utils::degreesToRadians(yaw_mode.yaw_or_rate), vz); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void commandVelocityZ(float vx, float vy, float z, const YawMode& yaw_mode) override { //Utils::log(Utils::stringf("commandVelocityZ %f, %f, %f, %f", vx, vy, z, yaw_mode.yaw_or_rate)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::VelocityWorld, GoalModeType::VelocityWorld, yaw_mode.is_rate ? GoalModeType::AngleRate : GoalModeType::AngleLevel, GoalModeType::PositionWorld); simple_flight::Axis4r goal(vy, vx, Utils::degreesToRadians(yaw_mode.yaw_or_rate), z); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual void setControllerGains(uint8_t controller_type, const vector<float>& kp, const vector<float>& ki, const vector<float>& kd) override { simple_flight::GoalModeType controller_type_enum = static_cast<simple_flight::GoalModeType>(controller_type); vector<float> kp_axis4(4); vector<float> ki_axis4(4); vector<float> kd_axis4(4); switch (controller_type_enum) { // roll gain, pitch gain, yaw gain, and no gains in throttle / z axis case simple_flight::GoalModeType::AngleRate: kp_axis4 = { kp[0], kp[1], kp[2], 1.0 }; ki_axis4 = { ki[0], ki[1], ki[2], 0.0 }; kd_axis4 = { kd[0], kd[1], kd[2], 0.0 }; params_.angle_rate_pid.p.setValues(kp_axis4); params_.angle_rate_pid.i.setValues(ki_axis4); params_.angle_rate_pid.d.setValues(kd_axis4); params_.gains_changed = true; break; case simple_flight::GoalModeType::AngleLevel: kp_axis4 = { kp[0], kp[1], kp[2], 1.0 }; ki_axis4 = { ki[0], ki[1], ki[2], 0.0 }; kd_axis4 = { kd[0], kd[1], kd[2], 0.0 }; params_.angle_level_pid.p.setValues(kp_axis4); params_.angle_level_pid.i.setValues(ki_axis4); params_.angle_level_pid.d.setValues(kd_axis4); params_.gains_changed = true; break; case simple_flight::GoalModeType::VelocityWorld: kp_axis4 = { kp[1], kp[0], 0.0, kp[2] }; ki_axis4 = { ki[1], ki[0], 0.0, ki[2] }; kd_axis4 = { kd[1], kd[0], 0.0, kd[2] }; params_.velocity_pid.p.setValues(kp_axis4); params_.velocity_pid.i.setValues(ki_axis4); params_.velocity_pid.d.setValues(kd_axis4); params_.gains_changed = true; break; case simple_flight::GoalModeType::PositionWorld: kp_axis4 = { kp[1], kp[0], 0.0, kp[2] }; ki_axis4 = { ki[1], ki[0], 0.0, ki[2] }; kd_axis4 = { kd[1], kd[0], 0.0, kd[2] }; params_.position_pid.p.setValues(kp_axis4); params_.position_pid.i.setValues(ki_axis4); params_.position_pid.d.setValues(kd_axis4); params_.gains_changed = true; break; default: Utils::log("Unimplemented controller type"); break; } } virtual void commandPosition(float x, float y, float z, const YawMode& yaw_mode) override { //Utils::log(Utils::stringf("commandPosition %f, %f, %f, %f", x, y, z, yaw_mode.yaw_or_rate)); typedef simple_flight::GoalModeType GoalModeType; simple_flight::GoalMode mode(GoalModeType::PositionWorld, GoalModeType::PositionWorld, yaw_mode.is_rate ? GoalModeType::AngleRate : GoalModeType::AngleLevel, GoalModeType::PositionWorld); simple_flight::Axis4r goal(y, x, Utils::degreesToRadians(yaw_mode.yaw_or_rate), z); std::string message; firmware_->offboardApi().setGoalAndMode(&goal, &mode, message); } virtual const MultirotorApiParams& getMultirotorApiParams() const override { return safety_params_; } //*** End: MultirotorApiBase implementation ***// private: //convert pitch, roll, yaw from -1 to 1 to PWM static uint16_t angleToPwm(float angle) { return static_cast<uint16_t>(angle * 500.0f + 1500.0f); } static uint16_t thrustToPwm(float thrust) { return static_cast<uint16_t>((thrust < 0 ? 0 : thrust) * 1000.0f + 1000.0f); } static uint16_t switchTopwm(float switchVal, uint maxSwitchVal = 1) { return static_cast<uint16_t>(1000.0f * switchVal / maxSwitchVal + 1000.0f); } void readSettings(const AirSimSettings::VehicleSetting& vehicle_setting) { params_.default_vehicle_state = simple_flight::VehicleState::fromString( vehicle_setting.default_vehicle_state == "" ? "Armed" : vehicle_setting.default_vehicle_state); remote_control_id_ = vehicle_setting.rc.remote_control_id; params_.rc.allow_api_when_disconnected = vehicle_setting.rc.allow_api_when_disconnected; params_.rc.allow_api_always = vehicle_setting.allow_api_always; } private: const MultiRotorParams* vehicle_params_; int remote_control_id_ = 0; simple_flight::Params params_; unique_ptr<AirSimSimpleFlightBoard> board_; unique_ptr<AirSimSimpleFlightCommLink> comm_link_; unique_ptr<AirSimSimpleFlightEstimator> estimator_; unique_ptr<simple_flight::IFirmware> firmware_; MultirotorApiParams safety_params_; RCData last_rcData_; }; } } //namespace #endif
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/SimpleFlightApi.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/SimpleFlightApi.hpp", "repo_id": "AirSim", "token_count": 8392 }
12
#pragma once #include "interfaces/CommonStructs.hpp" namespace simple_flight { template <typename T> class StdPidIntegrator : public IPidIntegrator<T> { public: StdPidIntegrator(const PidConfig<T>& config) : config_(config) { } virtual ~StdPidIntegrator() {} virtual void reset() override { iterm_int_ = T(); } virtual void set(T val) override { iterm_int_ = val; clipIterm(); } virtual void update(float dt, T error, uint64_t last_time) override { unused(last_time); //to supoort changes in ki at runtime, we accumulate iterm //instead of error iterm_int_ = iterm_int_ * config_.iterm_discount + dt * error * config_.ki; //don't let iterm grow beyond limits (integral windup) clipIterm(); } virtual T getOutput() override { return iterm_int_; } private: void clipIterm() { iterm_int_ = clip(iterm_int_, config_.min_output, config_.max_output); } //TODO: replace with std::clamp after moving to C++17 static T clip(T val, T min_value, T max_value) { return std::max(min_value, std::min(val, max_value)); } private: float iterm_int_; const PidConfig<T> config_; }; } //namespace
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/StdPidIntegrator.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/StdPidIntegrator.hpp", "repo_id": "AirSim", "token_count": 566 }
13
#pragma once namespace simple_flight { class IUpdatable { public: virtual void reset() { if (reset_called && !update_called) throw std::runtime_error("Multiple reset() calls detected without call to update()"); reset_called = true; } virtual void update() { if (!reset_called) throw std::runtime_error("reset() must be called first before update()"); update_called = true; } virtual ~IUpdatable() = default; protected: void clearResetUpdateAsserts() { reset_called = false; update_called = false; } private: bool reset_called = false; bool update_called = false; }; }
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IUpdatable.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IUpdatable.hpp", "repo_id": "AirSim", "token_count": 281 }
14
#ifndef msr_AirLibUnitTests_QuaternionTest_hpp #define msr_AirLibUnitTests_QuaternionTest_hpp #include "TestBase.hpp" #include "common/Common.hpp" namespace msr { namespace airlib { class QuaternionTest : public TestBase { public: virtual void run() override { //eulerAngleTest(); //lookAtTest(); rotationOrderTest(); } private: void rotationOrderTest() { Quaternionr q1 = VectorMath::toQuaternion(0, 0, Utils::degreesToRadians(90.0f)); Quaternionr q2 = VectorMath::toQuaternion(Utils::degreesToRadians(90.0f), 0, 0); Quaternionr q12 = q1 * q2; Quaternionr q21 = q2 * q1; float pitch, roll, yaw; VectorMath::toEulerianAngle(q12, pitch, roll, yaw); VectorMath::toEulerianAngle(q21, pitch, roll, yaw); } void worldBodyTransformTest() { //vehicle wrt to world Quaternionr vehicle_world_q = VectorMath::toQuaternion(0, 0, Utils::degreesToRadians(45.0f)); //lidar wrt to vehicle Quaternionr lidar_vehicle_q = VectorMath::toQuaternion(0, 0, Utils::degreesToRadians(10.0f)); //lidar wrt to world Quaternionr lidar_world_q = VectorMath::rotateQuaternion(lidar_vehicle_q, vehicle_world_q, false); float pitch, roll, yaw; VectorMath::toEulerianAngle(vehicle_world_q, pitch, roll, yaw); VectorMath::toEulerianAngle(lidar_world_q, pitch, roll, yaw); Utils::log(Utils::stringf("%f", Utils::radiansToDegrees(yaw))); } Quaternionr lookAt(Vector3r sourcePoint, Vector3r destPoint) { Vector3r toVector = (destPoint - sourcePoint).normalized(); Vector3r rotAxis = VectorMath::front().cross(toVector).normalized(); if (rotAxis.squaredNorm() == 0) rotAxis = VectorMath::up(); float dot = VectorMath::front().dot(toVector); float ang = std::acos(dot); return VectorMath::toQuaternion(rotAxis, ang); } Quaternionr toQuaternion(const Vector3r& axis, float angle) { auto s = std::sin(angle / 2.0f); auto u = axis.normalized(); return Quaternionr(std::cos(angle / 2.0f), u.x() * s, u.y() * s, u.z() * s); } void lookAtTest() { auto q = lookAt(Vector3r::Zero(), Vector3r(-1.f, 0, 0)); std::cout << VectorMath::toString(q) << std::endl; float pitch, roll, yaw; VectorMath::toEulerianAngle(q, pitch, roll, yaw); std::cout << pitch << "\t" << roll << "\t" << yaw << "\t" << std::endl; //q = VectorMath::toQuaternion(0, 0, Utils::degreesToRadians(180.0f)); //std::cout << VectorMath::toString(q) << std::endl; //VectorMath::toEulerianAngle(q, pitch, roll, yaw); //std::cout << pitch << "\t" << roll << "\t" << yaw << "\t" << std::endl; } void eulerAngleTest() { RandomGeneratorR r(-1000.0f, 1000.0f); RandomGeneratorR rw(-1000.0f, 1000.0f); for (auto i = 0; i < 1000; ++i) { Quaternionr q(rw.next(), r.next(), r.next(), r.next()); q.normalize(); float pitch, roll, yaw; VectorMath::toEulerianAngle(q, pitch, roll, yaw); Quaternionr qd = VectorMath::toQuaternion(pitch, roll, yaw); if (std::signbit(qd.w()) != std::signbit(q.w())) { qd.coeffs() = -qd.coeffs(); } auto dw = std::abs(qd.w() - q.w()); auto dx = std::abs(qd.z() - q.z()); auto dy = std::abs(qd.y() - q.y()); auto dz = std::abs(qd.z() - q.z()); testAssert(dw + dx + dy + dz < 1E-5, "quaternion transformations are not symmetric"); } } }; } } #endif
AirSim/AirLibUnitTests/QuaternionTest.hpp/0
{ "file_path": "AirSim/AirLibUnitTests/QuaternionTest.hpp", "repo_id": "AirSim", "token_count": 2093 }
15
{ "SeeDocsAt": "https://github.com/Microsoft/AirSim/blob/main/docs/settings.md", "SettingsVersion": 1.2, "SimMode": "ComputerVision", "CameraDefaults": { "CaptureSettings": [ { "ImageType": 0, "TargetGamma": 1.5, "Width": 256, "Height": 144, "FOV_Degrees": 90 }, { "ImageType": 1, "Width": 256, "Height": 144, "FOV_Degrees": 90 }, { "ImageType": 4, "Width": 256, "Height": 144, "FOV_Degrees": 90 } ] }, "SubWindows": [ {"WindowID": 0, "CameraID": 1, "ImageType": 0, "Visible": true}, {"WindowID": 1, "CameraID": 2, "ImageType": 0, "Visible": true}, {"WindowID": 2, "CameraID": 2, "ImageType": 3, "Visible": true} ], "Recording": { "RecordOnMove": true, "RecordInterval": 1, "Cameras": [ { "CameraID": 1, "ImageType": 0, "PixelsAsFloat": false, "Compress": true }, { "CameraID": 2, "ImageType": 0, "PixelsAsFloat": false, "Compress": true }, { "CameraID": 2, "ImageType": 3, "PixelsAsFloat": false, "Compress": false } ] } }
AirSim/Examples/DepthNav/DepthNav_settings.json/0
{ "file_path": "AirSim/Examples/DepthNav/DepthNav_settings.json", "repo_id": "AirSim", "token_count": 510 }
16
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="RelWithDebInfo|Win32"> <Configuration>RelWithDebInfo</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="RelWithDebInfo|x64"> <Configuration>RelWithDebInfo</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <ItemGroup> <ProjectReference Include="..\AirLib\AirLib.vcxproj"> <Project>{4bfb7231-077a-4671-bd21-d3ade3ea36e7}</Project> </ProjectReference> <ProjectReference Include="..\MavLinkCom\MavLinkCom.vcxproj"> <Project>{8510c7a4-bf63-41d2-94f6-d8731d137a5a}</Project> </ProjectReference> </ItemGroup> <PropertyGroup Label="Globals"> <VCProjectVersion>15.0</VCProjectVersion> <ProjectGuid>{99CBF376-5EBA-4164-A657-E7D708C9D685}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>HelloSpawnedDrones</RootNamespace> <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="Shared"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>true</LinkIncremental> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'"> <LinkIncremental>false</LinkIncremental> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;AirLib.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'"> <ClCompile> <PrecompiledHeader>Use</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> <WholeProgramOptimization>false</WholeProgramOptimization> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;AirLib.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> <WholeProgramOptimization>false</WholeProgramOptimization> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;AirLib.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="HelloSpawnedDrones.cpp" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
AirSim/HelloSpawnedDrones/HelloSpawnedDrones.vcxproj/0
{ "file_path": "AirSim/HelloSpawnedDrones/HelloSpawnedDrones.vcxproj", "repo_id": "AirSim", "token_count": 5006 }
17
<c:CustomizableButton x:Class="LogViewer.Controls.CloseBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:LogViewer.Controls" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" Background="{DynamicResource CloseBoxNormalBackground}" Foreground="{DynamicResource CloseBoxNormalForeground}" MousePressedBackground="{DynamicResource CloseBoxMousePressedBackground}" MousePressedForeground="{DynamicResource CloseBoxMousePressedForeground}" MouseOverBackground="{DynamicResource CloseBoxMouseOverBackground}" MouseOverForeground="{DynamicResource CloseBoxMouseOverForeground}" mc:Ignorable="d" Width="16" Height="16" d:DesignHeight="16" d:DesignWidth="16"> <Button.Template> <ControlTemplate TargetType="{x:Type c:CloseBox}"> <Grid Opacity="{TemplateBinding Opacity}" > <Ellipse x:Name="Ellipse" HorizontalAlignment="Left" Height="{TemplateBinding Width}" Width="{TemplateBinding Height}" VerticalAlignment="Top" Fill="{TemplateBinding Background}" Stroke="{TemplateBinding Foreground}" StrokeThickness="{TemplateBinding BorderThickness}"> </Ellipse> <Path x:Name="CrossShape" Data="M0,0 L6,6 M3,0 L 0,6" StrokeThickness="1.5" StrokeEndLineCap="Round" StrokeStartLineCap="Round" Stroke="{TemplateBinding Foreground}"/> </Grid> <!--<ControlTemplate.Triggers> <DataTrigger Binding="{Binding IsMouseOver}"> <Setter TargetName="Ellipse" Property="Fill" Value="{TemplateBinding MouseOverBackground}"/> <Setter TargetName="CrossShape" Property="Stroke" Value="{TemplateBinding MouseOverForeground}"/> </DataTrigger> <DataTrigger Binding="{Binding IsPressed}"> <Setter TargetName="Ellipse" Property="Fill" Value="{TemplateBinding MousePressedBackground}"/> <Setter TargetName="CrossShape" Property="Stroke" Value="{TemplateBinding MousePressedForeground}"/> </DataTrigger> </ControlTemplate.Triggers>--> </ControlTemplate> </Button.Template> </c:CustomizableButton>
AirSim/LogViewer/LogViewer/Controls/CloseBox.xaml/0
{ "file_path": "AirSim/LogViewer/LogViewer/Controls/CloseBox.xaml", "repo_id": "AirSim", "token_count": 1121 }
18
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Windows; using System.Windows.Input; using System.Windows.Media.Media3D; using System.Windows.Threading; namespace LogViewer.Gestures { class RotateGesture3D : IMouseGesture { bool m_tracking; Point m_start; FrameworkElement container; double m_XRotation; double m_YRotation; double m_PreviousXRotation; double m_degreesXVelocity; double m_degreesXAcceleration; double m_PreviousYRotation; double m_degreesYVelocity; double m_degreesYAcceleration; double m_Zoom; Quaternion m_StartRotation; DispatcherTimer flickTimer; double breakingAcceleration; public RotateGesture3D(FrameworkElement container) { this.container = container; container.MouseLeftButtonDown += OnMouseLeftButtonDown; container.MouseLeftButtonUp += OnMouseLeftButtonUp; container.MouseMove += OnMouseMove; container.MouseWheel += OnMouseWheel; container.LostMouseCapture += OnLostMouseCapture; Sensitivity = 100; BrakingAcceleration = 0.05; MinFlickThreshold = 5.0; } public event EventHandler Changed; private void OnChanged() { // movement in the Y dimension is interpretted as rotation about the horizontal axis RotateTransform3D startTransform = new RotateTransform3D(new QuaternionRotation3D(m_StartRotation)); Quaternion yRotation = new Quaternion(startTransform.Inverse.Transform(new Point3D(1, 0, 0)).ToVector3D(), this.m_YRotation); RotateTransform3D yTransform = new RotateTransform3D(new QuaternionRotation3D(yRotation)); // movement in the X dimension is interpretted as rotation about the vertical axis. var xAxis = yTransform.Transform(new Point3D(0, 0, 1)).ToVector3D(); Quaternion xRotation = new Quaternion(xAxis, this.m_XRotation); this.Rotation = m_StartRotation * (xRotation * yRotation); if (Changed != null) { Changed(this, EventArgs.Empty); } } /// <summary> /// This is the rotation being applied by the user. /// </summary> public Quaternion Rotation { get; set; } public double Zoom { get { return m_Zoom; } set { m_Zoom = value; } } private void OnMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e) { int clicks = e.Delta; if (clicks > 0) { m_Zoom--; } else { m_Zoom++; } OnChanged(); } const double XM_PI = 3.141592654f; const double XM_2PI = 6.283185307f; public double Sensitivity { get; set; } public double BrakingAcceleration { get { return breakingAcceleration; } set { breakingAcceleration = Math.Min(Math.Max(value,0),1); } } public double MinFlickThreshold { get; set; } private void OnMouseMove(object sender, System.Windows.Input.MouseEventArgs e) { if (m_tracking) { // Rotation about the mouse down position. Point position = e.GetPosition(container); // XRotation is rotation about the Y axis. double delta = (position.X - m_start.X) / Sensitivity; m_XRotation = (XM_2PI * 2.0f * delta); if (m_PreviousXRotation != 0) { m_degreesXVelocity = m_XRotation - m_PreviousXRotation; if (Math.Abs(m_degreesXVelocity) > 0.1) { m_degreesXVelocity *= 30; } else { // allow minimal wiggle with no acceleration. m_degreesXVelocity = 0; } // put the brakes on so movement slows down (like a flick gesture). m_degreesXAcceleration = -(m_degreesXVelocity * BrakingAcceleration); } m_PreviousXRotation = m_XRotation; // y-rotation is rotation about the X axis. delta = (position.Y - m_start.Y) / Sensitivity; m_YRotation = (XM_2PI * 2.0f * delta); if (m_PreviousYRotation != 0) { m_degreesYVelocity = m_YRotation - m_PreviousYRotation; if (Math.Abs(m_degreesYVelocity) > 0.1) { m_degreesYVelocity *= 30; } else { // allow minimal wiggle with no acceleration. m_degreesYVelocity = 0; } // put the brakes on so movement slows down (like a flick gesture). m_degreesYAcceleration = -(m_degreesYVelocity * BrakingAcceleration); } m_PreviousYRotation = m_YRotation; OnChanged(); } } private void OnMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { m_tracking = false; StartTimer(); if (captured) { this.container.ReleaseMouseCapture(); captured = false; } } private void OnLostMouseCapture(object sender, System.Windows.Input.MouseEventArgs e) { m_tracking = false; StartTimer(); captured = false; } private void StartTimer() { StopTimer(); DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(30); // 30 FPS is ok timer.Tick += OnTick; timer.Start(); flickTimer = timer; } private void StopTimer() { DispatcherTimer timer = this.flickTimer; this.flickTimer = null; if (timer != null) { timer.Stop(); timer.Tick -= OnTick; } } private void OnTick(object sender, EventArgs e) { Update(); } private void OnMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { // different gesture then. return; } StopTimer(); m_tracking = true; m_YRotation = 0; m_XRotation = 0; m_PreviousXRotation = 0; m_PreviousYRotation = 0; m_start = e.GetPosition(container); m_StartRotation = this.Rotation; this.captured = this.container.CaptureMouse(); } bool captured; private void Update() { if (!m_tracking) { // Apply the brakes on the XRotation (about the Y Axis) double degreesPerSecond = m_degreesXVelocity / 30; // 30fps m_XRotation = (m_XRotation + degreesPerSecond) % 360; m_degreesXVelocity += m_degreesXAcceleration; if (m_degreesXAcceleration <= 0 && m_degreesXVelocity <= 0) { m_degreesXVelocity = 0; m_degreesXAcceleration *= 0.9f; } else if (m_degreesXAcceleration >= 0 && m_degreesXVelocity >= 0) { m_degreesXVelocity = 0; m_degreesXAcceleration *= 0.9f; } // Apply the brakes on the YRotation (about the X Axis) degreesPerSecond = m_degreesYVelocity / 30; // 30fps m_YRotation = (m_YRotation + degreesPerSecond) % 360; m_degreesYVelocity += m_degreesYAcceleration; if (m_degreesYAcceleration <= 0 && m_degreesYVelocity <= 0) { m_degreesYVelocity = 0; m_degreesYAcceleration *= 0.9f; } else if (m_degreesYAcceleration >= 0 && m_degreesYVelocity >= 0) { m_degreesYVelocity = 0; m_degreesYAcceleration *= 0.9f; } OnChanged(); if (m_degreesYVelocity == 0 && m_degreesXVelocity == 0) { StopTimer(); } } } } }
AirSim/LogViewer/LogViewer/Gestures/RotateGesture3D.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Gestures/RotateGesture3D.cs", "repo_id": "AirSim", "token_count": 4834 }
19
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; namespace LogViewer.Utilities { public static class XamlExtensions { public static void Flyout(this FrameworkElement e) { e.Visibility = Visibility.Visible; e.UpdateLayout(); double width = e.ActualWidth; TranslateTransform transform = new TranslateTransform(width, 0); e.RenderTransform = transform; transform.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(0, new Duration(TimeSpan.FromSeconds(0.2))) { EasingFunction = new ExponentialEase() { EasingMode = EasingMode.EaseOut } }); } public static T FindAncestorOfType<T>(this DependencyObject d) where T : DependencyObject { while (!(d is T) && d != null) { d = VisualTreeHelper.GetParent(d); } return (T)d; } public static IEnumerable<T> FindDescendantsOfType<T>(this DependencyObject d) where T : DependencyObject { List<T> result = new List<T>(); CollectDescendantsOfType(d, result); return result; } private static void CollectDescendantsOfType<T>(DependencyObject d, List<T> result) where T : DependencyObject { if (typeof(T).IsAssignableFrom(d.GetType())) { result.Add((T)d); } bool content = (d is ContentElement); if (content || d is FrameworkElement) { //use the logical tree for content / framework elements foreach (object obj in LogicalTreeHelper.GetChildren(d)) { var child = obj as DependencyObject; if (child != null) { CollectDescendantsOfType(child, result); } } } if (!content) { //use the visual tree per default int count = VisualTreeHelper.GetChildrenCount(d); for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(d, i); CollectDescendantsOfType(child, result); } } } public static BitmapFrame LoadImage(string filePath) { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { return LoadImage(fs); } } public static BitmapFrame LoadImage(Stream stream) { // Load it into memory first so we stop the BitmapDecoder from locking the file. MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[16000]; int len = stream.Read(buffer, 0, buffer.Length); while (len > 0) { ms.Write(buffer, 0, len); len = stream.Read(buffer, 0, buffer.Length); } ms.Seek(0, SeekOrigin.Begin); BitmapDecoder decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None); BitmapFrame frame = decoder.Frames[0]; return frame; } public static BitmapFrame LoadImageResource(string resourceName) { using (Stream s = typeof(XamlExtensions).Assembly.GetManifestResourceStream("LogViewer." + resourceName)) { return LoadImage(s); } } [DllImport("GDI32.dll")] private static extern int GetDeviceCaps(HandleRef hDC, int nIndex); [DllImport("User32.dll")] private static extern IntPtr GetDC(HandleRef hWnd); [DllImport("User32.dll")] private static extern int ReleaseDC(HandleRef hWnd, HandleRef hDC); private static int _dpi = 0; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806")] private static int DPI { get { if (_dpi == 0) { HandleRef desktopHwnd = new HandleRef(null, IntPtr.Zero); HandleRef desktopDC = new HandleRef(null, GetDC(desktopHwnd)); _dpi = GetDeviceCaps(desktopDC, 88 /*LOGPIXELSX*/); ReleaseDC(desktopHwnd, desktopDC); } return _dpi; } } internal static double ConvertToDeviceIndependentPixels(int pixels) { return (double)pixels * 96 / (double)DPI; } internal static int ConvertFromDeviceIndependentPixels(double pixels) { return (int)(pixels * (double)DPI / 96); } } }
AirSim/LogViewer/LogViewer/Utilities/XamlExtensions.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Utilities/XamlExtensions.cs", "repo_id": "AirSim", "token_count": 2528 }
20
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{7F5D2A5F-60CC-4C88-8D43-B8B1573D6398}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MavLinkComGenerator</RootNamespace> <AssemblyName>MavLinkComGenerator</AssemblyName> <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Data" /> <Reference Include="System.Net.Http" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="MavLinkGenerator.cs" /> <Compile Include="MavLinkMessage.cs" /> <Compile Include="MavlinkParser.cs" /> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
AirSim/MavLinkCom/MavLinkComGenerator/MavLinkComGenerator.csproj/0
{ "file_path": "AirSim/MavLinkCom/MavLinkComGenerator/MavLinkComGenerator.csproj", "repo_id": "AirSim", "token_count": 981 }
21
#pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include <SDKDDKVer.h>
AirSim/MavLinkCom/MavLinkMoCap/targetver.h/0
{ "file_path": "AirSim/MavLinkCom/MavLinkMoCap/targetver.h", "repo_id": "AirSim", "token_count": 87 }
22
// in header only mode, control library is not available #ifndef AIRLIB_HEADER_ONLY //if using Unreal Build system then include precompiled header file first #ifdef AIRLIB_PCH #include "AirSim.h" #endif #include "FileSystem.hpp" #include <codecvt> #include <fstream> #ifdef _WIN32 #include <Shlobj.h> #include <direct.h> #include <stdlib.h> #include <direct.h> #else #include <unistd.h> #include <sys/param.h> // MAXPATHLEN definition #include <sys/stat.h> // get mkdir, stat #endif using namespace mavlink_utils; // File names are unicode (std::wstring), because users can create folders containing unicode characters on both // Windows, OSX and Linux. std::string FileSystem::createDirectory(std::string fullPath) { #ifdef _WIN32 #ifndef ONECORE std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(fullPath); int hr = CreateDirectory(wide_path.c_str(), NULL); if (hr == 0) { hr = GetLastError(); if (hr != ERROR_ALREADY_EXISTS) { throw std::invalid_argument(Utils::stringf("Error creating directory, hr=%d", hr)); } } #endif #else mkdir(fullPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif return fullPath; } void FileSystem::remove(std::string fileName) { #ifdef _WIN32 // WIN32 will create the wrong file names if we don't first convert them to UTF-16. std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(fileName); if (!DeleteFile(wide_path.c_str())) { int hr = GetLastError(); if (hr != ERROR_FILE_NOT_FOUND) { throw std::runtime_error(Utils::stringf("Failed to delete file '%s', error=%d.", fileName.c_str(), hr)); } } #else int hr = unlink(fileName.c_str()); if (hr != 0) { hr = errno; if (hr != ENOENT) { throw std::runtime_error(Utils::stringf("Failed to delete file '%s', error=%d.", fileName.c_str(), hr)); } } #endif } std::string FileSystem::getUserDocumentsFolder() { #ifdef _WIN32 #ifndef ONECORE // Windows users can move the Documents folder to any location they want // SHGetFolderPath knows how to find it. wchar_t szPath[MAX_PATH]; if (0 == SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS | CSIDL_FLAG_CREATE, NULL, 0, szPath)) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; return converter.to_bytes(szPath); } #endif // fall back in case SHGetFolderPath failed for some reason. #endif return combine(getUserHomeFolder(), "Documents"); } std::string FileSystem::getFullPath(const std::string fileName) { #ifdef _WIN32 std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(fileName); // convert from std::path '/' to windows backslash. size_t length = wide_path.size(); for (size_t i = 0; i < length; i++) { if (wide_path[i] == '/') { wide_path[i] = kPathSeparator; } } wchar_t szPath[MAX_PATH]; int len = GetFullPathName(wide_path.c_str(), MAX_PATH, szPath, NULL); if (len == 0) { int hr = GetLastError(); throw std::runtime_error(Utils::stringf("getFullPath of '%s' failed with error=%d.", fileName.c_str(), hr)); } szPath[len] = '\0'; return converter.to_bytes(szPath); #else char buf[PATH_MAX]; char* cwd = getcwd(buf, PATH_MAX); std::string path = cwd; size_t size = fileName.size(); if (size == 0) { return path; } if (fileName[0] == kPathSeparator) { return fileName; } return resolve(path, fileName); #endif } bool FileSystem::isDirectory(const std::string path) { #ifdef _WIN32 std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(path); unsigned long attrib = GetFileAttributes(wide_path.c_str()); return (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY)); #else struct stat buf; int rc = ::stat(path.c_str(), &buf); return rc == 0 && S_ISDIR(buf.st_mode); #endif } bool FileSystem::exists(const std::string path) { #ifdef _WIN32 std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(path); unsigned long attrib = GetFileAttributes(wide_path.c_str()); return (attrib != INVALID_FILE_ATTRIBUTES); #else struct stat buf; int rc = ::stat(path.c_str(), &buf); return rc == 0; #endif } #endif
AirSim/MavLinkCom/common_utils/FileSystem.cpp/0
{ "file_path": "AirSim/MavLinkCom/common_utils/FileSystem.cpp", "repo_id": "AirSim", "token_count": 2011 }
23
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef MavLinkCom_MavLinkLog_hpp #define MavLinkCom_MavLinkLog_hpp #include <string> #include <stdio.h> #include <cstdint> #include <mutex> #include "MavLinkMessageBase.hpp" #define MAVLINK_STX_MAVLINK1 0xFE // marker for old protocol namespace mavlinkcom { // This abstract class defines the interface for logging MavLinkMessages. class MavLinkLog { public: virtual void write(const mavlinkcom::MavLinkMessage& msg, uint64_t timestamp = 0) = 0; virtual ~MavLinkLog() = default; }; // This implementation of MavLinkLog reads/writes MavLinkMessages to a local file. class MavLinkFileLog : public MavLinkLog { std::string file_name_; FILE* ptr_; bool reading_; bool writing_; bool json_; std::mutex log_lock_; public: MavLinkFileLog(); virtual ~MavLinkFileLog(); bool isOpen(); void openForReading(const std::string& filename); void openForWriting(const std::string& filename, bool json = false); void close(); virtual void write(const mavlinkcom::MavLinkMessage& msg, uint64_t timestamp = 0) override; bool read(mavlinkcom::MavLinkMessage& msg, uint64_t& timestamp); static uint64_t getTimeStamp(); }; } #endif
AirSim/MavLinkCom/include/MavLinkLog.hpp/0
{ "file_path": "AirSim/MavLinkCom/include/MavLinkLog.hpp", "repo_id": "AirSim", "token_count": 460 }
24
#pragma once // clang-format off #include "string.h" #include "checksum.h" #include "mavlink_types.h" #include "mavlink_conversions.h" #include <stdio.h> #ifndef MAVLINK_HELPER #define MAVLINK_HELPER #endif #include "mavlink_sha256.h" #ifdef MAVLINK_USE_CXX_NAMESPACE namespace mavlink { #endif /* * Internal function to give access to the channel status for each channel */ #ifndef MAVLINK_GET_CHANNEL_STATUS MAVLINK_HELPER mavlink_status_t* mavlink_get_channel_status(uint8_t chan) { #ifdef MAVLINK_EXTERNAL_RX_STATUS // No m_mavlink_status array defined in function, // has to be defined externally #else static mavlink_status_t m_mavlink_status[MAVLINK_COMM_NUM_BUFFERS]; #endif return &m_mavlink_status[chan]; } #endif /* * Internal function to give access to the channel buffer for each channel */ #ifndef MAVLINK_GET_CHANNEL_BUFFER MAVLINK_HELPER mavlink_message_t* mavlink_get_channel_buffer(uint8_t chan) { #ifdef MAVLINK_EXTERNAL_RX_BUFFER // No m_mavlink_buffer array defined in function, // has to be defined externally #else static mavlink_message_t m_mavlink_buffer[MAVLINK_COMM_NUM_BUFFERS]; #endif return &m_mavlink_buffer[chan]; } #endif // MAVLINK_GET_CHANNEL_BUFFER /* Enable this option to check the length of each message. This allows invalid messages to be caught much sooner. Use if the transmission medium is prone to missing (or extra) characters (e.g. a radio that fades in and out). Only use if the channel will only contain messages types listed in the headers. */ //#define MAVLINK_CHECK_MESSAGE_LENGTH /** * @brief Reset the status of a channel. */ MAVLINK_HELPER void mavlink_reset_channel_status(uint8_t chan) { mavlink_status_t *status = mavlink_get_channel_status(chan); status->parse_state = MAVLINK_PARSE_STATE_IDLE; } /** * @brief create a signature block for a packet */ MAVLINK_HELPER uint8_t mavlink_sign_packet(mavlink_signing_t *signing, uint8_t signature[MAVLINK_SIGNATURE_BLOCK_LEN], const uint8_t *header, uint8_t header_len, const uint8_t *packet, uint8_t packet_len, const uint8_t crc[2]) { mavlink_sha256_ctx ctx; union { uint64_t t64; uint8_t t8[8]; } tstamp; if (signing == NULL || !(signing->flags & MAVLINK_SIGNING_FLAG_SIGN_OUTGOING)) { return 0; } signature[0] = signing->link_id; tstamp.t64 = signing->timestamp; memcpy(&signature[1], tstamp.t8, 6); signing->timestamp++; mavlink_sha256_init(&ctx); mavlink_sha256_update(&ctx, signing->secret_key, sizeof(signing->secret_key)); mavlink_sha256_update(&ctx, header, header_len); mavlink_sha256_update(&ctx, packet, packet_len); mavlink_sha256_update(&ctx, crc, 2); mavlink_sha256_update(&ctx, signature, 7); mavlink_sha256_final_48(&ctx, &signature[7]); return MAVLINK_SIGNATURE_BLOCK_LEN; } /** * @brief Trim payload of any trailing zero-populated bytes (MAVLink 2 only). * * @param payload Serialised payload buffer. * @param length Length of full-width payload buffer. * @return Length of payload after zero-filled bytes are trimmed. */ MAVLINK_HELPER uint8_t _mav_trim_payload(const char *payload, uint8_t length) { while (length > 1 && payload[length-1] == 0) { length--; } return length; } /** * @brief check a signature block for a packet */ MAVLINK_HELPER bool mavlink_signature_check(mavlink_signing_t *signing, mavlink_signing_streams_t *signing_streams, const mavlink_message_t *msg) { if (signing == NULL) { return true; } const uint8_t *p = (const uint8_t *)&msg->magic; const uint8_t *psig = msg->signature; const uint8_t *incoming_signature = psig+7; mavlink_sha256_ctx ctx; uint8_t signature[6]; uint16_t i; mavlink_sha256_init(&ctx); mavlink_sha256_update(&ctx, signing->secret_key, sizeof(signing->secret_key)); mavlink_sha256_update(&ctx, p, MAVLINK_CORE_HEADER_LEN+1+msg->len); mavlink_sha256_update(&ctx, msg->ck, 2); mavlink_sha256_update(&ctx, psig, 1+6); mavlink_sha256_final_48(&ctx, signature); if (memcmp(signature, incoming_signature, 6) != 0) { return false; } // now check timestamp union tstamp { uint64_t t64; uint8_t t8[8]; } tstamp; uint8_t link_id = psig[0]; tstamp.t64 = 0; memcpy(tstamp.t8, psig+1, 6); if (signing_streams == NULL) { return false; } // find stream for (i=0; i<signing_streams->num_signing_streams; i++) { if (msg->sysid == signing_streams->stream[i].sysid && msg->compid == signing_streams->stream[i].compid && link_id == signing_streams->stream[i].link_id) { break; } } if (i == signing_streams->num_signing_streams) { if (signing_streams->num_signing_streams >= MAVLINK_MAX_SIGNING_STREAMS) { // over max number of streams return false; } // new stream. Only accept if timestamp is not more than 1 minute old if (tstamp.t64 + 6000*1000UL < signing->timestamp) { return false; } // add new stream signing_streams->stream[i].sysid = msg->sysid; signing_streams->stream[i].compid = msg->compid; signing_streams->stream[i].link_id = link_id; signing_streams->num_signing_streams++; } else { union tstamp last_tstamp; last_tstamp.t64 = 0; memcpy(last_tstamp.t8, signing_streams->stream[i].timestamp_bytes, 6); if (tstamp.t64 <= last_tstamp.t64) { // repeating old timestamp return false; } } // remember last timestamp memcpy(signing_streams->stream[i].timestamp_bytes, psig+1, 6); // our next timestamp must be at least this timestamp if (tstamp.t64 > signing->timestamp) { signing->timestamp = tstamp.t64; } return true; } /** * @brief Finalize a MAVLink message with channel assignment * * This function calculates the checksum and sets length and aircraft id correctly. * It assumes that the message id and the payload are already correctly set. This function * can also be used if the message header has already been written before (as in mavlink_msg_xxx_pack * instead of mavlink_msg_xxx_pack_headerless), it just introduces little extra overhead. * * @param msg Message to finalize * @param system_id Id of the sending (this) system, 1-127 * @param length Message length */ MAVLINK_HELPER uint16_t mavlink_finalize_message_buffer(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id, mavlink_status_t* status, uint8_t min_length, uint8_t length, uint8_t crc_extra) { bool mavlink1 = (status->flags & MAVLINK_STATUS_FLAG_OUT_MAVLINK1) != 0; bool signing = (!mavlink1) && status->signing && (status->signing->flags & MAVLINK_SIGNING_FLAG_SIGN_OUTGOING); uint8_t signature_len = signing? MAVLINK_SIGNATURE_BLOCK_LEN : 0; uint8_t header_len = MAVLINK_CORE_HEADER_LEN+1; uint8_t buf[MAVLINK_CORE_HEADER_LEN+1]; if (mavlink1) { msg->magic = MAVLINK_STX_MAVLINK1; header_len = MAVLINK_CORE_HEADER_MAVLINK1_LEN+1; } else { msg->magic = MAVLINK_STX; } msg->len = mavlink1?min_length:_mav_trim_payload(_MAV_PAYLOAD(msg), length); msg->sysid = system_id; msg->compid = component_id; msg->incompat_flags = 0; if (signing) { msg->incompat_flags |= MAVLINK_IFLAG_SIGNED; } msg->compat_flags = 0; msg->seq = status->current_tx_seq; status->current_tx_seq = status->current_tx_seq + 1; // form the header as a byte array for the crc buf[0] = msg->magic; buf[1] = msg->len; if (mavlink1) { buf[2] = msg->seq; buf[3] = msg->sysid; buf[4] = msg->compid; buf[5] = msg->msgid & 0xFF; } else { buf[2] = msg->incompat_flags; buf[3] = msg->compat_flags; buf[4] = msg->seq; buf[5] = msg->sysid; buf[6] = msg->compid; buf[7] = msg->msgid & 0xFF; buf[8] = (msg->msgid >> 8) & 0xFF; buf[9] = (msg->msgid >> 16) & 0xFF; } uint16_t checksum = crc_calculate(&buf[1], header_len-1); crc_accumulate_buffer(&checksum, _MAV_PAYLOAD(msg), msg->len); crc_accumulate(crc_extra, &checksum); mavlink_ck_a(msg) = (uint8_t)(checksum & 0xFF); mavlink_ck_b(msg) = (uint8_t)(checksum >> 8); msg->checksum = checksum; if (signing) { mavlink_sign_packet(status->signing, msg->signature, (const uint8_t *)buf, header_len, (const uint8_t *)_MAV_PAYLOAD(msg), msg->len, (const uint8_t *)_MAV_PAYLOAD(msg)+(uint16_t)msg->len); } return msg->len + header_len + 2 + signature_len; } MAVLINK_HELPER uint16_t mavlink_finalize_message_chan(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id, uint8_t chan, uint8_t min_length, uint8_t length, uint8_t crc_extra) { mavlink_status_t *status = mavlink_get_channel_status(chan); return mavlink_finalize_message_buffer(msg, system_id, component_id, status, min_length, length, crc_extra); } /** * @brief Finalize a MAVLink message with MAVLINK_COMM_0 as default channel */ MAVLINK_HELPER uint16_t mavlink_finalize_message(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id, uint8_t min_length, uint8_t length, uint8_t crc_extra) { return mavlink_finalize_message_chan(msg, system_id, component_id, MAVLINK_COMM_0, min_length, length, crc_extra); } static inline void _mav_parse_error(mavlink_status_t *status) { status->parse_error++; } #ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS MAVLINK_HELPER void _mavlink_send_uart(mavlink_channel_t chan, const char *buf, uint16_t len); /** * @brief Finalize a MAVLink message with channel assignment and send */ MAVLINK_HELPER void _mav_finalize_message_chan_send(mavlink_channel_t chan, uint32_t msgid, const char *packet, uint8_t min_length, uint8_t length, uint8_t crc_extra) { uint16_t checksum; uint8_t buf[MAVLINK_NUM_HEADER_BYTES]; uint8_t ck[2]; mavlink_status_t *status = mavlink_get_channel_status(chan); uint8_t header_len = MAVLINK_CORE_HEADER_LEN; uint8_t signature_len = 0; uint8_t signature[MAVLINK_SIGNATURE_BLOCK_LEN]; bool mavlink1 = (status->flags & MAVLINK_STATUS_FLAG_OUT_MAVLINK1) != 0; bool signing = (!mavlink1) && status->signing && (status->signing->flags & MAVLINK_SIGNING_FLAG_SIGN_OUTGOING); if (mavlink1) { length = min_length; if (msgid > 255) { // can't send 16 bit messages _mav_parse_error(status); return; } header_len = MAVLINK_CORE_HEADER_MAVLINK1_LEN; buf[0] = MAVLINK_STX_MAVLINK1; buf[1] = length; buf[2] = status->current_tx_seq; buf[3] = mavlink_system.sysid; buf[4] = mavlink_system.compid; buf[5] = msgid & 0xFF; } else { uint8_t incompat_flags = 0; if (signing) { incompat_flags |= MAVLINK_IFLAG_SIGNED; } length = _mav_trim_payload(packet, length); buf[0] = MAVLINK_STX; buf[1] = length; buf[2] = incompat_flags; buf[3] = 0; // compat_flags buf[4] = status->current_tx_seq; buf[5] = mavlink_system.sysid; buf[6] = mavlink_system.compid; buf[7] = msgid & 0xFF; buf[8] = (msgid >> 8) & 0xFF; buf[9] = (msgid >> 16) & 0xFF; } status->current_tx_seq++; checksum = crc_calculate((const uint8_t*)&buf[1], header_len); crc_accumulate_buffer(&checksum, packet, length); crc_accumulate(crc_extra, &checksum); ck[0] = (uint8_t)(checksum & 0xFF); ck[1] = (uint8_t)(checksum >> 8); if (signing) { // possibly add a signature signature_len = mavlink_sign_packet(status->signing, signature, buf, header_len+1, (const uint8_t *)packet, length, ck); } MAVLINK_START_UART_SEND(chan, header_len + 3 + (uint16_t)length + (uint16_t)signature_len); _mavlink_send_uart(chan, (const char *)buf, header_len+1); _mavlink_send_uart(chan, packet, length); _mavlink_send_uart(chan, (const char *)ck, 2); if (signature_len != 0) { _mavlink_send_uart(chan, (const char *)signature, signature_len); } MAVLINK_END_UART_SEND(chan, header_len + 3 + (uint16_t)length + (uint16_t)signature_len); } /** * @brief re-send a message over a uart channel * this is more stack efficient than re-marshalling the message * If the message is signed then the original signature is also sent */ MAVLINK_HELPER void _mavlink_resend_uart(mavlink_channel_t chan, const mavlink_message_t *msg) { uint8_t ck[2]; ck[0] = (uint8_t)(msg->checksum & 0xFF); ck[1] = (uint8_t)(msg->checksum >> 8); // XXX use the right sequence here uint8_t header_len; uint8_t signature_len; if (msg->magic == MAVLINK_STX_MAVLINK1) { header_len = MAVLINK_CORE_HEADER_MAVLINK1_LEN + 1; signature_len = 0; MAVLINK_START_UART_SEND(chan, header_len + msg->len + 2 + signature_len); // we can't send the structure directly as it has extra mavlink2 elements in it uint8_t buf[MAVLINK_CORE_HEADER_MAVLINK1_LEN + 1]; buf[0] = msg->magic; buf[1] = msg->len; buf[2] = msg->seq; buf[3] = msg->sysid; buf[4] = msg->compid; buf[5] = msg->msgid & 0xFF; _mavlink_send_uart(chan, (const char*)buf, header_len); } else { header_len = MAVLINK_CORE_HEADER_LEN + 1; signature_len = (msg->incompat_flags & MAVLINK_IFLAG_SIGNED)?MAVLINK_SIGNATURE_BLOCK_LEN:0; MAVLINK_START_UART_SEND(chan, header_len + msg->len + 2 + signature_len); uint8_t buf[MAVLINK_CORE_HEADER_LEN + 1]; buf[0] = msg->magic; buf[1] = msg->len; buf[2] = msg->incompat_flags; buf[3] = msg->compat_flags; buf[4] = msg->seq; buf[5] = msg->sysid; buf[6] = msg->compid; buf[7] = msg->msgid & 0xFF; buf[8] = (msg->msgid >> 8) & 0xFF; buf[9] = (msg->msgid >> 16) & 0xFF; _mavlink_send_uart(chan, (const char *)buf, header_len); } _mavlink_send_uart(chan, _MAV_PAYLOAD(msg), msg->len); _mavlink_send_uart(chan, (const char *)ck, 2); if (signature_len != 0) { _mavlink_send_uart(chan, (const char *)msg->signature, MAVLINK_SIGNATURE_BLOCK_LEN); } MAVLINK_END_UART_SEND(chan, header_len + msg->len + 2 + signature_len); } #endif // MAVLINK_USE_CONVENIENCE_FUNCTIONS /** * @brief Pack a message to send it over a serial byte stream */ MAVLINK_HELPER uint16_t mavlink_msg_to_send_buffer(uint8_t *buf, const mavlink_message_t *msg) { uint8_t signature_len, header_len; uint8_t *ck; uint8_t length = msg->len; if (msg->magic == MAVLINK_STX_MAVLINK1) { signature_len = 0; header_len = MAVLINK_CORE_HEADER_MAVLINK1_LEN; buf[0] = msg->magic; buf[1] = length; buf[2] = msg->seq; buf[3] = msg->sysid; buf[4] = msg->compid; buf[5] = msg->msgid & 0xFF; memcpy(&buf[6], _MAV_PAYLOAD(msg), msg->len); ck = buf + header_len + 1 + (uint16_t)msg->len; } else { length = _mav_trim_payload(_MAV_PAYLOAD(msg), length); header_len = MAVLINK_CORE_HEADER_LEN; buf[0] = msg->magic; buf[1] = length; buf[2] = msg->incompat_flags; buf[3] = msg->compat_flags; buf[4] = msg->seq; buf[5] = msg->sysid; buf[6] = msg->compid; buf[7] = msg->msgid & 0xFF; buf[8] = (msg->msgid >> 8) & 0xFF; buf[9] = (msg->msgid >> 16) & 0xFF; memcpy(&buf[10], _MAV_PAYLOAD(msg), length); ck = buf + header_len + 1 + (uint16_t)length; signature_len = (msg->incompat_flags & MAVLINK_IFLAG_SIGNED)?MAVLINK_SIGNATURE_BLOCK_LEN:0; } ck[0] = (uint8_t)(msg->checksum & 0xFF); ck[1] = (uint8_t)(msg->checksum >> 8); if (signature_len > 0) { memcpy(&ck[2], msg->signature, signature_len); } return header_len + 1 + 2 + (uint16_t)length + (uint16_t)signature_len; } union __mavlink_bitfield { uint8_t uint8; int8_t int8; uint16_t uint16; int16_t int16; uint32_t uint32; int32_t int32; }; MAVLINK_HELPER void mavlink_start_checksum(mavlink_message_t* msg) { uint16_t crcTmp = 0; crc_init(&crcTmp); msg->checksum = crcTmp; } MAVLINK_HELPER void mavlink_update_checksum(mavlink_message_t* msg, uint8_t c) { uint16_t checksum = msg->checksum; crc_accumulate(c, &checksum); msg->checksum = checksum; } /* return the crc_entry value for a msgid */ #ifndef MAVLINK_GET_MSG_ENTRY MAVLINK_HELPER const mavlink_msg_entry_t *mavlink_get_msg_entry(uint32_t msgid) { static const mavlink_msg_entry_t mavlink_message_crcs[] = MAVLINK_MESSAGE_CRCS; /* use a bisection search to find the right entry. A perfect hash may be better Note that this assumes the table is sorted by msgid */ uint32_t low=0, high=sizeof(mavlink_message_crcs)/sizeof(mavlink_message_crcs[0]) - 1; while (low < high) { uint32_t mid = (low+1+high)/2; if (msgid < mavlink_message_crcs[mid].msgid) { high = mid-1; continue; } if (msgid > mavlink_message_crcs[mid].msgid) { low = mid; continue; } low = mid; break; } if (mavlink_message_crcs[low].msgid != msgid) { // msgid is not in the table return NULL; } return &mavlink_message_crcs[low]; } #endif // MAVLINK_GET_MSG_ENTRY /* return the crc_extra value for a message */ MAVLINK_HELPER uint8_t mavlink_get_crc_extra(const mavlink_message_t *msg) { const mavlink_msg_entry_t *e = mavlink_get_msg_entry(msg->msgid); return e?e->crc_extra:0; } /* return the min message length */ #define MAVLINK_HAVE_MIN_MESSAGE_LENGTH MAVLINK_HELPER uint8_t mavlink_min_message_length(const mavlink_message_t *msg) { const mavlink_msg_entry_t *e = mavlink_get_msg_entry(msg->msgid); return e?e->min_msg_len:0; } /* return the max message length (including extensions) */ #define MAVLINK_HAVE_MAX_MESSAGE_LENGTH MAVLINK_HELPER uint8_t mavlink_max_message_length(const mavlink_message_t *msg) { const mavlink_msg_entry_t *e = mavlink_get_msg_entry(msg->msgid); return e?e->max_msg_len:0; } /** * This is a variant of mavlink_frame_char() but with caller supplied * parsing buffers. It is useful when you want to create a MAVLink * parser in a library that doesn't use any global variables * * @param rxmsg parsing message buffer * @param status parsing status buffer * @param c The char to parse * * @param r_message NULL if no message could be decoded, otherwise the message data * @param r_mavlink_status if a message was decoded, this is filled with the channel's stats * @return 0 if no message could be decoded, 1 on good message and CRC, 2 on bad CRC * */ MAVLINK_HELPER uint8_t mavlink_frame_char_buffer(mavlink_message_t* rxmsg, mavlink_status_t* status, uint8_t c, mavlink_message_t* r_message, mavlink_status_t* r_mavlink_status) { int bufferIndex = 0; status->msg_received = MAVLINK_FRAMING_INCOMPLETE; switch (status->parse_state) { case MAVLINK_PARSE_STATE_UNINIT: case MAVLINK_PARSE_STATE_IDLE: if (c == MAVLINK_STX) { status->parse_state = MAVLINK_PARSE_STATE_GOT_STX; rxmsg->len = 0; rxmsg->magic = c; status->flags &= ~MAVLINK_STATUS_FLAG_IN_MAVLINK1; mavlink_start_checksum(rxmsg); } else if (c == MAVLINK_STX_MAVLINK1) { status->parse_state = MAVLINK_PARSE_STATE_GOT_STX; rxmsg->len = 0; rxmsg->magic = c; status->flags |= MAVLINK_STATUS_FLAG_IN_MAVLINK1; mavlink_start_checksum(rxmsg); } break; case MAVLINK_PARSE_STATE_GOT_STX: if (status->msg_received /* Support shorter buffers than the default maximum packet size */ #if (MAVLINK_MAX_PAYLOAD_LEN < 255) || c > MAVLINK_MAX_PAYLOAD_LEN #endif ) { status->buffer_overrun++; _mav_parse_error(status); status->msg_received = 0; status->parse_state = MAVLINK_PARSE_STATE_IDLE; } else { // NOT counting STX, LENGTH, SEQ, SYSID, COMPID, MSGID, CRC1 and CRC2 rxmsg->len = c; status->packet_idx = 0; mavlink_update_checksum(rxmsg, c); if (status->flags & MAVLINK_STATUS_FLAG_IN_MAVLINK1) { rxmsg->incompat_flags = 0; rxmsg->compat_flags = 0; status->parse_state = MAVLINK_PARSE_STATE_GOT_COMPAT_FLAGS; } else { status->parse_state = MAVLINK_PARSE_STATE_GOT_LENGTH; } } break; case MAVLINK_PARSE_STATE_GOT_LENGTH: rxmsg->incompat_flags = c; if ((rxmsg->incompat_flags & ~MAVLINK_IFLAG_MASK) != 0) { // message includes an incompatible feature flag _mav_parse_error(status); status->msg_received = 0; status->parse_state = MAVLINK_PARSE_STATE_IDLE; break; } mavlink_update_checksum(rxmsg, c); status->parse_state = MAVLINK_PARSE_STATE_GOT_INCOMPAT_FLAGS; break; case MAVLINK_PARSE_STATE_GOT_INCOMPAT_FLAGS: rxmsg->compat_flags = c; mavlink_update_checksum(rxmsg, c); status->parse_state = MAVLINK_PARSE_STATE_GOT_COMPAT_FLAGS; break; case MAVLINK_PARSE_STATE_GOT_COMPAT_FLAGS: rxmsg->seq = c; mavlink_update_checksum(rxmsg, c); status->parse_state = MAVLINK_PARSE_STATE_GOT_SEQ; break; case MAVLINK_PARSE_STATE_GOT_SEQ: rxmsg->sysid = c; mavlink_update_checksum(rxmsg, c); status->parse_state = MAVLINK_PARSE_STATE_GOT_SYSID; break; case MAVLINK_PARSE_STATE_GOT_SYSID: rxmsg->compid = c; mavlink_update_checksum(rxmsg, c); status->parse_state = MAVLINK_PARSE_STATE_GOT_COMPID; break; case MAVLINK_PARSE_STATE_GOT_COMPID: rxmsg->msgid = c; mavlink_update_checksum(rxmsg, c); if (status->flags & MAVLINK_STATUS_FLAG_IN_MAVLINK1) { if(rxmsg->len > 0) { status->parse_state = MAVLINK_PARSE_STATE_GOT_MSGID3; } else { status->parse_state = MAVLINK_PARSE_STATE_GOT_PAYLOAD; } #ifdef MAVLINK_CHECK_MESSAGE_LENGTH if (rxmsg->len < mavlink_min_message_length(rxmsg) || rxmsg->len > mavlink_max_message_length(rxmsg)) { _mav_parse_error(status); status->parse_state = MAVLINK_PARSE_STATE_IDLE; break; } #endif } else { status->parse_state = MAVLINK_PARSE_STATE_GOT_MSGID1; } break; case MAVLINK_PARSE_STATE_GOT_MSGID1: rxmsg->msgid |= c<<8; mavlink_update_checksum(rxmsg, c); status->parse_state = MAVLINK_PARSE_STATE_GOT_MSGID2; break; case MAVLINK_PARSE_STATE_GOT_MSGID2: rxmsg->msgid |= ((uint32_t)c)<<16; mavlink_update_checksum(rxmsg, c); if(rxmsg->len > 0){ status->parse_state = MAVLINK_PARSE_STATE_GOT_MSGID3; } else { status->parse_state = MAVLINK_PARSE_STATE_GOT_PAYLOAD; } #ifdef MAVLINK_CHECK_MESSAGE_LENGTH if (rxmsg->len < mavlink_min_message_length(rxmsg) || rxmsg->len > mavlink_max_message_length(rxmsg)) { _mav_parse_error(status); status->parse_state = MAVLINK_PARSE_STATE_IDLE; break; } #endif break; case MAVLINK_PARSE_STATE_GOT_MSGID3: _MAV_PAYLOAD_NON_CONST(rxmsg)[status->packet_idx++] = (char)c; mavlink_update_checksum(rxmsg, c); if (status->packet_idx == rxmsg->len) { status->parse_state = MAVLINK_PARSE_STATE_GOT_PAYLOAD; } break; case MAVLINK_PARSE_STATE_GOT_PAYLOAD: { const mavlink_msg_entry_t *e = mavlink_get_msg_entry(rxmsg->msgid); uint8_t crc_extra = e?e->crc_extra:0; mavlink_update_checksum(rxmsg, crc_extra); if (c != (rxmsg->checksum & 0xFF)) { status->parse_state = MAVLINK_PARSE_STATE_GOT_BAD_CRC1; } else { status->parse_state = MAVLINK_PARSE_STATE_GOT_CRC1; } rxmsg->ck[0] = c; // zero-fill the packet to cope with short incoming packets if (e && status->packet_idx < e->max_msg_len) { memset(&_MAV_PAYLOAD_NON_CONST(rxmsg)[status->packet_idx], 0, e->max_msg_len - status->packet_idx); } break; } case MAVLINK_PARSE_STATE_GOT_CRC1: case MAVLINK_PARSE_STATE_GOT_BAD_CRC1: if (status->parse_state == MAVLINK_PARSE_STATE_GOT_BAD_CRC1 || c != (rxmsg->checksum >> 8)) { // got a bad CRC message status->msg_received = MAVLINK_FRAMING_BAD_CRC; } else { // Successfully got message status->msg_received = MAVLINK_FRAMING_OK; } rxmsg->ck[1] = c; if (rxmsg->incompat_flags & MAVLINK_IFLAG_SIGNED) { status->parse_state = MAVLINK_PARSE_STATE_SIGNATURE_WAIT; status->signature_wait = MAVLINK_SIGNATURE_BLOCK_LEN; // If the CRC is already wrong, don't overwrite msg_received, // otherwise we can end up with garbage flagged as valid. if (status->msg_received != MAVLINK_FRAMING_BAD_CRC) { status->msg_received = MAVLINK_FRAMING_INCOMPLETE; } } else { if (status->signing && (status->signing->accept_unsigned_callback == NULL || !status->signing->accept_unsigned_callback(status, rxmsg->msgid))) { // If the CRC is already wrong, don't overwrite msg_received. if (status->msg_received != MAVLINK_FRAMING_BAD_CRC) { status->msg_received = MAVLINK_FRAMING_BAD_SIGNATURE; } } status->parse_state = MAVLINK_PARSE_STATE_IDLE; if (r_message != NULL) { memcpy(r_message, rxmsg, sizeof(mavlink_message_t)); } } break; case MAVLINK_PARSE_STATE_SIGNATURE_WAIT: rxmsg->signature[MAVLINK_SIGNATURE_BLOCK_LEN-status->signature_wait] = c; status->signature_wait--; if (status->signature_wait == 0) { // we have the whole signature, check it is OK bool sig_ok = mavlink_signature_check(status->signing, status->signing_streams, rxmsg); if (!sig_ok && (status->signing->accept_unsigned_callback && status->signing->accept_unsigned_callback(status, rxmsg->msgid))) { // accepted via application level override sig_ok = true; } if (sig_ok) { status->msg_received = MAVLINK_FRAMING_OK; } else { status->msg_received = MAVLINK_FRAMING_BAD_SIGNATURE; } status->parse_state = MAVLINK_PARSE_STATE_IDLE; if (r_message !=NULL) { memcpy(r_message, rxmsg, sizeof(mavlink_message_t)); } } break; } bufferIndex++; // If a message has been sucessfully decoded, check index if (status->msg_received == MAVLINK_FRAMING_OK) { //while(status->current_seq != rxmsg->seq) //{ // status->packet_rx_drop_count++; // status->current_seq++; //} status->current_rx_seq = rxmsg->seq; // Initial condition: If no packet has been received so far, drop count is undefined if (status->packet_rx_success_count == 0) status->packet_rx_drop_count = 0; // Count this packet as received status->packet_rx_success_count++; } if (r_message != NULL) { r_message->len = rxmsg->len; // Provide visibility on how far we are into current msg } if (r_mavlink_status != NULL) { r_mavlink_status->parse_state = status->parse_state; r_mavlink_status->packet_idx = status->packet_idx; r_mavlink_status->current_rx_seq = status->current_rx_seq+1; r_mavlink_status->packet_rx_success_count = status->packet_rx_success_count; r_mavlink_status->packet_rx_drop_count = status->parse_error; r_mavlink_status->flags = status->flags; } status->parse_error = 0; if (status->msg_received == MAVLINK_FRAMING_BAD_CRC) { /* the CRC came out wrong. We now need to overwrite the msg CRC with the one on the wire so that if the caller decides to forward the message anyway that mavlink_msg_to_send_buffer() won't overwrite the checksum */ if (r_message != NULL) { r_message->checksum = rxmsg->ck[0] | (rxmsg->ck[1]<<8); } } return status->msg_received; } /** * This is a convenience function which handles the complete MAVLink parsing. * the function will parse one byte at a time and return the complete packet once * it could be successfully decoded. This function will return 0, 1 or * 2 (MAVLINK_FRAMING_INCOMPLETE, MAVLINK_FRAMING_OK or MAVLINK_FRAMING_BAD_CRC) * * Messages are parsed into an internal buffer (one for each channel). When a complete * message is received it is copies into *r_message and the channel's status is * copied into *r_mavlink_status. * * @param chan ID of the channel to be parsed. * A channel is not a physical message channel like a serial port, but a logical partition of * the communication streams. COMM_NB is the limit for the number of channels * on MCU (e.g. ARM7), while COMM_NB_HIGH is the limit for the number of channels in Linux/Windows * @param c The char to parse * * @param r_message NULL if no message could be decoded, otherwise the message data * @param r_mavlink_status if a message was decoded, this is filled with the channel's stats * @return 0 if no message could be decoded, 1 on good message and CRC, 2 on bad CRC * * A typical use scenario of this function call is: * * @code * #include <mavlink.h> * * mavlink_status_t status; * mavlink_message_t msg; * int chan = 0; * * * while(serial.bytesAvailable > 0) * { * uint8_t byte = serial.getNextByte(); * if (mavlink_frame_char(chan, byte, &msg, &status) != MAVLINK_FRAMING_INCOMPLETE) * { * printf("Received message with ID %d, sequence: %d from component %d of system %d", msg.msgid, msg.seq, msg.compid, msg.sysid); * } * } * * * @endcode */ MAVLINK_HELPER uint8_t mavlink_frame_char(uint8_t chan, uint8_t c, mavlink_message_t* r_message, mavlink_status_t* r_mavlink_status) { return mavlink_frame_char_buffer(mavlink_get_channel_buffer(chan), mavlink_get_channel_status(chan), c, r_message, r_mavlink_status); } /** * Set the protocol version */ MAVLINK_HELPER void mavlink_set_proto_version(uint8_t chan, unsigned int version) { mavlink_status_t *status = mavlink_get_channel_status(chan); if (version > 1) { status->flags &= ~(MAVLINK_STATUS_FLAG_OUT_MAVLINK1); } else { status->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1; } } /** * Get the protocol version * * @return 1 for v1, 2 for v2 */ MAVLINK_HELPER unsigned int mavlink_get_proto_version(uint8_t chan) { mavlink_status_t *status = mavlink_get_channel_status(chan); if ((status->flags & MAVLINK_STATUS_FLAG_OUT_MAVLINK1) > 0) { return 1; } else { return 2; } } /** * This is a convenience function which handles the complete MAVLink parsing. * the function will parse one byte at a time and return the complete packet once * it could be successfully decoded. This function will return 0 or 1. * * Messages are parsed into an internal buffer (one for each channel). When a complete * message is received it is copies into *r_message and the channel's status is * copied into *r_mavlink_status. * * @param chan ID of the channel to be parsed. * A channel is not a physical message channel like a serial port, but a logical partition of * the communication streams. COMM_NB is the limit for the number of channels * on MCU (e.g. ARM7), while COMM_NB_HIGH is the limit for the number of channels in Linux/Windows * @param c The char to parse * * @param r_message NULL if no message could be decoded, otherwise the message data * @param r_mavlink_status if a message was decoded, this is filled with the channel's stats * @return 0 if no message could be decoded or bad CRC, 1 on good message and CRC * * A typical use scenario of this function call is: * * @code * #include <mavlink.h> * * mavlink_status_t status; * mavlink_message_t msg; * int chan = 0; * * * while(serial.bytesAvailable > 0) * { * uint8_t byte = serial.getNextByte(); * if (mavlink_parse_char(chan, byte, &msg, &status)) * { * printf("Received message with ID %d, sequence: %d from component %d of system %d", msg.msgid, msg.seq, msg.compid, msg.sysid); * } * } * * * @endcode */ MAVLINK_HELPER uint8_t mavlink_parse_char(uint8_t chan, uint8_t c, mavlink_message_t* r_message, mavlink_status_t* r_mavlink_status) { uint8_t msg_received = mavlink_frame_char(chan, c, r_message, r_mavlink_status); if (msg_received == MAVLINK_FRAMING_BAD_CRC || msg_received == MAVLINK_FRAMING_BAD_SIGNATURE) { // we got a bad CRC. Treat as a parse failure mavlink_message_t* rxmsg = mavlink_get_channel_buffer(chan); mavlink_status_t* status = mavlink_get_channel_status(chan); _mav_parse_error(status); status->msg_received = MAVLINK_FRAMING_INCOMPLETE; status->parse_state = MAVLINK_PARSE_STATE_IDLE; if (c == MAVLINK_STX) { status->parse_state = MAVLINK_PARSE_STATE_GOT_STX; rxmsg->len = 0; mavlink_start_checksum(rxmsg); } return 0; } return msg_received; } /** * @brief Put a bitfield of length 1-32 bit into the buffer * * @param b the value to add, will be encoded in the bitfield * @param bits number of bits to use to encode b, e.g. 1 for boolean, 2, 3, etc. * @param packet_index the position in the packet (the index of the first byte to use) * @param bit_index the position in the byte (the index of the first bit to use) * @param buffer packet buffer to write into * @return new position of the last used byte in the buffer */ MAVLINK_HELPER uint8_t put_bitfield_n_by_index(int32_t b, uint8_t bits, uint8_t packet_index, uint8_t bit_index, uint8_t* r_bit_index, uint8_t* buffer) { uint16_t bits_remain = bits; // Transform number into network order int32_t v; uint8_t i_bit_index, i_byte_index, curr_bits_n; #if MAVLINK_NEED_BYTE_SWAP union { int32_t i; uint8_t b[4]; } bin, bout; bin.i = b; bout.b[0] = bin.b[3]; bout.b[1] = bin.b[2]; bout.b[2] = bin.b[1]; bout.b[3] = bin.b[0]; v = bout.i; #else v = b; #endif // buffer in // 01100000 01000000 00000000 11110001 // buffer out // 11110001 00000000 01000000 01100000 // Existing partly filled byte (four free slots) // 0111xxxx // Mask n free bits // 00001111 = 2^0 + 2^1 + 2^2 + 2^3 = 2^n - 1 // = ((uint32_t)(1 << n)) - 1; // = 2^n - 1 // Shift n bits into the right position // out = in >> n; // Mask and shift bytes i_bit_index = bit_index; i_byte_index = packet_index; if (bit_index > 0) { // If bits were available at start, they were available // in the byte before the current index i_byte_index--; } // While bits have not been packed yet while (bits_remain > 0) { // Bits still have to be packed // there can be more than 8 bits, so // we might have to pack them into more than one byte // First pack everything we can into the current 'open' byte //curr_bits_n = bits_remain << 3; // Equals bits_remain mod 8 //FIXME if (bits_remain <= (uint8_t)(8 - i_bit_index)) { // Enough space curr_bits_n = (uint8_t)bits_remain; } else { curr_bits_n = (8 - i_bit_index); } // Pack these n bits into the current byte // Mask out whatever was at that position with ones (xxx11111) buffer[i_byte_index] &= (0xFF >> (8 - curr_bits_n)); // Put content to this position, by masking out the non-used part buffer[i_byte_index] |= ((0x00 << curr_bits_n) & v); // Increment the bit index i_bit_index += curr_bits_n; // Now proceed to the next byte, if necessary bits_remain -= curr_bits_n; if (bits_remain > 0) { // Offer another 8 bits / one byte i_byte_index++; i_bit_index = 0; } } *r_bit_index = i_bit_index; // If a partly filled byte is present, mark this as consumed if (i_bit_index != 7) i_byte_index++; return i_byte_index - packet_index; } #ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS // To make MAVLink work on your MCU, define comm_send_ch() if you wish // to send 1 byte at a time, or MAVLINK_SEND_UART_BYTES() to send a // whole packet at a time /* #include "mavlink_types.h" void comm_send_ch(mavlink_channel_t chan, uint8_t ch) { if (chan == MAVLINK_COMM_0) { uart0_transmit(ch); } if (chan == MAVLINK_COMM_1) { uart1_transmit(ch); } } */ MAVLINK_HELPER void _mavlink_send_uart(mavlink_channel_t chan, const char *buf, uint16_t len) { #ifdef MAVLINK_SEND_UART_BYTES /* this is the more efficient approach, if the platform defines it */ MAVLINK_SEND_UART_BYTES(chan, (const uint8_t *)buf, len); #else /* fallback to one byte at a time */ uint16_t i; for (i = 0; i < len; i++) { comm_send_ch(chan, (uint8_t)buf[i]); } #endif } #endif // MAVLINK_USE_CONVENIENCE_FUNCTIONS #ifdef MAVLINK_USE_CXX_NAMESPACE } // namespace mavlink #endif // clang-format on
AirSim/MavLinkCom/mavlink/mavlink_helpers.h/0
{ "file_path": "AirSim/MavLinkCom/mavlink/mavlink_helpers.h", "repo_id": "AirSim", "token_count": 16307 }
25
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "Semaphore.hpp" #include "Utils.hpp" using namespace mavlink_utils; #ifdef _WIN32 #include <Windows.h> class Semaphore::semaphore_impl { HANDLE semaphore; public: semaphore_impl() { this->semaphore = CreateSemaphore(NULL, 0, MAXINT32, NULL); if (this->semaphore == NULL) { throw std::runtime_error(Utils::stringf("CreateSemaphore failed with errno=%d!\n", GetLastError())); } } ~semaphore_impl() { CloseHandle(semaphore); semaphore = nullptr; } void post() { LONG previous; if (0 == ReleaseSemaphore(semaphore, 1, &previous)) { throw std::runtime_error(Utils::stringf("ReleaseSemaphore failed with errno=%d!\n", GetLastError())); } } // WaitOne indefinitely for one Signal. If a Signal has already been posted then WaitOne returns immediately // decrementing the count so the next WaitOne may block. void wait() { int rc = WaitForSingleObjectEx(semaphore, INFINITE, TRUE); if (rc == WAIT_OBJECT_0) { return; } else { throw std::runtime_error(Utils::stringf("WaitForSingleObjectEx failed with unexpected errno=%d!\n", GetLastError())); } } bool timed_wait(int milliseconds) { int rc = WaitForSingleObjectEx(semaphore, milliseconds, TRUE); if (rc == WAIT_OBJECT_0) { return true; } else if (rc == WAIT_ABANDONED) { throw std::runtime_error("Semaphore was destroyed while we are waiting on it."); } else if (rc != WAIT_TIMEOUT) { // perhaps we have WAIT_IO_COMPLETION interrupt... throw std::runtime_error(Utils::stringf("WaitForSingleObjectEx failed with errno=%d!\n", GetLastError())); } return false; } }; #elif defined(__APPLE__) #include <signal.h> //SIGALRM #include <semaphore.h> #include <mach/mach.h> #include <mach/task.h> #include <mach/semaphore.h> class Semaphore::semaphore_impl { semaphore_t semaphore; task_t owner; public: semaphore_impl() { owner = mach_task_self(); kern_return_t rc = semaphore_create(owner, &semaphore, /* policy */ SYNC_POLICY_FIFO, /* value*/ 0); if (rc != KERN_SUCCESS) { throw std::runtime_error(Utils::stringf("OSX semaphore_create failed with errno %d\n", rc)); } } ~semaphore_impl() { semaphore_destroy(owner, semaphore); } void post() { kern_return_t rc = semaphore_signal(semaphore); if (rc != KERN_SUCCESS) { throw std::runtime_error(Utils::stringf("OSX semaphore_signal failed with error %d\n", rc)); } } void wait() { kern_return_t rc = semaphore_wait(semaphore); if (rc != KERN_SUCCESS) { throw std::runtime_error(Utils::stringf("OSX semaphore_wait failed with unexpected error %d\n", rc)); } } bool timed_wait(int milliseconds) { // convert to absolute time. if (milliseconds < 0) { throw std::runtime_error("cannot wait for negative milliseconds"); } auto absolute = std::chrono::system_clock::now().time_since_epoch() + std::chrono::milliseconds(milliseconds); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(absolute); absolute = absolute - seconds; auto nanoSecondsRemaining = std::chrono::duration_cast<std::chrono::nanoseconds>(absolute); // use mach_timespec mach_timespec_t mts; mts.tv_nsec = nanoSecondsRemaining.count(); // nanoseconds mts.tv_sec = seconds.count(); // seconds kern_return_t rc = semaphore_timedwait(semaphore, mts); switch (rc) { case KERN_SUCCESS: return true; case KERN_OPERATION_TIMED_OUT: return false; case KERN_ABORTED: throw std::runtime_error("OSX semaphore_timedwait was aborted"); default: throw std::runtime_error(Utils::stringf("OSX semaphore_timedwait failed with unexpected error %d", rc)); } } }; #else // assume posix #include <semaphore.h> class Semaphore::semaphore_impl { sem_t semaphore; public: semaphore_impl() { if (sem_init(&semaphore, /* shared */ 0, /* value*/ 0) == -1) { throw std::runtime_error(Utils::stringf("sem_init failed with errno=%d!\n", errno)); } } ~semaphore_impl() { sem_destroy(&semaphore); } void post() { int status = sem_post(&semaphore); if (status < 0) { throw std::runtime_error(Utils::stringf("sem_post failed with errno=%d!\n", errno)); } } void wait() { int rc = sem_wait(&semaphore); if (rc != 0) { throw std::runtime_error(Utils::stringf("sem_wait failed with unexpected errno=%d!\n", rc)); } } bool timed_wait(int milliseconds) { // convert to absolute time. if (milliseconds < 0) { throw std::runtime_error("cannot wait for negative milliseconds"); } auto absolute = std::chrono::system_clock::now().time_since_epoch() + std::chrono::milliseconds(milliseconds); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(absolute); absolute = absolute - seconds; auto nanoSecondsRemaining = std::chrono::duration_cast<std::chrono::nanoseconds>(absolute); struct timespec ts; ts.tv_sec = seconds.count(); // seconds milliseconds -= (ts.tv_sec * 1000); ts.tv_nsec = nanoSecondsRemaining.count(); // nanoseconds int rc = sem_timedwait(&semaphore, &ts); if (rc != 0) { rc = errno; if (rc == ETIMEDOUT) { return false; } else if (rc != EINTR) { throw std::runtime_error(Utils::stringf("sem_timedwait failed with unexpected errno=%d!\n", rc)); } } return rc == 0; } }; #endif Semaphore::Semaphore() { impl_.reset(new semaphore_impl()); } Semaphore::~Semaphore() { } void Semaphore::wait() { impl_->wait(); } void Semaphore::post() { impl_->post(); } bool Semaphore::timed_wait(int millisecondTimeout) { return impl_->timed_wait(millisecondTimeout); }
AirSim/MavLinkCom/src/Semaphore.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/Semaphore.cpp", "repo_id": "AirSim", "token_count": 2928 }
26
#ifndef MavLinkCom_UdpSocketImpl_cpp #define MavLinkCom_UdpSocketImpl_cpp #include "UdpSocketImpl.hpp" using namespace mavlinkcom_impl; UdpSocketImpl::UdpSocketImpl() { fd = socket(AF_INET, SOCK_DGRAM, 0); } void UdpSocketImpl::close() { if (fd != -1) { #ifdef _WIN32 closesocket(fd); #else ::close(fd); #endif fd = -1; } } UdpSocketImpl::~UdpSocketImpl() { close(); } void UdpSocketImpl::make_sockaddr(const std::string& address, uint16_t port, struct sockaddr_in& sockaddr) { memset(&sockaddr, 0, sizeof(sockaddr)); #ifdef HAVE_SOCK_SIN_LEN sockaddr.sin_len = sizeof(sockaddr); #endif sockaddr.sin_port = htons(port); sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = inet_addr(address.c_str()); } /* connect the socket */ int UdpSocketImpl::connect(const std::string& address, uint16_t port) { struct sockaddr_in sockaddr; make_sockaddr(address, port, sockaddr); int rc = ::connect(fd, reinterpret_cast<struct sockaddr*>(&sockaddr), sizeof(sockaddr)); if (rc != 0) { int hr = WSAGetLastError(); throw std::runtime_error(Utils::stringf("UdpSocket connect failed with error: %d\n", hr)); return hr; } return 0; } /* bind the socket */ int UdpSocketImpl::bind(const std::string& address, uint16_t port) { struct sockaddr_in sockaddr; make_sockaddr(address, port, sockaddr); int rc = ::bind(fd, reinterpret_cast<struct sockaddr*>(&sockaddr), sizeof(sockaddr)); if (rc != 0) { int hr = WSAGetLastError(); throw std::runtime_error(Utils::stringf("UdpSocket bind failed with error: %d\n", hr)); return hr; } return 0; } /* set SO_REUSEADDR */ bool UdpSocketImpl::reuseaddress(void) { int one = 1; return (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&one), sizeof(one)) != -1); } /* send some data */ int UdpSocketImpl::send(const void* buf, size_t size) { int hr = ::send(fd, reinterpret_cast<const char*>(buf), static_cast<int>(size), 0); if (hr == SOCKET_ERROR) { hr = WSAGetLastError(); throw std::runtime_error(Utils::stringf("Udp socket send failed with error: %d\n", hr)); } return hr; } /* send some data */ int UdpSocketImpl::sendto(const void* buf, size_t size, const std::string& address, uint16_t port) { struct sockaddr_in sockaddr; make_sockaddr(address, port, sockaddr); int hr = ::sendto(fd, reinterpret_cast<const char*>(buf), static_cast<int>(size), 0, reinterpret_cast<struct sockaddr*>(&sockaddr), sizeof(sockaddr)); if (hr == SOCKET_ERROR) { hr = WSAGetLastError(); throw std::runtime_error(Utils::stringf("Udp socket send failed with error: %d\n", hr)); } return hr; } /* receive some data */ int UdpSocketImpl::recv(void* buf, size_t size, uint32_t timeout_ms) { if (!pollin(timeout_ms)) { return -1; } socklen_t len = sizeof(in_addr); int rc = ::recvfrom(fd, reinterpret_cast<char*>(buf), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&in_addr), &len); if (rc < 0) { rc = WSAGetLastError(); Utils::log(Utils::stringf("Udp Socket recv failed with error: %d", rc)); } return rc; } /* return the IP address and port of the last received packet */ void UdpSocketImpl::last_recv_address(std::string& ip_addr, uint16_t& port) { ip_addr = inet_ntoa(in_addr.sin_addr); port = ntohs(in_addr.sin_port); } void UdpSocketImpl::set_broadcast(void) { int one = 1; setsockopt(fd, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&one), sizeof(one)); } /* return true if there is pending data for input */ bool UdpSocketImpl::pollin(uint32_t timeout_ms) { fd_set fds; struct timeval tv; FD_ZERO(&fds); FD_SET(fd, &fds); tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000UL; #ifdef _WIN32 if (select(0, &fds, nullptr, nullptr, &tv) != 1) { #else if (select(fd + 1, &fds, nullptr, nullptr, &tv) != 1) { #endif return false; } return true; } /* return true if there is room for output data */ bool UdpSocketImpl::pollout(uint32_t timeout_ms) { fd_set fds; struct timeval tv; FD_ZERO(&fds); FD_SET(fd, &fds); tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000UL; #ifdef _WIN32 if (select(0, &fds, nullptr, nullptr, &tv) != 1) { #else if (select(fd + 1, &fds, nullptr, nullptr, &tv) != 1) { #endif return false; } return true; } #endif // MavLinkCom_UdpSocketImpl_cpp
AirSim/MavLinkCom/src/impl/UdpSocketImpl.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/impl/UdpSocketImpl.cpp", "repo_id": "AirSim", "token_count": 1976 }
27
instance_num=0 [ -n "$1" ] && instance_num="$1" export PX4_SIM_MODEL=iris SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" PARENT_DIR="$(dirname "$SCRIPT_DIR")" BUILD_DIR=$PARENT_DIR/Firmware/ROMFS/px4fmu_common instance_path=$PARENT_DIR/Firmware/build/px4_sitl_default BIN_DIR=$PARENT_DIR/Firmware/build/px4_sitl_default/bin/px4 TEST_DATA=$PARENT_DIR/Firmware/test_data working_dir="$instance_path/instance_$instance_num" [ ! -d "$working_dir" ] && mkdir -p "$working_dir" pushd "$working_dir" &>/dev/null $BIN_DIR -i $instance_num $BUILD_DIR -s "etc/init.d-posix/rcS" -t $TEST_DATA
AirSim/PX4Scripts/run_airsim_sitl.sh/0
{ "file_path": "AirSim/PX4Scripts/run_airsim_sitl.sh", "repo_id": "AirSim", "token_count": 266 }
28
# Python client example to change time-of-day using APIs # import setup_path import airsim import sys import math import time import argparse import pprint import numpy # Changes time of the day and makes the car move around class TimeOfDayTest: def __init__(self): # connect to the AirSim simulator self.client = airsim.CarClient() self.client.confirmConnection() self.client.enableApiControl(True) self.car_controls = airsim.CarControls() def execute(self): for i in range(8): # flip between specific time and default time enabled = False if (i % 2 == 0): enabled = True self.setTimeOfDay(enabled, "2018-11-27 {}:00:00".format(8+ (i * 2))) # go forward self.car_controls.throttle = 0.5 self.car_controls.steering = 0 self.client.setCarControls(self.car_controls) print("Go Forward") time.sleep(3) # let car drive a bit # Go forward + steer right self.car_controls.throttle = 0.5 self.car_controls.steering = 1 self.client.setCarControls(self.car_controls) print("Go Forward, steer right") time.sleep(3) # let car drive a bit def setTimeOfDay(self, enabled, time_of_day): if (enabled): airsim.wait_key('Press any key to change time of day to [{}]'.format(time_of_day)) self.client.simSetTimeOfDay(enabled, time_of_day) else: airsim.wait_key('Press any key to change time of day to default time') self.client.simSetTimeOfDay(enabled) def stop(self): airsim.wait_key('Press any key to reset to original state') self.client.reset() self.client.enableApiControl(False) print("Done!\n") # main if __name__ == "__main__": args = sys.argv args.pop(0) arg_parser = argparse.ArgumentParser("TimeOfDay.py changes time of the day") args = arg_parser.parse_args(args) timeOfDayTest = TimeOfDayTest() try: timeOfDayTest.execute() finally: timeOfDayTest.stop()
AirSim/PythonClient/car/car_time_of_day.py/0
{ "file_path": "AirSim/PythonClient/car/car_time_of_day.py", "repo_id": "AirSim", "token_count": 1012 }
29
import setup_path import airsim import os import tempfile client = airsim.VehicleClient() client.confirmConnection() tmp_dir = os.path.join(tempfile.gettempdir(), "airsim_cv_mode") print ("Saving images to %s" % tmp_dir) try: os.makedirs(tmp_dir) except OSError: if not os.path.isdir(tmp_dir): raise CAM_NAME = "front_center" print(f"Camera: {CAM_NAME}") airsim.wait_key('Press any key to get camera parameters') cam_info = client.simGetCameraInfo(CAM_NAME) print(cam_info) airsim.wait_key(f'Press any key to get images, saving to {tmp_dir}') requests = [airsim.ImageRequest(CAM_NAME, airsim.ImageType.Scene), airsim.ImageRequest(CAM_NAME, airsim.ImageType.DepthVis)] def save_images(responses, prefix = ""): for i, response in enumerate(responses): filename = os.path.join(tmp_dir, prefix + "_" + str(i)) if response.pixels_as_float: print(f"Type {response.image_type}, size {len(response.image_data_float)}, pos {response.camera_position}") airsim.write_pfm(os.path.normpath(filename + '.pfm'), airsim.get_pfm_array(response)) else: print(f"Type {response.image_type}, size {len(response.image_data_uint8)}, pos {response.camera_position}") airsim.write_file(os.path.normpath(filename + '.png'), response.image_data_uint8) responses = client.simGetImages(requests) save_images(responses, "old_fov") airsim.wait_key('Press any key to change FoV and get images') client.simSetCameraFov(CAM_NAME, 120) responses = client.simGetImages(requests) save_images(responses, "new_fov") new_cam_info = client.simGetCameraInfo(CAM_NAME) print(new_cam_info) print(f"Old FOV: {cam_info.fov}, New FOV: {new_cam_info.fov}")
AirSim/PythonClient/computer_vision/fov_change.py/0
{ "file_path": "AirSim/PythonClient/computer_vision/fov_change.py", "repo_id": "AirSim", "token_count": 694 }
30
import airsim import time client = airsim.VehicleClient() client.confirmConnection() # Access an existing light in the world lights = client.simListSceneObjects("PointLight.*") pose = client.simGetObjectPose(lights[0]) scale = airsim.Vector3r(1, 1, 1) # Destroy the light client.simDestroyObject(lights[0]) time.sleep(1) # Create a new light at the same pose new_light_name = client.simSpawnObject("PointLight", "PointLightBP", pose, scale, False, True) time.sleep(1) # Change the light's intensity for i in range(20): client.simSetLightIntensity(new_light_name, i * 100) time.sleep(0.5)
AirSim/PythonClient/environment/light_control.py/0
{ "file_path": "AirSim/PythonClient/environment/light_control.py", "repo_id": "AirSim", "token_count": 202 }
31
import setup_path import airsim import tempfile import os import numpy as np import cv2 import pprint # connect to the AirSim simulator client = airsim.MultirotorClient() client.confirmConnection() # add new vehicle vehicle_name = "Drone2" pose = airsim.Pose(airsim.Vector3r(0, 0, 0), airsim.to_quaternion(0, 0, 0)) client.simAddVehicle(vehicle_name, "simpleflight", pose) client.enableApiControl(True, vehicle_name) client.armDisarm(True, vehicle_name) client.takeoffAsync(10.0, vehicle_name) requests = [airsim.ImageRequest("0", airsim.ImageType.DepthVis), #depth visualization image airsim.ImageRequest("1", airsim.ImageType.DepthPerspective, True), #depth in perspective projection airsim.ImageRequest("1", airsim.ImageType.Scene), #scene vision image in png format airsim.ImageRequest("1", airsim.ImageType.Scene, False, False)] #scene vision image in uncompressed RGBA array responses = client.simGetImages(requests, vehicle_name=vehicle_name) print('Retrieved images: %d' % len(responses)) tmp_dir = os.path.join(tempfile.gettempdir(), "airsim_drone") print ("Saving images to %s" % tmp_dir) try: os.makedirs(tmp_dir) except OSError: if not os.path.isdir(tmp_dir): raise for idx, response in enumerate(responses): filename = os.path.join(tmp_dir, str(idx)) if response.pixels_as_float: print("Type %d, size %d, pos %s" % (response.image_type, len(response.image_data_float), pprint.pformat(response.camera_position))) airsim.write_pfm(os.path.normpath(filename + '.pfm'), airsim.get_pfm_array(response)) else: print("Type %d, size %d, pos %s" % (response.image_type, len(response.image_data_uint8), pprint.pformat(response.camera_position))) airsim.write_file(os.path.normpath(filename + '.png'), response.image_data_uint8)
AirSim/PythonClient/multirotor/add_drone.py/0
{ "file_path": "AirSim/PythonClient/multirotor/add_drone.py", "repo_id": "AirSim", "token_count": 686 }
32
# use open cv to show new images from AirSim import setup_path import airsim # requires Python 3.5.3 :: Anaconda 4.4.0 # pip install opencv-python import cv2 import time import math import sys import numpy as np client = airsim.MultirotorClient() client.confirmConnection() client.enableApiControl(True) client.armDisarm(True) client.takeoffAsync().join() # you must first press "1" in the AirSim view to turn on the depth capture # get depth image yaw = 0 pi = 3.14159265483 vx = 0 vy = 0 driving = 0 help = False while True: # this will return png width= 256, height= 144 result = client.simGetImage("0", airsim.ImageType.DepthVis) if (result == "\0"): if (not help): help = True print("Please press '1' in the AirSim view to enable the Depth camera view") else: rawImage = np.fromstring(result, np.int8) png = cv2.imdecode(rawImage, cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(png, cv2.COLOR_BGR2GRAY) # slice the image so we only check what we are headed into (and not what is down on the ground below us). top = np.vsplit(gray, 2)[0] # now look at 4 horizontal bands (far left, left, right, far right) and see which is most open. # the depth map uses black for far away (0) and white for very close (255), so we invert that # to get an estimate of distance. bands = np.hsplit(top, [50,100,150,200]); maxes = [np.max(x) for x in bands] min = np.argmin(maxes) distance = 255 - maxes[min] # sanity check on what is directly in front of us (slot 2 in our hsplit) current = 255 - maxes[2] if (current < 20): client.hoverAsync().join() airsim.wait_key("whoops - we are about to crash, so stopping!") pitch, roll, yaw = airsim.to_eularian_angles(client.simGetVehiclePose().orientation) if (distance > current + 30): # we have a 90 degree field of view (pi/2), we've sliced that into 5 chunks, each chunk then represents # an angular delta of the following pi/10. change = 0 driving = min if (min == 0): change = -2 * pi / 10 elif (min == 1): change = -pi / 10 elif (min == 2): change = 0 # center strip, go straight elif (min == 3): change = pi / 10 else: change = 2*pi/10 yaw = (yaw + change) vx = math.cos(yaw); vy = math.sin(yaw); print ("switching angle", math.degrees(yaw), vx, vy, min, distance, current) if (vx == 0 and vy == 0): vx = math.cos(yaw); vy = math.sin(yaw); print ("distance=", current) client.moveByVelocityZAsync(vx, vy,-6, 1, airsim.DrivetrainType.ForwardOnly, airsim.YawMode(False, 0)).join() x = int(driving * 50) cv2.rectangle(png, (x,0), (x+50,50), (0,255,0), 2) cv2.imshow("Top", png) key = cv2.waitKey(1) & 0xFF; if (key == 27 or key == ord('q') or key == ord('x')): break;
AirSim/PythonClient/multirotor/navigate.py/0
{ "file_path": "AirSim/PythonClient/multirotor/navigate.py", "repo_id": "AirSim", "token_count": 1460 }
33
import setup_path import airsim import sys import time import argparse class SurveyNavigator: def __init__(self, args): self.boxsize = args.size self.stripewidth = args.stripewidth self.altitude = args.altitude self.velocity = args.speed self.client = airsim.MultirotorClient() self.client.confirmConnection() self.client.enableApiControl(True) def start(self): print("arming the drone...") self.client.armDisarm(True) landed = self.client.getMultirotorState().landed_state if landed == airsim.LandedState.Landed: print("taking off...") self.client.takeoffAsync().join() landed = self.client.getMultirotorState().landed_state if landed == airsim.LandedState.Landed: print("takeoff failed - check Unreal message log for details") return # AirSim uses NED coordinates so negative axis is up. x = -self.boxsize z = -self.altitude print("climbing to altitude: " + str(self.altitude)) self.client.moveToPositionAsync(0, 0, z, self.velocity).join() print("flying to first corner of survey box") self.client.moveToPositionAsync(x, -self.boxsize, z, self.velocity).join() # let it settle there a bit. self.client.hoverAsync().join() time.sleep(2) # after hovering we need to re-enabled api control for next leg of the trip self.client.enableApiControl(True) # now compute the survey path required to fill the box path = [] distance = 0 while x < self.boxsize: distance += self.boxsize path.append(airsim.Vector3r(x, self.boxsize, z)) x += self.stripewidth distance += self.stripewidth path.append(airsim.Vector3r(x, self.boxsize, z)) distance += self.boxsize path.append(airsim.Vector3r(x, -self.boxsize, z)) x += self.stripewidth distance += self.stripewidth path.append(airsim.Vector3r(x, -self.boxsize, z)) distance += self.boxsize print("starting survey, estimated distance is " + str(distance)) trip_time = distance / self.velocity print("estimated survey time is " + str(trip_time)) try: result = self.client.moveOnPathAsync(path, self.velocity, trip_time, airsim.DrivetrainType.ForwardOnly, airsim.YawMode(False,0), self.velocity + (self.velocity/2), 1).join() except: errorType, value, traceback = sys.exc_info() print("moveOnPath threw exception: " + str(value)) pass print("flying back home") self.client.moveToPositionAsync(0, 0, z, self.velocity).join() if z < -5: print("descending") self.client.moveToPositionAsync(0, 0, -5, 2).join() print("landing...") self.client.landAsync().join() print("disarming.") self.client.armDisarm(False) if __name__ == "__main__": args = sys.argv args.pop(0) arg_parser = argparse.ArgumentParser("Usage: survey boxsize stripewidth altitude") arg_parser.add_argument("--size", type=float, help="size of the box to survey", default=50) arg_parser.add_argument("--stripewidth", type=float, help="stripe width of survey (in meters)", default=10) arg_parser.add_argument("--altitude", type=float, help="altitude of survey (in positive meters)", default=30) arg_parser.add_argument("--speed", type=float, help="speed of survey (in meters/second)", default=5) args = arg_parser.parse_args(args) nav = SurveyNavigator(args) nav.start()
AirSim/PythonClient/multirotor/survey.py/0
{ "file_path": "AirSim/PythonClient/multirotor/survey.py", "repo_id": "AirSim", "token_count": 1632 }
34
#include "UnityImageCapture.h" #include "PInvokeWrapper.h" #include "UnityUtilities.hpp" namespace AirSimUnity { UnityImageCapture::UnityImageCapture(std::string vehicle_name) : vehicle_name_(vehicle_name) { } UnityImageCapture::~UnityImageCapture() { } // implements getImages() method in the ImageCaptureBase class. void UnityImageCapture::getImages(const std::vector<msr::airlib::ImageCaptureBase::ImageRequest>& requests, std::vector<msr::airlib::ImageCaptureBase::ImageResponse>& responses) const { for (auto i = 0u; i < requests.size(); i++) { ImageResponse airsim_response; responses.push_back(airsim_response); AirSimImageRequest request = UnityUtilities::Convert_to_UnityRequest(requests[i]); AirSimImageResponse response = GetSimImages(request, vehicle_name_.c_str()); //Into Unity UnityUtilities::Convert_to_AirsimResponse(response, responses[i], request.camera_name); } } }
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityImageCapture.cpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityImageCapture.cpp", "repo_id": "AirSim", "token_count": 355 }
35
#include "SimModeCar.h" #include "common/AirSimSettings.hpp" #include "CarPawnSimApi.h" #include "vehicles/car/api/CarRpcLibServer.hpp" #include "../../PInvokeWrapper.h" SimModeCar::SimModeCar(int port_number) : SimModeBase(port_number) { } void SimModeCar::BeginPlay() { SimModeBase::BeginPlay(); initializePauseState(); } void SimModeCar::initializePauseState() { pause_period_ = 0; pause_period_start_ = 0; pause(false); } bool SimModeCar::isPaused() const { return current_clockspeed_ == 0; } void SimModeCar::pause(bool is_paused) { if (is_paused) current_clockspeed_ = 0; else current_clockspeed_ = getSettings().clock_speed; Pause(current_clockspeed_); } void SimModeCar::continueForTime(double seconds) { pause_period_start_ = ClockFactory::get()->nowNanos(); pause_period_ = seconds; pause(false); } void SimModeCar::setupClockSpeed() { current_clockspeed_ = getSettings().clock_speed; } void SimModeCar::Tick(float DeltaSeconds) { SimModeBase::Tick(DeltaSeconds); if (pause_period_start_ > 0) { if (ClockFactory::get()->elapsedSince(pause_period_start_) >= pause_period_) { if (!isPaused()) pause(true); pause_period_start_ = 0; } } } std::unique_ptr<msr::airlib::ApiServerBase> SimModeCar::createApiServer() const { #ifdef AIRLIB_NO_RPC return ASimModeBase::createApiServer(); #else auto ptr = std::unique_ptr<msr::airlib::ApiServerBase>(new msr::airlib::CarRpcLibServer( getApiProvider(), getSettings().api_server_address, port_number_)); return ptr; #endif } bool SimModeCar::isVehicleTypeSupported(const std::string& vehicle_type) const { return vehicle_type == AirSimSettings::kVehicleTypePhysXCar; } UnityPawn* SimModeCar::GetVehiclePawn(const std::string& vehicle_name) { return new CarPawn(vehicle_name); } std::unique_ptr<PawnSimApi> SimModeCar::createVehicleSimApi(const PawnSimApi::Params& pawn_sim_api_params) const { auto vehicle_sim_api = std::unique_ptr<PawnSimApi>(new CarPawnSimApi(pawn_sim_api_params, pawn_sim_api_params.vehicle_name)); vehicle_sim_api->initialize(); vehicle_sim_api->reset(); return vehicle_sim_api; } msr::airlib::VehicleApiBase* SimModeCar::getVehicleApi(const PawnSimApi::Params& pawn_sim_api_params, const PawnSimApi* sim_api) const { const auto car_sim_api = static_cast<const CarPawnSimApi*>(sim_api); return car_sim_api->getVehicleApi(); }
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Car/SimModeCar.cpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Car/SimModeCar.cpp", "repo_id": "AirSim", "token_count": 1092 }
36
# AirSim on Unity This page has moved [here](https://github.com/microsoft/AirSim/blob/main/docs/Unity.md)
AirSim/Unity/README.md/0
{ "file_path": "AirSim/Unity/README.md", "repo_id": "AirSim", "token_count": 36 }
37
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1001 &100100000 Prefab: m_ObjectHideFlags: 1 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 0} m_Modifications: [] m_RemovedComponents: [] m_ParentPrefab: {fileID: 0} m_RootGameObject: {fileID: 1329369738491184} m_IsPrefabParent: 1 --- !u!1 &1026079360174662 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4339702948892506} - component: {fileID: 20077861513634074} - component: {fileID: 114580299224493058} m_Layer: 0 m_Name: Window1Camera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1072339108199092 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4342755474433206} - component: {fileID: 146923271617559422} m_Layer: 9 m_Name: FrontRight m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1216076798016934 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4642956294365180} - component: {fileID: 20553964104206814} - component: {fileID: 114004780180960936} - component: {fileID: 114867335675244802} m_Layer: 0 m_Name: Front_Center m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1230540940376898 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4216331574548392} - component: {fileID: 146136613871667916} m_Layer: 9 m_Name: RearRight m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1233072145653026 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4358968009257496} m_Layer: 9 m_Name: RLTyre m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1283527703605684 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4404301945594638} - component: {fileID: 20136011729947338} - component: {fileID: 114207973695392862} m_Layer: 0 m_Name: Window2Camera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1302947263567762 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4749862588991954} m_Layer: 9 m_Name: FLTyre m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1329369738491184 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4753014077117344} - component: {fileID: 54849585016354144} - component: {fileID: 114964333826250464} - component: {fileID: 114282202431524204} m_Layer: 0 m_Name: Car_Dummy m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1338877991455792 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4854995913583428} m_Layer: 9 m_Name: FRTyre m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1402501540203588 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4798329813893982} m_Layer: 9 m_Name: Wheels m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1405731618464802 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4348587822072880} - component: {fileID: 146775457595753310} m_Layer: 9 m_Name: FrontLeft m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1460557443998090 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4581415631292410} m_Layer: 0 m_Name: LookAt m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1497855086877342 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4657732562493670} - component: {fileID: 146583011405799908} m_Layer: 9 m_Name: RearLeft m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1513505660775636 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4815285703598284} - component: {fileID: 33276657566142024} - component: {fileID: 23967305996175062} - component: {fileID: 65809985068279356} m_Layer: 9 m_Name: Body m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1537778653872498 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4347529183487264} - component: {fileID: 20520982555371894} - component: {fileID: 114220101242804216} - component: {fileID: 114660145942086934} m_Layer: 0 m_Name: Center_Bottom m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1541335777812696 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4491727576204778} m_Layer: 9 m_Name: RRTyre m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1590421803176656 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4626477014148830} - component: {fileID: 33261034354543720} - component: {fileID: 23768840481242582} m_Layer: 9 m_Name: Cylinder m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1673918224846890 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4288239054175866} m_Layer: 0 m_Name: WindowCameras m_TagString: ViewCameras m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1702119018127016 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4077391317304104} - component: {fileID: 33672749597679140} - component: {fileID: 23365761092946448} m_Layer: 9 m_Name: Cylinder m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1765484685534886 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4755892568849826} m_Layer: 0 m_Name: CaptureCameras m_TagString: CaptureCameras m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1775459115838106 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4253577859080964} - component: {fileID: 20220351056904626} - component: {fileID: 114510156474436944} - component: {fileID: 114598942947664106} m_Layer: 0 m_Name: Front_Right m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1794452882440758 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4171051593199254} - component: {fileID: 20217005539774590} - component: {fileID: 114827344459469444} m_Layer: 0 m_Name: Window3Camera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1832877963221596 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4623921038160740} - component: {fileID: 33966737565284252} - component: {fileID: 23363337580983444} m_Layer: 9 m_Name: Cylinder m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1865058557677598 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4242201856024818} - component: {fileID: 33602120333071936} - component: {fileID: 23030974813327470} m_Layer: 9 m_Name: Cylinder m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1890306339272320 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4514127165093764} - component: {fileID: 20162562676896596} - component: {fileID: 114511487346176382} - component: {fileID: 114613417918786552} m_Layer: 0 m_Name: Front_Left m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1893649520308268 GameObject: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4813892106906102} - component: {fileID: 20197740479366452} - component: {fileID: 114904577574796998} - component: {fileID: 114123037440150420} m_Layer: 0 m_Name: Rear_Center m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4077391317304104 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1702119018127016} m_LocalRotation: {x: 0, y: 0, z: 0.7071068, w: 0.7071068} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.7, y: 0.1, z: 0.7} m_Children: [] m_Father: {fileID: 4358968009257496} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 90} --- !u!4 &4171051593199254 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1794452882440758} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4288239054175866} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4216331574548392 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1230540940376898} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.5, y: -0.20000005, z: -1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4798329813893982} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4242201856024818 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1865058557677598} m_LocalRotation: {x: 0, y: 0, z: 0.7071068, w: 0.7071068} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.7, y: 0.1, z: 0.7} m_Children: [] m_Father: {fileID: 4491727576204778} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 90} --- !u!4 &4253577859080964 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1775459115838106} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.5, y: 0, z: 0.5} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4755892568849826} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4288239054175866 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1673918224846890} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4339702948892506} - {fileID: 4404301945594638} - {fileID: 4171051593199254} m_Father: {fileID: 4753014077117344} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4339702948892506 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1026079360174662} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4288239054175866} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4342755474433206 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1072339108199092} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.5, y: -0.20000005, z: 1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4798329813893982} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4347529183487264 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1537778653872498} m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4755892568849826} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0} --- !u!4 &4348587822072880 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1405731618464802} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: -0.5, y: -0.2, z: 1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4798329813893982} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4358968009257496 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1233072145653026} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -0.5, y: -0.37, z: -1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4077391317304104} m_Father: {fileID: 4798329813893982} m_RootOrder: 6 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4404301945594638 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1283527703605684} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4288239054175866} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4491727576204778 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1541335777812696} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.5, y: -0.37, z: -1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4242201856024818} m_Father: {fileID: 4798329813893982} m_RootOrder: 7 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4514127165093764 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1890306339272320} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -0.5, y: 0, z: 0.5} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4755892568849826} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4581415631292410 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1460557443998090} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4753014077117344} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4623921038160740 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1832877963221596} m_LocalRotation: {x: 0, y: 0, z: 0.7071068, w: 0.7071068} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.7, y: 0.1, z: 0.7} m_Children: [] m_Father: {fileID: 4749862588991954} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 90} --- !u!4 &4626477014148830 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1590421803176656} m_LocalRotation: {x: 0, y: 0, z: 0.7071068, w: 0.7071068} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.7, y: 0.1, z: 0.7} m_Children: [] m_Father: {fileID: 4854995913583428} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 90} --- !u!4 &4642956294365180 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1216076798016934} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0.5} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4755892568849826} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4657732562493670 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1497855086877342} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -0.5, y: -0.20000005, z: -1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4798329813893982} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4749862588991954 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1302947263567762} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -0.5, y: -0.37, z: 1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4623921038160740} m_Father: {fileID: 4798329813893982} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4753014077117344 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1329369738491184} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 2, z: 0} m_LocalScale: {x: 1.5, y: 1, z: 1} m_Children: - {fileID: 4815285703598284} - {fileID: 4798329813893982} - {fileID: 4581415631292410} - {fileID: 4288239054175866} - {fileID: 4755892568849826} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4755892568849826 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1765484685534886} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4642956294365180} - {fileID: 4253577859080964} - {fileID: 4514127165093764} - {fileID: 4347529183487264} - {fileID: 4813892106906102} m_Father: {fileID: 4753014077117344} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4798329813893982 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1402501540203588} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4348587822072880} - {fileID: 4342755474433206} - {fileID: 4657732562493670} - {fileID: 4216331574548392} - {fileID: 4749862588991954} - {fileID: 4854995913583428} - {fileID: 4358968009257496} - {fileID: 4491727576204778} m_Father: {fileID: 4753014077117344} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4813892106906102 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1893649520308268} m_LocalRotation: {x: 0, y: 1, z: 0, w: 0} m_LocalPosition: {x: 0, y: 0, z: -0.5} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4755892568849826} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0} --- !u!4 &4815285703598284 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1513505660775636} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 0.7, z: 3} m_Children: [] m_Father: {fileID: 4753014077117344} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4854995913583428 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1338877991455792} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0.5, y: -0.37, z: 1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4626477014148830} m_Father: {fileID: 4798329813893982} m_RootOrder: 5 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!20 &20077861513634074 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1026079360174662} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 1, g: 1, b: 1, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294965759 m_RenderingPath: 1 m_TargetTexture: {fileID: 8400000, guid: 3e2f16f77d6e1f248a7373bf0b951154, type: 2} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20136011729947338 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1283527703605684} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.29411766, g: 0.29411766, b: 0.29411766, a: 1} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294965759 m_RenderingPath: 1 m_TargetTexture: {fileID: 8400000, guid: b1339334589473548b8a4359d6e72454, type: 2} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20162562676896596 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1890306339272320} m_Enabled: 0 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 750 field of view: 90 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294966783 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20197740479366452 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1893649520308268} m_Enabled: 0 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 750 field of view: 90 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294966783 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20217005539774590 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1794452882440758} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294965759 m_RenderingPath: -1 m_TargetTexture: {fileID: 8400000, guid: ca5a26a47741d2943bf1ca546bffb563, type: 2} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 1 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20220351056904626 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1775459115838106} m_Enabled: 0 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 750 field of view: 90 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294966783 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20520982555371894 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1537778653872498} m_Enabled: 0 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 750 field of view: 90 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294966783 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20553964104206814 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1216076798016934} m_Enabled: 0 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 750 field of view: 90 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294966783 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!23 &23030974813327470 MeshRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1865058557677598} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 4294967295 m_Materials: - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!23 &23363337580983444 MeshRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1832877963221596} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 4294967295 m_Materials: - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!23 &23365761092946448 MeshRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1702119018127016} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 4294967295 m_Materials: - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!23 &23768840481242582 MeshRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1590421803176656} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 4294967295 m_Materials: - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!23 &23967305996175062 MeshRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1513505660775636} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 4294967295 m_Materials: - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &33261034354543720 MeshFilter: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1590421803176656} m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} --- !u!33 &33276657566142024 MeshFilter: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1513505660775636} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!33 &33602120333071936 MeshFilter: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1865058557677598} m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} --- !u!33 &33672749597679140 MeshFilter: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1702119018127016} m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} --- !u!33 &33966737565284252 MeshFilter: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1832877963221596} m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} --- !u!54 &54849585016354144 Rigidbody: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1329369738491184} serializedVersion: 2 m_Mass: 1000 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 0 --- !u!65 &65809985068279356 BoxCollider: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1513505660775636} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!114 &114004780180960936 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1216076798016934} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d488591858471a4bbef459e45d9a839, type: 3} m_Name: m_EditorClassIdentifier: --- !u!114 &114123037440150420 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1893649520308268} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 0 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114207973695392862 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1283527703605684} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 5 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114220101242804216 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1537778653872498} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d488591858471a4bbef459e45d9a839, type: 3} m_Name: m_EditorClassIdentifier: --- !u!114 &114282202431524204 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1329369738491184} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: e924d4c00c2c05d42830dd3a94dd86a8, type: 3} m_Name: m_EditorClassIdentifier: --- !u!114 &114510156474436944 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1775459115838106} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d488591858471a4bbef459e45d9a839, type: 3} m_Name: m_EditorClassIdentifier: --- !u!114 &114511487346176382 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1890306339272320} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d488591858471a4bbef459e45d9a839, type: 3} m_Name: m_EditorClassIdentifier: --- !u!114 &114580299224493058 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1026079360174662} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 3 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114598942947664106 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1775459115838106} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 0 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114613417918786552 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1890306339272320} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 0 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114660145942086934 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1537778653872498} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 0 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114827344459469444 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1794452882440758} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 0 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114867335675244802 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1216076798016934} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 0 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114904577574796998 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1893649520308268} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d488591858471a4bbef459e45d9a839, type: 3} m_Name: m_EditorClassIdentifier: --- !u!114 &114964333826250464 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1329369738491184} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: a41aa865e2b62374d891f09589b4e9e2, type: 3} m_Name: m_EditorClassIdentifier: m_CarDriveType: 2 m_WheelColliders: - {fileID: 146775457595753310} - {fileID: 146923271617559422} - {fileID: 146583011405799908} - {fileID: 146136613871667916} m_WheelMeshes: - {fileID: 1302947263567762} - {fileID: 1338877991455792} - {fileID: 1233072145653026} - {fileID: 1541335777812696} m_CentreOfMassOffset: {x: 0, y: 0, z: 0} m_MaximumSteerAngle: 30 m_SteerHelper: 0.5 m_TractionControl: 1 m_FullTorqueOverAllWheels: 2500 m_ReverseTorque: 500 m_MaxHandbrakeTorque: 100000 m_Downforce: 100 m_Topspeed: 200 NoOfGears: 5 m_RevRangeBoundary: 1 m_SlipLimit: 0.5 m_BrakeTorque: 250000 --- !u!146 &146136613871667916 WheelCollider: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1230540940376898} m_Center: {x: 0, y: 0, z: 0} m_Radius: 0.335 m_SuspensionSpring: spring: 70000 damper: 3500 targetPosition: 0.1 m_SuspensionDistance: 0.2 m_ForceAppPointDistance: 0.1 m_Mass: 20 m_WheelDampingRate: 0.25 m_ForwardFriction: m_ExtremumSlip: 0.4 m_ExtremumValue: 1 m_AsymptoteSlip: 0.8 m_AsymptoteValue: 0.5 m_Stiffness: 1 m_SidewaysFriction: m_ExtremumSlip: 0.2 m_ExtremumValue: 1 m_AsymptoteSlip: 0.5 m_AsymptoteValue: 0.75 m_Stiffness: 1 m_Enabled: 1 --- !u!146 &146583011405799908 WheelCollider: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1497855086877342} m_Center: {x: 0, y: 0, z: 0} m_Radius: 0.335 m_SuspensionSpring: spring: 70000 damper: 3500 targetPosition: 0.1 m_SuspensionDistance: 0.2 m_ForceAppPointDistance: 0.1 m_Mass: 20 m_WheelDampingRate: 0.25 m_ForwardFriction: m_ExtremumSlip: 0.4 m_ExtremumValue: 1 m_AsymptoteSlip: 0.8 m_AsymptoteValue: 0.5 m_Stiffness: 1 m_SidewaysFriction: m_ExtremumSlip: 0.2 m_ExtremumValue: 1 m_AsymptoteSlip: 0.5 m_AsymptoteValue: 0.75 m_Stiffness: 1 m_Enabled: 1 --- !u!146 &146775457595753310 WheelCollider: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1405731618464802} m_Center: {x: 0, y: 0, z: 0} m_Radius: 0.335 m_SuspensionSpring: spring: 70000 damper: 3500 targetPosition: 0.1 m_SuspensionDistance: 0.2 m_ForceAppPointDistance: 0.1 m_Mass: 20 m_WheelDampingRate: 0.25 m_ForwardFriction: m_ExtremumSlip: 0.4 m_ExtremumValue: 1 m_AsymptoteSlip: 0.8 m_AsymptoteValue: 0.5 m_Stiffness: 1 m_SidewaysFriction: m_ExtremumSlip: 0.2 m_ExtremumValue: 1 m_AsymptoteSlip: 0.5 m_AsymptoteValue: 0.75 m_Stiffness: 1 m_Enabled: 1 --- !u!146 &146923271617559422 WheelCollider: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1072339108199092} m_Center: {x: 0, y: 0, z: 0} m_Radius: 0.335 m_SuspensionSpring: spring: 70000 damper: 3500 targetPosition: 0.1 m_SuspensionDistance: 0.2 m_ForceAppPointDistance: 0.1 m_Mass: 20 m_WheelDampingRate: 0.25 m_ForwardFriction: m_ExtremumSlip: 0.4 m_ExtremumValue: 1 m_AsymptoteSlip: 0.8 m_AsymptoteValue: 0.5 m_Stiffness: 1 m_SidewaysFriction: m_ExtremumSlip: 0.2 m_ExtremumValue: 1 m_AsymptoteSlip: 0.5 m_AsymptoteValue: 0.75 m_Stiffness: 1 m_Enabled: 1
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/Car_Dummy.prefab/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/Car_Dummy.prefab", "repo_id": "AirSim", "token_count": 20630 }
38
using UnityEngine; using UnityEngine.Rendering; using System.Collections.Generic; using System.Text.RegularExpressions; namespace AirSimUnity { /* * MonoBehaviour class that is attached to cameras in the scene. * Used for applying image filters based on settings.json or Image request by the client to record the data. * The three filters, Depth, Segment and Vision are supported as in Unreal. * Note : Most of the code is based on Unity's Image Synthesis project */ [RequireComponent(typeof(Camera))] public class CameraFiltersScript : MonoBehaviour { public ImageType effect; public Shader effectsShader; private Camera myCamera; private static readonly Dictionary<string, int> segmentationIds = new Dictionary<string, int>(); private void Start() { myCamera = GetComponent<Camera>(); var renderers = FindObjectsOfType<Renderer>(); var mpb = new MaterialPropertyBlock(); foreach (var r in renderers) { var id = r.gameObject.GetInstanceID(); var layer = r.gameObject.layer; mpb.SetColor("_ObjectColor", ColorEncoding.EncodeIDAsColor(id)); mpb.SetColor("_CategoryColor", ColorEncoding.EncodeLayerAsColor(layer)); r.SetPropertyBlock(mpb); var objectName = r.gameObject.name; if (!segmentationIds.ContainsKey(objectName)) { segmentationIds.Add(r.gameObject.name, id); } } UpdateCameraEffect(); } private ImageType Effects { get { return effect; } set { effect = value; UpdateCameraEffect(); } } private void OnValidate() { Effects = effect; } public void SetShaderEffect(ImageType type) { effect = type; UpdateCameraEffect(); } public static bool SetSegmentationId(string objectName, int segmentationId, bool isNameRegex) { List<string> keyList = new List<string>(segmentationIds.Keys); if (isNameRegex) { bool isValueSet = false; foreach (string s in keyList) { if (!Regex.IsMatch(s, objectName)) { continue; } segmentationIds[s] = segmentationId; isValueSet = true; } return isValueSet; } if (!segmentationIds.ContainsKey(objectName)) { return false; } segmentationIds[objectName] = segmentationId; return true; } public static int GetSegmentationId(string objectName) { if (segmentationIds.ContainsKey(objectName)) { return segmentationIds[objectName]; } return -1; } private void SetSegmentationEffect() { var renderers = FindObjectsOfType<Renderer>(); var mpb = new MaterialPropertyBlock(); foreach (var r in renderers) { var id = r.gameObject.GetInstanceID(); segmentationIds.TryGetValue(r.gameObject.name, out id); var layer = r.gameObject.layer; mpb.SetColor("_ObjectColor", ColorEncoding.EncodeIDAsColor(id)); mpb.SetColor("_CategoryColor", ColorEncoding.EncodeLayerAsColor(layer)); r.SetPropertyBlock(mpb); } myCamera.renderingPath = RenderingPath.Forward; SetupCameraWithReplacementShader(0, Color.gray); } private void SetDepthEffect() { myCamera.renderingPath = RenderingPath.Forward; SetupCameraWithReplacementShader(2, Color.white); } private void ResetCameraEffects() { myCamera.renderingPath = RenderingPath.UsePlayerSettings; myCamera.clearFlags = CameraClearFlags.Skybox; myCamera.SetReplacementShader(null, null); } private void SetupCameraWithReplacementShader(int mode, Color clearColor) { var cb = new CommandBuffer(); cb.SetGlobalFloat("_OutputMode", (int)mode); myCamera.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, cb); myCamera.AddCommandBuffer(CameraEvent.BeforeFinalPass, cb); myCamera.SetReplacementShader(effectsShader, ""); myCamera.backgroundColor = clearColor; myCamera.clearFlags = CameraClearFlags.SolidColor; } private void UpdateCameraEffect() { if (!myCamera) { return; } myCamera.RemoveAllCommandBuffers(); switch (effect) { case ImageType.Scene: ResetCameraEffects(); break; case ImageType.DepthVis: SetDepthEffect(); break; case ImageType.Segmentation: SetSegmentationEffect(); break; default: ResetCameraEffects(); break; } } } }
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/HUD/CameraFiltersScript.cs/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/HUD/CameraFiltersScript.cs", "repo_id": "AirSim", "token_count": 2579 }
39
fileFormatVersion: 2 guid: 5f6d8ad91e27948408cb40f884114ba2 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/AirSimSettings.cs.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/AirSimSettings.cs.meta", "repo_id": "AirSim", "token_count": 93 }
40
fileFormatVersion: 2 guid: 9b4d726b63d838c4ca7789730de54343 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/WeatherFX/Prefabs.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/WeatherFX/Prefabs.meta", "repo_id": "AirSim", "token_count": 70 }
41
fileFormatVersion: 2 guid: df7823065d92e2948a9a715a3a586cb2 DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/Scenes/MultiDroneDemo.unity.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Scenes/MultiDroneDemo.unity.meta", "repo_id": "AirSim", "token_count": 65 }
42
fileFormatVersion: 2 guid: bedcbcc4d577778478a5f01fe1415af1 NativeFormatImporter: userData: assetBundleName:
AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarLightCoversWhite.mat.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarLightCoversWhite.mat.meta", "repo_id": "AirSim", "token_count": 47 }
43
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1386491679 &1 PresetManager: m_ObjectHideFlags: 0 m_DefaultList: - type: m_NativeTypeID: 108 m_ManagedTypePPtr: {fileID: 0} m_ManagedTypeFallback: defaultPresets: - m_Preset: {fileID: 2655988077585873504, guid: c1cf8506f04ef2c4a88b64b6c4202eea, type: 2} - type: m_NativeTypeID: 1020 m_ManagedTypePPtr: {fileID: 0} m_ManagedTypeFallback: defaultPresets: - m_Preset: {fileID: 2655988077585873504, guid: 0cd792cc87e492d43b4e95b205fc5cc6, type: 2} - type: m_NativeTypeID: 1006 m_ManagedTypePPtr: {fileID: 0} m_ManagedTypeFallback: defaultPresets: - m_Preset: {fileID: 2655988077585873504, guid: 7a99f8aa944efe94cb9bd74562b7d5f9, type: 2}
AirSim/Unity/UnityDemo/ProjectSettings/PresetManager.asset/0
{ "file_path": "AirSim/Unity/UnityDemo/ProjectSettings/PresetManager.asset", "repo_id": "AirSim", "token_count": 420 }
44
[ContentBrowser] ContentBrowserTab1.SelectedPaths=/Game/Flying [/Script/UnrealEd.EditorPerProjectUserSettings] bThrottleCPUWhenNotForeground=False
AirSim/Unreal/Environments/Blocks/Config/DefaultEditorPerProjectUserSettings.ini/0
{ "file_path": "AirSim/Unreal/Environments/Blocks/Config/DefaultEditorPerProjectUserSettings.ini", "repo_id": "AirSim", "token_count": 45 }
45
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Blocks.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE(FDefaultGameModuleImpl, Blocks, "Blocks");
AirSim/Unreal/Environments/Blocks/Source/Blocks/Blocks.cpp/0
{ "file_path": "AirSim/Unreal/Environments/Blocks/Source/Blocks/Blocks.cpp", "repo_id": "AirSim", "token_count": 63 }
46
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using UnrealBuildTool; using System.IO; public class AirSim : ModuleRules { private string ModulePath { get { return ModuleDirectory; } } private string AirLibPath { get { return Path.Combine(ModulePath, "AirLib"); } } private string AirSimPluginPath { get { return Directory.GetParent(ModulePath).FullName; } } private string ProjectBinariesPath { get { return Path.Combine( Directory.GetParent(AirSimPluginPath).Parent.FullName, "Binaries"); } } private string AirSimPluginDependencyPath { get { return Path.Combine(AirSimPluginPath, "Dependencies"); } } private enum CompileMode { HeaderOnlyNoRpc, HeaderOnlyWithRpc, CppCompileNoRpc, CppCompileWithRpc } private void SetupCompileMode(CompileMode mode, ReadOnlyTargetRules Target) { LoadAirSimDependency(Target, "MavLinkCom", "MavLinkCom"); switch (mode) { case CompileMode.HeaderOnlyNoRpc: PublicDefinitions.Add("AIRLIB_HEADER_ONLY=1"); PublicDefinitions.Add("AIRLIB_NO_RPC=1"); AddLibDependency("AirLib", Path.Combine(AirLibPath, "lib"), "AirLib", Target, false); break; case CompileMode.HeaderOnlyWithRpc: PublicDefinitions.Add("AIRLIB_HEADER_ONLY=1"); AddLibDependency("AirLib", Path.Combine(AirLibPath, "lib"), "AirLib", Target, false); LoadAirSimDependency(Target, "rpclib", "rpc"); break; case CompileMode.CppCompileNoRpc: LoadAirSimDependency(Target, "MavLinkCom", "MavLinkCom"); PublicDefinitions.Add("AIRLIB_NO_RPC=1"); break; case CompileMode.CppCompileWithRpc: LoadAirSimDependency(Target, "rpclib", "rpc"); break; default: throw new System.Exception("CompileMode specified in plugin's Build.cs file is not recognized"); } } public AirSim(ReadOnlyTargetRules Target) : base(Target) { //bEnforceIWYU = true; //to support 4.16 PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; bEnableExceptions = true; PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "ImageWrapper", "RenderCore", "RHI", "AssetRegistry", "PhysicsCore", "PhysXVehicles", "PhysXVehicleLib", "PhysX", "APEX", "Landscape", "CinematicCamera" }); PrivateDependencyModuleNames.AddRange(new string[] { "UMG", "Slate", "SlateCore" }); //suppress VC++ proprietary warnings PublicDefinitions.Add("_SCL_SECURE_NO_WARNINGS=1"); PublicDefinitions.Add("_CRT_SECURE_NO_WARNINGS=1"); PublicDefinitions.Add("HMD_MODULE_INCLUDED=0"); PublicIncludePaths.Add(Path.Combine(AirLibPath, "include")); PublicIncludePaths.Add(Path.Combine(AirLibPath, "deps", "eigen3")); AddOSLibDependencies(Target); SetupCompileMode(CompileMode.HeaderOnlyWithRpc, Target); } private void AddOSLibDependencies(ReadOnlyTargetRules Target) { if (Target.Platform == UnrealTargetPlatform.Win64) { // for SHGetFolderPath. PublicAdditionalLibraries.Add("Shell32.lib"); //for joystick support PublicAdditionalLibraries.Add("dinput8.lib"); PublicAdditionalLibraries.Add("dxguid.lib"); } if (Target.Platform == UnrealTargetPlatform.Linux) { // needed when packaging PublicAdditionalLibraries.Add("stdc++"); PublicAdditionalLibraries.Add("supc++"); } } static void CopyFileIfNewer(string srcFilePath, string destFolder) { FileInfo srcFile = new FileInfo(srcFilePath); FileInfo destFile = new FileInfo(Path.Combine(destFolder, srcFile.Name)); if (!destFile.Exists || srcFile.LastWriteTime > destFile.LastWriteTime) { srcFile.CopyTo(destFile.FullName, true); } //else skip } private bool LoadAirSimDependency(ReadOnlyTargetRules Target, string LibName, string LibFileName) { string LibrariesPath = Path.Combine(AirLibPath, "deps", LibName, "lib"); return AddLibDependency(LibName, LibrariesPath, LibFileName, Target, true); } private bool AddLibDependency(string LibName, string LibPath, string LibFileName, ReadOnlyTargetRules Target, bool IsAddLibInclude) { string PlatformString = (Target.Platform == UnrealTargetPlatform.Win64 || Target.Platform == UnrealTargetPlatform.Mac) ? "x64" : "x86"; string ConfigurationString = (Target.Configuration == UnrealTargetConfiguration.Debug) ? "Debug" : "Release"; bool isLibrarySupported = false; if (Target.Platform == UnrealTargetPlatform.Win64) { isLibrarySupported = true; PublicAdditionalLibraries.Add(Path.Combine(LibPath, PlatformString, ConfigurationString, LibFileName + ".lib")); } else if (Target.Platform == UnrealTargetPlatform.Linux || Target.Platform == UnrealTargetPlatform.Mac) { isLibrarySupported = true; PublicAdditionalLibraries.Add(Path.Combine(LibPath, "lib" + LibFileName + ".a")); } if (isLibrarySupported && IsAddLibInclude) { // Include path PublicIncludePaths.Add(Path.Combine(AirLibPath, "deps", LibName, "include")); } PublicDefinitions.Add(string.Format("WITH_" + LibName.ToUpper() + "_BINDING={0}", isLibrarySupported ? 1 : 0)); return isLibrarySupported; } }
AirSim/Unreal/Plugins/AirSim/Source/AirSim.Build.cs/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/AirSim.Build.cs", "repo_id": "AirSim", "token_count": 2423 }
47
#pragma once #include "CoreMinimal.h" #include "Components/SceneCaptureComponent2D.h" #include "Camera/CameraActor.h" #include "Materials/Material.h" #include "Runtime/Core/Public/PixelFormat.h" #include "common/ImageCaptureBase.hpp" #include "common/common_utils/Utils.hpp" #include "common/AirSimSettings.hpp" #include "NedTransform.h" #include "DetectionComponent.h" //CinemAirSim #include <CineCameraActor.h> #include <CineCameraComponent.h> #include "Materials/MaterialParameterCollection.h" #include "Materials/MaterialParameterCollectionInstance.h" #include "Materials/MaterialInstanceDynamic.h" #include "PIPCamera.generated.h" UCLASS() class AIRSIM_API APIPCamera : public ACineCameraActor //CinemAirSim { GENERATED_BODY() public: typedef msr::airlib::ImageCaptureBase::ImageType ImageType; typedef msr::airlib::AirSimSettings AirSimSettings; typedef AirSimSettings::CameraSetting CameraSetting; APIPCamera(const FObjectInitializer& ObjectInitializer); //CinemAirSim virtual void PostInitializeComponents() override; virtual void BeginPlay() override; virtual void Tick(float DeltaSeconds) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; void showToScreen(); void disableAll(); void disableAllPIP(); void disableMain(); void onViewModeChanged(bool nodisplay); //CinemAirSim methods std::vector<std::string> getPresetLensSettings() const; void setPresetLensSettings(std::string preset_string); std::vector<std::string> getPresetFilmbackSettings() const; void setPresetFilmbackSettings(std::string preset_string); std::string getLensSettings() const; std::string getFilmbackSettings() const; float setFilmbackSettings(float sensor_width, float sensor_height); float getFocalLength() const; void setFocalLength(float focal_length); void enableManualFocus(bool enable); float getFocusDistance() const; void setFocusDistance(float focus_distance); float getFocusAperture() const; void setFocusAperture(float focus_aperture); void enableFocusPlane(bool enable); std::string getCurrentFieldOfView() const; //end CinemAirSim methods void setCameraTypeEnabled(ImageType type, bool enabled); bool getCameraTypeEnabled(ImageType type) const; void setCaptureUpdate(USceneCaptureComponent2D* capture, bool nodisplay); void setCameraTypeUpdate(ImageType type, bool nodisplay); void setupCameraFromSettings(const CameraSetting& camera_setting, const NedTransform& ned_transform); void setCameraPose(const msr::airlib::Pose& relative_pose); void setCameraFoV(float fov_degrees); msr::airlib::CameraInfo getCameraInfo() const; std::vector<float> getDistortionParams() const; void setDistortionParam(const std::string& param_name, float value); msr::airlib::ProjectionMatrix getProjectionMatrix(const ImageType image_type) const; USceneCaptureComponent2D* getCaptureComponent(const ImageType type, bool if_active); UTextureRenderTarget2D* getRenderTarget(const ImageType type, bool if_active); UDetectionComponent* getDetectionComponent(const ImageType type, bool if_active) const; msr::airlib::Pose getPose() const; private: //members UPROPERTY() UMaterialParameterCollection* distortion_param_collection_; UPROPERTY() UMaterialParameterCollectionInstance* distortion_param_instance_; UPROPERTY() TArray<USceneCaptureComponent2D*> captures_; UPROPERTY() TArray<UTextureRenderTarget2D*> render_targets_; UPROPERTY() TArray<UDetectionComponent*> detections_; //CinemAirSim UPROPERTY() UCineCameraComponent* camera_; //TMap<int, UMaterialInstanceDynamic*> noise_materials_; //below is needed because TMap doesn't work with UPROPERTY, but we do have -ve index UPROPERTY() TArray<UMaterialInstanceDynamic*> noise_materials_; UPROPERTY() TArray<UMaterialInstanceDynamic*> distortion_materials_; UPROPERTY() UMaterial* noise_material_static_; UPROPERTY() UMaterial* distortion_material_static_; std::vector<bool> camera_type_enabled_; FRotator gimbald_rotator_; float gimbal_stabilization_; const NedTransform* ned_transform_; TMap<int, EPixelFormat> image_type_to_pixel_format_map_; FObjectFilter object_filter_; private: //methods typedef common_utils::Utils Utils; typedef AirSimSettings::CaptureSetting CaptureSetting; typedef AirSimSettings::NoiseSetting NoiseSetting; static unsigned int imageTypeCount(); void enableCaptureComponent(const ImageType type, bool is_enabled); static void updateCaptureComponentSetting(USceneCaptureComponent2D* capture, UTextureRenderTarget2D* render_target, bool auto_format, const EPixelFormat& pixel_format, const CaptureSetting& setting, const NedTransform& ned_transform, bool force_linear_gamma); void setNoiseMaterial(int image_type, UObject* outer, FPostProcessSettings& obj, const NoiseSetting& settings); void setDistortionMaterial(int image_type, UObject* outer, FPostProcessSettings& obj); static void updateCameraPostProcessingSetting(FPostProcessSettings& obj, const CaptureSetting& setting); //CinemAirSim static void updateCameraSetting(UCineCameraComponent* camera, const CaptureSetting& setting, const NedTransform& ned_transform); void copyCameraSettingsToAllSceneCapture(UCameraComponent* camera); void copyCameraSettingsToSceneCapture(UCameraComponent* src, USceneCaptureComponent2D* dst); //end CinemAirSim };
AirSim/Unreal/Plugins/AirSim/Source/PIPCamera.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/PIPCamera.h", "repo_id": "AirSim", "token_count": 1884 }
48
#pragma once #if defined _WIN32 || defined _WIN64 #include <memory> #include <string> class DirectInputJoyStick { public: struct DIGUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; }; struct Capabilities { bool x_axis = false, y_axis = false, z_axis = false; bool rx_axis = false, ry_axis = false, rz_axis = false; bool slider0 = false, slider1 = false; bool pov0 = false, pov1 = false, pov2 = false, pov3 = false; }; struct JoystickInfo { DIGUID instance_guide; std::string pid_vid; bool is_valid = false; }; struct JoystickState { long x = 0, y = 0, z = 0; long rx = 0, ry = 0, rz = 0; long slider0 = 0, slider1 = 0; unsigned long pov0 = 0, pov1 = 0, pov2 = 0, pov3 = 0; unsigned char buttons[128] = {}; bool is_valid = false; bool is_initialized = false; std::string message; }; public: DirectInputJoyStick(); ~DirectInputJoyStick(); bool initialize(int joystick_index); // strength ranges from -1 to 1 void setAutoCenter(double strength); // strength ranges from 0 to 1 void setWheelRumble(double strength); const JoystickState& getState(bool update_state = true); const Capabilities& getCapabilities(); const JoystickInfo& getJoystickInfo(); private: //pimpl struct impl; std::unique_ptr<impl> pimpl_; }; #endif
AirSim/Unreal/Plugins/AirSim/Source/SimJoyStick/DirectInputJoystick.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/SimJoyStick/DirectInputJoystick.h", "repo_id": "AirSim", "token_count": 647 }
49
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "UnrealSensorFactory.h" #include "UnrealSensors/UnrealDistanceSensor.h" #include "UnrealSensors/UnrealLidarSensor.h" UnrealSensorFactory::UnrealSensorFactory(AActor* actor, const NedTransform* ned_transform) { setActor(actor, ned_transform); } std::shared_ptr<msr::airlib::SensorBase> UnrealSensorFactory::createSensorFromSettings( const AirSimSettings::SensorSetting* sensor_setting) const { using SensorBase = msr::airlib::SensorBase; switch (sensor_setting->sensor_type) { case SensorBase::SensorType::Distance: return std::shared_ptr<UnrealDistanceSensor>(new UnrealDistanceSensor( *static_cast<const AirSimSettings::DistanceSetting*>(sensor_setting), actor_, ned_transform_)); case SensorBase::SensorType::Lidar: return std::shared_ptr<UnrealLidarSensor>(new UnrealLidarSensor( *static_cast<const AirSimSettings::LidarSetting*>(sensor_setting), actor_, ned_transform_)); default: return msr::airlib::SensorFactory::createSensorFromSettings(sensor_setting); } } void UnrealSensorFactory::setActor(AActor* actor, const NedTransform* ned_transform) { actor_ = actor; ned_transform_ = ned_transform; }
AirSim/Unreal/Plugins/AirSim/Source/UnrealSensors/UnrealSensorFactory.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/UnrealSensors/UnrealSensorFactory.cpp", "repo_id": "AirSim", "token_count": 448 }
50
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "SimModeComputerVision.h" #include "UObject/ConstructorHelpers.h" #include "Engine/World.h" #include "AirBlueprintLib.h" #include "common/AirSimSettings.hpp" #include "PawnSimApi.h" #include "AirBlueprintLib.h" #include "common/Common.hpp" #include "common/EarthUtils.hpp" #include "api/VehicleSimApiBase.hpp" #include "common/AirSimSettings.hpp" #include "physics/Kinematics.hpp" #include "api/RpcLibServerBase.hpp" std::unique_ptr<msr::airlib::ApiServerBase> ASimModeComputerVision::createApiServer() const { #ifdef AIRLIB_NO_RPC return ASimModeBase::createApiServer(); #else return std::unique_ptr<msr::airlib::ApiServerBase>(new msr::airlib::RpcLibServerBase( getApiProvider(), getSettings().api_server_address, getSettings().api_port)); #endif } void ASimModeComputerVision::getExistingVehiclePawns(TArray<AActor*>& pawns) const { UAirBlueprintLib::FindAllActor<TVehiclePawn>(this, pawns); } bool ASimModeComputerVision::isVehicleTypeSupported(const std::string& vehicle_type) const { return vehicle_type == msr::airlib::AirSimSettings::kVehicleTypeComputerVision; } std::string ASimModeComputerVision::getVehiclePawnPathName(const AirSimSettings::VehicleSetting& vehicle_setting) const { //decide which derived BP to use std::string pawn_path = vehicle_setting.pawn_path; if (pawn_path == "") pawn_path = "DefaultComputerVision"; return pawn_path; } PawnEvents* ASimModeComputerVision::getVehiclePawnEvents(APawn* pawn) const { return static_cast<TVehiclePawn*>(pawn)->getPawnEvents(); } const common_utils::UniqueValueMap<std::string, APIPCamera*> ASimModeComputerVision::getVehiclePawnCameras( APawn* pawn) const { return static_cast<const TVehiclePawn*>(pawn)->getCameras(); } void ASimModeComputerVision::initializeVehiclePawn(APawn* pawn) { static_cast<TVehiclePawn*>(pawn)->initializeForBeginPlay(); } std::unique_ptr<PawnSimApi> ASimModeComputerVision::createVehicleSimApi( const PawnSimApi::Params& pawn_sim_api_params) const { auto vehicle_sim_api = std::unique_ptr<PawnSimApi>(new PawnSimApi(pawn_sim_api_params)); vehicle_sim_api->initialize(); vehicle_sim_api->reset(); return vehicle_sim_api; } msr::airlib::VehicleApiBase* ASimModeComputerVision::getVehicleApi(const PawnSimApi::Params& pawn_sim_api_params, const PawnSimApi* sim_api) const { //we don't have real vehicle so no vehicle API return nullptr; }
AirSim/Unreal/Plugins/AirSim/Source/Vehicles/ComputerVision/SimModeComputerVision.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/ComputerVision/SimModeComputerVision.cpp", "repo_id": "AirSim", "token_count": 996 }
51
@echo off REM //---------- set up variable ---------- setlocal set ROOT_DIR=%~dp0 set cmake_minversion_minmaj=" 3. 14" set "cmake_version= . " where /q cmake if %ERRORLEVEL% EQU 0 ( for /F "tokens=3" %%a in ('cmake --version ^| find "cmake version"') do set cmake_version=%%a if "%cmake_version%" == "" ( echo Unable to get version of cmake. >&2 exit /b 2 ) ) else ( echo cmake was not found in path. goto :download_install ) set cmake_ver_major= set cmake_ver_minor= for /F "tokens=1,2 delims=." %%a in ("%cmake_version%") do ( set "cmake_ver_major= %%a" set "cmake_ver_minor= %%b" ) set cmake_ver_minmaj="%cmake_ver_major:~-4%.%cmake_ver_minor:~-4%" if %cmake_ver_minmaj% LSS %cmake_minversion_minmaj% ( echo( echo Newer AirSim requires cmake verion %cmake_minversion_minmaj% but you have %cmake_ver_minmaj% which is older. >&2 goto :download_install ) echo Found cmake version: %cmake_version% exit /b 0 :download_install set /p choice="Press any key to download and install cmake (make sure to add it in path in install options)" IF NOT EXIST %temp%\cmake-3.14.7-win64-x64.msi ( @echo on powershell -command "& { iwr https://cmake.org/files/v3.14/cmake-3.14.7-win64-x64.msi -OutFile %temp%\cmake-3.14.7-win64-x64.msi }" @echo off ) msiexec.exe /i "%temp%\cmake-3.14.7-win64-x64.msi" exit /b 1
AirSim/check_cmake.bat/0
{ "file_path": "AirSim/check_cmake.bat", "repo_id": "AirSim", "token_count": 583 }
52
# AirSim ROS Tutorials This is a set of sample AirSim `settings.json`s, roslaunch and rviz files to give a starting point for using AirSim with ROS. See [airsim_ros_pkgs](https://github.com/microsoft/AirSim/blob/main/ros/src/airsim_ros_pkgs/README.md) for the ROS API. ## Setup Make sure that the [airsim_ros_pkgs Setup](airsim_ros_pkgs.md) has been completed and the prerequisites installed. ```shell $ cd PATH_TO/AirSim/ros $ catkin build airsim_tutorial_pkgs ``` If your default GCC isn't 8 or greater (check using `gcc --version`), then compilation will fail. In that case, use `gcc-8` explicitly as follows- ```shell catkin build airsim_tutorial_pkgs -DCMAKE_C_COMPILER=gcc-8 -DCMAKE_CXX_COMPILER=g++-8 ``` !!! note For running examples, and also whenever a new terminal is opened, sourcing the `setup.bash` file is necessary. If you're using the ROS wrapper frequently, it might be helpful to add the `source PATH_TO/AirSim/ros/devel/setup.bash` to your `~/.profile` or `~/.bashrc` to avoid the need to run the command every time a new terminal is opened ## Examples ### Single drone with monocular and depth cameras, and lidar - Settings.json - [front_stereo_and_center_mono.json](https://github.com/microsoft/AirSim/blob/main/ros/src/airsim_tutorial_pkgs/settings/front_stereo_and_center_mono.json) ```shell $ source PATH_TO/AirSim/ros/devel/setup.bash $ roscd airsim_tutorial_pkgs $ cp settings/front_stereo_and_center_mono.json ~/Documents/AirSim/settings.json ## Start your unreal package or binary here $ roslaunch airsim_ros_pkgs airsim_node.launch; # in a new pane / terminal $ source PATH_TO/AirSim/ros/devel/setup.bash $ roslaunch airsim_tutorial_pkgs front_stereo_and_center_mono.launch ``` The above would start rviz with tf's, registered RGBD cloud using [depth_image_proc](https://wiki.ros.org/depth_image_proc) using the [`depth_to_pointcloud` launch file](https://github.com/microsoft/AirSim/blob/main/ros/src/airsim_tutorial_pkgs/launch/front_stereo_and_center_mono/depth_to_pointcloud.launch), and the lidar point cloud. ### Two drones, with cameras, lidar, IMU each - Settings.json - [two_drones_camera_lidar_imu.json](https://github.com/microsoft/AirSim/blob/main/ros/src/airsim_tutorial_pkgs/settings/two_drones_camera_lidar_imu.json) ```shell $ source PATH_TO/AirSim/ros/devel/setup.bash $ roscd airsim_tutorial_pkgs $ cp settings/two_drones_camera_lidar_imu.json ~/Documents/AirSim/settings.json ## Start your unreal package or binary here $ roslaunch airsim_ros_pkgs airsim_node.launch; $ roslaunch airsim_ros_pkgs rviz.launch ``` You can view the tfs in rviz. And do a `rostopic list` and `rosservice list` to inspect the services avaiable. ### Twenty-five drones in a square pattern - Settings.json - [twenty_five_drones.json](https://github.com/microsoft/AirSim/blob/main/ros/src/airsim_tutorial_pkgs/settings/twenty_five_drones.json) ```shell $ source PATH_TO/AirSim/ros/devel/setup.bash $ roscd airsim_tutorial_pkgs $ cp settings/twenty_five_drones.json ~/Documents/AirSim/settings.json ## Start your unreal package or binary here $ roslaunch airsim_ros_pkgs airsim_node.launch; $ roslaunch airsim_ros_pkgs rviz.launch ``` You can view the tfs in rviz. And do a `rostopic list` and `rosservice list` to inspect the services avaiable.
AirSim/docs/airsim_tutorial_pkgs.md/0
{ "file_path": "AirSim/docs/airsim_tutorial_pkgs.md", "repo_id": "AirSim", "token_count": 1154 }
53
# Development Workflow Below is the guide on how to perform different development activities while working with AirSim. If you are new to Unreal Engine based projects and want to contribute to AirSim or make your own forks for your custom requirements, this might save you some time. ## Development Environment ### OS We highly recommend Windows 10 and Visual Studio 2019 as your development environment. The support for other OSes and IDE is unfortunately not as mature on the Unreal Engine side and you may risk severe loss of productivity trying to do workarounds and jumping through the hoops. ### Hardware We recommend GPUs such as NVidia 1080 or NVidia Titan series with powerful desktop such as one with 64GB RAM, 6+ cores, SSDs and 2-3 displays (ideally 4K). We have found HP Z840 work quite well for our needs. The development experience on high-end laptops is generally sub-par compared to powerful desktops however they might be useful in a pinch. You generally want laptops with discrete NVidia GPU (at least M2000 or better) with 64GB RAM, SSDs and hopefully 4K display. We have found models such as Lenovo P50 work well for our needs. Laptops with only integrated graphics might not work well. ## Updating and Changing AirSim Code ### Overview AirSim is designed as plugin. This means it can't run by itself, you need to put it in an Unreal project (we call it "environment"). So building and testing AirSim has two steps: (1) build the plugin (2) deploy plugin in Unreal project and run the project. The first step is accomplished by build.cmd available in AirSim root. This command will update everything you need for the plugin in the `Unreal\Plugins` folder. So to deploy the plugin, you just need to copy `Unreal\Plugins` folder in to your Unreal project folder. Next you should remove all intermediate files in your Unreal project and then regenerate .sln file for your Unreal project. To do this, we have two handy .bat files in `Unreal\Environments\Blocks` folder: `clean.bat` and `GenerateProjectFiles.bat`. So just run these bat files in sequence from root of your Unreal project. Now you are ready to open new .sln in Visual Studio and press F5 to run it. ### Steps Below are the steps we use to make changes in AirSim and test them out. The best way to do development in AirSim code is to use [Blocks project](unreal_blocks.md). This is the light weight project so compile time is relatively faster. Generally the workflow is, ``` REM //Use x64 Native Tools Command Prompt for VS 2019 REM //Navigate to AirSim repo folder git pull build.cmd cd Unreal\Environments\Blocks update_from_git.bat start Blocks.sln ``` Above commands first builds the AirSim plugin and then deploys it to Blocks project using handy `update_from_git.bat`. Now you can work inside Visual Studio solution, make changes to the code and just run F5 to build, run and test your changes. The debugging, break points etc should work as usual. After you are done with you code changes, you might want to push your changes back to AirSim repo or your own fork or you may deploy the new plugin to your custom Unreal project. To do this, go back to command prompt and first update the AirSim repo folder: ``` REM //Use x64 Native Tools Command Prompt for VS 2019 REM //run this from Unreal\Environments\Blocks update_to_git.bat build.cmd ``` Above command will transfer your code changes from Unreal project folder back to `Unreal\Plugins` folder. Now your changes are ready to be pushed to AirSim repo or your own fork. You can also copy `Unreal\Plugins` to your custom Unreal engine project and see if everything works in your custom project as well. ### Take Away Once you understand how Unreal Build system and plugin model works as well as why we are doing above steps, you should feel quite comfortable in following this workflow. Don't be afraid of opening up .bat files to peek inside and see what its doing. They are quite minimal and straightforward (except, of course, build.cmd - don't look in to that one). ## FAQ #### I made changes in code in Blocks project but its not working. When you press F5 or F6 in Visual Studio to start build, the Unreal Build system kicks in and it tries to find out if any files are dirty and what it needs to build. Unfortunately, it often fails to recognize dirty files that is not the code that uses Unreal headers and object hierarchy. So, the trick is to just make some file dirty that Unreal Build system always recognizes. My favorite one is AirSimGameMode.cpp. Just insert a line, delete it and save the file. #### I made changes in the code outside of Visual Studio but its not working. Don't do that! Unreal Build system *assumes* that you are using Visual Studio and it does bunch of things to integrate with Visual Studio. If you do insist on using other editors then look up how to do command line builds in Unreal projects OR see docs on your editor on how it can integrate with Unreal build system OR run `clean.bat` + `GenerateProjectFiles.bat` to make sure VS solution is in sync. #### I'm trying to add new file in the Unreal Project and its not working. It won't! While you are indeed using Visual Studio solution, remember that this solution was actually generated by Unreal Build system. If you want to add new files in your project, first shut down Visual Studio, add an empty file at desired location and then run `GenerateProjectFiles.bat` which will scan all files in your project and then re-create the .sln file. Now open this new .sln file and you are in business. #### I copied Unreal\Plugins folder but nothing happens in Unreal Project. First make sure your project's .uproject file is referencing the plugin. Then make sure you have run `clean.bat` and then `GenerateProjectFiles.bat` as described in Overview above. #### I have multiple Unreal projects with AirSim plugin. How do I update them easily? You are in luck! We have `build_all_ue_projects.bat` which exactly does that. Don't treat it as black box (at least not yet), open it up and see what it does. It has 4 variables that are being set from command line args. If these args is not supplied they are set to default values in next set of statements. You might want to change default values for the paths. This batch file builds AirSim plugin, deploys it to all listed projects (see CALL statements later in the batch file), runs packaging for those projects and puts final binaries in specified folder - all in one step! This is what we use to create our own binary releases. #### How do I contribute back to AirSim? Before making any changes make sure you have created your feature branch. After you test your code changes in Blocks environment, follow the [usual steps](https://akrabat.com/the-beginners-guide-to-contributing-to-a-github-project/) to make contributions just like any other GitHub projects. Please use rebase and squash merge, for more information see [An introduction to Git merge and rebase: what they are, and how to use them](https://www.freecodecamp.org/news/an-introduction-to-git-merge-and-rebase-what-they-are-and-how-to-use-them-131b863785f/).
AirSim/docs/dev_workflow.md/0
{ "file_path": "AirSim/docs/dev_workflow.md", "repo_id": "AirSim", "token_count": 1743 }
54
# Object Detection ## About This feature lets you generate object detection using existing cameras in AirSim, similar to detection DNN. Using the API you can control which object to detect by name and radius from camera. One can control these settings for each camera, image type and vehicle combination separately. ## API - Set mesh name to detect in wildcard format ```simAddDetectionFilterMeshName(camera_name, image_type, mesh_name, vehicle_name = '')``` - Clear all mesh names previously added ```simClearDetectionMeshNames(camera_name, image_type, vehicle_name = '')``` - Set detection radius in cm ```simSetDetectionFilterRadius(camera_name, image_type, radius_cm, vehicle_name = '')``` - Get detections ```simGetDetections(camera_name, image_type, vehicle_name = '')``` The return value of `simGetDetections` is a `DetectionInfo` array: ```python DetectionInfo name = '' geo_point = GeoPoint() box2D = Box2D() box3D = Box3D() relative_pose = Pose() ``` ## Usage example Python script [detection.py](https://github.com/microsoft/AirSim/blob/main/PythonClient/detection/detection.py) shows how to set detection parameters and shows the result in OpenCV capture. A minimal example using API with Blocks environment to detect Cylinder objects: ```python camera_name = "0" image_type = airsim.ImageType.Scene client = airsim.MultirotorClient() client.confirmConnection() client.simSetDetectionFilterRadius(camera_name, image_type, 80 * 100) # in [cm] client.simAddDetectionFilterMeshName(camera_name, image_type, "Cylinder_*") client.simGetDetections(camera_name, image_type) detections = client.simClearDetectionMeshNames(camera_name, image_type) ``` Output result: ```python Cylinder: <DetectionInfo> { 'box2D': <Box2D> { 'max': <Vector2r> { 'x_val': 617.025634765625, 'y_val': 583.5487060546875}, 'min': <Vector2r> { 'x_val': 485.74359130859375, 'y_val': 438.33465576171875}}, 'box3D': <Box3D> { 'max': <Vector3r> { 'x_val': 4.900000095367432, 'y_val': 0.7999999523162842, 'z_val': 0.5199999809265137}, 'min': <Vector3r> { 'x_val': 3.8999998569488525, 'y_val': -0.19999998807907104, 'z_val': 1.5199999809265137}}, 'geo_point': <GeoPoint> { 'altitude': 16.979999542236328, 'latitude': 32.28772183970703, 'longitude': 34.864785008379876}, 'name': 'Cylinder9_2', 'relative_pose': <Pose> { 'orientation': <Quaternionr> { 'w_val': 0.9929741621017456, 'x_val': 0.0038591264747083187, 'y_val': -0.11333247274160385, 'z_val': 0.03381215035915375}, 'position': <Vector3r> { 'x_val': 4.400000095367432, 'y_val': 0.29999998211860657, 'z_val': 1.0199999809265137}}} ``` ![image](images/detection_ue4.png) ![image](images/detection_python.png)
AirSim/docs/object_detection.md/0
{ "file_path": "AirSim/docs/object_detection.md", "repo_id": "AirSim", "token_count": 1097 }
55
# LockStep The latest version of PX4 supports a new [lockstep feature](https://docs.px4.io/master/en/simulation/#lockstep-simulation) when communicating with the simulator over TCP. Lockstep is an important feature because it synchronizes PX4 and the simulator so they essentially use the same clock time. This makes PX4 behave normally even during unusually long delays in Simulator performance. It is recommended that when you are running a lockstep enabled version of PX4 in SITL mode that you tell AirSim to use a `SteppableClock`, and set `UseTcp` to `true` and `LockStep` to `true`. ``` { "SettingsVersion": 1.2, "SimMode": "Multirotor", "ClockType": "SteppableClock", "Vehicles": { "PX4": { "VehicleType": "PX4Multirotor", "UseTcp": true, "LockStep": true, ... ``` This causes AirSim to not use a "realtime" clock, but instead it advances the clock in step which each sensor update sent to PX4. This way PX4 thinks time is progressing smoothly no matter how long it takes AirSim to really process that update loop. This has the following advantages: - AirSim can be used on slow machines that cannot process updates quickly. - You can debug AirSim and hit a breakpoint, and when you resume PX4 will behave normally. - You can enable very slow sensors like the Lidar with large number of simulated points, and PX4 will still behave normally. There will be some side effects to `lockstep`, namely, slower update loops caused by running AirSim on an underpowered machine or from expensive sensors (like Lidar) will create some visible jerkiness in the simulated flight if you look at the updates on screen in realtime. # Disabling LockStep If you are running PX4 in cygwin, there is an [open issue with lockstep](https://github.com/microsoft/AirSim/issues/3415). PX4 is configured to use lockstep by default. To disable this feature, first [disable it in PX4](https://docs.px4.io/master/en/simulation/#disable-lockstep-simulation): 1. Navigate to `boards/px4/sitl/` in your local PX4 repository 1. Edit `default.cmake` and find the following line: ``` set(ENABLE_LOCKSTEP_SCHEDULER yes) ``` 1. Change this line to: ``` set(ENABLE_LOCKSTEP_SCHEDULER no) ``` 1. Disable it in AirSim by setting `LockStep` to `false` and either removing any `"ClockType": "SteppableClock"` setting or resetting `ClockType` back to default: ``` { ... "ClockType": "", "Vehicles": { "PX4": { "VehicleType": "PX4Multirotor", "LockStep": false, ... ``` 1. Now you can run PX4 SITL as you normally would (`make px4_sitl_default none_iris`) and it will use the host system time without waiting on AirSim.
AirSim/docs/px4_lockstep.md/0
{ "file_path": "AirSim/docs/px4_lockstep.md", "repo_id": "AirSim", "token_count": 1028 }
56
# Creating and Setting Up Unreal Environment This page contains the complete instructions start to finish for setting up Unreal environment with AirSim. The Unreal Marketplace has [several environment](https://www.unrealengine.com/marketplace/content-cat/assets/environments) available that you can start using in just few minutes. It is also possible to use environments available on websites such as [turbosquid.com](https://www.turbosquid.com/) or [cgitrader.com](https://www.cgtrader.com/) with bit more effort (here's [tutorial video](https://www.youtube.com/watch?v=y09VbdQWvQY&feature)). In addition there also several [free environments](https://github.com/Microsoft/AirSim/issues/424) available. Below we will use a freely downloadable environment from Unreal Marketplace called Landscape Mountain but the steps are same for any other environments. ## Note for Linux Users There is no `Epic Games Launcher` for Linux which means that if you need to create custom environment, you will need Windows machine to do that. Once you have Unreal project folder, just copy it over to your Linux machine. ## Step by Step Instructions 1. Make sure AirSim is built and Unreal 4.27 is installed as described in [build instructions](build_windows.md). 1. In `Epic Games Launcher` click the Learn tab then scroll down and find `Landscape Mountains`. Click the `Create Project` and download this content (~2GB download). ![current version](images/landscape_mountains.png) 1. Open `LandscapeMountains.uproject`, it should launch the Unreal Editor. ![unreal editor](images/unreal_editor.png) !!!note The Landscape Mountains project is supported up to Unreal Engine version 4.24. If you do not have 4.24 installed, you should see a dialog titled `Select Unreal Engine Version` with a dropdown to select from installed versions. Select 4.27 or greater to migrate the project to a supported engine version. If you have 4.24 installed, you can manually migrate the project by navigating to the corresponding .uproject file in Windows Explorer, right-clicking it, and selecting the `Switch Unreal Engine version...` option. 1. From the `File menu` select `New C++ class`, leave default `None` on the type of class, click `Next`, leave default name `MyClass`, and click `Create Class`. We need to do this because Unreal requires at least one source file in project. It should trigger compile and open up Visual Studio solution `LandscapeMountains.sln`. 1. Go to your folder for AirSim repo and copy `Unreal\Plugins` folder in to your `LandscapeMountains` folder. This way now your own Unreal project has AirSim plugin. !!!note If the AirSim installation is fresh, i.e, hasn't been built before, make sure that you run `build.cmd` from the root directory once before copying `Unreal\Plugins` folder so that `AirLib` files are also included. If you have made some changes in the Blocks environment, make sure to run `update_to_git.bat` from `Unreal\Environments\Blocks` to update the files in `Unreal\Plugins`. 1. Edit the `LandscapeMountains.uproject` so that it looks like this ```json { "FileVersion": 3, "EngineAssociation": "4.27", "Category": "Samples", "Description": "", "Modules": [ { "Name": "LandscapeMountains", "Type": "Runtime", "LoadingPhase": "Default", "AdditionalDependencies": [ "AirSim" ] } ], "TargetPlatforms": [ "MacNoEditor", "WindowsNoEditor" ], "Plugins": [ { "Name": "AirSim", "Enabled": true } ] } ``` 1. Edit the `Config\DefaultGame.ini` to add the following line at the end: ``` +MapsToCook=(FilePath="/AirSim/AirSimAssets") ``` Doing this forces Unreal to include all necessary AirSim content in packaged builds of your project. 1. Close Visual Studio and the `Unreal Editor` and right click the LandscapeMountains.uproject in Windows Explorer and select `Generate Visual Studio Project Files`. This step detects all plugins and source files in your Unreal project and generates `.sln` file for Visual Studio. ![regen](images/regen_sln.png) !!!tip If the `Generate Visual Studio Project Files` option is missing you may need to reboot your machine for the Unreal Shell extensions to take effect. If it is still missing then open the LandscapeMountains.uproject in the Unreal Editor and select `Refresh Visual Studio Project` from the `File` menu. 1. Reopen `LandscapeMountains.sln` in Visual Studio, and make sure "DebugGame Editor" and "Win64" build configuration is the active build configuration. ![build config](images/vsbuild_config.png) 1. Press `F5` to `run`. This will start the Unreal Editor. The Unreal Editor allows you to edit the environment, assets and other game related settings. First thing you want to do in your environment is set up `PlayerStart` object. In Landscape Mountains environment, `PlayerStart` object already exist and you can find it in the `World Outliner`. Make sure its location is setup as shown. This is where AirSim plugin will create and place the vehicle. If its too high up then vehicle will fall down as soon as you press play giving potentially random behavior ![lm_player_start_pos.png](images/lm_player_start_pos.png) 1. In `Window/World Settings` as shown below, set the `GameMode Override` to `AirSimGameMode`: ![sim_game_mode.png](images/sim_game_mode.png) 1. Go to 'Edit->Editor Preferences' in Unreal Editor, in the 'Search' box type 'CPU' and ensure that the 'Use Less CPU when in Background' is unchecked. If you don't do this then UE will be slowed down dramatically when UE window loses focus. 1. Be sure to `Save` these edits. Hit the Play button in the Unreal Editor. See [how to use AirSim](https://github.com/Microsoft/AirSim/#how-to-use-it). Congratulations! You are now running AirSim in your own Unreal environment. ## Choosing Your Vehicle: Car or Multirotor By default AirSim prompts user for which vehicle to use. You can easily change this by setting [SimMode](settings.md#SimMode). Please see [using car](using_car.md) guide. ## Updating Your Environment to Latest Version of AirSim Once you have your environment using above instructions, you should frequently update your local AirSim code to latest version from GitHub. Below are the instructions to do this: 1. First put [clean.bat](https://github.com/Microsoft/AirSim/blob/main/Unreal/Environments/Blocks/clean.bat) (or [clean.sh](https://github.com/Microsoft/AirSim/blob/main/Unreal/Environments/Blocks/clean.sh) for Linux users) in the root folder of your environment. Run this file to clean up all intermediate files in your Unreal project. 2. Do `git pull` in your AirSim repo followed by `build.cmd` (or `./build.sh` for Linux users). 3. Replace [your project]/Plugins folder with AirSim/Unreal/Plugins folder. 4. Right click on your .uproject file and chose "Generate Visual Studio project files" option. This is not required for Linux. ## FAQ #### What are other cool environments? [Unreal Marketplace](https://www.unrealengine.com/marketplace) has dozens of prebuilt extra-ordinarily detailed [environments](https://www.unrealengine.com/marketplace/content-cat/assets/environments) ranging from Moon to Mars and everything in between. The one we have used for testing is called [Modular Neighborhood Pack](https://www.unrealengine.com/marketplace/modular-neighborhood-pack) but you can use any environment. Another free environment is [Infinity Blade series](https://www.unrealengine.com/marketplace/infinity-blade-plain-lands). Alternatively, if you look under the Learn tab in Epic Game Launcher, you will find many free samples that you can use. One of our favorites is "A Boy and His Kite" which is a 100 square miles of highly detailed environment (caution: you will need *very* beefy PC to run it!). #### When I press Play button some kind of video starts instead of my vehicle. If the environment comes with MatineeActor, delete it to avoid any startup demo sequences. There might be other ways to remove it as well, for example, click on Blueprints button, then Level Blueprint and then look at Begin Play event in Event Graph. You might want to disconnect any connections that may be starting "matinee". #### Is there easy way to sync code in my Unreal project with code in AirSim repo? Sure, there is! You can find bunch of `.bat` files (for linux, `.sh`) in `AirSim\Unreal\Environments\Blocks`. Just copy them over to your own Unreal project. Most of these are quite simple and self explanatory. #### I get some error about map. You might have to set default map for your project. For example, if you are using Modular Neighborhood Pack, set the Editor Starter Map as well as Game Default Map to Demo_Map in Project Settings > Maps & Modes. #### I see "Add to project" option for environment but not "Create project" option. In this case, create a new blank C++ project with no Starter Content and add your environment in to it. #### I already have my own Unreal project. How do I use AirSim with it? Copy the `Unreal\Plugins` folder from the build you did in the above section into the root of your Unreal project's folder. In your Unreal project's .uproject file, add the key `AdditionalDependencies` to the "Modules" object as we showed in the `LandscapeMountains.uproject` above. ```json "AdditionalDependencies": [ "AirSim" ] ``` and the `Plugins` section to the top level object: ```json "Plugins": [ { "Name": "AirSim", "Enabled": true } ] ```
AirSim/docs/unreal_custenv.md/0
{ "file_path": "AirSim/docs/unreal_custenv.md", "repo_id": "AirSim", "token_count": 2699 }
57
# airsim_ros_pkgs This page has moved [here](https://github.com/microsoft/AirSim/blob/main/docs/airsim_ros_pkgs.md).
AirSim/ros/src/airsim_ros_pkgs/README.md/0
{ "file_path": "AirSim/ros/src/airsim_ros_pkgs/README.md", "repo_id": "AirSim", "token_count": 45 }
58
std_msgs/Header header float32 throttle float32 brake float32 steering bool handbrake bool manual int8 manual_gear bool gear_immediate
AirSim/ros/src/airsim_ros_pkgs/msg/CarControls.msg/0
{ "file_path": "AirSim/ros/src/airsim_ros_pkgs/msg/CarControls.msg", "repo_id": "AirSim", "token_count": 39 }
59
bool waitOnLastTask --- bool success
AirSim/ros/src/airsim_ros_pkgs/srv/Land.srv/0
{ "file_path": "AirSim/ros/src/airsim_ros_pkgs/srv/Land.srv", "repo_id": "AirSim", "token_count": 11 }
60
{ "SeeDocsAt": "https://github.com/Microsoft/AirSim/blob/main/docs/settings.md", "SettingsVersion": 1.2, "SimMode": "Car", "ViewMode": "SpringArmChase", "ClockSpeed": 1.0, "Vehicles": { "drone_1": { "VehicleType": "PhysXCar", "DefaultVehicleState": "Armed", "EnableCollisionPassthrogh": false, "EnableCollisions": true, "AllowAPIAlways": true, "Sensors": { "Gps": { "SensorType": 3, "Enabled" : true }, "Barometer": { "SensorType": 1, "Enabled" : true }, "Magnetometer": { "SensorType": 4, "Enabled" : true }, "Imu" : { "SensorType": 2, "Enabled": true }, "LidarCustom": { "SensorType": 6, "Enabled": true, "NumberOfChannels": 16, "PointsPerSecond": 10000, "X": 0, "Y": 0, "Z": -1.5, "DrawDebugPoints": true, "DataFrame": "SensorLocalFrame" } }, "Cameras": { "front_center_custom": { "CaptureSettings": [ { "PublishToRos": 1, "ImageType": 0, "Width": 640, "Height": 480, "FOV_Degrees": 27, "DepthOfFieldFstop": 2.8, "DepthOfFieldFocalDistance": 200.0, "DepthOfFieldFocalRegion": 200.0, "TargetGamma": 1.5 } ], "X": 1.75, "Y": 0, "Z": -1.25, "Pitch": 0, "Roll": 0, "Yaw": 0 }, "front_left_custom": { "CaptureSettings": [ { "PublishToRos": 1, "ImageType": 0, "Width": 672, "Height": 376, "FOV_Degrees": 90, "TargetGamma": 1.5 }, { "PublishToRos": 1, "ImageType": 1, "Width": 672, "Height": 376, "FOV_Degrees": 90, "TargetGamma": 1.5 } ], "X": 1.75, "Y": -0.06, "Z": -1.25, "Pitch": 0.0, "Roll": 0.0, "Yaw": 0.0 }, "front_right_custom": { "CaptureSettings": [ { "PublishToRos": 1, "ImageType": 0, "Width": 672, "Height": 376, "FOV_Degrees": 90, "TargetGamma": 1.5 } ], "X": 1.75, "Y": 0.06, "Z": -1.25, "Pitch": 0.0, "Roll": 0.0, "Yaw": 0.0 } }, "X": 0, "Y": 0, "Z": 0, "Pitch": 0, "Roll": 0, "Yaw": 0 } }, "SubWindows": [ {"WindowID": 0, "ImageType": 0, "CameraName": "front_left_custom", "Visible": true}, {"WindowID": 1, "ImageType": 0, "CameraName": "front_center_custom", "Visible": false}, {"WindowID": 2, "ImageType": 0, "CameraName": "front_right_custom", "Visible": true} ] }
AirSim/ros/src/airsim_tutorial_pkgs/settings/car.json/0
{ "file_path": "AirSim/ros/src/airsim_tutorial_pkgs/settings/car.json", "repo_id": "AirSim", "token_count": 1791 }
61
string[] vehicle_names bool wait_on_last_task --- bool success
AirSim/ros2/src/airsim_interfaces/srv/LandGroup.srv/0
{ "file_path": "AirSim/ros2/src/airsim_interfaces/srv/LandGroup.srv", "repo_id": "AirSim", "token_count": 19 }
62
from launch import LaunchDescription from launch.actions import DeclareLaunchArgument def generate_launch_description(): ld = LaunchDescription([ DeclareLaunchArgument( "max_vel_vert_abs", default_value='10.0'), DeclareLaunchArgument( "max_vel_horz_abs", default_value='0.5'), DeclareLaunchArgument( "max_yaw_rate_degree", default_value='1.0'), DeclareLaunchArgument( "gimbal_front_center_max_pitch", default_value='40.0'), DeclareLaunchArgument( "gimbal_front_center_min_pitch", default_value='-130.0'), DeclareLaunchArgument( "gimbal_front_center_max_yaw", default_value='320.0'), DeclareLaunchArgument( "gimbal_front_center_min_yaw", default_value='-320.0'), DeclareLaunchArgument( "gimbal_front_center_min_yaw", default_value='20.0'), DeclareLaunchArgument( "gimbal_front_center_min_yaw", default_value='-20.0') ]) return ld
AirSim/ros2/src/airsim_ros_pkgs/launch/dynamic_constraints.launch.py/0
{ "file_path": "AirSim/ros2/src/airsim_ros_pkgs/launch/dynamic_constraints.launch.py", "repo_id": "AirSim", "token_count": 516 }
63
@echo off REM //---------- set up variable ---------- setlocal set ROOT_DIR=%~dp0 REM should rebuild? set RebuildAirSim=%1 REM root folder containing all Unreal projects you want to build set UnrealProjsPath=%2 REM Output folder where the builds would be stored set OutputPath=%3 REM folder containing AirSim repo set AirSimPath=%4 REM path for UE toolset set ToolPath=%5 REM set defaults if ars are not supplied if "%UnrealProjsPath%"=="" set "UnrealProjsPath=D:\vso\msresearch\Theseus" if "%AirSimPath%"=="" set "AirSimPath=C:\GitHubSrc\AirSim" if "%OutputPath%"=="" set "OutputPath=%ROOT_DIR%build" if "%RebuildAirSim%"=="" set "RebuildAirSim=true" REM re-build airsim if "%RebuildAirSim%"=="true" ( cd /D "%AirSimPath%" CALL clean CALL build if ERRORLEVEL 1 goto :failed cd /D "%ROOT_DIR%" ) IF NOT EXIST "%OutputPath%" mkdir "%OutputPath%" call:doOneProject "TalkingHeads" call:doOneProject "ZhangJiaJie" call:doOneProject "AirSimEnvNH" call:doOneProject "SimpleMaze" call:doOneProject "LandscapeMountains" call:doOneProject "Africa_001" "Africa" call:doOneProject "Forest" call:doOneProject "Coastline" call:doOneProject "TrapCamera" call:doOneProject "CityEnviron" call:doOneProject "Warehouse" call:doOneProject "Plains" "" 4.19 goto :done :doOneProject REM args: OutputPath ToolPath UEVer if "%~2"=="" ( cd /D "%UnrealProjsPath%\%~1" ) else ( cd /D "%UnrealProjsPath%\%~2" ) if ERRORLEVEL 1 goto :failed robocopy "%AirSimPath%\Unreal\Environments\Blocks" . *.bat /njh /njs /ndl /np CALL update_from_git.bat "%AirSimPath%" if ERRORLEVEL 1 goto :failed CALL package.bat "%OutputPath%" "%ToolPath%" %~3 if ERRORLEVEL 1 goto :failed goto :done :failed echo "Error occured while building all UE projects" exit /b 1 :done cd "%ROOT_DIR%" if "%1"=="" pause
AirSim/tools/build_all_ue_projects.bat/0
{ "file_path": "AirSim/tools/build_all_ue_projects.bat", "repo_id": "AirSim", "token_count": 659 }
64
// LzmaDecoder.cs using System; namespace SevenZip.Compression.LZMA { using RangeCoder; public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream { class LenDecoder { BitDecoder m_Choice = new BitDecoder(); BitDecoder m_Choice2 = new BitDecoder(); BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); uint m_NumPosStates = 0; public void Create(uint numPosStates) { for (uint posState = m_NumPosStates; posState < numPosStates; posState++) { m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); } m_NumPosStates = numPosStates; } public void Init() { m_Choice.Init(); for (uint posState = 0; posState < m_NumPosStates; posState++) { m_LowCoder[posState].Init(); m_MidCoder[posState].Init(); } m_Choice2.Init(); m_HighCoder.Init(); } public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) { if (m_Choice.Decode(rangeDecoder) == 0) return m_LowCoder[posState].Decode(rangeDecoder); else { uint symbol = Base.kNumLowLenSymbols; if (m_Choice2.Decode(rangeDecoder) == 0) symbol += m_MidCoder[posState].Decode(rangeDecoder); else { symbol += Base.kNumMidLenSymbols; symbol += m_HighCoder.Decode(rangeDecoder); } return symbol; } } } class LiteralDecoder { struct Decoder2 { BitDecoder[] m_Decoders; public void Create() { m_Decoders = new BitDecoder[0x300]; } public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) { uint symbol = 1; do symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); while (symbol < 0x100); return (byte)symbol; } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) { uint symbol = 1; do { uint matchBit = (uint)(matchByte >> 7) & 1; matchByte <<= 1; uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); break; } } while (symbol < 0x100); return (byte)symbol; } } Decoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = ((uint)1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); } public void Init() { uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } uint GetState(uint pos, byte prevByte) { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } }; LZ.OutWindow m_OutWindow = new LZ.OutWindow(); RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); uint m_DictionarySize; uint m_DictionarySizeCheck; uint m_PosStateMask; public Decoder() { m_DictionarySize = 0xFFFFFFFF; for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } void SetDictionarySize(uint dictionarySize) { if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); m_OutWindow.Create(blockSize); } } void SetLiteralProperties(int lp, int lc) { if (lp > 8) throw new InvalidParamException(); if (lc > 8) throw new InvalidParamException(); m_LiteralDecoder.Create(lp, lc); } void SetPosBitsProperties(int pb) { if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); uint numPosStates = (uint)1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; } bool _solid = false; void Init(System.IO.Stream inStream, System.IO.Stream outStream) { m_RangeDecoder.Init(inStream); m_OutWindow.Init(outStream, _solid); uint i; for (i = 0; i < Base.kNumStates; i++) { for (uint j = 0; j <= m_PosStateMask; j++) { uint index = (i << Base.kNumPosStatesBitsMax) + j; m_IsMatchDecoders[index].Init(); m_IsRep0LongDecoders[index].Init(); } m_IsRepDecoders[i].Init(); m_IsRepG0Decoders[i].Init(); m_IsRepG1Decoders[i].Init(); m_IsRepG2Decoders[i].Init(); } m_LiteralDecoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); // m_PosSpecDecoder.Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) m_PosDecoders[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); } public void Code(System.IO.Stream inStream, System.IO.Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { Init(inStream, outStream); Base.State state = new Base.State(); state.Init(); uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; UInt64 nowPos64 = 0; UInt64 outSize64 = (UInt64)outSize; if (nowPos64 < outSize64) { if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) throw new DataErrorException(); state.UpdateChar(); byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); m_OutWindow.PutByte(b); nowPos64++; } while (nowPos64 < outSize64) { // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); // while(nowPos64 < next) { uint posState = (uint)nowPos64 & m_PosStateMask; if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { byte b; byte prevByte = m_OutWindow.GetByte(0); if (!state.IsCharState()) b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); else b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); m_OutWindow.PutByte(b); state.UpdateChar(); nowPos64++; } else { uint len; if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) { if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) { if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { state.UpdateShortRep(); m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); nowPos64++; continue; } } else { UInt32 distance; if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) { distance = rep1; } else { if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state.UpdateRep(); } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state.UpdateMatch(); uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (int)((posSlot >> 1) - 1); rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); } } else rep0 = posSlot; } if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) { if (rep0 == 0xFFFFFFFF) break; throw new DataErrorException(); } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; } } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); } public void SetDecoderProperties(byte[] properties) { if (properties.Length < 5) throw new InvalidParamException(); int lc = properties[0] % 9; int remainder = properties[0] / 9; int lp = remainder % 5; int pb = remainder / 5; if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); UInt32 dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); SetDictionarySize(dictionarySize); SetLiteralProperties(lp, lc); SetPosBitsProperties(pb); } public bool Train(System.IO.Stream stream) { _solid = true; return m_OutWindow.Train(stream); } /* public override bool CanRead { get { return true; }} public override bool CanWrite { get { return true; }} public override bool CanSeek { get { return true; }} public override long Length { get { return 0; }} public override long Position { get { return 0; } set { } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override void Write(byte[] buffer, int offset, int count) { } public override long Seek(long offset, System.IO.SeekOrigin origin) { return 0; } public override void SetLength(long value) {} */ } }
AssetStudio/AssetStudio/7zip/Compress/LZMA/LzmaDecoder.cs/0
{ "file_path": "AssetStudio/AssetStudio/7zip/Compress/LZMA/LzmaDecoder.cs", "repo_id": "AssetStudio", "token_count": 5396 }
65
/* Copyright 2015 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ namespace Org.Brotli.Dec { /// <summary>Contains a collection of huffman trees with the same alphabet size.</summary> internal sealed class HuffmanTreeGroup { /// <summary>The maximal alphabet size in this group.</summary> private int alphabetSize; /// <summary>Storage for Huffman lookup tables.</summary> internal int[] codes; /// <summary> /// Offsets of distinct lookup tables in /// <see cref="codes"/> /// storage. /// </summary> internal int[] trees; /// <summary>Initializes the Huffman tree group.</summary> /// <param name="group">POJO to be initialised</param> /// <param name="alphabetSize">the maximal alphabet size in this group</param> /// <param name="n">number of Huffman codes</param> internal static void Init(Org.Brotli.Dec.HuffmanTreeGroup group, int alphabetSize, int n) { group.alphabetSize = alphabetSize; group.codes = new int[n * Org.Brotli.Dec.Huffman.HuffmanMaxTableSize]; group.trees = new int[n]; } /// <summary>Decodes Huffman trees from input stream and constructs lookup tables.</summary> /// <param name="group">target POJO</param> /// <param name="br">data source</param> internal static void Decode(Org.Brotli.Dec.HuffmanTreeGroup group, Org.Brotli.Dec.BitReader br) { int next = 0; int n = group.trees.Length; for (int i = 0; i < n; i++) { group.trees[i] = next; Org.Brotli.Dec.Decode.ReadHuffmanCode(group.alphabetSize, group.codes, next, br); next += Org.Brotli.Dec.Huffman.HuffmanMaxTableSize; } } } }
AssetStudio/AssetStudio/Brotli/HuffmanTreeGroup.cs/0
{ "file_path": "AssetStudio/AssetStudio/Brotli/HuffmanTreeGroup.cs", "repo_id": "AssetStudio", "token_count": 594 }
66
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public class AnimationClipOverride { public PPtr<AnimationClip> m_OriginalClip; public PPtr<AnimationClip> m_OverrideClip; public AnimationClipOverride(ObjectReader reader) { m_OriginalClip = new PPtr<AnimationClip>(reader); m_OverrideClip = new PPtr<AnimationClip>(reader); } } public sealed class AnimatorOverrideController : RuntimeAnimatorController { public PPtr<RuntimeAnimatorController> m_Controller; public AnimationClipOverride[] m_Clips; public AnimatorOverrideController(ObjectReader reader) : base(reader) { m_Controller = new PPtr<RuntimeAnimatorController>(reader); int numOverrides = reader.ReadInt32(); m_Clips = new AnimationClipOverride[numOverrides]; for (int i = 0; i < numOverrides; i++) { m_Clips[i] = new AnimationClipOverride(reader); } } } }
AssetStudio/AssetStudio/Classes/AnimatorOverrideController.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/AnimatorOverrideController.cs", "repo_id": "AssetStudio", "token_count": 467 }
67
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public sealed class MovieTexture : Texture { public byte[] m_MovieData; public PPtr<AudioClip> m_AudioClip; public MovieTexture(ObjectReader reader) : base(reader) { var m_Loop = reader.ReadBoolean(); reader.AlignStream(); m_AudioClip = new PPtr<AudioClip>(reader); m_MovieData = reader.ReadUInt8Array(); } } }
AssetStudio/AssetStudio/Classes/MovieTexture.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/MovieTexture.cs", "repo_id": "AssetStudio", "token_count": 231 }
68
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public class Transform : Component { public Quaternion m_LocalRotation; public Vector3 m_LocalPosition; public Vector3 m_LocalScale; public PPtr<Transform>[] m_Children; public PPtr<Transform> m_Father; public Transform(ObjectReader reader) : base(reader) { m_LocalRotation = reader.ReadQuaternion(); m_LocalPosition = reader.ReadVector3(); m_LocalScale = reader.ReadVector3(); int m_ChildrenCount = reader.ReadInt32(); m_Children = new PPtr<Transform>[m_ChildrenCount]; for (int i = 0; i < m_ChildrenCount; i++) { m_Children[i] = new PPtr<Transform>(reader); } m_Father = new PPtr<Transform>(reader); } } }
AssetStudio/AssetStudio/Classes/Transform.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/Transform.cs", "repo_id": "AssetStudio", "token_count": 414 }
69
using System; using System.Runtime.InteropServices; namespace AssetStudio { [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct Color : IEquatable<Color> { public float R; public float G; public float B; public float A; public Color(float r, float g, float b, float a) { R = r; G = g; B = b; A = a; } public override int GetHashCode() { return ((Vector4)this).GetHashCode(); } public override bool Equals(object other) { if (!(other is Color)) return false; return Equals((Color)other); } public bool Equals(Color other) { return R.Equals(other.R) && G.Equals(other.G) && B.Equals(other.B) && A.Equals(other.A); } public static Color operator +(Color a, Color b) { return new Color(a.R + b.R, a.G + b.G, a.B + b.B, a.A + b.A); } public static Color operator -(Color a, Color b) { return new Color(a.R - b.R, a.G - b.G, a.B - b.B, a.A - b.A); } public static Color operator *(Color a, Color b) { return new Color(a.R * b.R, a.G * b.G, a.B * b.B, a.A * b.A); } public static Color operator *(Color a, float b) { return new Color(a.R * b, a.G * b, a.B * b, a.A * b); } public static Color operator *(float b, Color a) { return new Color(a.R * b, a.G * b, a.B * b, a.A * b); } public static Color operator /(Color a, float b) { return new Color(a.R / b, a.G / b, a.B / b, a.A / b); } public static bool operator ==(Color lhs, Color rhs) { return (Vector4)lhs == (Vector4)rhs; } public static bool operator !=(Color lhs, Color rhs) { return !(lhs == rhs); } public static implicit operator Vector4(Color c) { return new Vector4(c.R, c.G, c.B, c.A); } } }
AssetStudio/AssetStudio/Math/Color.cs/0
{ "file_path": "AssetStudio/AssetStudio/Math/Color.cs", "repo_id": "AssetStudio", "token_count": 1146 }
70
using System; using System.IO; using SevenZip.Compression.LZMA; namespace AssetStudio { public static class SevenZipHelper { public static MemoryStream StreamDecompress(MemoryStream inStream) { var decoder = new Decoder(); inStream.Seek(0, SeekOrigin.Begin); var newOutStream = new MemoryStream(); var properties = new byte[5]; if (inStream.Read(properties, 0, 5) != 5) throw new Exception("input .lzma is too short"); long outSize = 0; for (var i = 0; i < 8; i++) { var v = inStream.ReadByte(); if (v < 0) throw new Exception("Can't Read 1"); outSize |= ((long)(byte)v) << (8 * i); } decoder.SetDecoderProperties(properties); var compressedSize = inStream.Length - inStream.Position; decoder.Code(inStream, newOutStream, compressedSize, outSize, null); newOutStream.Position = 0; return newOutStream; } public static void StreamDecompress(Stream compressedStream, Stream decompressedStream, long compressedSize, long decompressedSize) { var basePosition = compressedStream.Position; var decoder = new Decoder(); var properties = new byte[5]; if (compressedStream.Read(properties, 0, 5) != 5) throw new Exception("input .lzma is too short"); decoder.SetDecoderProperties(properties); decoder.Code(compressedStream, decompressedStream, compressedSize - 5, decompressedSize, null); compressedStream.Position = basePosition + compressedSize; } } }
AssetStudio/AssetStudio/SevenZipHelper.cs/0
{ "file_path": "AssetStudio/AssetStudio/SevenZipHelper.cs", "repo_id": "AssetStudio", "token_count": 782 }
71
#pragma once #include <fbxsdk.h> struct AsFbxMorphContext { FbxMesh* pMesh; FbxBlendShape* lBlendShape; FbxBlendShapeChannel* lBlendShapeChannel; FbxShape* lShape; AsFbxMorphContext(); ~AsFbxMorphContext() = default; };
AssetStudio/AssetStudioFBXNative/asfbx_morph_context.h/0
{ "file_path": "AssetStudio/AssetStudioFBXNative/asfbx_morph_context.h", "repo_id": "AssetStudio", "token_count": 107 }
72
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>WinExe</OutputType> <TargetFrameworks>net472;net5.0-windows;net6.0-windows</TargetFrameworks> <UseWindowsForms>true</UseWindowsForms> <ApplicationIcon>Resources\as.ico</ApplicationIcon> <Version>0.16.0.0</Version> <AssemblyVersion>0.16.0.0</AssemblyVersion> <FileVersion>0.16.0.0</FileVersion> <Copyright>Copyright © Perfare 2018-2022</Copyright> <DebugType>embedded</DebugType> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AssetStudioUtility\AssetStudioUtility.csproj" /> <ProjectReference Include="..\AssetStudio\AssetStudio.csproj" /> </ItemGroup> <ItemGroup> <None Include="Properties\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <LastGenOutput>Settings.Designer.cs</LastGenOutput> </None> <Compile Update="Properties\Settings.Designer.cs"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="Properties\Resources.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.cs</LastGenOutput> </EmbeddedResource> <Compile Update="Properties\Resources.Designer.cs"> <AutoGen>True</AutoGen> <DependentUpon>Resources.resx</DependentUpon> <DesignTime>True</DesignTime> </Compile> </ItemGroup> <ItemGroup> <ContentWithTargetPath Include="Libraries\x86\fmod.dll"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <TargetPath>x86\fmod.dll</TargetPath> </ContentWithTargetPath> <ContentWithTargetPath Include="Libraries\x64\fmod.dll"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <TargetPath>x64\fmod.dll</TargetPath> </ContentWithTargetPath> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' != 'net472' "> <PackageReference Include="OpenTK" Version="4.6.7" /> <Reference Include="OpenTK.WinForms"> <HintPath>Libraries\OpenTK.WinForms.dll</HintPath> </Reference> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'net472' "> <PackageReference Include="OpenTK" Version="3.1.0" /> <PackageReference Include="OpenTK.GLControl" Version="3.1.0" /> </ItemGroup> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> </ItemGroup> <Target Name="CopyExtraFiles" AfterTargets="AfterBuild"> <Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\Win32\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)x86" ContinueOnError="true" /> <Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\x64\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)x64" ContinueOnError="true" /> <Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\Win32\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)x86" ContinueOnError="true" /> <Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\x64\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)x64" ContinueOnError="true" /> </Target> <Target Name="PublishExtraFiles" AfterTargets="Publish"> <Copy SourceFiles="$(TargetDir)x86\AssetStudioFBXNative.dll" DestinationFolder="$(PublishDir)x86" ContinueOnError="true" /> <Copy SourceFiles="$(TargetDir)x64\AssetStudioFBXNative.dll" DestinationFolder="$(PublishDir)x64" ContinueOnError="true" /> <Copy SourceFiles="$(TargetDir)x86\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)x86" ContinueOnError="true" /> <Copy SourceFiles="$(TargetDir)x64\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)x64" ContinueOnError="true" /> </Target> </Project>
AssetStudio/AssetStudioGUI/AssetStudioGUI.csproj/0
{ "file_path": "AssetStudio/AssetStudioGUI/AssetStudioGUI.csproj", "repo_id": "AssetStudio", "token_count": 1325 }
73
using Mono.Cecil; namespace AssetStudio { public class MyAssemblyResolver : DefaultAssemblyResolver { public void Register(AssemblyDefinition assembly) { RegisterAssembly(assembly); } } }
AssetStudio/AssetStudioUtility/MyAssemblyResolver.cs/0
{ "file_path": "AssetStudio/AssetStudioUtility/MyAssemblyResolver.cs", "repo_id": "AssetStudio", "token_count": 97 }
74
#define T2D_API(ret_type)
AssetStudio/Texture2DDecoderNative/cpp.hint/0
{ "file_path": "AssetStudio/Texture2DDecoderNative/cpp.hint", "repo_id": "AssetStudio", "token_count": 13 }
75
#include "unitycrunch.h" #include <stdint.h> #include <algorithm> #include "unitycrunch/crn_decomp.h" bool unity_crunch_unpack_level(const uint8_t* data, uint32_t data_size, uint32_t level_index, void** ret, uint32_t* ret_size) { unitycrnd::crn_texture_info tex_info; if (!unitycrnd::crnd_get_texture_info(data, data_size, &tex_info)) { return false; } unitycrnd::crnd_unpack_context pContext = unitycrnd::crnd_unpack_begin(data, data_size); if (!pContext) { return false; } const crn_uint32 width = std::max(1U, tex_info.m_width >> level_index); const crn_uint32 height = std::max(1U, tex_info.m_height >> level_index); const crn_uint32 blocks_x = std::max(1U, (width + 3) >> 2); const crn_uint32 blocks_y = std::max(1U, (height + 3) >> 2); const crn_uint32 row_pitch = blocks_x * unitycrnd::crnd_get_bytes_per_dxt_block(tex_info.m_format); const crn_uint32 total_face_size = row_pitch * blocks_y; *ret = new uint8_t[total_face_size]; *ret_size = total_face_size; if (!unitycrnd::crnd_unpack_level(pContext, ret, total_face_size, row_pitch, level_index)) { unitycrnd::crnd_unpack_end(pContext); return false; } unitycrnd::crnd_unpack_end(pContext); return true; }
AssetStudio/Texture2DDecoderNative/unitycrunch.cpp/0
{ "file_path": "AssetStudio/Texture2DDecoderNative/unitycrunch.cpp", "repo_id": "AssetStudio", "token_count": 499 }
76
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>disable</Nullable> <LangVersion>12</LangVersion> <RootNamespace>ET</RootNamespace> <AssemblyName>ThirdParty</AssemblyName> </PropertyGroup> <PropertyGroup> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> <SatelliteResourceLanguages>en</SatelliteResourceLanguages> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DefineConstants>DOTNET;UNITY_DOTSPLAYER</DefineConstants> <OutputPath>..\..\Bin\</OutputPath> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Optimize>true</Optimize> <NoWarn>0169,0649,3021,8981,NU1903</NoWarn> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <DefineConstants>DOTNET;UNITY_DOTSPLAYER</DefineConstants> <OutputPath>..\..\Bin\</OutputPath> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <NoWarn>0169,0649,3021,8981,NU1903</NoWarn> </PropertyGroup> <ItemGroup> <Compile Include="..\..\Unity\Assets\Scripts\ThirdParty\TrueSync\**\*.cs"> <Link>TrueSync/%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\ThirdParty\ETTask\**\*.cs"> <Link>ETTask/%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\ThirdParty\Kcp\**\*.cs"> <Link>Kcp/%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\ThirdParty\NativeCollection\**\*.cs"> <Link>NativeCollection/%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\ThirdParty\DotRecast\**\*.cs"> <Link>DotRecast/%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Library\PackageCache\com.unity.mathematics*\Unity.Mathematics\**\*.cs"> <Link>Unity.Mathematics/$([System.String]::new(%(RecursiveDir)).Substring($([System.String]::new(%(RecursiveDir)).Indexof("Unity.Mathematics"))).Replace("Unity.Mathematics", ""))/%(FileName)%(Extension)</Link> </Compile> </ItemGroup> <ItemGroup> <PackageReference Include="CommandLineParser" Version="2.8.0" /> <PackageReference Include="EPPlus" Version="5.8.8" /> <PackageReference Include="MemoryPack" Version="1.10.0" /> <PackageReference Include="MongoDB.Driver" Version="2.17.1" /> <PackageReference Include="NLog" Version="4.7.15" /> <PackageReference Include="SharpZipLib" Version="1.3.3" /> <PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.0.1" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" /> </ItemGroup> </Project>
ET/DotNet/ThirdParty/DotNet.ThirdParty.csproj/0
{ "file_path": "ET/DotNet/ThirdParty/DotNet.ThirdParty.csproj", "repo_id": "ET", "token_count": 1363 }
77
using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace ET.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class EntityComponentAnalyzer:DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EntityComponentAnalyzerRule.Rule,DisableAccessEntityChildAnalyzerRule.Rule); public override void Initialize(AnalysisContext context) { if (!AnalyzerGlobalSetting.EnableAnalyzer) { return; } context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterCompilationStartAction((analysisContext => { if (AnalyzerHelper.IsAssemblyNeedAnalyze(analysisContext.Compilation.AssemblyName, AnalyzeAssembly.AllModelHotfix)) { analysisContext.RegisterSemanticModelAction((this.AnalyzeSemanticModel)); } } )); } private void AnalyzeSemanticModel(SemanticModelAnalysisContext analysisContext) { foreach (var memberAccessExpressionSyntax in analysisContext.SemanticModel.SyntaxTree.GetRoot().DescendantNodes<MemberAccessExpressionSyntax>()) { AnalyzeMemberAccessExpression(analysisContext, memberAccessExpressionSyntax); } } private void AnalyzeMemberAccessExpression(SemanticModelAnalysisContext context, MemberAccessExpressionSyntax memberAccessExpressionSyntax) { // 筛选出 Component函数syntax string methodName = memberAccessExpressionSyntax.Name.Identifier.Text; if (!Definition.ComponentMethod.Contains(methodName)) { return; } if (!(memberAccessExpressionSyntax?.Parent is InvocationExpressionSyntax invocationExpressionSyntax) || !(context.SemanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol addComponentMethodSymbol)) { return; } // 获取AComponent函数的调用者类型 ITypeSymbol? parentTypeSymbol = memberAccessExpressionSyntax.GetMemberAccessSyntaxParentType(context.SemanticModel); if (parentTypeSymbol==null) { return; } // 对于Entity基类会报错 除非标记了EnableAccessEntiyChild if (parentTypeSymbol.ToString() is Definition.EntityType or Definition.LSEntityType) { HandleAcessEntityChild(context,memberAccessExpressionSyntax); return; } // 非Entity的子类 跳过 if (parentTypeSymbol.BaseType?.ToString()!= Definition.EntityType && parentTypeSymbol.BaseType?.ToString()!= Definition.LSEntityType) { return; } // 获取 component实体类型 ISymbol? componentTypeSymbol = null; // Component为泛型调用 if (addComponentMethodSymbol.IsGenericMethod) { GenericNameSyntax? genericNameSyntax = memberAccessExpressionSyntax?.GetFirstChild<GenericNameSyntax>(); TypeArgumentListSyntax? typeArgumentList = genericNameSyntax?.GetFirstChild<TypeArgumentListSyntax>(); var componentTypeSyntax = typeArgumentList?.Arguments.First(); if (componentTypeSyntax == null) { Diagnostic diagnostic = Diagnostic.Create(EntityComponentAnalyzerRule.Rule, memberAccessExpressionSyntax?.Name.Identifier.GetLocation()); context.ReportDiagnostic(diagnostic); throw new Exception("componentTypeSyntax==null"); } componentTypeSymbol = context.SemanticModel.GetSymbolInfo(componentTypeSyntax).Symbol; } //Component为非泛型调用 else { SyntaxNode? firstArgumentSyntax = invocationExpressionSyntax.GetFirstChild<ArgumentListSyntax>()?.GetFirstChild<ArgumentSyntax>() ?.ChildNodes().First(); if (firstArgumentSyntax == null) { Diagnostic diagnostic = Diagnostic.Create(EntityComponentAnalyzerRule.Rule, memberAccessExpressionSyntax?.Name.Identifier.GetLocation()); context.ReportDiagnostic(diagnostic); return; } // 参数为typeOf时 提取Type类型 if (firstArgumentSyntax is TypeOfExpressionSyntax typeOfExpressionSyntax) { firstArgumentSyntax = typeOfExpressionSyntax.Type; } ISymbol? firstArgumentSymbol = context.SemanticModel.GetSymbolInfo(firstArgumentSyntax).Symbol; if (firstArgumentSymbol is ILocalSymbol childLocalSymbol) { componentTypeSymbol = childLocalSymbol.Type; } else if (firstArgumentSymbol is IParameterSymbol childParamaterSymbol) { componentTypeSymbol = childParamaterSymbol.Type; } else if (firstArgumentSymbol is IMethodSymbol methodSymbol) { componentTypeSymbol = methodSymbol.ReturnType; } else if (firstArgumentSymbol is IFieldSymbol fieldSymbol) { componentTypeSymbol = fieldSymbol.Type; } else if (firstArgumentSymbol is IPropertySymbol propertySymbol) { componentTypeSymbol = propertySymbol.Type; }else if (firstArgumentSymbol is INamedTypeSymbol namedTypeSymbol) { componentTypeSymbol = namedTypeSymbol; }else if (firstArgumentSymbol is ITypeParameterSymbol) { // 忽略typeof(T)参数类型 return; } else if (firstArgumentSymbol != null) { Diagnostic diagnostic = Diagnostic.Create(EntityComponentAnalyzerRule.Rule, memberAccessExpressionSyntax?.Name.Identifier.GetLocation(), firstArgumentSymbol.Name, parentTypeSymbol.Name); context.ReportDiagnostic(diagnostic); return; } else { Diagnostic diagnostic = Diagnostic.Create(EntityComponentAnalyzerRule.Rule, memberAccessExpressionSyntax?.Name.Identifier.GetLocation(), firstArgumentSyntax.GetText(), parentTypeSymbol.Name); context.ReportDiagnostic(diagnostic); return; } } if (componentTypeSymbol==null) { return; } // 忽略 component类型为泛型类型 if (componentTypeSymbol is ITypeParameterSymbol typeParameterSymbol) { return; } // 忽略 Type参数 if (componentTypeSymbol.ToString()=="System.Type") { return; } // 组件类型为Entity时 忽略检查 if (componentTypeSymbol.ToString() is Definition.EntityType or Definition.LSEntityType) { return; } // 判断component类型是否属于约束类型 //获取component类的parentType标记数据 INamedTypeSymbol? availableParentTypeSymbol = null; bool hasParentTypeAttribute = false; foreach (AttributeData? attributeData in componentTypeSymbol.GetAttributes()) { if (attributeData.AttributeClass?.ToString() == Definition.ComponentOfAttribute) { hasParentTypeAttribute = true; if (attributeData.ConstructorArguments[0].Value is INamedTypeSymbol typeSymbol) { availableParentTypeSymbol = typeSymbol; break; } } } if (hasParentTypeAttribute&&availableParentTypeSymbol==null) { return; } // 符合约束条件 通过检查 if (availableParentTypeSymbol!=null && availableParentTypeSymbol.ToString()==parentTypeSymbol.ToString()) { return; } { Diagnostic diagnostic = Diagnostic.Create(EntityComponentAnalyzerRule.Rule, memberAccessExpressionSyntax?.Name.Identifier.GetLocation(), componentTypeSymbol?.Name, parentTypeSymbol?.Name); context.ReportDiagnostic(diagnostic); } } private void HandleAcessEntityChild(SemanticModelAnalysisContext context, MemberAccessExpressionSyntax memberAccessExpressionSyntax) { //在方法体内 var methodDeclarationSyntax = memberAccessExpressionSyntax?.GetNeareastAncestor<MethodDeclarationSyntax>(); if (methodDeclarationSyntax!=null) { var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclarationSyntax); bool? enableAccessEntiyChild = methodSymbol?.GetAttributes().Any(x => x.AttributeClass?.ToString() == Definition.EnableAccessEntiyChildAttribute); if (enableAccessEntiyChild == null || !enableAccessEntiyChild.Value) { Diagnostic diagnostic = Diagnostic.Create(DisableAccessEntityChildAnalyzerRule.Rule, memberAccessExpressionSyntax?.Name.Identifier.GetLocation()); context.ReportDiagnostic(diagnostic); } return; } //在属性内 var propertyDeclarationSyntax = memberAccessExpressionSyntax?.GetNeareastAncestor<PropertyDeclarationSyntax>(); if (propertyDeclarationSyntax!=null) { var propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclarationSyntax); bool? enableAccessEntiyChild = propertySymbol?.GetAttributes().Any(x => x.AttributeClass?.ToString() == Definition.EnableAccessEntiyChildAttribute); if (enableAccessEntiyChild == null || !enableAccessEntiyChild.Value) { Diagnostic diagnostic = Diagnostic.Create(DisableAccessEntityChildAnalyzerRule.Rule, memberAccessExpressionSyntax?.Name.Identifier.GetLocation()); context.ReportDiagnostic(diagnostic); } return; } } } }
ET/Share/Analyzer/Analyzer/EntityComponentAnalyzer.cs/0
{ "file_path": "ET/Share/Analyzer/Analyzer/EntityComponentAnalyzer.cs", "repo_id": "ET", "token_count": 5567 }
78
namespace ET.Analyzer { public static class DiagnosticCategories { public const string Hotfix = "ETHotfixProjectAnalyzers"; public const string Model = "ETModelProjectAnalyzers"; public const string All = "ETAllProjectAnalyzers"; } }
ET/Share/Analyzer/Config/DiagnosticCategories.cs/0
{ "file_path": "ET/Share/Analyzer/Config/DiagnosticCategories.cs", "repo_id": "ET", "token_count": 96 }
79
mkdir -p build_linux64 && cd build_linux64 cmake ../ cd .. cmake --build build_linux64 --config Release cp build_linux64/RecastDll.so Plugins/x86_64/RecastDll.so rm -rf build_linux64
ET/Share/Libs/RecastDll/make_linux64.sh/0
{ "file_path": "ET/Share/Libs/RecastDll/make_linux64.sh", "repo_id": "ET", "token_count": 70 }
80
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>false</ImplicitUsings> <Nullable>disable</Nullable> <RootNamespace>ET</RootNamespace> <LangVersion>12</LangVersion> <PackageId>Apps.Tool</PackageId> <AssemblyName>Tool</AssemblyName> </PropertyGroup> <PropertyGroup> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> <SatelliteResourceLanguages>en</SatelliteResourceLanguages> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <OutputPath>..\..\Bin\</OutputPath> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DefineConstants>DOTNET</DefineConstants> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <OutputPath>..\..\Bin\</OutputPath> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DefineConstants>DOTNET</DefineConstants> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> </PropertyGroup> <ItemGroup> <Compile Include="..\..\Unity\Assets\Mono\Core\**\*.cs"> <Link>Core\%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\Model\Share\Module\Config\**\*.cs"> <Link>Module\Config\%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\Model\Share\Module\Log\**\*.cs"> <Link>Module\Log\%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\Core\Network\OpcodeRangeDefine.cs"> <Link>Module\Message\OpcodeRangeDefine.cs</Link> </Compile> </ItemGroup> <ItemGroup> <None Update="Template.txt"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\DotNet\Core\DotNet.Core.csproj" /> <ProjectReference Include="..\..\DotNet\ThirdParty\DotNet.ThirdParty.csproj" /> </ItemGroup> </Project>
ET/Share/Tool/Share.Tool.csproj/0
{ "file_path": "ET/Share/Tool/Share.Tool.csproj", "repo_id": "ET", "token_count": 999 }
81
uid = 0 gid = 0 use chroot = no max connections = 100 read only = no write only = no log file =/var/log/rsyncd.log fake super = yes [Upload] path = /home/ubuntu/ auth users = ubuntu secrets file = /etc/rsyncd.secrets list = yes
ET/Tools/cwRsync/Config/rsyncd.conf/0
{ "file_path": "ET/Tools/cwRsync/Config/rsyncd.conf", "repo_id": "ET", "token_count": 84 }
82
fileFormatVersion: 2 guid: ff3acf49577de0f44b9e1e1afc6f131e folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Bundles/Config.meta/0
{ "file_path": "ET/Unity/Assets/Bundles/Config.meta", "repo_id": "ET", "token_count": 72 }
83
fileFormatVersion: 2 guid: 3a57d524d1e0d7543828b2ac7273f608 folderAsset: yes timeCreated: 1487209399 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Bundles/UI.meta/0
{ "file_path": "ET/Unity/Assets/Bundles/UI.meta", "repo_id": "ET", "token_count": 77 }
84
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &1610378981859644 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4373147931430276} - component: {fileID: 114007285335791192} m_Layer: 0 m_Name: Unit m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4373147931430276 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1610378981859644} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &114007285335791192 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1610378981859644} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 502d8cafd6a5a0447ab1db9a24cdcb10, type: 3} m_Name: m_EditorClassIdentifier: data: - key: Skeleton gameObject: {fileID: 1248987324363926, guid: 9e27b0bdab1ad7242a009899d15c0e67, type: 3}
ET/Unity/Assets/Bundles/Unit/Unit.prefab/0
{ "file_path": "ET/Unity/Assets/Bundles/Unit/Unit.prefab", "repo_id": "ET", "token_count": 641 }
85
fileFormatVersion: 2 guid: c216baca1410ef044bfe845483e6f6e4 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Config/Excel/StartConfig/Localhost.meta/0
{ "file_path": "ET/Unity/Assets/Config/Excel/StartConfig/Localhost.meta", "repo_id": "ET", "token_count": 69 }
86
syntax = "proto3"; package ET; // ResponseType ObjectQueryResponse message ObjectQueryRequest // IRequest { int32 RpcId = 1; int64 Key = 2; int64 InstanceId = 3; } // ResponseType A2M_Reload message M2A_Reload // IRequest { int32 RpcId = 1; } message A2M_Reload // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; } // ResponseType G2G_LockResponse message G2G_LockRequest // IRequest { int32 RpcId = 1; int64 Id = 2; string Address = 3; } message G2G_LockResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; } // ResponseType G2G_LockReleaseResponse message G2G_LockReleaseRequest // IRequest { int32 RpcId = 1; int64 Id = 2; string Address = 3; } message G2G_LockReleaseResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; } // ResponseType ObjectAddResponse message ObjectAddRequest // IRequest { int32 RpcId = 1; int32 Type = 2; int64 Key = 3; ActorId ActorId = 4; } message ObjectAddResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; } // ResponseType ObjectLockResponse message ObjectLockRequest // IRequest { int32 RpcId = 1; int32 Type = 2; int64 Key = 3; ActorId ActorId = 4; int32 Time = 5; } message ObjectLockResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; } // ResponseType ObjectUnLockResponse message ObjectUnLockRequest // IRequest { int32 RpcId = 1; int32 Type = 2; int64 Key = 3; ActorId OldActorId = 4; ActorId NewActorId = 5; } message ObjectUnLockResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; } // ResponseType ObjectRemoveResponse message ObjectRemoveRequest // IRequest { int32 RpcId = 1; int32 Type = 2; int64 Key = 3; } message ObjectRemoveResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; } // ResponseType ObjectGetResponse message ObjectGetRequest // IRequest { int32 RpcId = 1; int32 Type = 2; int64 Key = 3; } message ObjectGetResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; int32 Type = 4; ActorId ActorId = 5; } // ResponseType G2R_GetLoginKey message R2G_GetLoginKey // IRequest { int32 RpcId = 1; string Account = 2; } message G2R_GetLoginKey // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; int64 Key = 4; int64 GateId = 5; } message G2M_SessionDisconnect // ILocationMessage { int32 RpcId = 1; } message ObjectQueryResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; bytes Entity = 4; } // ResponseType M2M_UnitTransferResponse message M2M_UnitTransferRequest // IRequest { int32 RpcId = 1; ActorId OldActorId = 2; bytes Unit = 3; repeated bytes Entitys = 4; } message M2M_UnitTransferResponse // IResponse { int32 RpcId = 1; int32 Error = 2; string Message = 3; }
ET/Unity/Assets/Config/Proto/InnerMessage_S_20001.proto/0
{ "file_path": "ET/Unity/Assets/Config/Proto/InnerMessage_S_20001.proto", "repo_id": "ET", "token_count": 1091 }
87
fileFormatVersion: 2 guid: 3638a874ef536fa4494da5c9c2c3256e folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Plugins/MongoDB/runtimes.meta/0
{ "file_path": "ET/Unity/Assets/Plugins/MongoDB/runtimes.meta", "repo_id": "ET", "token_count": 70 }
88
fileFormatVersion: 2 guid: faf34db9a0adfa5479844f8588715832 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Res/Mat.meta/0
{ "file_path": "ET/Unity/Assets/Res/Mat.meta", "repo_id": "ET", "token_count": 69 }
89
fileFormatVersion: 2 guid: aa7ffd1f629b75b4ca96a3a143abaedf NativeFormatImporter: externalObjects: {} mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Resources/YooAssetSettings.asset.meta/0
{ "file_path": "ET/Unity/Assets/Resources/YooAssetSettings.asset.meta", "repo_id": "ET", "token_count": 77 }
90
using System; using System.Collections.Generic; using MemoryPack; using MongoDB.Bson.Serialization.Attributes; namespace ET { [Flags] public enum EntityStatus: byte { None = 0, IsFromPool = 1, IsRegister = 1 << 1, IsComponent = 1 << 2, IsCreated = 1 << 3, IsNew = 1 << 4, } [MemoryPackable(GenerateType.NoGenerate)] public abstract partial class Entity: DisposeObject, IPool { #if ENABLE_VIEW && UNITY_EDITOR [BsonIgnore] [UnityEngine.HideInInspector] [MemoryPackIgnore] public UnityEngine.GameObject ViewGO; #endif [MemoryPackIgnore] [BsonIgnore] public long InstanceId { get; protected set; } protected Entity() { } [BsonIgnore] private EntityStatus status = EntityStatus.None; [MemoryPackIgnore] [BsonIgnore] public bool IsFromPool { get => (this.status & EntityStatus.IsFromPool) == EntityStatus.IsFromPool; set { if (value) { this.status |= EntityStatus.IsFromPool; } else { this.status &= ~EntityStatus.IsFromPool; } } } [BsonIgnore] protected bool IsRegister { get => (this.status & EntityStatus.IsRegister) == EntityStatus.IsRegister; set { if (this.IsRegister == value) { return; } if (value) { this.status |= EntityStatus.IsRegister; } else { this.status &= ~EntityStatus.IsRegister; } if (value) { this.RegisterSystem(); } #if ENABLE_VIEW && UNITY_EDITOR if (value) { this.ViewGO = new UnityEngine.GameObject(this.ViewName); this.ViewGO.AddComponent<ComponentView>().Component = this; this.ViewGO.transform.SetParent(this.Parent == null? UnityEngine.GameObject.Find("Global/Scenes").transform : this.Parent.ViewGO.transform); } else { UnityEngine.Object.Destroy(this.ViewGO); } #endif } } protected virtual void RegisterSystem() { this.iScene.Fiber.EntitySystem.RegisterSystem(this); } protected virtual string ViewName { get { return this.GetType().FullName; } } [BsonIgnore] protected bool IsComponent { get => (this.status & EntityStatus.IsComponent) == EntityStatus.IsComponent; set { if (value) { this.status |= EntityStatus.IsComponent; } else { this.status &= ~EntityStatus.IsComponent; } } } [BsonIgnore] protected bool IsCreated { get => (this.status & EntityStatus.IsCreated) == EntityStatus.IsCreated; set { if (value) { this.status |= EntityStatus.IsCreated; } else { this.status &= ~EntityStatus.IsCreated; } } } [BsonIgnore] protected bool IsNew { get => (this.status & EntityStatus.IsNew) == EntityStatus.IsNew; set { if (value) { this.status |= EntityStatus.IsNew; } else { this.status &= ~EntityStatus.IsNew; } } } [MemoryPackIgnore] [BsonIgnore] public bool IsDisposed => this.InstanceId == 0; [BsonIgnore] private Entity parent; // 可以改变parent,但是不能设置为null [MemoryPackIgnore] [BsonIgnore] public Entity Parent { get => this.parent; protected set { if (value == null) { throw new Exception($"cant set parent null: {this.GetType().FullName}"); } if (value == this) { throw new Exception($"cant set parent self: {this.GetType().FullName}"); } // 严格限制parent必须要有domain,也就是说parent必须在数据树上面 if (value.IScene == null) { throw new Exception($"cant set parent because parent domain is null: {this.GetType().FullName} {value.GetType().FullName}"); } if (this.parent != null) // 之前有parent { // parent相同,不设置 if (this.parent == value) { Log.Error($"重复设置了Parent: {this.GetType().FullName} parent: {this.parent.GetType().FullName}"); return; } this.parent.RemoveFromChildren(this); } this.parent = value; this.IsComponent = false; this.parent.AddToChildren(this); if (this is IScene scene) { scene.Fiber = this.parent.iScene.Fiber; this.IScene = scene; } else { this.IScene = this.parent.iScene; } #if ENABLE_VIEW && UNITY_EDITOR this.ViewGO.GetComponent<ComponentView>().Component = this; this.ViewGO.transform.SetParent(this.Parent == null ? UnityEngine.GameObject.Find("Global").transform : this.Parent.ViewGO.transform); foreach (var child in this.Children.Values) { child.ViewGO.transform.SetParent(this.ViewGO.transform); } foreach (var comp in this.Components.Values) { comp.ViewGO.transform.SetParent(this.ViewGO.transform); } #endif } } // 该方法只能在AddComponent中调用,其他人不允许调用 [BsonIgnore] private Entity ComponentParent { set { if (value == null) { throw new Exception($"cant set parent null: {this.GetType().FullName}"); } if (value == this) { throw new Exception($"cant set parent self: {this.GetType().FullName}"); } // 严格限制parent必须要有domain,也就是说parent必须在数据树上面 if (value.IScene == null) { throw new Exception($"cant set parent because parent domain is null: {this.GetType().FullName} {value.GetType().FullName}"); } if (this.parent != null) // 之前有parent { // parent相同,不设置 if (this.parent == value) { Log.Error($"重复设置了Parent: {this.GetType().FullName} parent: {this.parent.GetType().FullName}"); return; } this.parent.RemoveFromComponents(this); } this.parent = value; this.IsComponent = true; this.parent.AddToComponents(this); if (this is IScene scene) { scene.Fiber = this.parent.iScene.Fiber; this.IScene = scene; } else { this.IScene = this.parent.iScene; } } } public T GetParent<T>() where T : Entity { return this.Parent as T; } [BsonIgnoreIfDefault] [BsonDefaultValue(0L)] [BsonElement] [BsonId] public long Id { get; protected set; } [BsonIgnore] protected IScene iScene; [MemoryPackIgnore] [BsonIgnore] public IScene IScene { get { return this.iScene; } protected set { if (value == null) { throw new Exception($"domain cant set null: {this.GetType().FullName}"); } if (this.iScene == value) { return; } IScene preScene = this.iScene; this.iScene = value; if (preScene == null) { if (this.InstanceId == 0) { this.InstanceId = IdGenerater.Instance.GenerateInstanceId(); } this.IsRegister = true; // 反序列化出来的需要设置父子关系 if (this.componentsDB != null) { foreach (Entity component in this.componentsDB) { component.IsComponent = true; this.Components.Add(this.GetLongHashCode(component.GetType()), component); component.parent = this; } } if (this.childrenDB != null) { foreach (Entity child in this.childrenDB) { child.IsComponent = false; this.Children.Add(child.Id, child); child.parent = this; } } } // 递归设置孩子的Domain if (this.children != null) { foreach (Entity entity in this.children.Values) { entity.IScene = this.iScene; } } if (this.components != null) { foreach (Entity component in this.components.Values) { component.IScene = this.iScene; } } if (!this.IsCreated) { this.IsCreated = true; EntitySystemSingleton.Instance.Deserialize(this); } } } [MemoryPackInclude] [BsonElement("Children")] [BsonIgnoreIfNull] protected List<Entity> childrenDB; [BsonIgnore] private SortedDictionary<long, Entity> children; [MemoryPackIgnore] [BsonIgnore] public SortedDictionary<long, Entity> Children { get { return this.children ??= ObjectPool.Instance.Fetch<SortedDictionary<long, Entity>>(); } } private void AddToChildren(Entity entity) { this.Children.Add(entity.Id, entity); } private void RemoveFromChildren(Entity entity) { if (this.children == null) { return; } this.children.Remove(entity.Id); if (this.children.Count == 0) { ObjectPool.Instance.Recycle(this.children); this.children = null; } } [MemoryPackInclude] [BsonElement("C")] [BsonIgnoreIfNull] protected List<Entity> componentsDB; [BsonIgnore] private SortedDictionary<long, Entity> components; [MemoryPackIgnore] [BsonIgnore] public SortedDictionary<long, Entity> Components { get { return this.components ??= ObjectPool.Instance.Fetch<SortedDictionary<long, Entity>>(); } } public int ComponentsCount() { if (this.components == null) { return 0; } return this.components.Count; } public int ChildrenCount() { if (this.children == null) { return 0; } return this.children.Count; } public override void Dispose() { if (this.IsDisposed) { return; } this.IsRegister = false; this.InstanceId = 0; ObjectPool objectPool = ObjectPool.Instance; // 清理Children if (this.children != null) { foreach (Entity child in this.children.Values) { child.Dispose(); } this.children.Clear(); objectPool.Recycle(this.children); this.children = null; if (this.childrenDB != null) { this.childrenDB.Clear(); // 创建的才需要回到池中,从db中不需要回收 if (this.IsNew) { objectPool.Recycle(this.childrenDB); this.childrenDB = null; } } } // 清理Component if (this.components != null) { foreach (var kv in this.components) { kv.Value.Dispose(); } this.components.Clear(); objectPool.Recycle(this.components); this.components = null; // 创建的才需要回到池中,从db中不需要回收 if (this.componentsDB != null) { this.componentsDB.Clear(); if (this.IsNew) { objectPool.Recycle(this.componentsDB); this.componentsDB = null; } } } // 触发Destroy事件 if (this is IDestroy) { EntitySystemSingleton.Instance.Destroy(this); } this.iScene = null; if (this.parent != null && !this.parent.IsDisposed) { if (this.IsComponent) { this.parent.RemoveComponent(this); } else { this.parent.RemoveFromChildren(this); } } this.parent = null; base.Dispose(); // 把status字段其它的status标记都还原 bool isFromPool = this.IsFromPool; this.status = EntityStatus.None; this.IsFromPool = isFromPool; ObjectPool.Instance.Recycle(this); } private void AddToComponents(Entity component) { this.Components.Add(this.GetLongHashCode(component.GetType()), component); } private void RemoveFromComponents(Entity component) { if (this.components == null) { return; } this.components.Remove(this.GetLongHashCode(component.GetType())); if (this.components.Count == 0) { ObjectPool.Instance.Recycle(this.components); this.components = null; } } public K GetChild<K>(long id) where K : Entity { if (this.children == null) { return null; } this.children.TryGetValue(id, out Entity child); return child as K; } public void RemoveChild(long id) { if (this.children == null) { return; } if (!this.children.TryGetValue(id, out Entity child)) { return; } this.children.Remove(id); child.Dispose(); } public void RemoveComponent<K>() where K : Entity { if (this.IsDisposed) { return; } if (this.components == null) { return; } Type type = typeof (K); Entity c; if (!this.components.TryGetValue(this.GetLongHashCode(type), out c)) { return; } this.RemoveFromComponents(c); c.Dispose(); } private void RemoveComponent(Entity component) { if (this.IsDisposed) { return; } if (this.components == null) { return; } Entity c; if (!this.components.TryGetValue(this.GetLongHashCode(component.GetType()), out c)) { return; } if (c.InstanceId != component.InstanceId) { return; } this.RemoveFromComponents(c); c.Dispose(); } public void RemoveComponent(Type type) { if (this.IsDisposed) { return; } Entity c; if (!this.components.TryGetValue(this.GetLongHashCode(type), out c)) { return; } RemoveFromComponents(c); c.Dispose(); } public K GetComponent<K>() where K : Entity { if (this.components == null) { return null; } // 如果有IGetComponent接口,则触发GetComponentSystem if (this is IGetComponentSys) { EntitySystemSingleton.Instance.GetComponentSys(this, typeof(K)); } Entity component; if (!this.components.TryGetValue(this.GetLongHashCode(typeof (K)), out component)) { return default; } return (K) component; } public Entity GetComponent(Type type) { if (this.components == null) { return null; } // 如果有IGetComponent接口,则触发GetComponentSystem // 这个要在tryget之前调用,因为有可能components没有,但是执行GetComponentSystem后又有了 if (this is IGetComponentSys) { EntitySystemSingleton.Instance.GetComponentSys(this, type); } Entity component; if (!this.components.TryGetValue(this.GetLongHashCode(type), out component)) { return null; } return component; } private static Entity Create(Type type, bool isFromPool) { Entity component; if (isFromPool) { component = (Entity) ObjectPool.Instance.Fetch(type); } else { component = Activator.CreateInstance(type) as Entity; } component.IsFromPool = isFromPool; component.IsCreated = true; component.IsNew = true; component.Id = 0; return component; } public Entity AddComponent(Entity component) { Type type = component.GetType(); if (this.components != null && this.components.ContainsKey(this.GetLongHashCode(type))) { throw new Exception($"entity already has component: {type.FullName}"); } component.ComponentParent = this; return component; } public Entity AddComponent(Type type, bool isFromPool = false) { if (this.components != null && this.components.ContainsKey(this.GetLongHashCode(type))) { throw new Exception($"entity already has component: {type.FullName}"); } Entity component = Create(type, isFromPool); component.Id = this.Id; component.ComponentParent = this; EntitySystemSingleton entitySystemSingleton = EntitySystemSingleton.Instance; entitySystemSingleton.Awake(component); return component; } public K AddComponentWithId<K>(long id, bool isFromPool = false) where K : Entity, IAwake, new() { Type type = typeof (K); if (this.components != null && this.components.ContainsKey(this.GetLongHashCode(type))) { throw new Exception($"entity already has component: {type.FullName}"); } Entity component = Create(type, isFromPool); component.Id = id; component.ComponentParent = this; EntitySystemSingleton entitySystemSingleton = EntitySystemSingleton.Instance; entitySystemSingleton.Awake(component); return component as K; } public K AddComponentWithId<K, P1>(long id, P1 p1, bool isFromPool = false) where K : Entity, IAwake<P1>, new() { Type type = typeof (K); if (this.components != null && this.components.ContainsKey(this.GetLongHashCode(type))) { throw new Exception($"entity already has component: {type.FullName}"); } Entity component = Create(type, isFromPool); component.Id = id; component.ComponentParent = this; EntitySystemSingleton entitySystemSingleton = EntitySystemSingleton.Instance; entitySystemSingleton.Awake(component, p1); return component as K; } public K AddComponentWithId<K, P1, P2>(long id, P1 p1, P2 p2, bool isFromPool = false) where K : Entity, IAwake<P1, P2>, new() { Type type = typeof (K); if (this.components != null && this.components.ContainsKey(this.GetLongHashCode(type))) { throw new Exception($"entity already has component: {type.FullName}"); } Entity component = Create(type, isFromPool); component.Id = id; component.ComponentParent = this; EntitySystemSingleton entitySystemSingleton = EntitySystemSingleton.Instance; entitySystemSingleton.Awake(component, p1, p2); return component as K; } public K AddComponentWithId<K, P1, P2, P3>(long id, P1 p1, P2 p2, P3 p3, bool isFromPool = false) where K : Entity, IAwake<P1, P2, P3>, new() { Type type = typeof (K); if (this.components != null && this.components.ContainsKey(this.GetLongHashCode(type))) { throw new Exception($"entity already has component: {type.FullName}"); } Entity component = Create(type, isFromPool); component.Id = id; component.ComponentParent = this; EntitySystemSingleton entitySystemSingleton = EntitySystemSingleton.Instance; entitySystemSingleton.Awake(component, p1, p2, p3); return component as K; } public K AddComponent<K>(bool isFromPool = false) where K : Entity, IAwake, new() { return this.AddComponentWithId<K>(this.Id, isFromPool); } public K AddComponent<K, P1>(P1 p1, bool isFromPool = false) where K : Entity, IAwake<P1>, new() { return this.AddComponentWithId<K, P1>(this.Id, p1, isFromPool); } public K AddComponent<K, P1, P2>(P1 p1, P2 p2, bool isFromPool = false) where K : Entity, IAwake<P1, P2>, new() { return this.AddComponentWithId<K, P1, P2>(this.Id, p1, p2, isFromPool); } public K AddComponent<K, P1, P2, P3>(P1 p1, P2 p2, P3 p3, bool isFromPool = false) where K : Entity, IAwake<P1, P2, P3>, new() { return this.AddComponentWithId<K, P1, P2, P3>(this.Id, p1, p2, p3, isFromPool); } public Entity AddChild(Entity entity) { entity.Parent = this; return entity; } public T AddChild<T>(bool isFromPool = false) where T : Entity, IAwake { Type type = typeof (T); T component = (T) Entity.Create(type, isFromPool); component.Id = IdGenerater.Instance.GenerateId(); component.Parent = this; EntitySystemSingleton.Instance.Awake(component); return component; } public T AddChild<T, A>(A a, bool isFromPool = false) where T : Entity, IAwake<A> { Type type = typeof (T); T component = (T) Entity.Create(type, isFromPool); component.Id = IdGenerater.Instance.GenerateId(); component.Parent = this; EntitySystemSingleton.Instance.Awake(component, a); return component; } public T AddChild<T, A, B>(A a, B b, bool isFromPool = false) where T : Entity, IAwake<A, B> { Type type = typeof (T); T component = (T) Entity.Create(type, isFromPool); component.Id = IdGenerater.Instance.GenerateId(); component.Parent = this; EntitySystemSingleton.Instance.Awake(component, a, b); return component; } public T AddChild<T, A, B, C>(A a, B b, C c, bool isFromPool = false) where T : Entity, IAwake<A, B, C> { Type type = typeof (T); T component = (T) Entity.Create(type, isFromPool); component.Id = IdGenerater.Instance.GenerateId(); component.Parent = this; EntitySystemSingleton.Instance.Awake(component, a, b, c); return component; } public T AddChildWithId<T>(long id, bool isFromPool = false) where T : Entity, IAwake { Type type = typeof (T); T component = Entity.Create(type, isFromPool) as T; component.Id = id; component.Parent = this; EntitySystemSingleton.Instance.Awake(component); return component; } public T AddChildWithId<T, A>(long id, A a, bool isFromPool = false) where T : Entity, IAwake<A> { Type type = typeof (T); T component = (T) Entity.Create(type, isFromPool); component.Id = id; component.Parent = this; EntitySystemSingleton.Instance.Awake(component, a); return component; } public T AddChildWithId<T, A, B>(long id, A a, B b, bool isFromPool = false) where T : Entity, IAwake<A, B> { Type type = typeof (T); T component = (T) Entity.Create(type, isFromPool); component.Id = id; component.Parent = this; EntitySystemSingleton.Instance.Awake(component, a, b); return component; } public T AddChildWithId<T, A, B, C>(long id, A a, B b, C c, bool isFromPool = false) where T : Entity, IAwake<A, B, C> { Type type = typeof (T); T component = (T) Entity.Create(type, isFromPool); component.Id = id; component.Parent = this; EntitySystemSingleton.Instance.Awake(component, a, b, c); return component; } protected virtual long GetLongHashCode(Type type) { return type.TypeHandle.Value.ToInt64(); } public override void BeginInit() { EntitySystemSingleton.Instance.Serialize(this); if (!this.IsCreated) return; this.componentsDB?.Clear(); if (this.components != null && this.components.Count != 0) { ObjectPool objectPool = ObjectPool.Instance; foreach (Entity entity in this.components.Values) { if (entity is not ISerializeToEntity) { continue; } this.componentsDB ??= objectPool.Fetch<List<Entity>>(); this.componentsDB.Add(entity); entity.BeginInit(); } } this.childrenDB?.Clear(); if (this.children != null && this.children.Count != 0) { ObjectPool objectPool = ObjectPool.Instance; foreach (Entity entity in this.children.Values) { if (entity is not ISerializeToEntity) { continue; } this.childrenDB ??= objectPool.Fetch<List<Entity>>(); this.childrenDB.Add(entity); entity.BeginInit(); } } } } }
ET/Unity/Assets/Scripts/Core/Entity/Entity.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/Entity.cs", "repo_id": "ET", "token_count": 16852 }
91
using System; namespace ET { public interface IDestroy { } public interface IDestroySystem: ISystemType { void Run(Entity o); } [EntitySystem] public abstract class DestroySystem<T> : SystemObject, IDestroySystem where T: Entity, IDestroy { void IDestroySystem.Run(Entity o) { this.Destroy((T)o); } Type ISystemType.SystemType() { return typeof(IDestroySystem); } int ISystemType.GetInstanceQueueIndex() { return InstanceQueueIndex.None; } Type ISystemType.Type() { return typeof(T); } protected abstract void Destroy(T self); } }
ET/Unity/Assets/Scripts/Core/Entity/IDestroySystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/IDestroySystem.cs", "repo_id": "ET", "token_count": 234 }
92
using System; namespace ET { public interface IUpdate { } public interface IUpdateSystem: ISystemType { void Run(Entity o); } [EntitySystem] public abstract class UpdateSystem<T> : SystemObject, IUpdateSystem where T: Entity, IUpdate { void IUpdateSystem.Run(Entity o) { this.Update((T)o); } Type ISystemType.Type() { return typeof(T); } Type ISystemType.SystemType() { return typeof(IUpdateSystem); } int ISystemType.GetInstanceQueueIndex() { return InstanceQueueIndex.Update; } protected abstract void Update(T self); } }
ET/Unity/Assets/Scripts/Core/Entity/IUpdateSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/IUpdateSystem.cs", "repo_id": "ET", "token_count": 228 }
93
using System; using System.Collections.Generic; namespace ET { [EntitySystemOf(typeof(CoroutineLockComponent))] public static partial class CoroutineLockComponentSystem { [EntitySystem] public static void Awake(this CoroutineLockComponent self) { } [EntitySystem] public static void Update(this CoroutineLockComponent self) { // 循环过程中会有对象继续加入队列 while (self.nextFrameRun.Count > 0) { (int coroutineLockType, long key, int count) = self.nextFrameRun.Dequeue(); self.Notify(coroutineLockType, key, count); } } public static void RunNextCoroutine(this CoroutineLockComponent self, int coroutineLockType, long key, int level) { // 一个协程队列一帧处理超过100个,说明比较多了,打个warning,检查一下是否够正常 if (level == 100) { Log.Warning($"too much coroutine level: {coroutineLockType} {key}"); } self.nextFrameRun.Enqueue((coroutineLockType, key, level)); } public static async ETTask<CoroutineLock> Wait(this CoroutineLockComponent self, int coroutineLockType, long key, int time = 60000) { CoroutineLockQueueType coroutineLockQueueType = self.GetChild<CoroutineLockQueueType>(coroutineLockType) ?? self.AddChildWithId<CoroutineLockQueueType>(coroutineLockType); return await coroutineLockQueueType.Wait(key, time); } private static void Notify(this CoroutineLockComponent self, int coroutineLockType, long key, int level) { CoroutineLockQueueType coroutineLockQueueType = self.GetChild<CoroutineLockQueueType>(coroutineLockType); if (coroutineLockQueueType == null) { return; } coroutineLockQueueType.Notify(key, level); } } [ComponentOf(typeof(Scene))] public class CoroutineLockComponent: Entity, IAwake, IScene, IUpdate { public Fiber Fiber { get; set; } public SceneType SceneType { get; set; } public readonly Queue<(int, long, int)> nextFrameRun = new(); } }
ET/Unity/Assets/Scripts/Core/Fiber/Module/CoroutineLock/CoroutineLockComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Fiber/Module/CoroutineLock/CoroutineLockComponent.cs", "repo_id": "ET", "token_count": 1035 }
94
using System.IO; using System.Security.Cryptography; namespace ET { public static class MD5Helper { public static string FileMD5(string filePath) { byte[] retVal; using (FileStream file = new FileStream(filePath, FileMode.Open)) { MD5 md5 = MD5.Create(); retVal = md5.ComputeHash(file); } return retVal.ToHex("x2"); } } }
ET/Unity/Assets/Scripts/Core/Helper/MD5Helper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Helper/MD5Helper.cs", "repo_id": "ET", "token_count": 175 }
95
using System.IO; using ICSharpCode.SharpZipLib.Zip.Compression; namespace ET { public static class ZipHelper { public static byte[] Compress(byte[] content) { //return content; Deflater compressor = new Deflater(); compressor.SetLevel(Deflater.BEST_COMPRESSION); compressor.SetInput(content); compressor.Finish(); using (MemoryStream bos = new MemoryStream(content.Length)) { var buf = new byte[1024]; while (!compressor.IsFinished) { int n = compressor.Deflate(buf); bos.Write(buf, 0, n); } return bos.ToArray(); } } public static byte[] Decompress(byte[] content) { return Decompress(content, 0, content.Length); } public static byte[] Decompress(byte[] content, int offset, int count) { //return content; Inflater decompressor = new Inflater(); decompressor.SetInput(content, offset, count); using (MemoryStream bos = new MemoryStream(content.Length)) { var buf = new byte[1024]; while (!decompressor.IsFinished) { int n = decompressor.Inflate(buf); bos.Write(buf, 0, n); } return bos.ToArray(); } } } } /* using System.IO; using System.IO.Compression; namespace ET { public static class ZipHelper { public static byte[] Compress(byte[] content) { using (MemoryStream ms = new MemoryStream()) using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Compress, true)) { stream.Write(content, 0, content.Length); return ms.ToArray(); } } public static byte[] Decompress(byte[] content) { return Decompress(content, 0, content.Length); } public static byte[] Decompress(byte[] content, int offset, int count) { using (MemoryStream ms = new MemoryStream()) using (DeflateStream stream = new DeflateStream(new MemoryStream(content, offset, count), CompressionMode.Decompress, true)) { byte[] buffer = new byte[1024]; while (true) { int bytesRead = stream.Read(buffer, 0, 1024); if (bytesRead == 0) { break; } ms.Write(buffer, 0, bytesRead); } return ms.ToArray(); } } } } */
ET/Unity/Assets/Scripts/Core/Helper/ZipHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Helper/ZipHelper.cs", "repo_id": "ET", "token_count": 851 }
96
using System; using System.IO; using System.Net; namespace ET { public enum ChannelType { Connect, Accept, } public struct Packet { public const int MinPacketSize = 2; public const int OpcodeLength = 2; public const int ActorIdIndex = 0; public const int ActorIdLength = 16; public ushort Opcode; public long ActorId; public MemoryStream MemoryStream; } public abstract class AChannel: IDisposable { public long Id; public ChannelType ChannelType { get; protected set; } public int Error { get; set; } private IPEndPoint remoteAddress; public IPEndPoint RemoteAddress { get { return this.remoteAddress; } set { this.remoteAddress = value; } } public bool IsDisposed { get { return this.Id == 0; } } public abstract void Dispose(); } }
ET/Unity/Assets/Scripts/Core/Network/AChannel.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/AChannel.cs", "repo_id": "ET", "token_count": 551 }
97
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; namespace ET { public class KChannel : AChannel { private const int MaxKcpMessageSize = 10000; private readonly KService Service; private Kcp kcp { get; set; } private readonly Queue<MemoryBuffer> waitSendMessages = new(); public readonly uint CreateTime; public uint LocalConn { get { return (uint)this.Id; } private set { this.Id = value; } } public uint RemoteConn { get; set; } private readonly byte[] sendCache = new byte[2 * 1024]; public bool IsConnected { get; set; } public string RealAddress { get; set; } private MemoryBuffer readMemory; private int needReadSplitCount; private void InitKcp() { switch (this.Service.ServiceType) { case ServiceType.Inner: this.kcp.SetNoDelay(1, 10, 2, true); this.kcp.SetWindowSize(1024, 1024); this.kcp.SetMtu(1400); // 默认1400 this.kcp.SetMinrto(30); this.kcp.SetArrayPool(this.Service.byteArrayPool); break; case ServiceType.Outer: this.kcp.SetNoDelay(1, 10, 2, true); this.kcp.SetWindowSize(256, 256); this.kcp.SetMtu(470); this.kcp.SetMinrto(30); this.kcp.SetArrayPool(this.Service.byteArrayPool); break; } } // connect public KChannel(uint localConn, IPEndPoint remoteEndPoint, KService kService) { this.Service = kService; this.LocalConn = localConn; this.ChannelType = ChannelType.Connect; Log.Info($"channel create: {this.LocalConn} {remoteEndPoint} {this.ChannelType}"); this.RemoteAddress = remoteEndPoint; this.CreateTime = kService.TimeNow; this.Connect(this.CreateTime); } // accept public KChannel(uint localConn, uint remoteConn, IPEndPoint remoteEndPoint, KService kService) { this.Service = kService; this.ChannelType = ChannelType.Accept; Log.Info($"channel create: {localConn} {remoteConn} {remoteEndPoint} {this.ChannelType}"); this.LocalConn = localConn; this.RemoteConn = remoteConn; this.RemoteAddress = remoteEndPoint; this.kcp = new Kcp(this.RemoteConn, this.Output); this.InitKcp(); this.CreateTime = kService.TimeNow; } public override void Dispose() { if (this.IsDisposed) { return; } uint localConn = this.LocalConn; uint remoteConn = this.RemoteConn; Log.Info($"channel dispose: {localConn} {remoteConn} {this.Error}"); long id = this.Id; this.Id = 0; this.Service.Remove(id); try { if (this.Error != ErrorCore.ERR_PeerDisconnect) { this.Service.Disconnect(localConn, remoteConn, this.Error, this.RemoteAddress, 3); } } catch (Exception e) { Log.Error(e); } this.kcp = null; } public void HandleConnnect() { // 如果连接上了就不用处理了 if (this.IsConnected) { return; } this.kcp = new Kcp(this.RemoteConn, this.Output); this.InitKcp(); Log.Info($"channel connected: {this.LocalConn} {this.RemoteConn} {this.RemoteAddress}"); this.IsConnected = true; while (true) { if (this.waitSendMessages.Count <= 0) { break; } MemoryBuffer buffer = this.waitSendMessages.Dequeue(); this.Send(buffer); } } private long lastConnectTime = long.MaxValue; /// <summary> /// 发送请求连接消息 /// </summary> private void Connect(uint timeNow) { try { if (this.IsConnected) { return; } // 300毫秒后再次update发送connect请求 if (timeNow < this.lastConnectTime + 300) { this.Service.AddToUpdate(300, this.Id); return; } // 10秒连接超时 if (timeNow > this.CreateTime + KService.ConnectTimeoutTime) { Log.Error($"kChannel connect timeout: {this.Id} {this.RemoteConn} {timeNow} {this.CreateTime} {this.ChannelType} {this.RemoteAddress}"); this.OnError(ErrorCore.ERR_KcpConnectTimeout); return; } byte[] buffer = sendCache; buffer.WriteTo(0, KcpProtocalType.SYN); buffer.WriteTo(1, this.LocalConn); buffer.WriteTo(5, this.RemoteConn); this.Service.Transport.Send(buffer, 0, 9, this.RemoteAddress); // 这里很奇怪 调用socket.LocalEndPoint会动到this.RemoteAddressNonAlloc里面的temp,这里就不仔细研究了 Log.Info($"kchannel connect {this.LocalConn} {this.RemoteConn} {this.RealAddress}"); this.lastConnectTime = timeNow; this.Service.AddToUpdate(300, this.Id); } catch (Exception e) { Log.Error(e); this.OnError(ErrorCore.ERR_SocketCantSend); } } public void Update(uint timeNow) { if (this.IsDisposed) { return; } // 如果还没连接上,发送连接请求 if (!this.IsConnected && this.ChannelType == ChannelType.Connect) { this.Connect(timeNow); return; } if (this.kcp == null) { return; } try { this.kcp.Update(timeNow); } catch (Exception e) { Log.Error(e); this.OnError(ErrorCore.ERR_SocketError); return; } uint nextUpdateTime = this.kcp.Check(timeNow); this.Service.AddToUpdate(nextUpdateTime, this.Id); } public void HandleRecv(byte[] date, int offset, int length) { if (this.IsDisposed) { return; } this.kcp.Input(date.AsSpan(offset, length)); this.Service.AddToUpdate(0, this.Id); while (true) { if (this.IsDisposed) { break; } int n = this.kcp.PeekSize(); if (n < 0) { break; } if (n == 0) { this.OnError((int)SocketError.NetworkReset); return; } if (this.needReadSplitCount > 0) // 说明消息分片了 { byte[] buffer = readMemory.GetBuffer(); int count = this.kcp.Receive(buffer.AsSpan((int)(this.readMemory.Length - this.needReadSplitCount), n)); this.needReadSplitCount -= count; if (n != count) { Log.Error($"kchannel read error1: {this.LocalConn} {this.RemoteConn}"); this.OnError(ErrorCore.ERR_KcpReadNotSame); return; } if (this.needReadSplitCount < 0) { Log.Error($"kchannel read error2: {this.LocalConn} {this.RemoteConn}"); this.OnError(ErrorCore.ERR_KcpSplitError); return; } // 没有读完 if (this.needReadSplitCount != 0) { continue; } } else { this.readMemory = this.Service.Fetch(n); this.readMemory.SetLength(n); this.readMemory.Seek(0, SeekOrigin.Begin); byte[] buffer = readMemory.GetBuffer(); int count = this.kcp.Receive(buffer.AsSpan(0, n)); if (n != count) { break; } // 判断是不是分片 if (n == 8) { int headInt = BitConverter.ToInt32(this.readMemory.GetBuffer(), 0); if (headInt == 0) { this.needReadSplitCount = BitConverter.ToInt32(readMemory.GetBuffer(), 4); if (this.needReadSplitCount <= MaxKcpMessageSize) { Log.Error($"kchannel read error3: {this.needReadSplitCount} {this.LocalConn} {this.RemoteConn}"); this.OnError(ErrorCore.ERR_KcpSplitCountError); return; } this.readMemory.SetLength(this.needReadSplitCount); this.readMemory.Seek(0, SeekOrigin.Begin); continue; } } } MemoryBuffer memoryBuffer = this.readMemory; this.readMemory = null; memoryBuffer.Seek(0, SeekOrigin.Begin); this.OnRead(memoryBuffer); } } private void Output(byte[] bytes, int count) { if (this.IsDisposed) { return; } try { // 没连接上 kcp不往外发消息, 其实本来没连接上不会调用update,这里只是做一层保护 if (!this.IsConnected) { return; } if (count == 0) { Log.Error($"output 0"); return; } bytes.WriteTo(0, KcpProtocalType.MSG); // 每个消息头部写下该channel的id; bytes.WriteTo(1, this.LocalConn); this.Service.Transport.Send(bytes, 0, count + 5, this.RemoteAddress); } catch (Exception e) { Log.Error(e); } } private void KcpSend(MemoryBuffer memoryStream) { if (this.IsDisposed) { return; } int count = (int) (memoryStream.Length - memoryStream.Position); // 超出maxPacketSize需要分片 if (count <= MaxKcpMessageSize) { this.kcp.Send(memoryStream.GetBuffer().AsSpan((int)memoryStream.Position, count)); } else { // 先发分片信息 this.sendCache.WriteTo(0, 0); this.sendCache.WriteTo(4, count); this.kcp.Send(this.sendCache.AsSpan(0, 8)); // 分片发送 int alreadySendCount = 0; while (alreadySendCount < count) { int leftCount = count - alreadySendCount; int sendCount = leftCount < MaxKcpMessageSize? leftCount: MaxKcpMessageSize; this.kcp.Send(memoryStream.GetBuffer().AsSpan((int)memoryStream.Position + alreadySendCount, sendCount)); alreadySendCount += sendCount; } } this.Service.AddToUpdate(0, this.Id); } public void Send(MemoryBuffer memoryBuffer) { if (!this.IsConnected) { this.waitSendMessages.Enqueue(memoryBuffer); return; } if (this.kcp == null) { throw new Exception("kchannel connected but kcp is zero!"); } // 检查等待发送的消息,如果超出最大等待大小,应该断开连接 int n = this.kcp.WaitSnd; int maxWaitSize = 0; switch (this.Service.ServiceType) { case ServiceType.Inner: maxWaitSize = Kcp.InnerMaxWaitSize; break; case ServiceType.Outer: maxWaitSize = Kcp.OuterMaxWaitSize; break; default: throw new ArgumentOutOfRangeException(); } if (n > maxWaitSize) { Log.Error($"kcp wait snd too large: {n}: {this.LocalConn} {this.RemoteConn}"); this.OnError(ErrorCore.ERR_KcpWaitSendSizeTooLarge); return; } this.KcpSend(memoryBuffer); this.Service.Recycle(memoryBuffer); } private void OnRead(MemoryBuffer memoryStream) { try { this.Service.ReadCallback(this.Id, memoryStream); } catch (Exception e) { Log.Error(e); this.OnError(ErrorCore.ERR_PacketParserError); } } public void OnError(int error) { long channelId = this.Id; this.Service.Remove(channelId, error); this.Service.ErrorCallback(channelId, error); } } }
ET/Unity/Assets/Scripts/Core/Network/KChannel.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/KChannel.cs", "repo_id": "ET", "token_count": 4964 }
98
using MemoryPack; namespace ET { [Message(ushort.MaxValue)] [MemoryPackable] public partial class MessageResponse: MessageObject, IResponse { [MemoryPackOrder(1)] public int RpcId { get; set; } [MemoryPackOrder(2)] public int Error { get; set; } [MemoryPackOrder(3)] public string Message { get; set; } } }
ET/Unity/Assets/Scripts/Core/Network/Response.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/Response.cs", "repo_id": "ET", "token_count": 158 }
99
fileFormatVersion: 2 guid: ca28b9e6da52d7a4488b584e6ce3c685 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Object/DisposeObject.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Object/DisposeObject.cs.meta", "repo_id": "ET", "token_count": 96 }
100
using System; using System.ComponentModel; using System.IO; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; namespace ET { public static class MongoHelper { [StaticField] private static readonly JsonWriterSettings defaultSettings = new() { OutputMode = JsonOutputMode.RelaxedExtendedJson }; public static string ToJson(object obj) { if (obj is ISupportInitialize supportInitialize) { supportInitialize.BeginInit(); } return obj.ToJson(defaultSettings); } public static string ToJson(object obj, JsonWriterSettings settings) { if (obj is ISupportInitialize supportInitialize) { supportInitialize.BeginInit(); } return obj.ToJson(settings); } public static T FromJson<T>(string str) { try { return BsonSerializer.Deserialize<T>(str); } catch (Exception e) { throw new Exception($"{str}\n{e}"); } } public static object FromJson(Type type, string str) { return BsonSerializer.Deserialize(str, type); } public static byte[] Serialize(object obj) { if (obj is ISupportInitialize supportInitialize) { supportInitialize.BeginInit(); } return obj.ToBson(); } public static void Serialize(object message, MemoryStream stream) { if (message is ISupportInitialize supportInitialize) { supportInitialize.BeginInit(); } using BsonBinaryWriter bsonWriter = new(stream, BsonBinaryWriterSettings.Defaults); BsonSerializationContext context = BsonSerializationContext.CreateRoot(bsonWriter); BsonSerializationArgs args = default; args.NominalType = typeof (object); IBsonSerializer serializer = BsonSerializer.LookupSerializer(args.NominalType); serializer.Serialize(context, args, message); } public static object Deserialize(Type type, byte[] bytes) { try { return BsonSerializer.Deserialize(bytes, type); } catch (Exception e) { throw new Exception($"from bson error: {type.FullName} {bytes.Length}", e); } } public static object Deserialize(Type type, byte[] bytes, int index, int count) { try { using MemoryStream memoryStream = new(bytes, index, count); return BsonSerializer.Deserialize(memoryStream, type); } catch (Exception e) { throw new Exception($"from bson error: {type.FullName} {bytes.Length} {index} {count}", e); } } public static object Deserialize(Type type, Stream stream) { try { return BsonSerializer.Deserialize(stream, type); } catch (Exception e) { throw new Exception($"from bson error: {type.FullName} {stream.Position} {stream.Length}", e); } } public static T Deserialize<T>(byte[] bytes) { try { using MemoryStream memoryStream = new(bytes); return (T)BsonSerializer.Deserialize(memoryStream, typeof (T)); } catch (Exception e) { throw new Exception($"from bson error: {typeof (T).FullName} {bytes.Length}", e); } } public static T Deserialize<T>(byte[] bytes, int index, int count) { return (T)Deserialize(typeof (T), bytes, index, count); } public static T Clone<T>(T t) { return Deserialize<T>(Serialize(t)); } } }
ET/Unity/Assets/Scripts/Core/Serialize/MongoHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Serialize/MongoHelper.cs", "repo_id": "ET", "token_count": 2096 }
101
fileFormatVersion: 2 guid: 9e8f0bd4aa4045ddb59117f81ff62be5 timeCreated: 1687104833
ET/Unity/Assets/Scripts/Core/World/ActorId.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/ActorId.cs.meta", "repo_id": "ET", "token_count": 38 }
102
namespace ET { public class CodeAttribute: BaseAttribute { } }
ET/Unity/Assets/Scripts/Core/World/Module/Code/CodeAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Code/CodeAttribute.cs", "repo_id": "ET", "token_count": 31 }
103
using System; namespace ET { public class EventAttribute: BaseAttribute { public SceneType SceneType { get; } public EventAttribute(SceneType sceneType) { this.SceneType = sceneType; } } }
ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/EventAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/EventAttribute.cs", "repo_id": "ET", "token_count": 74 }
104
fileFormatVersion: 2 guid: bdc1761525ecfa642b1780a6b4e0243d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/World/Module/Log/Log.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Log/Log.cs.meta", "repo_id": "ET", "token_count": 94 }
105
using System; using System.Collections.Generic; namespace ET { public class World: IDisposable { [StaticField] private static World instance; [StaticField] public static World Instance { get { return instance ??= new World(); } } private readonly Stack<Type> stack = new(); private readonly Dictionary<Type, ASingleton> singletons = new(); private World() { } public void Dispose() { instance = null; lock (this) { while (this.stack.Count > 0) { Type type = this.stack.Pop(); if (this.singletons.Remove(type, out ASingleton singleton)) { singleton.Dispose(); } } // dispose剩下的singleton,主要为了把instance置空 foreach (var kv in this.singletons) { kv.Value.Dispose(); } } } public T AddSingleton<T>() where T : ASingleton, ISingletonAwake, new() { T singleton = new(); singleton.Awake(); AddSingleton(singleton); return singleton; } public T AddSingleton<T, A>(A a) where T : ASingleton, ISingletonAwake<A>, new() { T singleton = new(); singleton.Awake(a); AddSingleton(singleton); return singleton; } public T AddSingleton<T, A, B>(A a, B b) where T : ASingleton, ISingletonAwake<A, B>, new() { T singleton = new(); singleton.Awake(a, b); AddSingleton(singleton); return singleton; } public T AddSingleton<T, A, B, C>(A a, B b, C c) where T : ASingleton, ISingletonAwake<A, B, C>, new() { T singleton = new(); singleton.Awake(a, b, c); AddSingleton(singleton); return singleton; } public void AddSingleton(ASingleton singleton) { lock (this) { Type type = singleton.GetType(); if (singleton is ISingletonReverseDispose) { this.stack.Push(type); } singletons[type] = singleton; } singleton.Register(); } } }
ET/Unity/Assets/Scripts/Core/World/World.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/World.cs", "repo_id": "ET", "token_count": 1508 }
106
fileFormatVersion: 2 guid: c21d447f26b99ec4fab0de98860bba8d folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor.meta", "repo_id": "ET", "token_count": 70 }
107
using System; using UnityEditor; namespace ET { [TypeDrawer] public class DateTimeTypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (DateTime); } // Note: This is a very basic implementation. The ToString() method conversion will cut off milliseconds. public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { var dateString = value.ToString(); var newDateString = EditorGUILayout.TextField(memberName, dateString); return newDateString != dateString ? DateTime.Parse(newDateString) : value; } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/DateTimeTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/DateTimeTypeDrawer.cs", "repo_id": "ET", "token_count": 311 }
108