public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     base.Init(objectBuilder, cubeGrid);
     MyObjectBuilder_UserControllableGun builder = (objectBuilder as MyObjectBuilder_UserControllableGun);
     m_shootingSaved = builder.IsLargeTurret ? builder.IsShootingFromTerminal : builder.IsShooting;
     NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;      
 }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            ResourceSink = new MyResourceSinkComponent();
            ResourceSink.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                this.CalculateRequiredPowerInput);

            base.Init(objectBuilder, cubeGrid);

            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink.Update();

            if (Physics != null)
            {
                Physics.Close();
            }

            var detectorShape = new HkBoxShape(new Vector3(cubeGrid.GridSize / 3.0f));
            var massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(detectorShape.HalfExtents, BlockDefinition.VirtualMass);
            Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT);
            Physics.IsPhantom = false;
            Physics.CreateFromCollisionObject(detectorShape, Vector3.Zero, WorldMatrix, massProperties, MyPhysics.CollisionLayers.VirtualMassLayer);
            Physics.Enabled = IsWorking && cubeGrid.Physics != null && cubeGrid.Physics.Enabled;
            Physics.RigidBody.Activate();
            detectorShape.Base.RemoveReference();

            UpdateText();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            InitializeSinkComponent();
            base.Init(objectBuilder, cubeGrid);
            if (CubeGrid.CreatePhysics)
            {
            	// Put on my fake, because it does performance issues
                if (MyFakes.ENABLE_GRAVITY_PHANTOM)
                {
                        var shape = CreateFieldShape();
                        Physics = new Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_KINEMATIC);
                        Physics.IsPhantom = true;
                        Physics.CreateFromCollisionObject(shape, PositionComp.LocalVolume.Center, WorldMatrix, null, Sandbox.Engine.Physics.MyPhysics.CollisionLayers.GravityPhantomLayer);
                        shape.Base.RemoveReference();
                        Physics.Enabled = IsWorking;
                }
                NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

                SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
                ResourceSink.Update();
            }
            m_soundEmitter = new MyEntity3DSoundEmitter(this);
            m_baseIdleSound.Init("BlockGravityGen");
			
        }
예제 #4
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            m_cargoDefinition = (MyCargoContainerDefinition)MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());
            var cargoBuilder = (MyObjectBuilder_CargoContainer)objectBuilder;
            m_containerType = cargoBuilder.ContainerType;

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            // Backward compatibility - inventory component not defined in definition files and in entity container
            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(m_cargoDefinition.InventorySize.Volume, m_cargoDefinition.InventorySize, MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive);
                Components.Add<MyInventoryBase>(inventory);
                
                if (m_containerType != null && MyFakes.RANDOM_CARGO_PLACEMENT && (cargoBuilder.Inventory == null || cargoBuilder.Inventory.Items.Count == 0))
                    SpawnRandomCargo();
            }

            //Backward compatibility
            if (cargoBuilder.Inventory != null && cargoBuilder.Inventory.Items.Count > 0)
                this.GetInventory().Init(cargoBuilder.Inventory);

            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");
            this.GetInventory().SetFlags(MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive);
            m_conveyorEndpoint = new MyMultilineConveyorEndpoint(this);
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));
            UpdateIsWorking();
        }
예제 #5
0
 public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
 {
     base.Init(builder, cubeGrid);
     this.NeedsUpdate = MyEntityUpdateEnum.EACH_100TH_FRAME;
     m_emissivitySet = false;
     AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorSegment(m_segment));
 }
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            ResourceSink = new MyResourceSinkComponent();
            ResourceSink.Init(
                MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup),
                BlockDefinition.PowerConsumptionMoving,
                UpdatePowerInput);

            base.Init(builder, cubeGrid);

            var ob = (MyObjectBuilder_AirtightDoorGeneric)builder;
            m_open.Value = ob.Open;
            m_currOpening = ob.CurrOpening;

            m_openingSpeed = BlockDefinition.OpeningSpeed;
            m_sound = new MySoundPair(BlockDefinition.Sound);
            m_subpartMovementDistance = BlockDefinition.SubpartMovementDistance;
	
			if (!Enabled || !ResourceSink.IsPoweredByType(MyResourceDistributorComponent.ElectricityId))
                UpdateDoorPosition();

            OnStateChange();

            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink.Update();
            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
			ResourceSink.Update();
        }
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            var rotorOb = builder as MyObjectBuilder_MotorRotor;

            base.Init(builder, cubeGrid);

            LoadDummies();
        }
예제 #8
0
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     base.Init(objectBuilder, cubeGrid);
     if (CubeGrid.GridSizeEnum == MyCubeSize.Large)
     {
         IDLE_SOUND.Init("ToolLrgGrindIdle");
         METAL_SOUND.Init("ToolLrgGrindMetal");
     }
     m_rotationSpeed = 0.0f;
 }
 public static object CreateCubeBlock(MyObjectBuilder_CubeBlock builder)
 {
     var obj = m_objectFactory.CreateInstance(builder.TypeId);
     var entity = obj as MyEntity; // Some are SlimBlocks
     if (entity != null)
     {
         MyEntityFactory.AddScriptGameLogic(entity, builder.TypeId, builder.SubtypeName);
     }
     return obj;
 }
예제 #10
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;

            base.Init(objectBuilder, cubeGrid);

            m_missingComponents = new Dictionary<string, int>();

            var builder = (MyObjectBuilder_ShipWelder)objectBuilder;
            m_helpOthers.Value = builder.HelpOthers;

        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);
            if (CubeGrid.GridSizeEnum == MyCubeSize.Large)
            {
                IDLE_SOUND.Init("ToolLrgGrindIdle");
                METAL_SOUND.Init("ToolLrgGrindMetal");
            }
            m_rotationSpeed = 0.0f;

            HeatUpFrames = MyShipGrinderConstants.GRINDER_HEATUP_FRAMES;
        }
예제 #12
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            var ob = (MyObjectBuilder_FunctionalBlock)objectBuilder;
            m_soundEmitter = new MyEntity3DSoundEmitter(this, true);

            m_enabled.Value = ob.Enabled;
            IsWorkingChanged += CubeBlock_IsWorkingChanged;
            m_baseIdleSound = BlockDefinition.PrimarySound;
            m_actionSound = BlockDefinition.ActionSound;
        }
예제 #13
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            MyDebug.AssertDebug(BlockDefinition.Id.TypeId == typeof(MyObjectBuilder_Reactor));
            m_reactorDefinition = BlockDefinition as MyReactorDefinition;
            MyDebug.AssertDebug(m_reactorDefinition != null);

            SourceComp.Init(
                m_reactorDefinition.ResourceSourceGroup,
                new MyResourceSourceInfo
                {
                    ResourceTypeId = MyResourceDistributorComponent.ElectricityId,
                    DefinedOutput = m_reactorDefinition.MaxPowerOutput,
                    ProductionToCapacityMultiplier = 60 * 60
                });
            SourceComp.HasCapacityRemainingChanged += (id, source) => UpdateIsWorking();
            SourceComp.OutputChanged += Source_OnOutputChanged;
            SourceComp.ProductionEnabledChanged += Source_ProductionEnabledChanged;
            SourceComp.Enabled = Enabled;

            base.Init(objectBuilder, cubeGrid);
         
            var obGenerator = (MyObjectBuilder_Reactor)objectBuilder;

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(m_reactorDefinition.InventoryMaxVolume, m_reactorDefinition.InventorySize, MyInventoryFlags.CanReceive);
                Components.Add<MyInventoryBase>(inventory);
                inventory.Init(obGenerator.Inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            this.GetInventory().Constraint = m_reactorDefinition.InventoryConstraint;

            if (Sync.IsServer)
            {
                RefreshRemainingCapacity();
            }
            
            UpdateText();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_useConveyorSystem.Value = obGenerator.UseConveyorSystem;
			UpdateMaxOutputAndEmissivity();
        }
예제 #14
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            // User settings:
            m_randomStandbyChangeConst_ms = MyUtils.GetRandomInt(3500, 4500);

            if (m_gunBase.HasAmmoMagazines)
                m_shootingCueEnum = m_gunBase.ShootSound;
            m_rotatingCueEnum.Init("WepTurretInteriorRotate");

            Render.NeedsDraw = true;
        }
예제 #15
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
          
            base.Init(objectBuilder, cubeGrid);

            //var boxshape = new HkBoxShape((LocalAABB.Max - LocalAABB.Min) / 2);
            //var boxshape = new HkBoxShape(new Vector3(0.43f, MyDefinitionManager.Static.GetCubeSize(MyCubeSize.Large) / 2.0f, 0.43f));
            //Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE);
            //Physics.CreateFromCollisionObject((HkShape)boxshape, Vector3.Zero, WorldMatrix);
            //Physics.Enabled = true;
            //boxshape.Base.RemoveReference();
            AddDebugRenderComponent(new MyDebugRenderComponentLadder(this));
         
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            m_useConveyorSystem.Value = true;

            var builder = objectBuilder as MyObjectBuilder_ConveyorTurretBase;
            var builder2 = objectBuilder as MyObjectBuilder_TurretBase; // Compatibility

            Debug.Assert(builder != null || builder2 != null, "Turret builder was incorrect!");

            if (builder != null)
                m_useConveyorSystem.Value = builder.UseConveyorSystem;
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            m_cameraDummy = Matrix.Identity;
            m_characterDummy = Matrix.Identity;

            base.Init(objectBuilder, cubeGrid);

            if (ResourceSink == null)
            {
                // we've already created ResourceSink in ancestor!
                var sinkComp = new MyResourceSinkComponent();
                sinkComp.Init(
                    MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup),
                    BlockDefinition.IdlePowerConsumption,
                    this.CalculateRequiredPowerInput);
                sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;
                ResourceSink = sinkComp;
            }
            else
            {
                // override electricity settings
                ResourceSink.SetMaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId, BlockDefinition.IdlePowerConsumption);
                ResourceSink.SetRequiredInputFuncByType(MyResourceDistributorComponent.ElectricityId, this.CalculateRequiredPowerInput);
                ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            }

            var chamberOb = objectBuilder as MyObjectBuilder_CryoChamber;

            if (chamberOb.SteamId != null && chamberOb.SerialId != null)
            {
                m_currentPlayerId = new MyPlayer.PlayerId(chamberOb.SteamId.Value, chamberOb.SerialId.Value);
            }
            else
            {
                m_currentPlayerId = null;
            }


            var overlayTexture = BlockDefinition.OverlayTexture;
            if (!string.IsNullOrEmpty(overlayTexture))
            {
                m_overlayTextureName = overlayTexture;
            }

          
            HorizonIndicatorEnabled = false;

            NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME;
        }
예제 #18
0
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            base.Init(builder, cubeGrid);

            NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_connectedBlocks = new Dictionary<ConveyorLinePosition, MyCubeBlock>();
            m_dummies = new SortedDictionary<string,MyModelDummy>(VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies);

            InitDummies();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
            IsWorkingChanged += MyUpgradeModule_IsWorkingChanged;

            m_upgrades = BlockDefinition.Upgrades;
            UpdateIsWorking();
        }
예제 #19
0
        // This function does some modifications to the cube block's object builder before it's built, usually integrity changes, etc...
        public virtual void BeforeCreateBlock(MyCubeBlockDefinition definition, MyEntity builder, MyObjectBuilder_CubeBlock ob, bool buildAsAdmin)
        {
            if (definition.EntityComponents == null) return;

            if (ob.ComponentContainer == null)
            {
                ob.ComponentContainer = new MyObjectBuilder_ComponentContainer();
            }

            foreach (var componentOb in definition.EntityComponents)
            {
                var data = new MyObjectBuilder_ComponentContainer.ComponentData();
                data.TypeId = componentOb.Key.ToString();
                data.Component = componentOb.Value;
                ob.ComponentContainer.Components.Add(data);
            }
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            // User settings:
            m_randomStandbyChangeConst_ms = 4000;
            m_rotationSpeed = MathHelper.Pi / 2000.0f;
            m_elevationSpeed = MathHelper.Pi / 2000.0f;

            if (BlockDefinition != null)
            {
                m_rotationSpeed = BlockDefinition.RotationSpeed;
                m_elevationSpeed = BlockDefinition.ElevationSpeed;
            }

            if (m_gunBase.HasAmmoMagazines)
                m_shootingCueEnum = m_gunBase.ShootSound;
            m_rotatingCueEnum.Init("WepTurretGatlingRotate");
        }
