//bool initialPos = false; protected virtual void OnEnterToState(KFSMState kfsmState) { if (FlightGlobals.ActiveVessel == null) { return; } Log.Info("OnEnterToState: InitialState"); if (FlightGlobals.ActiveVessel.situation != Vessel.Situations.PRELAUNCH) { Machine.RunEvent("Finish"); } _obj = new GameObject("Helper"); _dummy = _obj.AddComponent <DummyComponent>(); StyleFactory.Scale = ConfigInfo.Instance.Scale; StyleFactory.Reload(); #if false if (!initialPos) { initialPos = true; _windowRect = ScaleRect(GUIUtil.ScreenCenteredRect(459, 120)); } #else _windowRect = CountDownMain.saveLoadWinPos.initialWindow; // CountDownMain.saveLoadWinPos.initialWindow; //if (!initialPos) //{ // initialPos = true; // _windowRect = ScaleRect(_windowRect); //} #endif }
public void Setup() { Allocators.PreCacheBuffer <DummyComponent>(); m_Root = new GameObject("Root").AddComponent <DummyComponent>(); m_Root.gameObject.AddComponent <DummyComponent>(); m_Child = new GameObject("Child").transform; m_Child.SetParent(m_Root.transform); m_Leaf = new GameObject("GrandChild 0").AddComponent <DummyComponent>(); m_Leaf.transform.SetParent(m_Child); for (int i = 0; i < 2; ++i) { var grandchild = new GameObject("GrandChild " + (i + 1)).AddComponent <DummyComponent>(); grandchild.transform.SetParent(m_Child); } for (int i = 0; i < 2; ++i) { var grandchild = new GameObject("GrandChild " + (i + 3)).AddComponent <DummyComponent>(); grandchild.transform.SetParent(m_Child); grandchild.gameObject.SetActive(false); } }
static void Prefix(DummyComponent __instance) { if (Object.FindObjectsOfType(__instance.GetType()).Length > 1) { Object.Destroy(__instance); } }
static bool Prefix() { watch = new Stopwatch(); watch.Start(); if (File.Exists(GetSavePath())) // It's a better save { betterSave = true; DummyComponent comp = UnityEngine.Object.FindObjectOfType <DummyComponent>(); comp.StartCoroutine(LoadCoroutine()); return(false); } betterSave = false; return(true); }
public void TempList_ForEach_NoAlloc() { var list = m_Root.GetComponentsNonAlloc <DummyComponent>(); Assert.That(() => { DummyComponent comp = null; foreach (var component in list) { comp = component; } }, Is.Not.AllocatingGCMemory()); }
public void HasNetComponentTest() { // Arrange var manager = ManagerFactory(out var entityManager); var entity = EntityFactory(entityManager); var component = new DummyComponent(); component.Owner = entity; manager.AddComponent(entity, component); // Act var result = manager.HasComponent(entity.Uid, CompNetId); // Assert Assert.That(result, Is.True); }
public void AddComponentTest() { // Arrange var manager = ManagerFactory(out var entityManager); var entity = EntityFactory(entityManager); var component = new DummyComponent(); component.Owner = entity; // Act manager.AddComponent(entity, component); // Assert var result = manager.GetComponent <DummyComponent>(entity.Uid); Assert.That(result, Is.EqualTo(component)); }
public void RemoveNetComponentTest() { // Arrange var manager = ManagerFactory(out var entityManager); var entity = EntityFactory(entityManager); var component = new DummyComponent(); component.Owner = entity; manager.AddComponent(entity, component); // Act manager.RemoveComponent(entity.Uid, CompNetId); manager.CullRemovedComponents(); // Assert Assert.That(manager.HasComponent(entity.Uid, component.GetType()), Is.False); }
private void EnterState(KFSMState kfsmState) { Log.Info("EnterState: LaunchedState"); if (ConfigInfo.Instance.CurrentAudio == null) { return; } _obj = new GameObject(); _audioSource = _obj.AddComponent <AudioSource>(); _audioSource.spatialBlend = 0; _audioSource.volume = GameSettings.VOICE_VOLUME; //_obj.AddComponent<MonoBehaviour>().StartCoroutine(LaunchedSuccess()); _dummy = _obj.AddComponent <DummyComponent>(); _dummy.StartCoroutine(LaunchedSuccess()); }
public void GetAllComponentInstances() { // Arrange var manager = ManagerFactory(out var entityManager); var entity = EntityFactory(entityManager); var component = new DummyComponent(); component.Owner = entity; manager.AddComponent(entity, component); // Act var result = manager.GetComponents(entity.Uid); // Assert var list = result.ToList(); Assert.That(list.Count, Is.EqualTo(1)); Assert.That(list[0], Is.EqualTo(component)); }
//bool initialPos = false; protected virtual void OnEnterToState(KFSMState kfsmState) { if (FlightGlobals.ActiveVessel == null) { return; } Log.Info("OnEnterToState: InitialState"); if (FlightGlobals.ActiveVessel.situation != Vessel.Situations.PRELAUNCH) { Machine.RunEvent("Finish"); } _obj = new GameObject("Helper"); _dummy = _obj.AddComponent <DummyComponent>(); StyleFactory.Scale = ConfigInfo.Instance.Scale; StyleFactory.Reload(); _windowRect = CountDownMain.instance.saveLoadWinPos.initialWindow; }
public void AddComponent_ExistingDeleted() { // Arrange var manager = ManagerFactory(out var entityManager); var entity = EntityFactory(entityManager); var firstComp = new DummyComponent { Owner = entity }; manager.AddComponent(entity, firstComp); manager.RemoveComponent <DummyComponent>(entity.Uid); var secondComp = new DummyComponent { Owner = entity }; // Act manager.AddComponent(entity, secondComp); // Assert var result = manager.GetComponent <DummyComponent>(entity.Uid); Assert.That(result, Is.EqualTo(secondComp)); }
private void MyRefHandler(EntityUid uid, DummyComponent component, ref TestStructEvent args) { }
public void ResolveComponent_WhenWellFormed_ReturnsComponentObject() { var registry = new Registry(); var plugin = registry.RegisterPlugin(new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"))); var service = registry.RegisterService(new ServiceRegistration(plugin, "serviceId", new TypeName(typeof(DummyService)))); var handlerFactory = MockRepository.GenerateMock<IHandlerFactory>(); var component = registry.RegisterComponent(new ComponentRegistration(plugin, service, "componentId", new TypeName(typeof(DummyComponent))) { ComponentHandlerFactory = handlerFactory, ComponentProperties = { { "Name", "Value" } } }); var handler = MockRepository.GenerateMock<IHandler>(); var componentInstance = new DummyComponent(); handlerFactory.Expect(x => x.CreateHandler(null, null, null, null)) .Constraints(Is.NotNull(), Is.Equal(typeof(DummyService)), Is.Equal(typeof(DummyComponent)), Is.Equal(new PropertySet() { { "Name", "Value" } })) .Return(handler); handler.Expect(x => x.Activate()).Return(componentInstance); var result = (DummyComponent) component.ResolveComponent(); Assert.AreSame(componentInstance, result); handlerFactory.VerifyAllExpectations(); handler.VerifyAllExpectations(); }
public void Startup() { Allocators.PreCacheBuffer <DummyComponent>(); m_Root = new GameObject("Root").AddComponent <DummyComponent>(); }
static void Main(string[] args) { { double[][] arr; arr = new double[3][]; arr[0] = new double[4] { 9, 8, 7, 6 }; arr[1] = new double[4] { 42, 13, 7, 2 }; arr[2] = new double[4] { 101, 102, 103, 104 }; MeshAttributeCLASSES meshComponent2 = MeshAttributeCLASSES.makeDouble4(arr); double[] readback = meshComponent2.getDouble4Accessor()[1]; int breakPointHere = 42; } // test solver for trivial cases { double one = 1.0; double J11 = 1.0, J22 = 1.0, J33 = 1.0, // principal moments of inertia of the body w1 = 0, w2 = 0, w3 = 0, // angular velocity of spacecraft in spacecraft frame // result values q1Dot, q2Dot, q3Dot, q4Dot, w1Dot, w2Dot, w3Dot, // coeefficients, taken from the paper gamma = 0.7, aCoefficient = 1.25, d = 7.5, k = 3.0, betaOne = 0.001; Quaternion spacecraftOrientationError; // set to identity /* * spacecraftOrientationError.i = 0; * spacecraftOrientationError.j = 0; * spacecraftOrientationError.k = 0; * spacecraftOrientationError.scalar = 1; */ spacecraftOrientationError = QuaternionUtilities.makeFromAxisAndAngle(new SpatialVectorDouble(new double[] { 1, 0, 0 }), 1.0); QuaternionFeedbackRegulatorForSpacecraft.calcControl( J11, J22, J33, spacecraftOrientationError.i, spacecraftOrientationError.j, spacecraftOrientationError.k, spacecraftOrientationError.scalar, w1, w2, w3, out q1Dot, out q2Dot, out q3Dot, out q4Dot, out w1Dot, out w2Dot, out w3Dot, aCoefficient, gamma, d, k, betaOne ); // changes must be zero Debug.Assert(q1Dot == 0); Debug.Assert(q2Dot == 0); Debug.Assert(q3Dot == 0); Debug.Assert(q4Dot == 0); Debug.Assert(w1Dot == 0); Debug.Assert(w2Dot == 0); Debug.Assert(w3Dot == 0); int breakPointHere = 42; } SimplexSolver simplexSolver = new SimplexSolver(); /* first example from video tutorial, https://www.youtube.com/watch?v=Axg9OhJ4cjg, bottom row is negative unlike in the video */ simplexSolver.matrix = Matrix.makeByRowsAndColumns(3, 5); simplexSolver.matrix[0, 0] = 4; simplexSolver.matrix[0, 1] = 8; simplexSolver.matrix[0, 2] = 1; simplexSolver.matrix[0, 3] = 0; simplexSolver.matrix[0, 4] = 24; simplexSolver.matrix[1, 0] = 2; simplexSolver.matrix[1, 1] = 1; simplexSolver.matrix[1, 2] = 0; simplexSolver.matrix[1, 3] = 1; simplexSolver.matrix[1, 4] = 10; simplexSolver.matrix[2, 0] = -3; simplexSolver.matrix[2, 1] = -4; simplexSolver.matrix[2, 2] = 0; simplexSolver.matrix[2, 3] = 0; simplexSolver.matrix[2, 4] = 0; simplexSolver.iterate(); // result must be ~16.67 Debug.Assert(simplexSolver.matrix[2, 4] > 16.6 && simplexSolver.matrix[2, 4] < 16.8); // TODO< move into unittest for Matrix > Matrix toInverseMatrix = new Matrix(2, 2); toInverseMatrix[0, 0] = 2.0f; toInverseMatrix[0, 1] = 1.0f; toInverseMatrix[1, 0] = 2.0f; toInverseMatrix[1, 1] = 2.0f; Matrix inversedMatrix = toInverseMatrix.inverse(); Debug.Assert(System.Math.Abs(inversedMatrix[0, 0] - 1.0f) < 0.001f); Debug.Assert(System.Math.Abs(inversedMatrix[0, 1] - -0.5f) < 0.001f); Debug.Assert(System.Math.Abs(inversedMatrix[1, 0] - -1.0f) < 0.001f); Debug.Assert(System.Math.Abs(inversedMatrix[1, 1] - 1.0f) < 0.001f); // test pid controller if (false) { Pid.Configuration pidConfiguration = new Pid.Configuration(); pidConfiguration.integral = 0; pidConfiguration.derivative = 0.1; pidConfiguration.proportial = 0.3; Pid pid = Pid.makeByTargetAndConfiguration(0, pidConfiguration); double value = 1.0; double control; control = pid.step(value, 0.5); value += control; for (int i = 0; i < 10; i++) { control = pid.step(value, 0.5); value += control; Console.WriteLine("value={0} control={1}", value, control); } int breakPointHere0 = 1; } EntityManager entityManager = new EntityManager(); SolidResponsibility solidResponsibility; EffectResponsibility effectResponsibility; ThrusterResponsibility thrusterResponsibility; AttitudeAndAccelerationControlResponsibility attitudeAndAccelerationControlResponsibility; thrusterResponsibility = new ThrusterResponsibility(); attitudeAndAccelerationControlResponsibility = new AttitudeAndAccelerationControlResponsibility(thrusterResponsibility); effectResponsibility = new EffectResponsibility(); solidResponsibility = new SolidResponsibility(); solidResponsibility.mapping = new PhysicsObjectIdToSolidClusterMapping(); EntityController entityController = new EntityController(); IKeyboardInputHandler keyboardInputHandler = new PlayerShipControlInputHandler(entityController); KeyboardInputRemapper keyboardInputRemapper = new KeyboardInputRemapper(keyboardInputHandler); SoftwareRenderer softwareRenderer = new SoftwareRenderer(); PrototypeForm prototypeForm = new PrototypeForm(); prototypeForm.softwareRenderer = softwareRenderer; IGuiRenderer guiRenderer = prototypeForm.softwareGuiRenderer; GuiContext guiContext = new GuiContext(guiRenderer); prototypeForm.guiContext = guiContext; KeyboardEventRouterOfGui keyboardEventRouterOfGui = new KeyboardEventRouterOfGui(guiContext.selectionTracker); KeyboardInputRouter keyboardInputRouter = new KeyboardInputRouter(keyboardInputRemapper, keyboardEventRouterOfGui); prototypeForm.keyboardInputRouter = keyboardInputRouter; prototypeForm.Show(); PhysicsEngine physicsEngine = new PhysicsEngine(); solidResponsibility.physicsEngine = physicsEngine; physicsEngine.collisionHandlers.Add(new DefaultCollisionHandler()); // add the default collision handler for absorbing all particles AttachedForce thruster = new AttachedForce( new SpatialVectorDouble(new double[] { 0, 1, 0 }), // localLocation new SpatialVectorDouble(new double[] { 1, 0, 0 }) // localDirection ); PhysicsComponent physicsComponent; { double mass = 1.0; Matrix inertiaTensor = InertiaHelper.calcInertiaTensorForCube(mass, 1.0, 1.0, 1.0); physicsComponent = physicsEngine.createPhysicsComponent(new SpatialVectorDouble(new double[] { 0, 0, 10 }), new SpatialVectorDouble(new double[] { 0, 0, 0 }), mass, inertiaTensor); } physicsComponent.attachedForces.Add(thruster); MeshComponent meshComponent = new MeshComponent(); meshComponent.mesh = new MeshWithExplicitFaces(); meshComponent.mesh.faces = new MeshWithExplicitFaces.Face[1]; meshComponent.mesh.faces[0] = new MeshWithExplicitFaces.Face(); meshComponent.mesh.faces[0].verticesIndices = new uint[] { 0, 1, 2 }; { // create a VerticesWithAttributes with just positions MutableMeshAttribute positionMeshAttribute = MutableMeshAttribute.makeDouble4ByLength(4); positionMeshAttribute.getDouble4Accessor()[0] = new double[] { -1, -1, 0, 1 }; positionMeshAttribute.getDouble4Accessor()[1] = new double[] { 1, -1, 0, 1 }; positionMeshAttribute.getDouble4Accessor()[2] = new double[] { 0, 1, 0, 1 }; positionMeshAttribute.getDouble4Accessor()[3] = new double[] { 0, 0, 1, 1 }; VerticesWithAttributes verticesWithAttributes = new VerticesWithAttributes(new AbstractMeshAttribute[] { positionMeshAttribute }, 0); meshComponent.mesh.verticesWithAttributes = verticesWithAttributes; } //TransformedMeshComponent transformedMeshComponentForPhysics = new TransformedMeshComponent(); //transformedMeshComponentForPhysics.meshComponent = meshComponent; IList <ColliderComponent> colliderComponents = new List <ColliderComponent>(); { SpatialVectorDouble colliderComponentSize = new SpatialVectorDouble(new double[] { 2, 2, 2 }); SpatialVectorDouble colliderComponentLocalPosition = new SpatialVectorDouble(new double[] { 0, 0, 0 }); SpatialVectorDouble colliderComponentLocalRotation = new SpatialVectorDouble(new double[] { 0, 0, 0 }); ColliderComponent colliderComponent0 = ColliderComponent.makeBox(colliderComponentSize, colliderComponentLocalPosition, colliderComponentLocalRotation); colliderComponents.Add(colliderComponent0); } ///physicsEngine.physicsAndMeshPairs.Add(new PhysicsComponentAndCollidersPair(physicsComponent, colliderComponents)); // same mesh for the visualization TransformedMeshComponent transformedMeshComponentForRendering = new TransformedMeshComponent(); transformedMeshComponentForRendering.meshComponent = meshComponent; ///softwareRenderer.physicsAndMeshPairs.Add(new PhysicsComponentAndMeshPair(physicsComponent, transformedMeshComponentForRendering)); physicsEngine.tick(); // TODO< read object description from json and create physics and graphics objects > // TODO< read and create solid description from json > // create and store solids of rocket // refactored /* * if ( true ) { * * * SolidCluster solidClusterOfRocket = new SolidCluster(); * * // create solid of rocket * { * SpatialVectorDouble solidSize = new SpatialVectorDouble(new double[] { 2, 2, 2 }); * double massOfSolidInKilogram = 1.0; * IList<CompositionFraction> solidCompositionFractions = new List<CompositionFraction>() { new CompositionFraction(new Isotope("Fe56"), massOfSolidInKilogram) }; * Composition solidComposition = new Composition(solidCompositionFractions); * * physics.solid.Solid solid = physics.solid.Solid.makeBox(solidComposition, solidSize); * * SpatialVectorDouble solidLocalPosition = new SpatialVectorDouble(new double[] { 0, 0, 0 }); * SpatialVectorDouble solidLocalRotation = new SpatialVectorDouble(new double[] { 0, 0, 0 }); * * solidClusterOfRocket.solids.Add(new SolidCluster.SolidWithPositionAndRotation(solid, solidLocalPosition, solidLocalRotation)); * } * * /// TODO, uncommented because it uses the not existing physics object * /// solidResponsibility.mapping.physicsObjectIdToSolidCluster[rocketPhysicsObject.id] = solidClusterOfRocket; * } */ // add test particle if (false) { SpatialVectorDouble particlePosition = new SpatialVectorDouble(new double[] { 0, 0, 0 }); SpatialVectorDouble particleVelocity = new SpatialVectorDouble(new double[] { 0, 0, 1 }); PhysicsComponent particlePhysicsComponent = physicsEngine.createPhysicsComponent(particlePosition, particleVelocity, 1.0, null); physicsEngine.addParticle(particlePhysicsComponent); } // write game object for TestMissile if (true) { DemoObjectSerializer.seralizeAndWriteShip(); DemoObjectSerializer.serializeAndWriteMissile(); } GameObjectBuilder gameObjectBuilder = new GameObjectBuilder(); gameObjectBuilder.physicsEngine = physicsEngine; gameObjectBuilder.softwareRenderer = softwareRenderer; gameObjectBuilder.solidResponsibility = solidResponsibility; gameObjectBuilder.effectResponsibility = effectResponsibility; gameObjectBuilder.thrusterResponsibility = thrusterResponsibility; gameObjectBuilder.attitudeAndAccelerationControlResponsibility = attitudeAndAccelerationControlResponsibility; // load missile game object from json and construct it if (false) { GameObjectTemplate deserilizedGameObjectTemplate; // load { List <string> uriParts = new List <string>(AssemblyDirectory.Uri.Segments); uriParts.RemoveAt(0); // remove first "/" uriParts.RemoveRange(uriParts.Count - 4, 4); uriParts.AddRange(new string[] { "gameResources/", "prototypingMissile.json" }); string path = string.Join("", uriParts).Replace('/', '\\').Replace("%20", " "); string fileContent = File.ReadAllText(path); deserilizedGameObjectTemplate = GameObjectTemplate.deserialize(fileContent); } // build game object from template Entity createdEntity; { SpatialVectorDouble globalPosition = new SpatialVectorDouble(new double[] { 0, 0, 5 }); SpatialVectorDouble globalVelocity = new SpatialVectorDouble(new double[] { 0, 0, 0 }); createdEntity = gameObjectBuilder.buildFromTemplate(deserilizedGameObjectTemplate, globalPosition, globalVelocity); entityManager.addEntity(createdEntity); } // manually add components { // TODO< chemical explosive ignition component > DummyComponent chemicalExplosiveIgnitionComponent = new DummyComponent(); // remap proximityEnter to explode EventRemapperComponent eventRemapper = new EventRemapperComponent(chemicalExplosiveIgnitionComponent); eventRemapper.eventTypeMap["proximityEnter"] = "explode"; // TODO< blacklist somehow other missiles > PhysicsComponent parentPhysicsComponent = createdEntity.getSingleComponentsByType <PhysicsComponent>(); ProximityDetectorComponent proximityDetector = ProximityDetectorComponent.makeSphereDetector(physicsEngine, parentPhysicsComponent, 20.0, eventRemapper); entityManager.addComponentToEntity(createdEntity, proximityDetector); } } Entity playerShip; if (true) { GameObjectTemplate deserilizedGameObjectTemplate; // load { List <string> uriParts = new List <string>(AssemblyDirectory.Uri.Segments); uriParts.RemoveAt(0); // remove first "/" uriParts.RemoveRange(uriParts.Count - 4, 4); uriParts.AddRange(new string[] { "gameResources/", "prototypingShip.json" }); string path = string.Join("", uriParts).Replace('/', '\\').Replace("%20", " "); string fileContent = File.ReadAllText(path); deserilizedGameObjectTemplate = GameObjectTemplate.deserialize(fileContent); } // build game object from template { SpatialVectorDouble globalPosition = new SpatialVectorDouble(new double[] { 0, 0, 10 }); SpatialVectorDouble globalVelocity = new SpatialVectorDouble(new double[] { 0, 0, 0 }); Entity createdEntity = gameObjectBuilder.buildFromTemplate(deserilizedGameObjectTemplate, globalPosition, globalVelocity); entityManager.addEntity(createdEntity); playerShip = createdEntity; } } Entity aiShip = null; EntityController aiShipController = new EntityController(); VehicleAlignToCommand command = null; bool withTestAiShip = true; if (withTestAiShip) { GameObjectTemplate deserilizedGameObjectTemplate; // load { List <string> uriParts = new List <string>(AssemblyDirectory.Uri.Segments); uriParts.RemoveAt(0); // remove first "/" uriParts.RemoveRange(uriParts.Count - 4, 4); uriParts.AddRange(new string[] { "gameResources/", "prototypingShip.json" }); string path = string.Join("", uriParts).Replace('/', '\\').Replace("%20", " "); string fileContent = File.ReadAllText(path); deserilizedGameObjectTemplate = GameObjectTemplate.deserialize(fileContent); } // build game object from template { SpatialVectorDouble globalPosition = new SpatialVectorDouble(new double[] { 0, 0, 10 }); SpatialVectorDouble globalVelocity = new SpatialVectorDouble(new double[] { 0, 0, 0 }); Entity createdEntity = gameObjectBuilder.buildFromTemplate(deserilizedGameObjectTemplate, globalPosition, globalVelocity); entityManager.addEntity(createdEntity); aiShip = createdEntity; } { // control aiShip.getSingleComponentsByType <VehicleControllerComponent>().controller = aiShipController; } { // AI initialization double dt = 1.0 / 60.0; SpatialVectorDouble targetDirection = new SpatialVectorDouble(new double[] { 1, 0, 0.1 }).normalized(); double targetDerivationDistance = 0.001; ulong targetPhysicsObjectId = aiShip.getSingleComponentsByType <PhysicsComponent>().id; command = VehicleAlignToCommand.makeByGettingPidConfigurationFromAttitudeAndAccelerationControlResponsibility( attitudeAndAccelerationControlResponsibility, physicsEngine, dt, targetDirection, aiShipController, targetPhysicsObjectId, targetDerivationDistance); } } // { } playerShip.getSingleComponentsByType <VehicleControllerComponent>().controller = entityController; // create test GUI { Button button = new subsystems.gui.Button(); button.position = new SpatialVectorDouble(new double[] { 0.2, 0.2 }); button.size = new SpatialVectorDouble(new double[] { 0.3, 0.1 }); button.text = "[Gamesave05-res.save](35)"; button.textScale = new SpatialVectorDouble(new double[] { 0.05, 0.08 }); guiContext.addGuiElement(button); } ulong frameCounter = 0; ulong debugFrameCounter = 0; // used to limit the frames we do for debugging a scenario bool isFixedScenarioDebugMode = false; // TODO< use logger > StreamWriter debugLogFileOfVariables = null; // used to debug variables and coeeficients of the debug scenario if (isFixedScenarioDebugMode) { if (!File.Exists("E:\\myLogShipOrientation.txt")) { using (var stream = File.Create("E:\\myLogShipOrientation.txt")); } debugLogFileOfVariables = File.AppendText("E:\\myLogShipOrientation.txt"); } for (;;) { Console.WriteLine("frame={0}", frameCounter); guiContext.tick(); physicsEngine.tick(); if (!isFixedScenarioDebugMode) { prototypeForm.Refresh(); Application.DoEvents(); // HACK, EVIL } // AI { // we just do this small AI because we are testing if (false && aiShip != null) { command.process(); } } // AI - attitude control test // we change the rotation velocity of the spacecraft directly to simulate "perfect" thruster control { PhysicsComponent objectOfControlledSpacecraft = aiShip.getSingleComponentsByType <PhysicsComponent>(); double // principal moments of inertia of the body // the controller assumes that the body has an inertia tensor like an box, but small derivations are propably fine, too J11 = objectOfControlledSpacecraft.inertiaTensor[0, 0], J22 = objectOfControlledSpacecraft.inertiaTensor[1, 1], J33 = objectOfControlledSpacecraft.inertiaTensor[2, 2], // angular velocity of spacecraft in spacecraft frame w1 = objectOfControlledSpacecraft.eulerLocalAngularVelocity.x, w2 = objectOfControlledSpacecraft.eulerLocalAngularVelocity.y, w3 = objectOfControlledSpacecraft.eulerLocalAngularVelocity.z, // result values q1Dot, q2Dot, q3Dot, q4Dot, w1Dot, w2Dot, w3Dot, // coeefficients, taken from the paper gamma = 0.7, aCoefficient = 1.25, d = 7.5, k = 3.0, betaOne = 0.001; // calculate the rotation delta to our target orientation from the current orientation double debugMagnitude = objectOfControlledSpacecraft.rotation.magnitude; Quaternion spacecraftOrientationError = objectOfControlledSpacecraft.rotation.difference(QuaternionUtilities.makeFromEulerAngles(0, 0.5, 0)); QuaternionFeedbackRegulatorForSpacecraft.calcControl( J11, J22, J33, spacecraftOrientationError.i, spacecraftOrientationError.j, spacecraftOrientationError.k, spacecraftOrientationError.scalar, w1, w2, w3, out q1Dot, out q2Dot, out q3Dot, out q4Dot, out w1Dot, out w2Dot, out w3Dot, aCoefficient, gamma, d, k, betaOne ); Console.WriteLine( "w1dot={0}, w2dot={1}, w3dot={2}", w1Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w2Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w3Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture) ); if (isFixedScenarioDebugMode) { debugLogFileOfVariables.WriteLine("w1dot={0}, w2dot={1}, w3dot={2}", w1Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w2Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w3Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture)); debugLogFileOfVariables.Flush(); } // access directly objectOfControlledSpacecraft.eulerLocalAngularVelocity.x += (w1Dot * (1.0 / 60.0)); objectOfControlledSpacecraft.eulerLocalAngularVelocity.y += (w2Dot * (1.0 / 60.0)); objectOfControlledSpacecraft.eulerLocalAngularVelocity.z += (w3Dot * (1.0 / 60.0)); } attitudeAndAccelerationControlResponsibility.resetAllThrusters(); entityManager.updateAllEntities(); // order after update is important attitudeAndAccelerationControlResponsibility.limitAllThrusters(); attitudeAndAccelerationControlResponsibility.transferThrusterForce(); //thruster.forceInNewton = 0.5 * entityController.inputAcceleration; if (!isFixedScenarioDebugMode) { Thread.Sleep((int)((1.0 / 60.0) * 1000.0)); } if (isFixedScenarioDebugMode) { debugLogFileOfVariables.WriteLine("{0},", aiShip.getSingleComponentsByType <PhysicsComponent>().rotation.j.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture)); debugLogFileOfVariables.Flush(); } //File.AppendText("E:\\myLogShipOrientation.txt").WriteLine("{0},", aiShip.getSingleComponentsByType<PhysicsComponent>().rotation.y); if (isFixedScenarioDebugMode && debugFrameCounter >= 8000) // 30000 { break; } debugFrameCounter++; frameCounter++; } }
private void LoadTileSet(XmlHelper xmlHelper, Map map) { string id = xmlHelper.GetAttribute("name"); int firstGid = xmlHelper.GetIntAttribute("firstgid"); int tileWidth = xmlHelper.GetIntAttribute("tilewidth"); int tileHeight = xmlHelper.GetIntAttribute("tileheight"); Size tileSize = new Size(tileWidth, tileHeight); int marginValue = xmlHelper.GetIntAttribute("margin", 0); Size margin = new Size(marginValue); int spacingValue = xmlHelper.GetIntAttribute("spacing", 0); Size spacing = new Size(spacingValue); xmlHelper.AdvanceStartElement("image"); string imageSource = xmlHelper.GetAttribute("source"); xmlHelper.AdvanceEndElement("image"); Size sheetSize = new Size(); try { using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(imageSource)) { sheetSize.Width = (bitmap.Width + spacingValue - marginValue) / (tileWidth + spacingValue); sheetSize.Height = (bitmap.Height + spacingValue - marginValue) / (tileHeight + spacingValue); } } catch (Exception exception) { throw new Exception("Unable to determine sheet size from image source", exception); } TileSheet tileSheet = new TileSheet(id, map, imageSource, sheetSize, tileSize); tileSheet.Margin = margin; tileSheet.Spacing = spacing; // keep track of first gid as custom property tileSheet.Properties["@FirstGid"] = firstGid; // also add lastgid to facilitate import tileSheet.Properties["@LastGid"] = firstGid + tileSheet.TileCount - 1; // properties at tile level within tile sets not supported // but are mapped as prefixed properties at tile sheet level XmlNodeType xmlNodeType = xmlHelper.AdvanceNode(); while (xmlNodeType == XmlNodeType.Element && xmlHelper.XmlReader.Name == "tile") { int tileId = xmlHelper.GetIntAttribute("id"); xmlHelper.AdvanceNamedNode(XmlNodeType.Element, "properties"); Component dummyComponent = new DummyComponent(); LoadProperties(xmlHelper, dummyComponent); xmlHelper.AdvanceEndElement("tile"); foreach (string propertyName in dummyComponent.Properties.Keys) { tileSheet.Properties["@Tile@" + tileId + "@" + propertyName] = dummyComponent.Properties[propertyName]; } xmlNodeType = xmlHelper.AdvanceNode(); } map.AddTileSheet(tileSheet); }
private void MyRefHandler(EntityUid uid, DummyComponent component, ref TestStructEvent args) { Assert.That(args.TestNumber, Is.EqualTo(5)); args.TestNumber = 10; }
static void HandleGameData(HazelBinaryReader reader, GameDataType datatype, bool send) { var dir = send ? "SEND" : "RECV"; switch (datatype) { case GameDataType.RpcCall: var RPC = RpcCall.Deserialize(reader); var reciver = EntityTracker.Get(RPC.targetNetId); if (LogRPC) { Console.WriteLine($"[RPC][{RPC.callId}]sent to {reciver?.GetType()?.Name ?? "unknown"} size: {reader.GetBytesLeft()}"); } if (reciver != null) { reciver.HandleRpcCall(RPC.callId, reader); } //DumpToConsole(RPC, LogRPC); //Console.WriteLine($"RPC for type: {RPC} size: {data.body.Length}"); switch (RPC.callId) { case RpcCalls.CheckColor: var CheckColor = CmdCheckColor.Deserialize(reader); DumpToConsole(CheckColor, LogRPC); break; case RpcCalls.CheckName: var CheckName = CmdCheckName.Deserialize(reader); DumpToConsole(CheckName, LogRPC); break; case RpcCalls.CloseDoorsOfType: var CloseDoorsOfType = RpcCloseDoorsOfType.Deserialize(reader); DumpToConsole(CloseDoorsOfType, LogRPC); break; case RpcCalls.EnterVent: var EnterVent = RpcEnterVent.Deserialize(reader); DumpToConsole(EnterVent, LogRPC); break; case RpcCalls.ExitVent: var ExitVent = RpcExitVent.Deserialize(reader); DumpToConsole(ExitVent, LogRPC); break; case RpcCalls.Exiled: var exileid = reader.ReadPackedInt32(); Console.WriteLine("Exile id: " + exileid); break; case RpcCalls.SendChat: var chat = RpcSendChat.Deserialize(reader); LogChatToConsole(RPC.targetNetId.ToString(), chat.text); break; case RpcCalls.SendChatNote: var chatnote = RpcSendChatNote.Deserialize(reader); LogChatToConsole("server", "SendChatNote"); break; case RpcCalls.SetColor: var SetColor = RpcSetColor.Deserialize(reader); DumpToConsole(SetColor, LogRPC); break; case RpcCalls.SetSkin: var skin = RpcSetSkin.Deserialize(reader); DumpToConsole(skin, LogRPC); break; case RpcCalls.SetHat: var hat = RpcSetHat.Deserialize(reader); Console.WriteLine($"Set hat: [{(int)hat.hatId}]{hat.hatId}"); break; case RpcCalls.SetPet: var setpet = RpcSetPet.Deserialize(reader); DumpToConsole(setpet, LogRPC); break; case RpcCalls.SetName: var setname = RpcSetName.Deserialize(reader); DumpToConsole(setname, LogRPC); break; case RpcCalls.SetTasks: var SetTasks = RpcSetTasks.Deserialize(reader); DumpToConsole(SetTasks, LogRPC); break; case RpcCalls.SetInfected: var infected = RpcSetInfected.Deserialize(reader); DumpToConsole(infected); break; case RpcCalls.SetScanner: var SetScanner = RpcSetScanner.Deserialize(reader); DumpToConsole(SetScanner, LogRPC); break; case RpcCalls.AddVote: var addvote = RpcAddVote.Deserialize(reader); DumpToConsole(addvote, LogRPC); break; case RpcCalls.PlayAnimation: var anim = RpcPlayAnimation.Deserialize(reader); DumpToConsole(anim, LogRPC); break; case RpcCalls.CastVote: var castvote = CmdCastVote.Deserialize(reader); DumpToConsole(castvote, LogRPC); break; case RpcCalls.CompleteTask: var complete = RpcCompleteTask.Deserialize(reader); DumpToConsole(complete, LogRPC); break; case RpcCalls.MurderPlayer: var MurderPlayer = RpcMurderPlayer.Deserialize(reader); var player = EntityTracker.Get(MurderPlayer.netId); DumpToConsole(MurderPlayer, LogRPC); break; case RpcCalls.RepairSystem: var RepairSystem = RpcRepairSystem.Deserialize(reader); DumpToConsole(RepairSystem, LogRPC); break; case RpcCalls.ReportDeadBody: var ReportDeadBody = CmdReportDeadBody.Deserialize(reader); DumpToConsole(ReportDeadBody, LogRPC); break; case RpcCalls.SnapTo: var SnapTo = RpcSnapTo.Deserialize(reader); DumpToConsole(SnapTo, LogRPC); break; case RpcCalls.StartMeeting: var StartMeeting = RpcStartMeeting.Deserialize(reader); DumpToConsole(StartMeeting, LogRPC); break; case RpcCalls.VotingComplete: var VotingComplete = RpcVotingComplete.Deserialize(reader); DumpToConsole(VotingComplete, LogRPC); break; case RpcCalls.SetStartCounter: var startcounter = RpcSetStartCounter.Deserialize(reader); DumpToConsole(startcounter, LogRPC); break; case RpcCalls.SyncSettings: var syncsettings = RpcSyncSettings.Deserialize(reader); DumpToConsole(syncsettings, LogRPC); break; //Dont have a message body case RpcCalls.Close: break; //ComponentSpecific - it contains diffrent data depending on what component it's inteded for case RpcCalls.UpdateGameData: var update = RpcUpdateGameData.Deserialize(reader); DumpToConsole(update, LogRPC); break; default: Console.WriteLine($"Unhandled RPC command: " + RPC.callId); break; } if (reader.GetBytesLeft() > 0 && LogNotConsumed) { Console.WriteLine($"[{RPC.callId}]{reader.GetBytesLeft()} bytes not cunsumed"); reader.ReadBytesToEnd(); } break; case GameDataType.Data: var data = Data.Deserialize(reader); InnerNetObject entity; if (!EntityTracker.entities.TryGetValue(data.netId, out entity)) { Console.WriteLine($"Entity missing for id: {data.netId} size: {data.data.Length}"); return; } if (!(entity is CustomNetworkTransform)) { Console.WriteLine($"Recived Data for: {entity.GetType().Name} size: {data.data.Length}"); } entity.Deserialize(new HazelBinaryReader(data.data), false); if (LogMoves && entity is CustomNetworkTransform move) { Console.WriteLine($"[{dir}]Move command player: {move.OwnerId:0000} seq: {move.seq:0000} pos: {move.position} delta: {move.velocity}"); } break; case GameDataType.Spawn: var spawn = Spawn.Deserialize(reader); Console.WriteLine("Spawning: " + spawn.spawnId); switch (spawn.spawnId) { case 0: var shipStatus = new ShipStatus(); shipStatus.OwnerId = spawn.ownerId; shipStatus.NetId = spawn.children[0].netId; shipStatus.Deserialize(new HazelBinaryReader(spawn.children[0].body), true); EntityTracker.Add(shipStatus); break; case 1: var meeting = new MeetingHud(); meeting.OwnerId = spawn.ownerId; meeting.NetId = spawn.children[0].netId; meeting.Deserialize(new HazelBinaryReader(spawn.children[0].body), true); EntityTracker.Add(meeting); break; case 2: var lobby = new LobbyBehaviour(); lobby.OwnerId = spawn.ownerId; lobby.NetId = spawn.children[0].netId; EntityTracker.Add(lobby); break; case 3: var gdc = new GameDataComponent(); gdc.OwnerId = spawn.ownerId; gdc.NetId = spawn.children[0].netId; gdc.Deserialize(new HazelBinaryReader(spawn.children[0].body), true); EntityTracker.Add(gdc); var dummy2 = new DummyComponent(); dummy2.name = "gamedata.dummy1"; dummy2.OwnerId = spawn.ownerId; dummy2.NetId = spawn.children[1].netId; dummy2.Deserialize(new HazelBinaryReader(spawn.children[1].body), true); EntityTracker.Add(dummy2); break; case 4: //player character var player = new PlayerControl(); player.OwnerId = spawn.ownerId; player.NetId = spawn.children[0].netId; player.Deserialize(new HazelBinaryReader(spawn.children[0].body), true); EntityTracker.Add(player); player.dummy1 = new DummyComponent(); player.dummy1.name = "player.dummy1"; player.dummy1.OwnerId = spawn.ownerId; player.dummy1.NetId = spawn.children[1].netId; player.dummy1.Deserialize(new HazelBinaryReader(spawn.children[1].body), true); EntityTracker.Add(player.dummy1); player.transform = new CustomNetworkTransform(); player.transform.OwnerId = spawn.ownerId; player.transform.NetId = spawn.children[2].netId; player.transform.Deserialize(new HazelBinaryReader(spawn.children[2].body), true); EntityTracker.Add(player.transform); DumpToConsole(player); break; case 5: //HeadQuarters var hq = new ShipStatus(); hq.OwnerId = spawn.ownerId; hq.NetId = spawn.children[0].netId; hq.Deserialize(new HazelBinaryReader(spawn.children[0].body), true); EntityTracker.Add(hq); break; case 6: //PlanetMap var polus = new ShipStatus(); polus.OwnerId = spawn.ownerId; polus.NetId = spawn.children[0].netId; polus.Deserialize(new HazelBinaryReader(spawn.children[0].body), true); EntityTracker.Add(polus); break; case 7: //AprilShipStatus default: Console.WriteLine($"Unhandled spawnid: {spawn.spawnId}"); break; } break; case GameDataType.SceneChange: var scene = SceneChange.Deserialize(reader); if (scene.sceneName == "OnlineGame") { //Starting game } DumpToConsole(scene); break; case GameDataType.Despawn: var despawn = Despawn.Deserialize(reader); EntityTracker.entities.Remove(despawn.netId); LogToConsole("Despawn Netid: " + despawn.netId); break; case GameDataType.Ready: var ready = Ready.Deserialize(reader); Console.WriteLine($"Ready: " + ready.playerId); break; case GameDataType.ChangeSettings: var changesettings = ChangeSettings.Deserialize(reader); DumpToConsole(changesettings); break; default: Console.WriteLine($"Unhandled Gamedatatype: {datatype}"); break; } if (reader.GetBytesLeft() > 0 && LogNotConsumed) { Console.WriteLine($"[{datatype}]{reader.GetBytesLeft()} bytes not cunsumed"); reader.ReadBytesToEnd(); } }