예제 #21
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            IsWorkingChanged += OnIsWorkingChanged;
            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            InitializeConveyorEndpoint();

            SourceComp.Init(
                BlockDefinition.ResourceSourceGroup,
                new MyResourceSourceInfo
                {
                    ResourceTypeId = BlockDefinition.ProducedGas,
                    DefinedOutput = BlockDefinition.MaxGasOutput,
                    ProductionToCapacityMultiplier = 1,
                    IsInfiniteCapacity = true,
                });
            SourceComp.Enabled = IsWorking;

            ResourceSink.Init(
                BlockDefinition.ResourceSinkGroup,
                new MyResourceSinkInfo
                {
                    ResourceTypeId = MyResourceDistributorComponent.ElectricityId,
                    MaxRequiredInput = BlockDefinition.OperationalPowerConsumption,
                    RequiredInputFunc = ComputeRequiredPower,
                });
            ResourceSink.IsPoweredChanged += PowerReceiver_IsPoweredChanged;
            ResourceSink.Update();

            GameLogic = new MySolarGameLogicComponent();
            SolarComponent = GameLogic as MySolarGameLogicComponent;

            SolarComponent.Initialize(BlockDefinition.PanelOrientation, BlockDefinition.IsTwoSided, BlockDefinition.PanelOffset, this);

            AddDebugRenderComponent(new MyDebugRenderComponentSolarPanel(this));

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_OnIsFunctionalChanged;

            UpdateVisual();
            UpdateDisplay();
        }
예제 #22
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var ob = objectBuilder as MyObjectBuilder_Collector;

            var sinkComp = new MyResourceSinkComponent();
            sinkComp.Init(
                MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup),
                BlockDefinition.RequiredPowerInput,
                ComputeRequiredPower);
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);

            m_useConveyorSystem.Value = true;
            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(BlockDefinition.InventorySize.Volume, BlockDefinition.InventorySize, MyInventoryFlags.CanSend);
                Components.Add<MyInventoryBase>(inventory);
                inventory.Init(ob.Inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            if (Sync.IsServer && CubeGrid.CreatePhysics)
                LoadDummies();

            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink,this));

            SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver;
            base.EnabledChanged += UpdateReceiver;

            m_useConveyorSystem.Value = ob.UseConveyorSystem;

            ResourceSink.Update();
            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;
        }
예제 #23
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var def = BlockDefinition as MyPoweredCargoContainerDefinition;
            var sinkComp = new MyResourceSinkComponent();
            sinkComp.Init(
                MyStringHash.GetOrCompute(def.ResourceSinkGroup),
                MyEnergyConstants.MAX_REQUIRED_POWER_COLLECTOR,
                () => base.CheckIsWorking() ? ResourceSink.MaxRequiredInput : 0f);
            ResourceSink = sinkComp;
            ResourceSink.Update();

            base.Init(objectBuilder, cubeGrid);
           
            var ob = objectBuilder as MyObjectBuilder_Collector;

            m_useConveyorSystem.Value = true;
            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            if (this.GetInventory() == null)
            {
               Components.Add<MyInventoryBase>( new MyInventory(def.InventorySize.Volume, def.InventorySize, MyInventoryFlags.CanSend, this));
               this.GetInventory().Init(ob.Inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            if (Sync.IsServer && CubeGrid.CreatePhysics)
                LoadDummies();

			
			ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink,this));

            SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver;
            base.EnabledChanged += UpdateReceiver;

            m_useConveyorSystem.Value = ob.UseConveyorSystem;
        }
예제 #24
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            // Need to be initialized before base.Init because when loading world with producting refinery
            // it will be missing when recompute power and cause disappearing of refinery.
            UpgradeValues.Add("Productivity", 0f);
            UpgradeValues.Add("Effectiveness", 1f);
            UpgradeValues.Add("PowerEfficiency", 1f);

            base.Init(objectBuilder, cubeGrid);

            MyDebug.AssertDebug(BlockDefinition is MyRefineryDefinition);
            m_refineryDef = BlockDefinition as MyRefineryDefinition;

            if (InventoryAggregate.InventoryCount > 2)
            {
                Debug.Fail("Inventory aggregate has to many inventories, probably wrong save. If you continue the unused inventories will be removed. Save the world to correct it. Please report this is if problem prevail.");

                FixInputOutputInventories(m_refineryDef.InputInventoryConstraint, m_refineryDef.OutputInventoryConstraint);
            }

            InputInventory.Constraint = m_refineryDef.InputInventoryConstraint;
            bool removed = InputInventory.FilterItemsUsingConstraint();
            Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder.");

            OutputInventory.Constraint = m_refineryDef.OutputInventoryConstraint;
            removed = OutputInventory.FilterItemsUsingConstraint();
            Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder.");

            m_queueNeedsRebuild = true;

            m_baseIdleSound = BlockDefinition.PrimarySound;
            m_processSound = BlockDefinition.ActionSound;

            ResourceSink.RequiredInputChanged += PowerReceiver_RequiredInputChanged;
            OnUpgradeValuesChanged += UpdateDetailedInfo;

            UpdateDetailedInfo();
            NeedsUpdate |= VRage.ModAPI.MyEntityUpdateEnum.EACH_100TH_FRAME;
        }       
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            //Matrix barrelMatrix = MyMath.NormalizeMatrix(ModelLod0.Dummies["axis"].Matrix);
            Matrix barrelMatrix = Matrix.Identity;

            // User settings:
            m_randomStandbyChangeConst_ms = 4000;
            m_rotationSpeed = MathHelper.Pi / 2000.0f;
            m_elevationSpeed = MathHelper.Pi / 2000.0f;

            if (BlockDefinition != null)
            {
                m_rotationSpeed = BlockDefinition.RotationSpeed;
                m_elevationSpeed = BlockDefinition.ElevationSpeed;
            }

            if (m_gunBase.HasAmmoMagazines)
                m_shootingCueEnum = m_gunBase.ShootSound;
            m_rotatingCueEnum.Init("WepTurretGatlingRotate");
        }
예제 #26
0
	    public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            SolarPanelDefinition = BlockDefinition as MySolarPanelDefinition;
            IsWorkingChanged += OnIsWorkingChanged;
            NeedsUpdate = MyEntityUpdateEnum.EACH_100TH_FRAME;

		    var sourceDataList = new List<MyResourceSourceInfo>
		    {
			    new MyResourceSourceInfo {ResourceTypeId = MyResourceDistributorComponent.ElectricityId, DefinedOutput = SolarPanelDefinition.MaxPowerOutput, IsInfiniteCapacity = true, ProductionToCapacityMultiplier = 60*60}
		    };

			SourceComp.Init(SolarPanelDefinition.ResourceSourceGroup, sourceDataList);

            GameLogic = new MySolarGameLogicComponent();
            SolarComponent = GameLogic as MySolarGameLogicComponent;

            SolarComponent.Initialize(SolarPanelDefinition.PanelOrientation, SolarPanelDefinition.IsTwoSided, SolarPanelDefinition.PanelOffset, this);

            AddDebugRenderComponent(new Sandbox.Game.Components.MyDebugRenderComponentSolarPanel(this));
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                () => (Enabled && IsFunctional) ? ResourceSink.MaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId) : 0f);
            sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);
            this.IsLargeLight = cubeGrid.GridSizeEnum == MyCubeSize.Large;

            var     builder    = (MyObjectBuilder_LightingBlock)objectBuilder;
            MyModel lightModel = VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model);

            foreach (var pair in lightModel.Dummies)
            {
                if (!pair.Key.ToLower().Contains("light"))
                {
                    continue;
                }

                m_lightLocalPosition = pair.Value.Matrix.Translation;
                break;
            }

            Vector4 color = (builder.ColorAlpha == -1)
                ? LightColorDef
                : new Vector4(builder.ColorRed, builder.ColorGreen, builder.ColorBlue, builder.ColorAlpha);

            float radius          = RadiusBounds.Clamp((builder.Radius == -1f) ? RadiusBounds.Default : builder.Radius);
            float reflectorRadius = ReflectorRadiusBounds.Clamp((builder.ReflectorRadius == -1f) ? ReflectorRadiusBounds.Default : builder.ReflectorRadius);
            float falloff         = FalloffBounds.Clamp(builder.Falloff);

            m_blinkIntervalSeconds.Value = BlinkIntervalSecondsBounds.Clamp((builder.BlinkIntervalSeconds == -1f) ? BlinkIntervalSecondsBounds.Default : builder.BlinkIntervalSeconds);

            m_blinkLength.Value = BlinkLenghtBounds.Clamp((builder.BlinkLenght == -1f) ? BlinkLenghtBounds.Default : builder.BlinkLenght);

            m_blinkOffset.Value = BlinkOffsetBounds.Clamp((builder.BlinkOffset == -1f) ? BlinkOffsetBounds.Default : builder.BlinkOffset);

            m_intesity.Value = IntensityBounds.Clamp((builder.Intensity == -1f) ? IntensityBounds.Default : builder.Intensity);


            m_positionDirty = true;
            m_light         = MyLights.AddLight();
            InitLight(m_light, color, radius, falloff);

            m_light.ReflectorRange = reflectorRadius;
            m_light.Range          = radius;
            m_light.ReflectorOn    = false;
            m_light.LightOn        = false;
            m_light.GlareOn        = false;

            UpdateRadius(m_light.IsTypeSpot ? reflectorRadius : radius);
            UpdateIntensity();
            UpdateLightPosition();

            NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME;
            Render.NeedsDrawFromParent = true;


            AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(ResourceSink, this));
            ResourceSink.Update();
            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
            IsWorkingChanged += CubeBlock_OnWorkingChanged;
        }
 IMySlimBlock IMyCubeGrid.AddBlock(MyObjectBuilder_CubeBlock objectBuilder, bool testMerge)
 {
     return(AddBlock(objectBuilder, testMerge));
 }
예제 #29
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            MyEntityThrustComponent entityThrustComponent;

            if (!cubeGrid.Components.TryGet(out entityThrustComponent))
            {
                entityThrustComponent = new MyThrusterBlockThrustComponent();

                entityThrustComponent.Init();
                cubeGrid.Components.Add <MyEntityThrustComponent>(entityThrustComponent);
            }

            m_thrustComponent = entityThrustComponent;

            BlockDefinition = (MyThrustDefinition)base.BlockDefinition;

            MyDefinitionId fuelId = new MyDefinitionId();

            if (!BlockDefinition.FuelConverter.FuelId.IsNull())
            {
                fuelId = BlockDefinition.FuelConverter.FuelId;
            }

            MyGasProperties fuelDef = null;

            if (MyFakes.ENABLE_HYDROGEN_FUEL)
            {
                MyDefinitionManager.Static.TryGetDefinition(fuelId, out fuelDef);
            }

            FuelDefinition = fuelDef ?? new MyGasProperties // Use electricity by default
            {
                Id            = MyResourceDistributorComponent.ElectricityId,
                EnergyDensity = 1f,
            };

            base.Init(objectBuilder, cubeGrid);



            var builder = (MyObjectBuilder_Thrust)objectBuilder;

            ThrustColor = BlockDefinition.FlameIdleColor;

            m_thrustOverride.Value = (builder.ThrustOverride * 100f) / BlockDefinition.ForceMagnitude;

            LoadDummies();
            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_light = MyLights.AddLight();
            m_light.ReflectorDirection = WorldMatrix.Forward;
            m_light.ReflectorUp        = WorldMatrix.Up;
            m_light.ReflectorRange     = CubeGrid.GridScale;
            m_light.Color          = ThrustColor;
            m_light.GlareMaterial  = BlockDefinition.FlameGlareMaterial;
            m_light.GlareQuerySize = BlockDefinition.FlameGlareQuerySize * CubeGrid.GridScale;

            m_glareSize = BlockDefinition.FlameGlareSize * CubeGrid.GridScale;
            m_maxBillboardDistanceSquared = BlockDefinition.FlameVisibilityDistance * BlockDefinition.FlameVisibilityDistance;
            m_maxLightDistanceSquared     = m_maxBillboardDistanceSquared / 100;

            m_light.Start(MyLight.LightTypeEnum.PointLight, 1);

            UpdateDetailedInfo();

            FuelConverterDefinition = !MyFakes.ENABLE_HYDROGEN_FUEL ? new MyFuelConverterInfo {
                Efficiency = 1.0f
            } : BlockDefinition.FuelConverter;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
        }
        // This function does some modifications to the cube block's object builder before it's built, usually integrity changes, etc...
        public virtual void BeforeCreateBlock(MyCubeBlockDefinition definition, MyEntity builder, MyObjectBuilder_CubeBlock ob, bool buildAsAdmin)
        {
            if (definition.EntityComponents == null)
            {
                return;
            }

            if (ob.ComponentContainer == null)
            {
                ob.ComponentContainer = new MyObjectBuilder_ComponentContainer();
            }

            foreach (var componentOb in definition.EntityComponents)
            {
                var data = new MyObjectBuilder_ComponentContainer.ComponentData();
                data.TypeId    = componentOb.Key.ToString();
                data.Component = componentOb.Value;
                ob.ComponentContainer.Components.Add(data);
            }
        }
예제 #31
0
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     base.Init(objectBuilder, cubeGrid);
 }
예제 #32
0
 private bool ApplyDelegate(MyObjectBuilder_CubeGrid grid, MyObjectBuilder_CubeBlock source, string srcName, MyObjectBuilder_CubeBlock dest, Base6Directions.Direction destDir)
 {
     if (srcName.StartsWithICase(MountDelegated))
     {
         var     lTransOrig = new MatrixI(source.BlockOrientation);
         var     lTrans     = new MatrixI(dest.BlockOrientation);
         MatrixI iTrans;
         MatrixI.Invert(ref lTrans, out iTrans);
         var arguments = PartDummyUtils.ConfigArguments(srcName.Substring(MountDelegated.Length).Trim()).Select(
             (arg) =>
         {
             if (arg.StartsWithICase(PartDummyUtils.ArgumentBiasDirection))
             {
                 Base6Directions.Direction dir;
                 if (Enum.TryParse(arg.Substring(PartDummyUtils.ArgumentBiasDirection.Length), out dir))
                 {
                     return(PartDummyUtils.ArgumentBiasDirection +
                            iTrans.GetDirection(lTransOrig.GetDirection(dir)));
                 }
                 else
                 {
                     this.Error("Failed to parse bias argument \"{0}\"", arg);
                 }
             }
             else if (arg.StartsWithICase(PartDummyUtils.ArgumentSecondBiasDirection))
             {
                 Base6Directions.Direction dir;
                 if (Enum.TryParse(arg.Substring(PartDummyUtils.ArgumentSecondBiasDirection.Length), out dir))
                 {
                     return(PartDummyUtils.ArgumentSecondBiasDirection +
                            iTrans.GetDirection(lTransOrig.GetDirection(dir)));
                 }
                 else
                 {
                     this.Error("Failed to parse second bias argument \"{0}\"", arg);
                 }
             }
             return(arg);
         }).ToList();
         arguments.Add(PartDummyUtils.ArgumentMountDirection + iTrans.GetDirection(Base6Directions.GetOppositeDirection(destDir)));
         var anchorPoint = source.Min + Base6Directions.GetIntVector(destDir);
         var del         = anchorPoint - dest.Min;
         if (del != Vector3I.Zero)
         {
             arguments.Add(PartDummyUtils.ArgumentAnchorPoint + del.X + ":" + del.Y + ":" + del.Z);
         }
         var outName = PartMetadata.MountPrefix + " " + string.Join(" ", arguments);
         if (string.IsNullOrWhiteSpace(dest.Name))
         {
             dest.Name = outName;
         }
         else
         {
             dest.Name = dest.Name + PartMetadata.MultiUseSentinel + outName;
         }
         return(true);
     }
     if (srcName.StartsWithICase(ReservedSpaceDelegated))
     {
         var baseName = srcName.Substring(ReservedSpaceDelegated.Length).Trim();
         var args     = baseName.Split(' ').Select(x => x.Trim()).Where(x => x.Length > 0).ToArray();
         var box      = PartDummyUtils.ParseReservedSpace(MyDefinitionManager.Static.GetCubeSize(grid.GridSizeEnum), source, args, this.Error);
         var del      = source.Min - (Vector3I)dest.Min;
         box.Box.Max += del;
         box.Box.Min += del;
         var boxLocalFloat = Utilities.TransformBoundingBox(box.Box, Matrix.Invert(new MatrixI(dest.BlockOrientation).GetFloatMatrix()));
         var boxLocal      = new BoundingBoxI(Vector3I.Floor(boxLocalFloat.Min), Vector3I.Ceiling(boxLocalFloat.Max));
         var outName       = $"{PartMetadata.ReservedSpacePrefix} NE:{boxLocal.Min.X}:{boxLocal.Min.Y}:{boxLocal.Min.Z} PE:{boxLocal.Max.X}:{boxLocal.Max.Y}:{boxLocal.Max.Z}";
         if (box.IsShared)
         {
             outName += " shared";
         }
         if (box.IsOptional)
         {
             outName += " optional";
         }
         if (string.IsNullOrWhiteSpace(dest.Name))
         {
             dest.Name = outName;
         }
         else
         {
             dest.Name = dest.Name + PartMetadata.MultiUseSentinel + outName;
         }
         return(true);
     }
     return(false);
 }
예제 #33
0
        public MyObjectBuilder_CubeGrid BuildEntity()
        {
            var entity = new MyObjectBuilder_CubeGrid
            {
                EntityId        = SpaceEngineersApi.GenerateEntityId(IDType.ENTITY),
                PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                Skeleton        = new System.Collections.Generic.List <BoneInfo>(),
                LinearVelocity  = new VRageMath.Vector3(0, 0, 0),
                AngularVelocity = new VRageMath.Vector3(0, 0, 0)
            };

            var blockPrefix = "";

            switch (ClassType)
            {
            case ImportImageClassType.SmallShip:
                entity.GridSizeEnum = MyCubeSize.Small;
                blockPrefix        += "Small";
                entity.IsStatic     = false;
                break;

            case ImportImageClassType.SmallStation:
                entity.GridSizeEnum = MyCubeSize.Small;
                blockPrefix        += "Small";
                entity.IsStatic     = true;
                Position            = Position.RoundOff(MyCubeSize.Small.ToLength());
                Forward             = Forward.RoundToAxis();
                Up = Up.RoundToAxis();
                break;

            case ImportImageClassType.LargeShip:
                entity.GridSizeEnum = MyCubeSize.Large;
                blockPrefix        += "Large";
                entity.IsStatic     = false;
                break;

            case ImportImageClassType.LargeStation:
                entity.GridSizeEnum = MyCubeSize.Large;
                blockPrefix        += "Large";
                entity.IsStatic     = true;
                Position            = Position.RoundOff(MyCubeSize.Large.ToLength());
                Forward             = Forward.RoundToAxis();
                Up = Up.RoundToAxis();
                break;
            }

            switch (ArmorType)
            {
            case ImportArmorType.Heavy: blockPrefix += "HeavyBlockArmor"; break;

            case ImportArmorType.Light: blockPrefix += "BlockArmor"; break;
            }

            entity.PositionAndOrientation = new MyPositionAndOrientation
            {
                // TODO: reposition based scale.
                Position = Position.ToVector3D(),
                Forward  = Forward.ToVector3(),
                Up       = Up.ToVector3()
            };

            // Large|BlockArmor|Corner
            // Large|RoundArmor_|Corner
            // Large|HeavyBlockArmor|Block,
            // Small|BlockArmor|Slope,
            // Small|HeavyBlockArmor|Corner,

            entity.CubeBlocks = new System.Collections.Generic.List <MyObjectBuilder_CubeBlock>();
            var image = ImageHelper.ResizeImage(_sourceImage, NewImageSize.Size);

            using (var palatteImage = new Bitmap(image))
            {
                // Optimal order load. from grid coordinate (0,0,0) and up.
                for (var x = palatteImage.Width - 1; x >= 0; x--)
                {
                    for (var y = palatteImage.Height - 1; y >= 0; y--)
                    {
                        const int z     = 0;
                        var       color = palatteImage.GetPixel(x, y);

                        // Specifically ignore anything with less than half "Transparent" Alpha.
                        if (IsAlphaLevel && color.A < AlphaLevel)
                        {
                            continue;
                        }

                        if (IsKeyColor && color.R == KeyColor.R && color.G == KeyColor.G && color.B == KeyColor.B)
                        {
                            continue;
                        }

                        // Parse the string through the Enumeration to check that the 'subtypeid' is still valid in the game engine.
                        var armor = (SubtypeId)Enum.Parse(typeof(SubtypeId), blockPrefix + "Block");

                        MyObjectBuilder_CubeBlock newCube;
                        entity.CubeBlocks.Add(newCube = new MyObjectBuilder_CubeBlock());
                        newCube.SubtypeName           = armor.ToString();
                        newCube.EntityId         = 0;
                        newCube.BlockOrientation = Modelling.GetCubeOrientation(CubeType.Cube);
                        newCube.Min          = new VRageMath.Vector3I(palatteImage.Width - x - 1, palatteImage.Height - y - 1, z);
                        newCube.ColorMaskHSV = color.FromPaletteColorToHsvMask();
                    }
                }
            }

            return(entity);
        }
예제 #34
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var          medicalRoomDefinition = BlockDefinition as MyMedicalRoomDefinition;
            MyStringHash resourceSinkGroup;

            if (medicalRoomDefinition != null)
            {
                m_idleSound       = new MySoundPair(medicalRoomDefinition.IdleSound);
                m_progressSound   = new MySoundPair(medicalRoomDefinition.ProgressSound);
                resourceSinkGroup = MyStringHash.GetOrCompute(medicalRoomDefinition.ResourceSinkGroup);
            }
            else
            {
                m_idleSound       = new MySoundPair("BlockMedical");
                m_progressSound   = new MySoundPair("BlockMedicalProgress");
                resourceSinkGroup = MyStringHash.GetOrCompute("Utility");
            }

            SinkComp = new MyResourceSinkComponent();
            SinkComp.Init(
                resourceSinkGroup,
                MyEnergyConstants.MAX_REQUIRED_POWER_MEDICAL_ROOM,
                () => (Enabled && IsFunctional) ? SinkComp.MaxRequiredInput : 0f);
            SinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;

            base.Init(objectBuilder, cubeGrid);

            m_rechargeSocket = new MyRechargeSocket();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME;

            SteamUserId = (objectBuilder as MyObjectBuilder_MedicalRoom).SteamUserId;

            if (SteamUserId != 0) //backward compatibility
            {
                MyPlayer controller = Sync.Players.GetPlayerById(new MyPlayer.PlayerId(SteamUserId));
                if (controller != null)
                {
                    IDModule.Owner     = controller.Identity.IdentityId;
                    IDModule.ShareMode = MyOwnershipShareModeEnum.Faction;
                }
            }
            SteamUserId = 0;

            m_takeSpawneeOwnership = (objectBuilder as MyObjectBuilder_MedicalRoom).TakeOwnership;
            m_setFactionToSpawnee  = (objectBuilder as MyObjectBuilder_MedicalRoom).SetFaction;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            InitializeConveyorEndpoint();
            SinkComp.Update();

            AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(SinkComp, this));

            if (this.CubeGrid.CreatePhysics)
            {
                Components.Add <MyRespawnComponent>(new MyRespawnComponent());
            }

            m_healingAllowed            = medicalRoomDefinition.HealingAllowed;
            m_refuelAllowed             = medicalRoomDefinition.RefuelAllowed;
            m_suitChangeAllowed         = medicalRoomDefinition.SuitChangeAllowed;
            m_customWardrobesEnabled    = medicalRoomDefinition.CustomWardrobesEnabled;
            m_forceSuitChangeOnRespawn  = medicalRoomDefinition.ForceSuitChangeOnRespawn;
            m_customWardrobeNames       = medicalRoomDefinition.CustomWardrobeNames;
            m_respawnSuitName           = medicalRoomDefinition.RespawnSuitName;
            m_spawnWithoutOxygenEnabled = medicalRoomDefinition.SpawnWithoutOxygenEnabled;
            RespawnAllowed = medicalRoomDefinition.RespawnAllowed;
        }
        protected override void LoadDynamic()
        {
            try
            {
                HashSet <Object> rawEntities = GetBackingDataHashSet();
                Dictionary <long, BaseObject> internalDataCopy = new Dictionary <long, BaseObject>(GetInternalData());

                //Update the main data mapping
                foreach (Object entity in rawEntities)
                {
                    try
                    {
                        if (!IsValidEntity(entity))
                        {
                            continue;
                        }

                        MyObjectBuilder_CubeBlock baseEntity = (MyObjectBuilder_CubeBlock)CubeBlockEntity.InvokeEntityMethod(entity, CubeBlockEntity.CubeBlockGetObjectBuilderMethod);
                        if (baseEntity == null)
                        {
                            continue;
                        }

                        Vector3I cubePosition           = baseEntity.Min;
                        long     packedBlockCoordinates = (long)cubePosition.X + (long)cubePosition.Y * 10000 + (long)cubePosition.Z * 100000000;

                        //If the original data already contains an entry for this, skip creation
                        if (internalDataCopy.ContainsKey(packedBlockCoordinates))
                        {
                            CubeBlockEntity matchingCubeBlock = (CubeBlockEntity)GetEntry(packedBlockCoordinates);
                            if (matchingCubeBlock.IsDisposed)
                            {
                                continue;
                            }

                            matchingCubeBlock.BackingObject = entity;
                            matchingCubeBlock.ObjectBuilder = baseEntity;
                        }
                        else
                        {
                            CubeBlockEntity newCubeBlock = null;

                            if (BlockRegistry.Instance.ContainsGameType(baseEntity.TypeId))
                            {
                                //Get the matching API type from the registry
                                Type apiType = BlockRegistry.Instance.GetAPIType(baseEntity.TypeId);

                                //Create a new API cube block
                                newCubeBlock = (CubeBlockEntity)Activator.CreateInstance(apiType, new object[] { m_parent, baseEntity, entity });
                            }

                            if (newCubeBlock == null)
                            {
                                newCubeBlock = new CubeBlockEntity(m_parent, baseEntity, entity);
                            }

                            AddEntry(packedBlockCoordinates, newCubeBlock);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.ErrorLog.WriteLine(ex);
                    }
                }

                //Cleanup old entities
                foreach (var entry in internalDataCopy)
                {
                    try
                    {
                        if (!rawEntities.Contains(entry.Value.BackingObject))
                        {
                            DeleteEntry(entry.Value);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.ErrorLog.WriteLine(ex);
                    }
                }

                if (GetInternalData().Count > 0 && m_isLoading)
                {
                    //Trigger an event now that this cube grid has finished loading
                    EntityEventManager.EntityEvent newEvent = new EntityEventManager.EntityEvent();
                    newEvent.type      = EntityEventManager.EntityEventType.OnCubeGridLoaded;
                    newEvent.timestamp = DateTime.Now;
                    newEvent.entity    = this.m_parent;
                    newEvent.priority  = 1;
                    EntityEventManager.Instance.AddEvent(newEvent);

                    m_isLoading = false;
                }
            }
            catch (Exception ex)
            {
                LogManager.ErrorLog.WriteLine(ex);
            }
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;
            base.Init(objectBuilder, cubeGrid);

            m_inputInventory = new MyInventory(
                ProductionBlockDefinition.InventoryMaxVolume,
                ProductionBlockDefinition.InventorySize,
                MyInventoryFlags.CanReceive,
                this);

            m_outputInventory = new MyInventory(
                ProductionBlockDefinition.InventoryMaxVolume,
                ProductionBlockDefinition.InventorySize,
                MyInventoryFlags.CanSend,
                this);

            var ob = (MyObjectBuilder_ProductionBlock)objectBuilder;

            if (ob.InputInventory != null)
            {
                InputInventory.Init(ob.InputInventory);
            }
            if (ob.OutputInventory != null)
            {
                OutputInventory.Init(ob.OutputInventory);
            }

            m_nextItemId = ob.NextItemId;
            bool nextIdWasZero = m_nextItemId == 0;

            base.IsWorkingChanged += CubeBlock_IsWorkingChanged;

            PowerReceiver = new MyPowerReceiver(
                MyConsumerGroupEnum.Factory,
                false,
                ProductionBlockDefinition.OperationalPowerConsumption,
                ComputeRequiredPower);
            PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged;
            PowerReceiver.Update();
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(PowerReceiver, this));

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            if (ob.Queue != null)
            {
                m_queue.Clear();
                if (m_queue.Capacity < ob.Queue.Length)
                {
                    m_queue.Capacity = ob.Queue.Length;
                }
                for (int i = 0; i < ob.Queue.Length; ++i)
                {
                    var item = ob.Queue[i];
                    Debug.Assert(item.ItemId != null || nextIdWasZero, "Item index was null while next id for production block was given non-zero. This is inconsistency.");

                    var deserializedItem = DeserializeQueueItem(item);
                    Debug.Assert(deserializedItem.Blueprint != null, "Could not add item into production block's queue: Blueprint was not found.");
                    if (deserializedItem.Blueprint != null)
                    {
                        m_queue.Add(deserializedItem);
                        MySandboxGame.Log.WriteLine(string.Format("Could not add item into production block's queue: Blueprint {0} was not found.", item.Id));
                    }
                }

                UpdatePower();
            }

            m_useConveyorSystem = ob.UseConveyorSystem;

            m_lastUpdateTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;
        }
예제 #37
0
 public CubeItemModel(MyObjectBuilder_CubeBlock cube, MyObjectBuilder_CubeBlockDefinition definition)
 {
     SetProperties(cube, definition);
 }
 void IMyCubeBlock.Init(MyObjectBuilder_CubeBlock builder, IMyCubeGrid cubeGrid)
 {
     Init(builder, cubeGrid);
 }
예제 #39
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);
            m_cubeGrid = cubeGrid;

            MyDebug.AssertDebug(BlockDefinition is MyAssemblerDefinition);
            m_assemblerDef = BlockDefinition as MyAssemblerDefinition;

            InputInventory.Constraint  = m_assemblerDef.InputInventoryConstraint;
            OutputInventory.Constraint = m_assemblerDef.OutputInventoryConstraint;

            if (Sync.IsServer)
            {
                OutputInventory.ContentsChanged += OutputInventory_ContentsChanged;
            }

            bool removed = InputInventory.FilterItemsUsingConstraint();

            Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder.");

            var builder = (MyObjectBuilder_Assembler)objectBuilder;

            if (builder.OtherQueue != null)
            {
                m_otherQueue.Clear();
                if (m_otherQueue.Capacity < builder.OtherQueue.Length)
                {
                    m_otherQueue.Capacity = builder.OtherQueue.Length;
                }
                for (int i = 0; i < builder.OtherQueue.Length; ++i)
                {
                    var item = builder.OtherQueue[i];

                    var blueprint = MyDefinitionManager.Static.TryGetBlueprintDefinitionByResultId(item.Id);
                    if (blueprint != null)
                    {
                        m_otherQueue.Add(new QueueItem()
                        {
                            Blueprint = blueprint,
                            Amount    = item.Amount,
                        });
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLine(string.Format("No blueprint that produces a single result with Id '{0}'", item.Id));
                    }
                }
            }
            CurrentProgress            = builder.CurrentProgress;
            m_disassembleEnabled       = builder.DisassembleEnabled;
            m_repeatAssembleEnabled    = builder.RepeatAssembleEnabled;
            m_repeatDisassembleEnabled = builder.RepeatDisassembleEnabled;
            m_slave = builder.SlaveEnabled;
            UpdateInventoryFlags();

            UpgradeValues.Add("Productivity", 0f);
            UpgradeValues.Add("PowerEfficiency", 1f);

            OnUpgradeValuesChanged += UpdateDetailedInfo;

            PowerReceiver.RequiredInputChanged += PowerReceiver_RequiredInputChanged;
            UpdateDetailedInfo();
        }
예제 #40
0
        //[TerminalValues(MySpaceTexts.SwitchText_On, MySpaceTexts.SwitchText_Off)]
        //[Terminal(2, MyPropertyDisplayEnum.Switch, MySpaceTexts.Terminal_UseConveyorSystem, MySpaceTexts.Blank)]
        //[Obfuscation(Feature = Obfuscator.NoRename, Exclude = true)]
        //public MyStringId UseConveyorSystemGui
        //{
        //    get { return m_useConveyorSystem ? MySpaceTexts.SwitchText_On : MySpaceTexts.SwitchText_Off; }
        //    set
        //    {
        //        if (m_useConveyorSystem != (value == MySpaceTexts.SwitchText_On))
        //        {
        //            m_useConveyorSystem = (value == MySpaceTexts.SwitchText_On);
        //            OnPropertiesChanged();
        //        }
        //    }
        //}
        //[TerminalValueSetter(2)]
        //public void RequestUseConveyorSystemChange(MyStringId newVal)
        //{
        //    MySyncConveyors.SendChangeUseConveyorSystemRequest(EntityId, newVal == MySpaceTexts.SwitchText_On);
        //}

        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;
            var ob = builder as MyObjectBuilder_SmallMissileLauncher;


            MyStringHash resourceSinkGroup;
            var          weaponBlockDefinition = BlockDefinition as MyWeaponBlockDefinition;

            if (weaponBlockDefinition != null && this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(weaponBlockDefinition.InventoryMaxVolume, new Vector3(1.2f, 0.98f, 0.98f), MyInventoryFlags.CanReceive);
                Components.Add <MyInventoryBase>(inventory);
                resourceSinkGroup = weaponBlockDefinition.ResourceSinkGroup;
            }
            else
            {
                if (this.GetInventory() == null) // this could be already inicialized object builder
                {
                    MyInventory inventory = null;
                    if (cubeGrid.GridSizeEnum == MyCubeSize.Small)
                    {
                        inventory = new MyInventory(240.0f / 1000, new Vector3(1.2f, 0.45f, 0.45f), MyInventoryFlags.CanReceive); // 4 missiles
                    }
                    else
                    {
                        inventory = new MyInventory(1140.0f / 1000, new Vector3(1.2f, 0.98f, 0.98f), MyInventoryFlags.CanReceive); // 19 missiles
                    }
                    Components.Add(inventory);
                }

                resourceSinkGroup = MyStringHash.GetOrCompute("Defense");
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                resourceSinkGroup,
                MyEnergyConstants.MAX_REQUIRED_POWER_SHIP_GUN,
                () => (Enabled && IsFunctional) ? ResourceSink.MaxRequiredInput : 0.0f);
            ResourceSink = sinkComp;
            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;

            base.Init(builder, cubeGrid);

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }
            ResourceSink.Update();
            this.GetInventory().Init(ob.Inventory);
            m_gunBase.Init(ob.GunBase, BlockDefinition, this);
            m_shotsLeftInBurst = m_gunBase.ShotsInBurst;

            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink, this));

            m_useConveyorSystem.Value = ob.UseConveyorSystem;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            LoadDummies();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;
        }
예제 #41
0
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            base.Init(builder, cubeGrid);
            ProfilerShort.Begin("FP.Init");
            CheckConnectionAllowed = true;
            var ob = builder as MyObjectBuilder_FracturedBlock;

            if (ob.Shapes.Count == 0)
            {
                ProfilerShort.End();
                if (ob.CreatingFracturedBlock)
                {
                    return;
                }
                Debug.Fail("No relevant shape was found for fractured block. It was probably reexported and names changed.");
                throw new Exception("No relevant shape was found for fractured block. It was probably reexported and names changed.");
            }

            OriginalBlocks = new List <MyDefinitionId>();
            Orientations   = new List <MyBlockOrientation>();
            var lst = new List <HkdShapeInstanceInfo>();

            foreach (var def in ob.BlockDefinitions)
            {
                var blockDef = MyDefinitionManager.Static.GetCubeBlockDefinition(def);

                var model = blockDef.Model;
                if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null)
                {
                    MyDestructionData.Static.LoadModelDestruction(model, blockDef, Vector3.One);
                }
                var shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0];
                var si    = new HkdShapeInstanceInfo(shape, null, null);
                lst.Add(si);
                m_children.Add(si);
                shape.GetChildren(m_children);
                if (blockDef.BuildProgressModels != null)
                {
                    foreach (var progress in blockDef.BuildProgressModels)
                    {
                        model = progress.File;
                        if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null)
                        {
                            MyDestructionData.Static.LoadModelDestruction(model, blockDef, Vector3.One);
                        }
                        shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0];
                        si    = new HkdShapeInstanceInfo(shape, null, null);
                        lst.Add(si);
                        m_children.Add(si);
                        shape.GetChildren(m_children);
                    }
                }


                OriginalBlocks.Add(def);
            }

            foreach (var or in ob.BlockOrientations)
            {
                Orientations.Add(or);
            }

            if (ob.MultiBlocks.Count > 0)
            {
                MultiBlocks = new List <MultiBlockPartInfo>();
                foreach (var mbpart in ob.MultiBlocks)
                {
                    if (mbpart != null)
                    {
                        MultiBlocks.Add(new MultiBlockPartInfo()
                        {
                            MultiBlockDefinition = mbpart.MultiBlockDefinition, MultiBlockId = mbpart.MultiBlockId
                        });
                    }
                    else
                    {
                        MultiBlocks.Add(null);
                    }
                }
            }

            m_shapes.AddRange(ob.Shapes);
            for (int i = 0; i < m_children.Count; i++)
            {
                var child = m_children[i];
                Func <MyObjectBuilder_FracturedBlock.ShapeB, bool> x = s => s.Name == child.ShapeName;
                var result = m_shapes.Where(x);
                if (result.Count() > 0)
                {
                    var found = result.First();
                    var m     = Matrix.CreateFromQuaternion(found.Orientation);
                    m.Translation = child.GetTransform().Translation;
                    var si = new HkdShapeInstanceInfo(child.Shape.Clone(), m);
                    if (found.Fixed)
                    {
                        si.Shape.SetFlagRecursively(HkdBreakableShape.Flags.IS_FIXED);
                    }
                    lst.Add(si);
                    m_shapeInfos.Add(si);
                    m_shapes.Remove(found);
                }
                else
                {
                    child.GetChildren(m_children);
                }
            }

            if (m_shapeInfos.Count == 0)
            {
                m_children.Clear();
                ProfilerShort.End();
                Debug.Fail("No relevant shape was found for fractured block. It was probably reexported and names changed.");
                throw new Exception("No relevant shape was found for fractured block. It was probably reexported and names changed.");
            }

            foreach (var shape in m_shapeInfos)
            {
                if (!string.IsNullOrEmpty(shape.Shape.Name))
                {
                    Render.AddPiece(shape.Shape.Name, Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(shape.GetTransform().GetOrientation())));
                }
            }

            if (CubeGrid.CreatePhysics)
            {
                HkdBreakableShape compound = new HkdCompoundBreakableShape(null, m_shapeInfos);
                ((HkdCompoundBreakableShape)compound).RecalcMassPropsFromChildren();
                Shape = compound;
                var mp = new HkMassProperties();
                compound.BuildMassProperties(ref mp);
                Shape = new HkdBreakableShape(compound.GetShape(), ref mp);
                compound.RemoveReference();
                foreach (var si in m_shapeInfos)
                {
                    var siRef = si;
                    Shape.AddShape(ref siRef);
                }
                Shape.SetStrenght(MyDestructionConstants.STRENGTH);
                CreateMountPoints();
            }
            m_children.Clear();
            foreach (var si in m_shapeInfos)
            {
                si.Shape.RemoveReference();
            }
            foreach (var si in lst)
            {
                si.RemoveReference();
            }
            m_shapeInfos.Clear();

            ProfilerShort.End();
        }
예제 #42
0
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     SlimBlock.HasPhysics = BlockDefinition.HasPhysics;
     base.Init(objectBuilder, cubeGrid);
 }
예제 #43
0
        public MyObjectBuilder_CubeBlock ConvertToOriginalBlocksWithFractureComponent()
        {
            List <MyObjectBuilder_CubeBlock> blockBuilders = new List <MyObjectBuilder_CubeBlock>();
            Quaternion q;

            for (int i = 0; i < OriginalBlocks.Count; ++i)
            {
                var defId = OriginalBlocks[i];
                MyCubeBlockDefinition def;
                MyDefinitionManager.Static.TryGetCubeBlockDefinition(defId, out def);
                if (def == null)
                {
                    Debug.Fail("Cube block definition not found");
                    continue;
                }
                var orientation = Orientations[i];
                MultiBlockPartInfo multiBlockInfo = MultiBlocks != null && MultiBlocks.Count > i ? MultiBlocks[i] : null;

                MyObjectBuilder_CubeBlock blockBuilder = MyObjectBuilderSerializer.CreateNewObject(defId) as MyObjectBuilder_CubeBlock;
                orientation.GetQuaternion(out q);
                blockBuilder.Orientation          = q;
                blockBuilder.Min                  = Position;
                blockBuilder.MultiBlockId         = multiBlockInfo != null ? multiBlockInfo.MultiBlockId : 0;
                blockBuilder.MultiBlockDefinition = null;
                if (multiBlockInfo != null)
                {
                    blockBuilder.MultiBlockDefinition = multiBlockInfo.MultiBlockDefinition;
                }
                blockBuilder.ComponentContainer = new MyObjectBuilder_ComponentContainer();

                var fractureBuilder = new MyObjectBuilder_FractureComponentCubeBlock();
                m_tmpNamesAndBuildProgress.Clear();
                GetAllBlockBreakableShapeNames(def, m_tmpNamesAndBuildProgress);
                float buildProgress;
                ConvertAllShapesToFractureComponentShapeBuilder(Shape, ref Matrix.Identity, orientation, m_tmpNamesAndBuildProgress, fractureBuilder, out buildProgress);
                m_tmpNamesAndBuildProgress.Clear();
                // Count of shapes can be 0!
                if (fractureBuilder.Shapes.Count == 0)
                {
                    continue;
                }

                float previousBuildRatioUpperBound = 0f;
                if (def.BuildProgressModels != null)
                {
                    foreach (var progress in def.BuildProgressModels)
                    {
                        if (progress.BuildRatioUpperBound >= buildProgress)
                        {
                            break;
                        }

                        previousBuildRatioUpperBound = progress.BuildRatioUpperBound;
                    }
                }

                var componentData = new MyObjectBuilder_ComponentContainer.ComponentData();
                componentData.TypeId    = typeof(MyFractureComponentBase).Name;
                componentData.Component = fractureBuilder;
                blockBuilder.ComponentContainer.Components.Add(componentData);
                blockBuilder.BuildPercent = buildProgress;
                Debug.Assert(buildProgress > previousBuildRatioUpperBound);
                blockBuilder.IntegrityPercent = MyDefinitionManager.Static.DestructionDefinition.ConvertedFractureIntegrityRatio * buildProgress;

                if (i == 0 && CubeGrid.GridSizeEnum == MyCubeSize.Small)
                {
                    return(blockBuilder);
                }

                blockBuilders.Add(blockBuilder);
            }

            if (blockBuilders.Count > 0)
            {
                MyObjectBuilder_CompoundCubeBlock compoundBuilder = MyCompoundCubeBlock.CreateBuilder(blockBuilders);
                return(compoundBuilder);
            }

            return(null);
        }
예제 #44
0
        private void Process(CommandFeedback feedback, IMyCubeGrid grid)
        {
            if (grid.CustomName == null || !grid.CustomName.StartsWithICase("EqProcBuild"))
            {
                return;
            }
            var ob = grid.GetObjectBuilder(true) as MyObjectBuilder_CubeGrid;

            if (ob == null)
            {
                return;
            }
            this.Info("Begin processing {0}", grid.CustomName);
            feedback?.Invoke("Processing {0}", grid.CustomName);
            try
            {
                var dummyDel  = new List <MyTuple <MyObjectBuilder_CubeBlock, string> >();
                var blockKeep = new List <MyObjectBuilder_CubeBlock>();
                var blockMap  = new Dictionary <Vector3I, MyObjectBuilder_CubeBlock>(Vector3I.Comparer);
                foreach (var block in ob.CubeBlocks)
                {
                    var mount = false;
                    foreach (var name in block.ConfigNames())
                    {
                        if (!name.StartsWithICase(MountDelegated) && !name.StartsWithICase(ReservedSpaceDelegated))
                        {
                            continue;
                        }
                        dummyDel.Add(MyTuple.Create(block, name));
                        mount = true;
                        break;
                    }
                    if (mount)
                    {
                        continue;
                    }

                    var      blockMin = (Vector3I)block.Min;
                    Vector3I blockMax;
                    BlockTransformations.ComputeBlockMax(block, out blockMax);
                    for (var rangeItr = new Vector3I_RangeIterator(ref blockMin, ref blockMax); rangeItr.IsValid(); rangeItr.MoveNext())
                    {
                        blockMap[rangeItr.Current] = block;
                    }
                    blockKeep.Add(block);
                }
                this.Info("Found {0} blocks to keep, {1} block mounts to remap", blockKeep.Count, dummyDel.Count);
                foreach (var pair in dummyDel)
                {
                    var block   = pair.Item1;
                    var useName = pair.Item2;

                    IEnumerable <Base6Directions.Direction> dirs = Base6Directions.EnumDirections;
                    var def       = MyDefinitionManager.Static.GetCubeBlockDefinition(pair.Item1);
                    var transform = new MatrixI(block.BlockOrientation);
                    if (def?.MountPoints != null)
                    {
                        var mountDirs = new HashSet <Base6Directions.Direction>();
                        foreach (var mount in def.MountPoints)
                        {
                            mountDirs.Add(Base6Directions.GetDirection(Vector3I.TransformNormal(mount.Normal, ref transform)));
                        }
                    }

                    var args     = useName.Split(' ');
                    var keepArgs = new List <string>(args.Length);
                    foreach (var arg in args)
                    {
                        if (arg.StartsWithICase(PartDummyUtils.ArgumentMountDirection))
                        {
                            Base6Directions.Direction dir;
                            if (Enum.TryParse(arg.Substring(2), out dir))
                            {
                                dirs = new[] { transform.GetDirection(Base6Directions.GetOppositeDirection(dir)) }
                            }
                            ;
                            else
                            {
                                this.Error("Failed to parse direction argument \"{0}\"", arg);
                                feedback?.Invoke("Error: Failed to parse direction argument \"{0}\"", arg);
                            }
                        }
                        else
                        {
                            keepArgs.Add(arg);
                        }
                    }
                    useName = string.Join(" ", keepArgs);

                    MyObjectBuilder_CubeBlock outputBlock = null;
                    var outputDir = Base6Directions.Direction.Forward;
                    foreach (var dir in dirs)
                    {
                        MyObjectBuilder_CubeBlock tmp;
                        if (!blockMap.TryGetValue(block.Min + Base6Directions.GetIntVector(dir), out tmp))
                        {
                            continue;
                        }
                        if (tmp.ConfigNames().Any(x => x.StartsWithICase(MountDelegated)))
                        {
                            continue;
                        }
                        if (outputBlock != null)
                        {
                            this.Error("Multiple directions found for {0}", pair.Item2);
                            feedback?.Invoke("Error: Multiple directions found for {0}", pair.Item2);
                        }
                        outputBlock = tmp;
                        outputDir   = dir;
                    }
                    if (outputBlock == null || !ApplyDelegate(ob, block, useName, outputBlock, outputDir))
                    {
                        this.Error("Failed to find delegated mount point for {0}", pair.Item2);
                        feedback?.Invoke("Error: Failed to find delegated mount point for {0}", pair.Item2);
                    }
                }
                ob.CubeBlocks = blockKeep;

                // Grab related grids!
                var relatedGrids = new HashSet <IMyCubeGrid> {
                    grid
                };
                var scanRelated           = new Queue <IMyCubeGrid>();
                var relatedGridController = new Dictionary <IMyCubeGrid, IMyCubeBlock>();
                scanRelated.Enqueue(grid);
                while (scanRelated.Count > 0)
                {
                    var          subGrid = scanRelated.Dequeue();
                    IMyCubeBlock controllerForThisGrid = null;
                    relatedGridController.TryGetValue(subGrid, out controllerForThisGrid);

                    subGrid.GetBlocks(null, (y) =>
                    {
                        var x = y?.FatBlock;
                        if (x == null)
                        {
                            return(false);
                        }
                        var childGrid = (x as IMyMechanicalConnectionBlock)?.TopGrid;
                        if (childGrid != null && relatedGrids.Add(childGrid))
                        {
                            scanRelated.Enqueue(childGrid);
                            relatedGridController[childGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        var parentGrid = (x as IMyAttachableTopBlock)?.Base?.CubeGrid;
                        // ReSharper disable once InvertIf
                        if (parentGrid != null && relatedGrids.Add(parentGrid))
                        {
                            scanRelated.Enqueue(parentGrid);
                            relatedGridController[parentGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        return(false);
                    });
                }
                relatedGrids.Remove(grid);
                var removedNoController = relatedGrids.RemoveWhere(x => !relatedGridController.ContainsKey(x));
                if (removedNoController > 0)
                {
                    this.Error("Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                               removedNoController);
                    feedback?.Invoke("Error: Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                                     removedNoController);
                }
                // Need to add reserved space for subgrids so they don't overlap.  So compute that.  Yay!
                foreach (var rel in relatedGrids)
                {
                    IMyCubeBlock root;
                    if (!relatedGridController.TryGetValue(rel, out root))
                    {
                        this.Error("Unable to find the mechanical connection for grid {0}", rel.CustomName);
                        feedback?.Invoke("Error: Unable to find the mechanical connection for grid {0}",
                                         rel.CustomName);
                        continue;
                    }
                    MyObjectBuilder_CubeBlock blockDest;
                    if (blockMap.TryGetValue(root.Min, out blockDest))
                    {
                        var blockLocal = (MatrixD) new MatrixI(blockDest.BlockOrientation).GetFloatMatrix();
                        blockLocal.Translation = (Vector3I)blockDest.Min * grid.GridSize;
                        var blockWorld = MatrixD.Multiply(blockLocal, grid.WorldMatrix);

                        var worldAABB = rel.WorldAABB;
                        worldAABB = Utilities.TransformBoundingBox(worldAABB, MatrixD.Invert(blockWorld));
                        var gridAABB = new BoundingBoxI(Vector3I.Floor(worldAABB.Min / grid.GridSize), Vector3I.Ceiling(worldAABB.Max / grid.GridSize));
                        var code     = $"{PartMetadata.ReservedSpacePrefix} NE:{gridAABB.Min.X}:{gridAABB.Min.Y}:{gridAABB.Min.Z} PE:{gridAABB.Max.X}:{gridAABB.Max.Y}:{gridAABB.Max.Z}";
                        this.Info("Added reserved space for subgrid {0}: Spec is \"{1}\"", rel.CustomName, code);
                        if (blockDest.Name == null || blockDest.Name.Trim().Length == 0)
                        {
                            blockDest.Name = code;
                        }
                        else
                        {
                            blockDest.Name += PartMetadata.MultiUseSentinel + code;
                        }
                    }
                    else
                    {
                        this.Error("Unable to find the OB for grid block {0} ({1}, {2}, {3}).  Is it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                        feedback?.Invoke("Unable to the find OB for grid block {0} ({1}, {2}, {3}).  Was it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                    }
                }

                var allGrids = new List <MyObjectBuilder_CubeGrid>(relatedGrids.Count + 1)
                {
                    ob
                };
                allGrids.AddRange(relatedGrids.Select(relGrid => relGrid.GetObjectBuilder(false)).OfType <MyObjectBuilder_CubeGrid>());

                // Compose description: TODO I'd love if this actually worked :/
                // var storage = new MyPartMetadata();
                // storage.InitFromGrids(ob, allGrids);
                // var data = Convert.ToBase64String(MyAPIGateway.Utilities.SerializeToBinary(storage.GetObjectBuilder()));

                var defOut = new MyObjectBuilder_PrefabDefinition()
                {
                    Id        = new SerializableDefinitionId(typeof(MyObjectBuilder_PrefabDefinition), grid.CustomName),
                    CubeGrids = allGrids.ToArray()
                };

                var fileName = grid.CustomName + ".sbc";
                this.Info("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);
                feedback?.Invoke("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);

                var mishMash = new MyObjectBuilder_Definitions()
                {
                    Prefabs = new MyObjectBuilder_PrefabDefinition[] { defOut }
                };
                var writer = MyAPIGateway.Utilities.WriteBinaryFileInLocalStorage(fileName, typeof(DesignTools));
                var obCode = MyAPIGateway.Utilities.SerializeToXML(mishMash);
                obCode = obCode.Replace("encoding=\"utf-16\"", "encoding=\"utf-8\"");
                writer.Write(Encoding.UTF8.GetBytes(obCode));
                writer.Close();
            }
            catch (Exception e)
            {
                this.Error("Failed to parse.  Error:\n{0}", e.ToString());
            }
        }
예제 #45
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                this.CalculateRequiredPowerInput);
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);

            m_items = new List <ToolbarItem>(2);
            for (int i = 0; i < 2; i++)
            {
                m_items.Add(new ToolbarItem()
                {
                    EntityID = 0
                });
            }
            Toolbar             = new MyToolbar(MyToolbarType.ButtonPanel, 2, 1);
            Toolbar.DrawNumbers = false;

            var builder = (MyObjectBuilder_SensorBlock)objectBuilder;

            m_fieldMin.Value = Vector3.Clamp(builder.FieldMin, new Vector3(-MaxRange), -Vector3.One);
            m_fieldMax.Value = Vector3.Clamp(builder.FieldMax, Vector3.One, new Vector3(MaxRange));

            PlayProximitySound    = builder.PlaySound;
            DetectPlayers         = builder.DetectPlayers;
            DetectFloatingObjects = builder.DetectFloatingObjects;
            DetectSmallShips      = builder.DetectSmallShips;
            DetectLargeShips      = builder.DetectLargeShips;
            DetectStations        = builder.DetectStations;
            DetectAsteroids       = builder.DetectAsteroids;
            DetectOwner           = builder.DetectOwner;
            DetectFriendly        = builder.DetectFriendly;
            DetectNeutral         = builder.DetectNeutral;
            DetectEnemy           = builder.DetectEnemy;
            m_active.Value        = builder.IsActive;

            Toolbar.Init(builder.Toolbar, this);

            for (int i = 0; i < 2; i++)
            {
                var item = Toolbar.GetItemAtIndex(i);
                if (item == null)
                {
                    continue;
                }
                m_items.RemoveAt(i);
                m_items.Insert(i, ToolbarItem.FromItem(item));
            }
            Toolbar.ItemChanged += Toolbar_ItemChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;


            ResourceSink.IsPoweredChanged     += Receiver_IsPoweredChanged;
            ResourceSink.RequiredInputChanged += Receiver_RequiredInputChanged;
            ResourceSink.Update();

            m_fieldShape = GetHkShape();

            OnClose += delegate(MyEntity self)
            {
                m_fieldShape.RemoveReference();
            };

            m_gizmoColor = new Vector4(0.35f, 0, 0, 0.5f);
        }
예제 #46
0
        /// <summary>
        /// Merges and copies blocks from ship2 into ship1.
        /// </summary>
        /// <param name="model1"></param>
        /// <param name="model2"></param>
        /// <returns></returns>
        internal bool MergeShipParts(StructureCubeGridModel model1, StructureCubeGridModel model2)
        {
            // find closest major axis for both parts.
            var q1 = Quaternion.CreateFromRotationMatrix(Matrix.CreateFromDir(model1.PositionAndOrientation.Value.Forward.RoundToAxis(), model1.PositionAndOrientation.Value.Up.RoundToAxis()));
            var q2 = Quaternion.CreateFromRotationMatrix(Matrix.CreateFromDir(model2.PositionAndOrientation.Value.Forward.RoundToAxis(), model2.PositionAndOrientation.Value.Up.RoundToAxis()));

            // Calculate the rotation between the two.
            var fixRotate = Quaternion.Inverse(q2) * q1;

            fixRotate.Normalize();

            // Rotate the orientation of model2 to (closely) match model1.
            // It's Inverse, as the ship is actually rotated inverse in response to rotation of the cubes.
            model2.RotateCubes(Quaternion.Inverse(fixRotate));

            // At this point ship2 has been reoriented around to closely match ship1.
            // The cubes in ship2 have be reoriended in reverse, so effectly there is no visual difference in ship2, except now all the cubes are aligned to the same X,Y,Z axis as ship1.

            // find two cubes, one from each ship that are closest to each other to use as the reference.
            var pos1    = (Vector3D)model1.PositionAndOrientation.Value.Position;
            var pos2    = (Vector3D)model2.PositionAndOrientation.Value.Position;
            var orient1 = model1.PositionAndOrientation.Value.ToQuaternion();
            var orient2 = model2.PositionAndOrientation.Value.ToQuaternion();
            var multi1  = model1.GridSize.ToLength();
            var multi2  = model2.GridSize.ToLength();

            var maxDistance = float.MaxValue;
            MyObjectBuilder_CubeBlock maxCube1 = null;
            MyObjectBuilder_CubeBlock maxCube2 = null;

            foreach (var cube1 in model1.CubeGrid.CubeBlocks)
            {
                var cPos1 = pos1 + Vector3.Transform(cube1.Min.ToVector3() * multi1, orient1);

                foreach (var cube2 in model2.CubeGrid.CubeBlocks)
                {
                    var cPos2 = pos2 + Vector3.Transform(cube2.Min.ToVector3() * multi2, orient2);

                    var d = Vector3.Distance(cPos1, cPos2);
                    if (maxDistance > d)
                    {
                        maxDistance = d;
                        maxCube1    = cube1;
                        maxCube2    = cube2;
                    }
                }
            }

            // Ignore ships that are too far away from one another.
            // A distance of 4 cubes to allow for large cubes, as we are only using the Min as position, not the entire size of a cube.
            if (maxDistance < (model1.GridSize.ToLength() * 5))
            {
                // calculate offset for merging of closest cubes.
                var cPos1       = pos1 + Vector3.Transform(maxCube1.Min.ToVector3() * multi1, orient1);
                var cPos2       = pos2 + Vector3.Transform(maxCube2.Min.ToVector3() * multi2, orient2);
                var adjustedPos = Vector3.Transform(cPos2 - pos1, VRageMath.Quaternion.Inverse(orient1)) / multi1;
                var offset      = adjustedPos.RoundToVector3I() - maxCube2.Min.ToVector3I();

                // Merge cubes in.
                foreach (var cube2 in model2.CubeGrid.CubeBlocks)
                {
                    var newcube = (MyObjectBuilder_CubeBlock)cube2.Clone();
                    newcube.Min = cube2.Min + offset;
                    model1.CubeGrid.CubeBlocks.Add(newcube);
                }

                // Merge Groupings in.
                foreach (var group in model2.CubeGrid.BlockGroups)
                {
                    var existingGroup = model1.CubeGrid.BlockGroups.FirstOrDefault(bg => bg.Name == group.Name);
                    if (existingGroup == null)
                    {
                        existingGroup = new MyObjectBuilder_BlockGroup {
                            Name = group.Name
                        };
                        model1.CubeGrid.BlockGroups.Add(existingGroup);
                    }

                    foreach (var block in group.Blocks)
                    {
                        existingGroup.Blocks.Add(block + offset);
                    }
                }

                // TODO: Merge Bones.
                //if (model2.CubeGrid.Skeleton != null)
                //{
                //    if (model1.CubeGrid.Skeleton == null)
                //        model1.CubeGrid.Skeleton = new List<BoneInfo>();

                //        for (var i = model2.CubeGrid.Skeleton.Count - 1; i >= 0; i--)
                //        //foreach (var bone in model2.CubeGrid.Skeleton)
                //        {
                //            var bone = model2.CubeGrid.Skeleton[i];
                //            model1.CubeGrid.Skeleton.Insert(0, new BoneInfo()
                //            {
                //                BonePosition = bone.BonePosition + offset,
                //                BoneOffset = bone.BoneOffset
                //            });
                //        }
                //}

                // TODO: Merge ConveyorLines
                // need to fix the rotation of ConveyorLines first.

                return(true);
            }

            return(false);
        }
예제 #47
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var beaconDefinition = BlockDefinition as MyBeaconDefinition;

            Debug.Assert(beaconDefinition != null);

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                MyStringHash.GetOrCompute(beaconDefinition.ResourceSinkGroup),
                MyEnergyConstants.MAX_REQUIRED_POWER_BEACON,
                UpdatePowerInput);

            ResourceSink = sinkComp;

            RadioBroadcaster = new MyRadioBroadcaster(10000);
            if (((MyObjectBuilder_Beacon)objectBuilder).BroadcastRadius != 0)
            {
                RadioBroadcaster.BroadcastRadius = ((MyObjectBuilder_Beacon)objectBuilder).BroadcastRadius;
            }

            base.Init(objectBuilder, cubeGrid);

            sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;
            sinkComp.Update();

            RadioBroadcaster.OnBroadcastRadiusChanged += OnBroadcastRadiusChanged;

            m_largeLight = cubeGrid.GridSizeEnum == MyCubeSize.Large;

            m_light = MyLights.AddLight();

            m_light.Start(MyLight.LightTypeEnum.PointLight, 1.5f);
            m_light.LightOwner         = m_largeLight ? MyLight.LightOwnerEnum.LargeShip : MyLight.LightOwnerEnum.SmallShip;
            m_light.UseInForwardRender = true;
            m_light.Range = 1;

            m_light.GlareOn        = true;
            m_light.GlareIntensity = m_largeLight ? 2 : 1;
            m_light.GlareQuerySize = m_largeLight ? 1.0f : 0.2f;
            m_light.GlareSize      = 1.0f;
            m_light.GlareType      = VRageRender.Lights.MyGlareTypeEnum.Distant;
            m_light.GlareMaterial  = m_largeLight ? "GlareLsLight"
                                                 : "GlareSsLight";
            m_light.GlareMaxDistance = GLARE_MAX_DISTANCE;

            if (m_largeLight)
            {
                m_lightPositionOffset = new Vector3(0f, CubeGrid.GridSize * 0.5f, 0f);
            }
            else
            {
                m_lightPositionOffset = Vector3.Zero;
            }

            UpdateLightPosition();


            AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(ResourceSink, this));

            AnimationRunning = true;
            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            IsWorkingChanged += MyBeacon_IsWorkingChanged;

            ShowOnHUD = false;

            UpdateText();
        }
예제 #48
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            LoadDummies();
            SlimBlock.DeformationRatio = (this.BlockDefinition as MyMergeBlockDefinition).DeformationRatio; // 3x times harder for destruction by high speed

            NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME;
            AddDebugRenderComponent(new MyDebugRenderComponentShipMergeBlock(this));
        }
예제 #49
0
        public override void BeforeCreateBlock(MyCubeBlockDefinition definition, MyEntity builder, MyObjectBuilder_CubeBlock ob, bool buildAsAdmin)
        {
            base.BeforeCreateBlock(definition, builder, ob, buildAsAdmin);

            if (builder != null && MySession.Static.SurvivalMode && !buildAsAdmin)
            {
                ob.IntegrityPercent = MyComponentStack.MOUNT_THRESHOLD;
                ob.BuildPercent     = MyComponentStack.MOUNT_THRESHOLD;
            }
        }
        private void CreateRemovalOrder(NaniteDeconstructionGrid deconstruct, IMySlimBlock startBlock)
        {
            IMySlimBlock currentBlock = startBlock;

            deconstruct.AddingList.Clear();
            deconstruct.GridsProcessed.Clear();

            while (true)
            {
                if (!deconstruct.GridsProcessed.Contains(currentBlock.CubeGrid))
                {
                    ((MyCubeGrid)currentBlock.CubeGrid).OnGridSplit += OnGridSplit;
                    deconstruct.GridsProcessed.Add(currentBlock.CubeGrid);
                }

                MyObjectBuilder_CubeBlock block = (MyObjectBuilder_CubeBlock)currentBlock.GetObjectBuilder();
                MyCubeBlockDefinition     blockDefinition;
                MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition);

                // Get real block max
                Vector3I Max = Vector3I.Zero;
                Vector3I Min = block.Min;
                ComputeMax(blockDefinition, block.BlockOrientation, ref Min, out Max);

                AddNeighbours(deconstruct, currentBlock, Min, new Vector3I(Min.X, Max.Y, Max.Z), -Vector3I.UnitX);
                AddNeighbours(deconstruct, currentBlock, Min, new Vector3I(Max.X, Min.Y, Max.Z), -Vector3I.UnitY);
                AddNeighbours(deconstruct, currentBlock, Min, new Vector3I(Max.X, Max.Y, Min.Z), -Vector3I.UnitZ);
                AddNeighbours(deconstruct, currentBlock, new Vector3I(Max.X, Min.Y, Min.Z), Max, Vector3I.UnitX);
                AddNeighbours(deconstruct, currentBlock, new Vector3I(Min.X, Max.Y, Min.Z), Max, Vector3I.UnitY);
                AddNeighbours(deconstruct, currentBlock, new Vector3I(Min.X, Min.Y, Max.Z), Max, Vector3I.UnitZ);

                // Check if currentBlock is a connector of some kind, then follow it
                AddConnectedGridBlock(deconstruct, currentBlock);

                // Add to removal list
                if (!deconstruct.RemoveList.Contains(currentBlock))
                {
                    deconstruct.RemoveList.AddStart(currentBlock);
                }

                if (deconstruct.AddingList.Count < 1 && deconstruct.AddingGridList.Count < 1)
                {
                    break;
                }

                if (deconstruct.AddingList.Count < 1 && deconstruct.AddingGridList.Count > 0)
                {
                    currentBlock = deconstruct.AddingGridList[0];
                    deconstruct.AddingGridList.Remove(currentBlock);
                    //deconstruct.TreePosition++;
                    //deconstruct.GridTree.Add(new Node<IMySlimBlock>(currentBlock));
                }
                else
                {
                    currentBlock = deconstruct.AddingList[0];
                    deconstruct.AddingList.Remove(currentBlock);
                }
            }

            // Find user defined priority blocks for deconstruction.
            FindPriorityBlocks(deconstruct, startBlock);

            Logging.Instance.WriteLine(string.Format("Block Count: {0}", deconstruct.RemoveList.Count));
            //Logging.Instance.WriteLine(string.Format("Grid Count: {0}", deconstruct.GridsProcessed.Count));
            //Logging.Instance.WriteLine(string.Format("Tree Size: {0}", deconstruct.GridTree.Sum(x => x.All.Count())));
        }
예제 #51
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var sinkComp = new MyResourceSinkComponent();
            sinkComp.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                CalculateRequiredPowerInput);
           
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);
            if (!MyFakes.ENABLE_PROJECTOR_BLOCK)
            {
                return;
            }

            var projectorBuilder = (MyObjectBuilder_ProjectorBase)objectBuilder;
            if (projectorBuilder.ProjectedGrid != null)
            {
                m_projectionOffset = projectorBuilder.ProjectionOffset;
                m_projectionRotation = projectorBuilder.ProjectionRotation;

                m_savedProjection = projectorBuilder.ProjectedGrid;
                KeepProjection = projectorBuilder.KeepProjection;
            }

            m_showOnlyBuildable = projectorBuilder.ShowOnlyBuildable;
            InstantBuildingEnabled = projectorBuilder.InstantBuildingEnabled;
            MaxNumberOfProjections = projectorBuilder.MaxNumberOfProjections;
            MaxNumberOfBlocksPerProjection = projectorBuilder.MaxNumberOfBlocks;
            GetOwnershipFromProjector = projectorBuilder.GetOwnershipFromProjector;

            m_projectionsRemaining = MathHelper.Clamp(projectorBuilder.ProjectionsRemaining, 0, m_maxNumberOfProjections);

			
            IsWorkingChanged += MyProjector_IsWorkingChanged;
            sinkComp.IsPoweredChanged += PowerReceiver_IsPoweredChanged;
			ResourceSink.Update();
            m_statsDirty = true;
            UpdateText();

            NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            CubeGrid.OnBlockAdded += previewGrid_OnBlockAdded;
            CubeGrid.OnBlockRemoved += previewGrid_OnBlockRemoved;
        
            CubeGrid.OnGridSplit += CubeGrid_OnGridSplit;
        }
예제 #52
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;

            var sinkComp = new MyResourceSinkComponent();
            sinkComp.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                ComputeRequiredPower);
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);

            var ob = objectBuilder as MyObjectBuilder_JumpDrive;

            NeedsUpdate |= VRage.ModAPI.MyEntityUpdateEnum.BEFORE_NEXT_FRAME | VRage.ModAPI.MyEntityUpdateEnum.EACH_FRAME | VRage.ModAPI.MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_storedPower.Value = Math.Min(ob.StoredPower,BlockDefinition.PowerNeededForJump);

            m_storedJumpTarget = ob.JumpTarget;
            if (ob.JumpTarget != null)
            {
                m_jumpTarget = MySession.Static.Gpss.GetGps(ob.JumpTarget.Value);
            }

            m_jumpDistanceRatio.Value = ob.JumpRatio;
            m_isRecharging.Value = ob.Recharging;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
            IsWorkingChanged += MyJumpDrive_IsWorkingChanged;

			ResourceSink.Update();
            UpdateEmissivity();
        }
예제 #53
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var sourceDataList = new List <MyResourceSourceInfo>
            {
                new MyResourceSourceInfo {
                    ResourceTypeId = MyResourceDistributorComponent.ElectricityId, DefinedOutput = BlockDefinition.MaxPowerOutput, ProductionToCapacityMultiplier = 60 * 60
                }
            };

            SourceComp.Init(BlockDefinition.ResourceSourceGroup, sourceDataList);
            SourceComp.HasCapacityRemainingChanged += (id, source) => UpdateIsWorking();
            SourceComp.ProductionEnabledChanged    += Source_ProductionEnabledChanged;

            var batteryBuilder = (MyObjectBuilder_BatteryBlock)objectBuilder;

            SourceComp.SetProductionEnabledByType(MyResourceDistributorComponent.ElectricityId, batteryBuilder.ProducerEnabled);

            MaxStoredPower = BlockDefinition.MaxStoredPower;

            ResourceSink.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                Sink_ComputeRequiredPower);

            base.Init(objectBuilder, cubeGrid);

            ResourceSink.Update();

            MyDebug.AssertDebug(BlockDefinition != null);
            MyDebug.AssertDebug(BlockDefinition.Id.TypeId == typeof(MyObjectBuilder_BatteryBlock));

            if (batteryBuilder.CurrentStoredPower >= 0)
            {
                CurrentStoredPower = batteryBuilder.CurrentStoredPower;
            }
            else
            {
                CurrentStoredPower = BlockDefinition.InitialStoredPowerRatio * BlockDefinition.MaxStoredPower;
            }

            m_storedPower.Value = CurrentStoredPower;


            SemiautoEnabled = batteryBuilder.SemiautoEnabled;
            OnlyRecharge    = !batteryBuilder.ProducerEnabled;
            OnlyDischarge   = batteryBuilder.OnlyDischargeEnabled;
            UpdateMaxOutputAndEmissivity();

            UpdateText();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
            IsWorkingChanged += MyBatteryBlock_IsWorkingChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_lastUpdateTime = MySession.Static.GameplayFrameCounter;

            if (IsWorking)
            {
                OnStartWorking();
            }
        }
예제 #54
0
        public static void SpawnPrefab(string prefabToSpawn, MatrixD spawnOrigin, Options options = null)
        {
            if (options == null)
            {
                options = new Options();
            }

            Core.GeneralLog.WriteToLog("SpawnPrefab", $"Spawning... {prefabToSpawn} {options.PreservePrograms}");

            List <MyObjectBuilder_EntityBase> tempList = new List <MyObjectBuilder_EntityBase>();

            try
            {
                MyAPIGateway.Parallel.Start(delegate
                {
                    List <MyObjectBuilder_Cockpit> myCockpitList             = new List <MyObjectBuilder_Cockpit>();
                    List <MyObjectBuilder_RemoteControl> myRemoteControlList = new List <MyObjectBuilder_RemoteControl>();

                    //WeaponSwapper.ProcessPrefab(prefab, options);

                    bool cubeGridZero             = true;
                    MatrixD mainGridInverseMatrix = MatrixD.Identity;
                    MatrixD mainGridSpawnMatrix   = MatrixD.Identity;

                    MyPrefabDefinition prefabs = MyDefinitionManager.Static.GetPrefabDefinition(prefabToSpawn);
                    if (prefabs.CubeGrids[0] == null)
                    {
                        return;
                    }


                    MyAPIGateway.Entities.RemapObjectBuilderCollection(prefabs.CubeGrids);

                    foreach (MyObjectBuilder_CubeGrid gridBuilderOrig in prefabs.CubeGrids)
                    {
                        MyObjectBuilder_CubeGrid gridBuilder = (MyObjectBuilder_CubeGrid)gridBuilderOrig.Clone();                          // TODO adds lag, need to fix?  problem is all cube blocks need to be cloned.

                        //MyObjectBuilderSerializer

                        tempList.Add(gridBuilder);

                        options.EntityId = gridBuilder.EntityId;
                        CubeProcessing.GeneralGridSettings(gridBuilder, options);

                        foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks)
                        {
                            if (block == null)
                            {
                                continue;
                            }
                            CubeProcessing.GeneralBlockSettings(block, options);

                            Action <MyObjectBuilder_CubeBlock, Options, MyCubeSize> action;
                            CubeProcessing.CubeBlockProcessing.TryGetValue(block.GetType(), out action);
                            action?.Invoke(block, options, gridBuilder.GridSizeEnum);

                            if (!cubeGridZero)
                            {
                                continue;
                            }
                            if (block.GetType() == typeof(MyObjectBuilder_Cockpit))
                            {
                                myCockpitList.Add(block as MyObjectBuilder_Cockpit);
                            }
                            if (block.GetType() == typeof(MyObjectBuilder_RemoteControl))
                            {
                                myRemoteControlList.Add(block as MyObjectBuilder_RemoteControl);
                            }
                        }

                        MyPositionAndOrientation gridPositionAndOrientation = gridBuilder.PositionAndOrientation ?? MyPositionAndOrientation.Default;
                        MatrixD gridTransform = gridPositionAndOrientation.GetMatrix();
                        MatrixD subGridOffset = MatrixD.Identity;

                        if (cubeGridZero)
                        {
                            mainGridInverseMatrix = MatrixD.Invert(ref gridTransform);
                            mainGridSpawnMatrix   = spawnOrigin;

                            MyObjectBuilder_CubeBlock mainOrientationBlock = GetMainOrientationBlock(myCockpitList, myRemoteControlList);

                            if (mainOrientationBlock != null)
                            {
                                Matrix blockMatrix;
                                ((MyBlockOrientation)mainOrientationBlock.BlockOrientation).GetMatrix(out blockMatrix);
                                blockMatrix.Translation = ((Vector3I)mainOrientationBlock.Min) * (gridBuilder.GridSizeEnum == MyCubeSize.Large ? 2.5f : 0.5f);

                                Matrix inverseBlockMatrix = Matrix.Invert(ref blockMatrix);
                                mainGridSpawnMatrix       = inverseBlockMatrix * mainGridSpawnMatrix;
                            }
                        }
                        else
                        {
                            subGridOffset = gridTransform * mainGridInverseMatrix;
                        }

                        if (gridBuilder.PositionAndOrientation != null)
                        {
                            MatrixD gridSpawnMatrix            = subGridOffset * mainGridSpawnMatrix;
                            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(ref gridSpawnMatrix);
                        }
                        cubeGridZero = false;
                    }
                    tempList.ForEach(item => MyAPIGateway.Entities.CreateFromObjectBuilderParallel(item, true));
                    //foreach (MyObjectBuilder_EntityBase item in tempList) MyAPIGateway.Entities.CreateFromObjectBuilderParallel(item, true);
                    //MyAPIGateway.Multiplayer.SendEntitiesCreated(tempList); // may need to uncomment this if entities aren't syncing
                    tempList.Clear();
                    myCockpitList.Clear();
                    myRemoteControlList.Clear();
                });
            }
            catch (Exception e)
            {
                Core.GeneralLog.WriteToLog("prefabToSpawn", $"Prefab Processing Exception! {e}");
            }
        }
예제 #55
0
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            m_defId = builder.GetId();
            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(m_defId) as MyShipDrillDefinition;

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                def.ResourceSinkGroup,
                ComputeMaxRequiredPower(),
                ComputeRequiredPower);
            ResourceSink = sinkComp;

            m_drillBase = new MyDrillBase(this,
                                          MyDrillConstants.DRILL_SHIP_DUST_EFFECT,
                                          MyDrillConstants.DRILL_SHIP_DUST_STONES_EFFECT,
                                          MyDrillConstants.DRILL_SHIP_SPARKS_EFFECT,
                                          new MyDrillSensorSphere(def.SensorRadius, def.SensorOffset),
                                          new MyDrillCutOut(def.SensorOffset, def.SensorRadius),
                                          HEAD_SLOWDOWN_TIME_IN_SECONDS, -0.4f, 0.4f, 1
                                          );

            base.Init(builder, cubeGrid);

            m_blockLength    = def.Size.Z;
            m_cubeSideLength = MyDefinitionManager.Static.GetCubeSize(def.CubeSize);

            float   inventoryVolume = def.Size.X * def.Size.Y * def.Size.Z * m_cubeSideLength * m_cubeSideLength * m_cubeSideLength * 0.5f;
            Vector3 inventorySize   = new Vector3(def.Size.X, def.Size.Y, def.Size.Z * 0.5f);

            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(inventoryVolume, inventorySize, MyInventoryFlags.CanSend);
                Components.Add <MyInventoryBase>(inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            this.GetInventory().Constraint = new MyInventoryConstraint(MySpaceTexts.ToolTipItemFilter_AnyOre)
                                             .AddObjectBuilderType(typeof(MyObjectBuilder_Ore));

            SlimBlock.UsesDeformation  = false;
            SlimBlock.DeformationRatio = def.DeformationRatio; // 3x times harder for destruction by high speed


            m_drillBase.OutputInventory = this.GetInventory();
            m_drillBase.IgnoredEntities.Add(this);
            m_drillBase.OnWorldPositionChanged(WorldMatrix);
            m_wantsToCollect = false;
            AddDebugRenderComponent(new MyDebugRenderCompomentDrawDrillBase(m_drillBase));


            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink.Update();

            AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(ResourceSink, this));

            var obDrill = (MyObjectBuilder_Drill)builder;

            this.GetInventory().Init(obDrill.Inventory);

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            m_useConveyorSystem.Value = obDrill.UseConveyorSystem;

            UpdateDetailedInfo();

            m_wantsToDrill    = obDrill.Enabled;
            IsWorkingChanged += OnIsWorkingChanged;

            m_drillBase.m_drillMaterial = MyStringHash.GetOrCompute("ShipDrill");
            m_drillBase.m_idleSoundLoop = new MySoundPair("ToolShipDrillIdle");
        }
예제 #56
0
        public static void GetMountedComponents(Dictionary <MyDefinitionId, int> addToDictionary, MyObjectBuilder_CubeBlock block)
        {
            int topGroup     = 0;
            int topComponent = 0;

            MyCubeBlockDefinition blockDef = null;

            MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDef);
            Debug.Assert(blockDef != null, "Could not find block definition");
            if (blockDef == null)
            {
                return;
            }

            Debug.Assert(block != null, "Getting mounted components of a null block");
            if (block == null)
            {
                return;
            }

            float integrity = block.IntegrityPercent * blockDef.MaxIntegrity;

            CalculateIndicesInternal(integrity, blockDef, ref topGroup, ref topComponent);

            Debug.Assert(topGroup < blockDef.Components.Count(), "Component group overflow in CalculateItemRequirements");
            if (topGroup >= blockDef.Components.Count())
            {
                return;
            }

            Debug.Assert(topComponent < blockDef.Components[topGroup].Count, "Component overflow in CalculateItemRequirements");
            if (topComponent >= blockDef.Components[topGroup].Count)
            {
                return;
            }

            int mountCount = topComponent;

            if (integrity >= MOUNT_THRESHOLD)
            {
                mountCount++;
            }

            MyDefinitionId componentId;
            int            count = 0;

            for (int group = 0; group < topGroup; ++group)
            {
                componentId = blockDef.Components[group].Definition.Id;
                count       = addToDictionary.GetValueOrDefault(componentId, 0);
                addToDictionary[componentId] = count + blockDef.Components[group].Count;
            }
            componentId = blockDef.Components[topGroup].Definition.Id;
            count       = addToDictionary.GetValueOrDefault(componentId, 0);
            addToDictionary[componentId] = count + mountCount;
        }
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     SlimBlock.HasPhysics = BlockDefinition.HasPhysics;
     base.Init(objectBuilder, cubeGrid);
 }
예제 #58
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;
            base.Init(objectBuilder, cubeGrid);

            m_items = new List <ToolbarItem>(2);
            for (int i = 0; i < 2; i++)
            {
                m_items.Add(new ToolbarItem()
                {
                    EntityID = 0
                });
            }
            Toolbar             = new MyToolbar(MyToolbarType.ButtonPanel, 2, 1);
            Toolbar.DrawNumbers = false;

            var builder = (MyObjectBuilder_SensorBlock)objectBuilder;

            m_fieldMin = Vector3.Clamp(builder.FieldMin, new Vector3(-50.0f), -Vector3.One);
            m_fieldMax = Vector3.Clamp(builder.FieldMax, Vector3.One, new Vector3(50.0f));

            DetectPlayers         = builder.DetectPlayers;
            DetectFloatingObjects = builder.DetectFloatingObjects;
            DetectSmallShips      = builder.DetectSmallShips;
            DetectLargeShips      = builder.DetectLargeShips;
            DetectStations        = builder.DetectStations;
            DetectAsteroids       = builder.DetectAsteroids;
            DetectOwner           = builder.DetectOwner;
            DetectFriendly        = builder.DetectFriendly;
            DetectNeutral         = builder.DetectNeutral;
            DetectEnemy           = builder.DetectEnemy;
            m_active = builder.IsActive;

            Toolbar.Init(builder.Toolbar, this);

            for (int i = 0; i < 2; i++)
            {
                var item = Toolbar.GetItemAtIndex(i);
                if (item == null)
                {
                    continue;
                }
                m_items.RemoveAt(i);
                m_items.Insert(i, GetToolbarItem(item));
            }
            Toolbar.ItemChanged += Toolbar_ItemChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            PowerReceiver = new MyPowerReceiver(
                MyConsumerGroupEnum.Utility,
                false,
                BlockDefinition.RequiredPowerInput,
                this.CalculateRequiredPowerInput);
            PowerReceiver.IsPoweredChanged     += Receiver_IsPoweredChanged;
            PowerReceiver.RequiredInputChanged += Receiver_RequiredInputChanged;
            PowerReceiver.Update();

            m_fieldShape = GetHkShape();

            OnClose += delegate(MyEntity self)
            {
                m_fieldShape.RemoveReference();
            };
        }
예제 #59
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);
            m_cubeGrid = cubeGrid;

            MyDebug.AssertDebug(BlockDefinition is MyAssemblerDefinition);
            m_assemblerDef = BlockDefinition as MyAssemblerDefinition;


            if (InventoryAggregate.InventoryCount > 2)
            {
                Debug.Fail("Inventory aggregate has to many inventories, probably wrong save. If you continue the unused inventories will be removed. Save the world to correct it. Please report this is if problem prevail.");

                FixInputOutputInventories(m_assemblerDef.InputInventoryConstraint, m_assemblerDef.OutputInventoryConstraint);
            }

            InputInventory.Constraint  = m_assemblerDef.InputInventoryConstraint;
            OutputInventory.Constraint = m_assemblerDef.OutputInventoryConstraint;

            bool removed = InputInventory.FilterItemsUsingConstraint();

            Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder.");

            var builder = (MyObjectBuilder_Assembler)objectBuilder;

            if (builder.OtherQueue != null)
            {
                m_otherQueue.Clear();
                if (m_otherQueue.Capacity < builder.OtherQueue.Length)
                {
                    m_otherQueue.Capacity = builder.OtherQueue.Length;
                }
                for (int i = 0; i < builder.OtherQueue.Length; ++i)
                {
                    var item = builder.OtherQueue[i];

                    var blueprint = MyDefinitionManager.Static.TryGetBlueprintDefinitionByResultId(item.Id);
                    if (blueprint != null)
                    {
                        m_otherQueue.Add(new QueueItem()
                        {
                            Blueprint = blueprint,
                            Amount    = item.Amount,
                        });
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLine(string.Format("No blueprint that produces a single result with Id '{0}'", item.Id));
                    }
                }
            }
            CurrentProgress            = builder.CurrentProgress;
            m_disassembleEnabled       = builder.DisassembleEnabled;
            m_repeatAssembleEnabled    = builder.RepeatAssembleEnabled;
            m_repeatDisassembleEnabled = builder.RepeatDisassembleEnabled;
            m_slave = builder.SlaveEnabled;
            UpdateInventoryFlags();

            UpgradeValues.Add("Productivity", 0f);
            UpgradeValues.Add("PowerEfficiency", 1f);

            m_baseIdleSound = BlockDefinition.PrimarySound;
            m_processSound  = BlockDefinition.ActionSound;

            OnUpgradeValuesChanged += UpdateDetailedInfo;

            ResourceSink.RequiredInputChanged += PowerReceiver_RequiredInputChanged;
            UpdateDetailedInfo();
        }
예제 #60
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;

            var sourceDataList = new List <MyResourceSourceInfo>();

            foreach (var producedInfo in BlockDefinition.ProducedGases)
            {
                sourceDataList.Add(new MyResourceSourceInfo
                {
                    ResourceTypeId = producedInfo.Id,
                    DefinedOutput  = BlockDefinition.IceConsumptionPerSecond * producedInfo.IceToGasRatio * (MySession.Static.CreativeMode ? 10f : 1f),
                    ProductionToCapacityMultiplier = 1
                });
            }

            SourceComp.Init(BlockDefinition.ResourceSourceGroup, sourceDataList);

            base.Init(objectBuilder, cubeGrid);

            var generatorBuilder = objectBuilder as MyObjectBuilder_OxygenGenerator;

            InitializeConveyorEndpoint();
            m_useConveyorSystem.Value = generatorBuilder.UseConveyorSystem;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            if (this.GetInventory() == null) // can be already initialized as deserialized component
            {
                MyInventory inventory = new MyInventory(BlockDefinition.InventoryMaxVolume, BlockDefinition.InventorySize, MyInventoryFlags.CanReceive);
                inventory.Constraint = BlockDefinition.InputInventoryConstraint;
                Components.Add <MyInventoryBase>(inventory);
            }
            else
            {
                this.GetInventory().Constraint = BlockDefinition.InputInventoryConstraint;
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            m_oreConstraint = new MyInventoryConstraint(this.GetInventory().Constraint.Description, this.GetInventory().Constraint.Icon, this.GetInventory().Constraint.IsWhitelist);
            foreach (var id in this.GetInventory().Constraint.ConstrainedIds)
            {
                if (id.TypeId != typeof(MyObjectBuilder_GasContainerObject))
                {
                    m_oreConstraint.Add(id);
                }
            }

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            if (this.GetInventory() != null)
            {
                this.GetInventory().Init(generatorBuilder.Inventory);
            }
            else
            {
                Debug.Fail("Trying to init inventory, but it's null!");
            }

            AutoRefill = generatorBuilder.AutoRefill;



            SourceComp.Enabled = Enabled;
            if (Sync.IsServer)
            {
                SourceComp.OutputChanged += Source_OutputChanged;
            }
            float iceAmount = IceAmount();

            foreach (var gasId in SourceComp.ResourceTypes)
            {
                var tmpGasId = gasId;
                m_sourceComp.SetRemainingCapacityByType(gasId, IceToGas(ref tmpGasId, iceAmount));
            }

            m_lastSourceUpdate = MySession.Static.GameplayFrameCounter;

            ResourceSink.Init(BlockDefinition.ResourceSinkGroup, new MyResourceSinkInfo
            {
                ResourceTypeId    = MyResourceDistributorComponent.ElectricityId,
                MaxRequiredInput  = BlockDefinition.OperationalPowerConsumption,
                RequiredInputFunc = ComputeRequiredPower
            });
            ResourceSink.IsPoweredChanged += PowerReceiver_IsPoweredChanged;
            ResourceSink.Update();

            UpdateEmissivity();
            UpdateText();

            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));

            m_useConveyorSystem.Value = generatorBuilder.UseConveyorSystem;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
            IsWorkingChanged += MyGasGenerator_IsWorkingChanged;
        }