public void AddLayoutControl_ExistingToolboxSection_VerifyControlIsProperlyAddedToTheToolbox() { //Arrange: Initialize the GridSystemInitializer, ToolboxesConfig and add a PageLayouts section, create a layouts section, create a dummy grid controls DummyGridSystemInitializer initializer = new DummyGridSystemInitializer(); var fakeTemplatePath = "~/fakeTemplatePath/"; var dummyData = initializer.PublicCreateLayoutControlsData(fakeTemplatePath); var toolboxesConfig = new DummyToolboxesConfig(); var pageControlsMock = new Toolbox(toolboxesConfig.Toolboxes); pageControlsMock.Name = "PageLayouts"; toolboxesConfig.Toolboxes.Add("PageLayouts", pageControlsMock); var htmlLayoutsSection = initializer.PublicCreateToolBoxSection(toolboxesConfig); var parentToolboxItem = htmlLayoutsSection.Tools; //Act: add the grid controls to the toolbox foreach (var gridControl in dummyData) { initializer.PublicAddLayoutControl(parentToolboxItem, gridControl); } //Assert: Verify the newly created controls are properly created Assert.AreEqual<int>(dummyData.Count, parentToolboxItem.Count, "Not all grid controls were added to the toolbox."); var oneColumnGridControl = dummyData.FirstOrDefault(); var oneColumnGridToolboxItem = parentToolboxItem.Where<ToolboxItem>(toolboxItem => toolboxItem.Name == oneColumnGridControl.Name).FirstOrDefault(); Assert.IsNotNull(oneColumnGridToolboxItem, "The grid control was not added to the toolbox."); Assert.AreEqual<string>(oneColumnGridControl.Title, oneColumnGridToolboxItem.Title, "The grid control toolbox item has wrong title."); Assert.AreEqual<string>(oneColumnGridControl.LayoutTemplatePath, oneColumnGridToolboxItem.LayoutTemplate, "The grid control toolbox item has layout template path."); }
void Awake() { toolbox = Toolbox.Instance; if (!toolbox) return; if (!toolbox.level_racing_complete && level_racing_icon) { disable_color(level_racing_icon); set_item_tag(level_racing_icon); } if (!toolbox.level_pirate_complete && level_pirate_icon) { disable_color(level_pirate_icon); set_item_tag(level_pirate_icon); } if (!toolbox.level_mideval_complete && level_mideval_icon) { disable_color(level_mideval_icon); set_item_tag(level_mideval_icon); } if (!toolbox.level_space_complete && level_space_icon) { disable_color(level_space_icon); set_item_tag(level_space_icon); } if (!toolbox.level_submarine_complete && level_submarine_icon) { disable_color(level_submarine_icon); set_item_tag(level_submarine_icon); } }
public Visualiser() { InitializeComponent(); //sourceFile = "../../Resources/salestable.xml"; //tvvm = new TreeViewViewModel(sourceFile); //ModelTreeView.DataContext = tvvm; myToolbox = new Toolbox(); //string elementsFile = DirectoryHelper.getFilePath("Resources\\ToolBoxItems.xml"); //loadToolboxes(elementsFile); suggestions = new ObservableCollection<Suggestion>(); suggestionsListBox.ItemsSource = suggestions; //initiate the scheduling canvas initiateSchedulingCanvas(); prettyPrinter = new XmlPrettyPrinter(); ShowSample = false;//set popup for sample to false popupTimer = new System.Windows.Threading.DispatcherTimer(); popupTimer.Tick += new EventHandler(dispatcherTimer_Tick); popupTimer.Interval = new TimeSpan(0, 0, 2); logger = new Logger("VisualiserLogger"); logsTab.Content = logger; }
// Public methods. /// <summary> /// Shows a dialog to add a tool method from the specified toolbox. /// </summary> /// <param name="owner">The owner window.</param> /// <param name="toolbox">The toolbox.</param> /// <param name="triggers">The list of triggers.</param> /// <returns>The dialog result.</returns> public DialogResult ShowDialog(IWin32Window owner, Toolbox toolbox, IEnumerable<ToolMethodTrigger> triggers) { // Initialize the control. this.control.Initialize(toolbox, triggers); // Show the dialog. return base.ShowDialog(owner); }
public void AddLayoutControl_ExistingToolboxSection_VerifyControlIsProperlyAddedToTheToolbox() { // Arrange: Initialize the GridWidgetRegistrator, ToolboxesConfig and add a PageLayouts section, create a layouts section, create a dummy grid controls var initializer = new DummyGridWidgetRegistrator(); var fakeTemplatePath = "~/GridSystem/Templates/grid1.html"; var dummyData = initializer.PublicCreateGridControlsData(fakeTemplatePath); var toolboxesConfig = new DummyToolboxesConfig(); var pageControlsMock = new Toolbox(toolboxesConfig.Toolboxes); pageControlsMock.Name = "PageLayouts"; toolboxesConfig.Toolboxes.Add("PageLayouts", pageControlsMock); var htmlLayoutsSection = initializer.PublicCreateToolBoxSection(toolboxesConfig, "BootstrapGrids", "BootstrapGridWidgets"); ConfigElementList<ToolboxItem> parentToolboxItem = htmlLayoutsSection.Tools; // Act: add the grid controls to the toolbox initializer.PublicAddGridControl(parentToolboxItem, dummyData); // Assert: Verify the newly created controls are properly created Assert.AreEqual(1, parentToolboxItem.Count, "The grid controls were added to the toolbox."); var oneColumnGridToolboxItem = parentToolboxItem.Where<ToolboxItem>(toolboxItem => toolboxItem.Name == dummyData.Name).FirstOrDefault(); Assert.IsNotNull(oneColumnGridToolboxItem, "The grid control was not added to the toolbox."); Assert.AreEqual(dummyData.Title, oneColumnGridToolboxItem.Title, "The grid control toolbox item has wrong title."); Assert.AreEqual(dummyData.LayoutTemplatePath, oneColumnGridToolboxItem.LayoutTemplate, "The grid control toolbox item has layout template path."); }
public void setToolbox(Toolbox tlb) { this.tlb = tlb; this.appContainer.Toolbox = tlb; this.picIcon.BackgroundImage = tlb.icon; this.lblName.Text = tlb.name; this.Location = tlb.position; this.BackColor = tlb.bgColor; }
// (optional) allow runtime registration of global objects /*public static T RegisterComponent<T> () where T: Component { return Instance.GetOrAddComponent<T>(); }*/ void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); // Your initialization code here. Debug.Log("Awake"); gameManager.Initialize(); } else { DestroyImmediate(gameObject); } }
public void GetOrCreateToolBoxSection_CreateFakeToolboxSection_VerifySectionIsAddedAndHasProperData() { //Arrange: Initialize the GridSystemInitializer, ToolboxesConfig and add a PageLayouts section DummyGridSystemInitializer initializer = new DummyGridSystemInitializer(); var toolboxesConfig = new DummyToolboxesConfig(); var pageControlsMock = new Toolbox(toolboxesConfig.Toolboxes); pageControlsMock.Name = "PageLayouts"; toolboxesConfig.Toolboxes.Add("PageLayouts", pageControlsMock); //Act: create a new toolbox section for the layout controls var htmlLayoutsSection = initializer.PublicCreateToolBoxSection(toolboxesConfig); //Assert: Verify the newly created section exists and has proper name and title Assert.IsNotNull(htmlLayoutsSection, "The toolbox section was not properly created."); Assert.AreEqual<string>("HtmlLayouts", htmlLayoutsSection.Name,"The toolbox section has unexpected name."); Assert.AreEqual<string>("Bootstrap grid widgets", htmlLayoutsSection.Title, "The toolbox section has unexpected title."); }
public static int TerrainTypeToVal(Toolbox.TerrainType terrain) { int plainsVal = 2; int hillsVal = 2; int desertVal = 4; int forrestVal = 4; int lakeVal = 999; int mountainsVal = 999; int wastelandVal = 3; int swampVal = 4; // int hillsVal = 3; // int desertVal = 5; // int forrestVal = 5; // int lakeVal = 999; // int mountainsVal = 999; // int wastelandVal = 4; // int swampVal = 5; if (Toolbox.Instance.isDay) { forrestVal = 3; } else { desertVal = 3; } switch (terrain){ case Toolbox.TerrainType.Plains: return plainsVal; case Toolbox.TerrainType.Hills: return hillsVal; case Toolbox.TerrainType.Desert: return desertVal; case Toolbox.TerrainType.Wasteland: return wastelandVal; case Toolbox.TerrainType.Forest: return forrestVal; case Toolbox.TerrainType.Lake: return lakeVal; case Toolbox.TerrainType.Mountains: return mountainsVal; case Toolbox.TerrainType.Swamp: return swampVal; default: throw new UnityException("Terrain type does not exist in Hex class"); } }
public void AddBlock(int val, Toolbox.AttackType type) { switch (type) { case Toolbox.AttackType.Physical: blocks[0] += val; break; case Toolbox.AttackType.Ice: blocks[1] += val; break; case Toolbox.AttackType.Fire: blocks[2] += val; break; case Toolbox.AttackType.ColdFire: blocks[3] += val; break; default: break; } UpdateLabels(); }
public CardAction(List<Toolbox.BasicAction> myActions, int myAttackVal=0, int myBlockVal=0, int myInfluenceVal=0, int myHealVal=0, int myMoveVal=0, Toolbox.AttackType myAttackColour = Toolbox.AttackType.Summon, Toolbox.AttackType myBlockColour = Toolbox.AttackType.Summon, int mySourceVal=0, int myWhiteVal = 0, int myRedVal = 0, int myBlueVal = 0, int myGreenVal = 0, int myDarkVal = 0) { actions = myActions; attackVal = myAttackVal; blockVal = myBlockVal; influenceVal = myInfluenceVal; moveVal = myMoveVal; healVal = myHealVal; attackColour = myAttackColour; blockColour = myBlockColour; sourceVal = mySourceVal; whiteVal = myWhiteVal; blueVal = myBlueVal; redVal = myRedVal; greenVal = myGreenVal; darkVal = myDarkVal; }
public void SetColour(Toolbox.EnergyColour newColour) { colour = newColour; switch (colour){ case Toolbox.EnergyColour.Blue: image.color = Color.blue; break; case Toolbox.EnergyColour.Red: image.color = Color.red; break; case Toolbox.EnergyColour.Green: image.color = Color.green; break; case Toolbox.EnergyColour.White: image.color = Color.white; break; case Toolbox.EnergyColour.Dark: image.color = Color.black; break; default: break; } }
internal void RaiseCriticalException(CriticalExceptionEventArgs e) { Toolbox.RaiseAsyncEvent <CriticalExceptionEventArgs>(CriticalException, this, e); }
public async Task <Toolbox> Update(Toolbox toolbox) { return(await _toolboxCollection.FindOneAndReplaceAsync(tb => tb.ToolboxId == toolbox.ToolboxId, toolbox)); }
private static void GetObjectiveData(MissionTemplateObjectiveRecord objectiveTemplate, bool useObjectivePreset, out string[] featuresID, out DBEntryObjectiveTarget targetDB, out DBEntryObjectiveTargetBehavior targetBehaviorDB, out DBEntryObjectiveTask taskDB, out ObjectiveOption[] objectiveOptions) { featuresID = objectiveTemplate.Features.ToArray(); targetDB = Database.Instance.GetEntry <DBEntryObjectiveTarget>(objectiveTemplate.Target); targetBehaviorDB = Database.Instance.GetEntry <DBEntryObjectiveTargetBehavior>(objectiveTemplate.TargetBehavior); taskDB = Database.Instance.GetEntry <DBEntryObjectiveTask>(objectiveTemplate.Task); objectiveOptions = objectiveTemplate.Options.ToArray(); if (useObjectivePreset && objectiveTemplate.Preset != "Custom") { DBEntryObjectivePreset presetDB = Database.Instance.GetEntry <DBEntryObjectivePreset>(objectiveTemplate.Preset); if (presetDB != null) { featuresID = presetDB.Features.ToArray(); targetDB = Database.Instance.GetEntry <DBEntryObjectiveTarget>(Toolbox.RandomFrom(presetDB.Targets)); targetBehaviorDB = Database.Instance.GetEntry <DBEntryObjectiveTargetBehavior>(Toolbox.RandomFrom(presetDB.TargetsBehaviors)); taskDB = Database.Instance.GetEntry <DBEntryObjectiveTask>(Toolbox.RandomFrom(presetDB.Tasks)); objectiveOptions = presetDB.Options.ToArray(); } } if (targetDB == null) { throw new BriefingRoomException($"Target \"{targetDB.UIDisplayName}\" not found for objective."); } if (targetBehaviorDB == null) { throw new BriefingRoomException($"Target behavior \"{targetBehaviorDB.UIDisplayName}\" not found for objective."); } if (taskDB == null) { throw new BriefingRoomException($"Task \"{taskDB.UIDisplayName}\" not found for objective."); } if (!taskDB.ValidUnitCategories.Contains(targetDB.UnitCategory)) { throw new BriefingRoomException($"Task \"{taskDB.UIDisplayName}\" not valid for objective targets, which belong to category \"{targetDB.UnitCategory}\"."); } }
private void CalculatePositioning(Mat RawMat, out Mat RawMatCropped, out Mat OtherZonesInGreen, out Mat TerrainFilledGreenRotated, out Mat TerrainTheoriqueDisplay, out double coefficientCorrelation) { //Découpage de l'image int RawMatCroppedSize = 300; int cropOffsetX = 0; int cropOffsetY = 0; Range rgX = new Range(RawMat.Width / 2 - RawMatCroppedSize / 2 + cropOffsetX, RawMat.Width / 2 + RawMatCroppedSize / 2 + cropOffsetX); Range rgY = new Range(RawMat.Height / 2 - RawMatCroppedSize / 2 + cropOffsetY, RawMat.Height / 2 + RawMatCroppedSize / 2 + cropOffsetY); RawMatCropped = new Mat(RawMat, rgY, rgX); //Test en utilisant une image théorique //Range rgX = new Range(TerrainTheorique.Width / 2 - tailleCroppedImage / 2 + cropOffsetX, TerrainTheorique.Width / 2 + tailleCroppedImage / 2 + cropOffsetX); //Range rgY = new Range(TerrainTheorique.Height / 2 - tailleCroppedImage / 2 + cropOffsetY, TerrainTheorique.Height / 2 + tailleCroppedImage / 2 + cropOffsetY); //Mat cropRawMat = new Mat(TerrainTheorique, rgY, rgX); //UpdateValues(RawMatCropped.Bitmap, 1); //TODO mise à jour des affichages //Initialisation de la mesure du temps de calcul Stopwatch watch = Stopwatch.StartNew(); //Conversion en HSV Mat HsvMatCropped = new Mat(); CvInvoke.CvtColor(RawMatCropped, HsvMatCropped, ColorConversion.Bgr2Hsv); //Filtrage du vert du terrain int HueOrange = 24; int HueVert = 180; Mat maskVert = new Mat(); int HTolVert = 20; int HInfVert = Math.Max(0, HueVert - HTolVert); int HSupVert = Math.Min(360, HueVert + HTolVert); int SInfVert = 0; int SSupVert = 255; int VInfVert = 80; int VSupVert = 255; CvInvoke.InRange(HsvMatCropped, new ScalarArray(new MCvScalar(HInfVert / 2, SInfVert, VInfVert)), new ScalarArray(new MCvScalar(HSupVert / 2, SSupVert, VSupVert)), maskVert); //Mat maskBlanc = new Mat(); //int HInfBlanc = 0; //int HSupBlanc = 360; //int SInfBlanc = 0; //int SSupBlanc = 255; //int VInfBlanc = 230; //int VSupBlanc = 255; //CvInvoke.InRange(HsvMatCropped, new ScalarArray(new MCvScalar(HInfBlanc / 2, SInfBlanc, VInfBlanc)), new ScalarArray(new MCvScalar(HSupBlanc / 2, SSupBlanc, VSupBlanc)), maskBlanc); var maskWhiteGreen = /*maskBlanc + */ maskVert; int interations = 7; //var element = CvInvoke.GetStructuringElement(ElementShape.Cross, new Size(4, 4), new Point(-1, -1)); int erosionSize = 2; int dilatationSize = 2; var elementErosion = CvInvoke.GetStructuringElement(ElementShape.Cross, new Size(2 * erosionSize + 1, 2 * erosionSize + 1), new Point(erosionSize, erosionSize)); var elementDilatation = CvInvoke.GetStructuringElement(ElementShape.Cross, new Size(2 * dilatationSize + 1, 2 * dilatationSize + 1), new Point(dilatationSize, dilatationSize)); //CvInvoke.Erode(maskVertBlanc, maskVertBlanc, elementErosion, new Point(-1, -1), interations, BorderType.Default, default(MCvScalar)); CvInvoke.Dilate(maskWhiteGreen, maskWhiteGreen, elementDilatation, new Point(-1, -1), interations + 2, BorderType.Default, default(MCvScalar)); CvInvoke.Erode(maskWhiteGreen, maskWhiteGreen, elementErosion, new Point(-1, -1), interations, BorderType.Default, default(MCvScalar)); Mat maskNotWhiteGreen = new Mat(); CvInvoke.BitwiseNot(maskWhiteGreen, maskNotWhiteGreen); //Filtrage de l'image pour ne garder que le terrain Mat TerrainFilteredGreenWhite = new Mat(); CvInvoke.BitwiseAnd(RawMatCropped, RawMatCropped, TerrainFilteredGreenWhite, maskWhiteGreen); var img = TerrainFilteredGreenWhite.ToImage <Bgr, byte>(); //img._EqualizeHist(); //img.Laplace(15); //img._GammaCorrect(5); TerrainFilteredGreenWhite = img.Mat; //var newImage = TerrainFilteredGreenWhite.Convert(b => SaturateCast(alpha * b + beta)); //Validé jusqu'ici //Détectiond de contours par Canny double cannyThreshold = 180.0; double cannyThresholdLinking = 200.0; UMat cannyEdges = new UMat(); CvInvoke.Canny(RawMatCropped, cannyEdges, cannyThreshold, cannyThresholdLinking); //Retrait de ce qui n'est pas terrain dans l'image et dans les contours de Canny Mat CannyTerrain = new Mat(); CvInvoke.BitwiseAnd(cannyEdges, cannyEdges, CannyTerrain, maskWhiteGreen); //Filtrage du noir Mat maskBlack = new Mat(); Mat maskNotBlack = new Mat(); int HInfBlack = 0; int HSupBlack = 360; int SInfBlack = 0; int SSupBlack = 255; int VInfBlack = 0; int VSupBlack = 100; //Sélection des zones noires CvInvoke.InRange(HsvMatCropped, new ScalarArray(new MCvScalar(HInfBlack / 2, SInfBlack, VInfBlack)), new ScalarArray(new MCvScalar(HSupBlack / 2, SSupBlack, VSupBlack)), maskBlack); //Dilatation des zones noires pour "manger" les bords CvInvoke.Dilate(maskBlack, maskBlack, elementDilatation, new Point(-1, -1), iterations: 1, BorderType.Default, default(MCvScalar)); CvInvoke.BitwiseNot(maskBlack, maskNotBlack); //On crée une image remplie de vert Mat MatGreen = new Mat(RawMatCropped.Size, DepthType.Cv8U, 3); MatGreen.SetTo(new Bgr(Color.Green).MCvScalar); //Suppression des bords de zones noires dans l'image des contours de Canny Mat CannyMapWithoutBlack = new Mat(); CvInvoke.BitwiseAnd(CannyTerrain, CannyTerrain, CannyMapWithoutBlack, maskNotBlack); LineSegment2D[] lines = CvInvoke.HoughLinesP( CannyMapWithoutBlack, 1, //Distance resolution in pixel-related units Math.PI / 90.0, //Angle resolution measured in radians. 20, //threshold 20, //min Line width 10); //gap between lines #region draw lines foreach (LineSegment2D line in lines) { CvInvoke.Line(RawMatCropped, line.P1, line.P2, new Bgr(Color.Red).MCvScalar, 2); } #endregion //Détermination de la liste des angles de chaque segment dans l'image List <double> listAngleSegments = new List <double>(); foreach (var segment in lines) { double angle = Math.Atan2(segment.P2.Y - segment.P1.Y, segment.P2.X - segment.P1.X); angle = Utilities.Toolbox.ModuloPiDivTwoAngleRadian(angle); listAngleSegments.Add(angle); } //Détermination de l'angle orientation terrain : angle médian de la liste des angles segments listAngleSegments.Sort(); double bestAngle = 0; if (listAngleSegments.Count > 0) { bestAngle = listAngleSegments[(int)(listAngleSegments.Count / 2)]; //Calcul de l'indice de confiance TODO } Console.WriteLine("Angle Terrain : " + Utilities.Toolbox.RadToDeg(bestAngle)); Mat rotMatrix = new Mat(); Mat TerrainFilteredGreenRotated = new Mat(); //Rotation du template de terrain récupéré CvInvoke.GetRotationMatrix2D(new PointF((float)TerrainFilteredGreenWhite.Width / 2, (float)RawMatCropped.Height / 2), Toolbox.RadToDeg(bestAngle), 1.0, rotMatrix); CvInvoke.WarpAffine(TerrainFilteredGreenWhite, TerrainFilteredGreenRotated, rotMatrix, new Size(RawMatCropped.Width, RawMatCropped.Height)); //Rotation du mask du template de terrain récupéré Mat maskWhiteGreenRotated = new Mat(); CvInvoke.WarpAffine(maskWhiteGreen, maskWhiteGreenRotated, rotMatrix, new Size(RawMatCropped.Width, RawMatCropped.Height)); //Remplacement des zones noires par des zones vertes Mat maskBlack2 = new Mat(); var lowerBound = new ScalarArray(new Bgr(Color.FromArgb(0, 0, 0)).MCvScalar); var upperBound = new ScalarArray(new Bgr(Color.FromArgb(255, 50, 255)).MCvScalar); CvInvoke.InRange(TerrainFilteredGreenRotated, lowerBound, upperBound, maskBlack2); //On crée une image avec les zones non vertes précédentes remplies en vert OtherZonesInGreen = new Mat(); CvInvoke.BitwiseAnd(MatGreen, MatGreen, OtherZonesInGreen, maskBlack2); TerrainFilledGreenRotated = new Mat(); TerrainFilledGreenRotated = OtherZonesInGreen + TerrainFilteredGreenRotated; // + ; //CvInvoke.BitwiseOr(BlackZonesInGreen, TerrainFilteredGreen, Te//rrainFilledGreen); ////Correlation Terrain théorique vertical !!!! //var w = (TerrainTheoriqueVertical.Width - RawMatCropped.Width) + 1; //var h = (TerrainTheoriqueVertical.Height - RawMatCropped.Height) + 1; Mat resultCorrelTerrainVertical = new Mat(); Mat TerrainFilledGreenRotated0degre = TerrainFilledGreenRotated.Clone(); CvInvoke.MatchTemplate(TerrainTheoriqueVertical, TerrainFilledGreenRotated0degre, resultCorrelTerrainVertical, TemplateMatchingType.CcorrNormed); // throws exception double minValV = 0, maxValV = 0; Point minLocV = new Point(); Point maxLocV = new Point(); CvInvoke.MinMaxLoc(resultCorrelTerrainVertical, ref minValV, ref maxValV, ref minLocV, ref maxLocV); Mat resultCorrelTerrainHorizontal = new Mat(); Mat TerrainFilledGreenRotated90 = new Mat(); CvInvoke.Rotate(TerrainFilledGreenRotated, TerrainFilledGreenRotated90, RotateFlags.Rotate90Clockwise); CvInvoke.MatchTemplate(TerrainTheoriqueVertical, TerrainFilledGreenRotated90, resultCorrelTerrainHorizontal, TemplateMatchingType.CcorrNormed, maskWhiteGreenRotated); // throws exception double minValH = 0, maxValH = 0; Point minLocH = new Point(); Point maxLocH = new Point(); CvInvoke.MinMaxLoc(resultCorrelTerrainHorizontal, ref minValH, ref maxValH, ref minLocH, ref maxLocH); Point maxLoc = new Point(); if (maxValV > maxValH) { maxLoc = maxLocV; coefficientCorrelation = maxValV; } else { maxLoc = maxLocH; coefficientCorrelation = maxValH; } //Affichage final //On clone le terrain théorique pour faire l'affichage sans détériorer le terrain de référence TerrainTheoriqueDisplay = TerrainTheoriqueVertical.Clone(); Mat MorceauTerrainAcquisRotated = new Mat(TerrainTheoriqueVertical.Size, DepthType.Cv8U, 3); //System.Drawing.Rectangle roi = new System.Drawing.Rectangle(20, 20, TerrainFilteredGreenRotated.Width, TerrainFilteredGreenRotated.Height); //Mat dstROI = new Mat(MorceauTerrainAcquisRotated, roi); System.Drawing.Rectangle roi2 = new System.Drawing.Rectangle(maxLoc.X, maxLoc.Y, TerrainFilledGreenRotated.Width, TerrainFilledGreenRotated.Height); Mat dstROI2 = new Mat(TerrainTheoriqueDisplay, roi2); //TerrainFilledGreenRotated.CopyTo(dstROI); if (maxValV > maxValH) { TerrainFilledGreenRotated0degre.CopyTo(dstROI2); } else { TerrainFilledGreenRotated90.CopyTo(dstROI2); } //CvInvoke. MorceauTerrainAcquisRotated //CvInvoke.Rectangle(TerrainTheoriqueDisplay, new System.Drawing.Rectangle(maxLoc.X, maxLoc.Y, // TerrainFilteredGreenRotated.Width, TerrainFilteredGreenRotated.Height), new MCvScalar(Color.Yellow.ToArgb()),3); //InformationString = // "Best correlation X : " + (minLoc.X+imgRotated.)+ " // Y : " + (yIndex-13) + " Score : "+minGlobal; long ComputeTime = watch.ElapsedMilliseconds; }
private void handleHandshake(PeerId id, HandshakeMessage message) { TorrentManager man = null; try { if (message.ProtocolString != VersionInfo.ProtocolStringV100) { throw new ProtocolException("Invalid protocol string in handshake"); } } catch (Exception ex) { Logger.Log(id.Connection, ex.Message); id.Connection.Dispose(); return; } ClientEngine.MainLoop.QueueWait((MainLoopTask) delegate { for (int i = 0; i < engine.Torrents.Count; i++) { if (message.infoHash == engine.Torrents[i].InfoHash) { man = engine.Torrents[i]; } } }); //FIXME: #warning FIXME: Don't stop the message loop until Dispose() and track all incoming connections if (man == null) // We're not hosting that torrent { Logger.Log(id.Connection, "ListenManager - Handshake requested nonexistant torrent"); id.Connection.Dispose(); return; } if (man.State == TorrentState.Stopped) { Logger.Log(id.Connection, "ListenManager - Handshake requested for torrent which is not running"); id.Connection.Dispose(); return; } if (!man.Mode.CanAcceptConnections) { Logger.Log(id.Connection, "ListenManager - Current mode does not support connections"); id.Connection.Dispose(); return; } id.Peer.PeerId = message.PeerId; id.TorrentManager = man; // If the handshake was parsed properly without encryption, then it definitely was not encrypted. If this is not allowed, abort if ((id.Encryptor is PlainTextEncryption && !Toolbox.HasEncryption(engine.Settings.AllowedEncryption, EncryptionTypes.PlainText)) && ClientEngine.SupportsEncryption) { Logger.Log(id.Connection, "ListenManager - Encryption is required but was not active"); id.Connection.Dispose(); return; } message.Handle(id); Logger.Log(id.Connection, "ListenManager - Handshake successful handled"); id.ClientApp = new Software(message.PeerId); message = new HandshakeMessage(id.TorrentManager.InfoHash, engine.PeerId, VersionInfo.ProtocolStringV100); var callback = engine.ConnectionManager.incomingConnectionAcceptedCallback; PeerIO.EnqueueSendMessage(id.Connection, id.Encryptor, message, id.TorrentManager.UploadLimiter, id.Monitor, id.TorrentManager.Monitor, callback, id); }
//Method to convert a Color value to a Tag //Input: Color //Output: Tag public static Tags ColorVal2Tag(Toolbox.Color Clr) { Tags RetClr; //Tag to return //Find what Color, return its tag equivalent switch (Clr) { case Toolbox.Color.Blue: RetClr = Tags.Blue; break; case Toolbox.Color.Red: RetClr = Tags.Red; break; case Toolbox.Color.Green: RetClr = Tags.Green; break; case Toolbox.Color.Yellow: RetClr = Tags.Yellow; break; default: RetClr=Tags.NoColor; break; } return RetClr; }
// Public methods. /// <summary> /// Initializes the current control with the specified toolbox. /// </summary> /// <param name="toolbox">The toolbox.</param> /// <param name="methods">The list of methods.</param> /// <param name="triggers">The list of triggers.</param> public void Initialize(Toolbox toolbox, string[] methods, IEnumerable<ToolMethodTrigger> triggers) { // Set the toolbox. this.toolbox = toolbox; // Set the triggers. this.triggers = triggers; // Load the list of methods. this.Load(methods); // Enable the control. this.Enabled = true; }
double CalculPenalisation(PointD ptCourant) { double penalisation = 0; if (globalWorldMap != null) { //Si le robot existe dans le distionnaire des robots if (globalWorldMap.teammateLocationList.ContainsKey(robotId)) { Location robotLocation = globalWorldMap.teammateLocationList[robotId]; double angleDestination = Math.Atan2(destinationLocation.Y - robotLocation.Y, destinationLocation.X - robotLocation.X); //On génère la liste des robots à éviter... Dictionary <int, Location> robotToAvoidDictionary = new Dictionary <int, Location>(); lock (globalWorldMap.teammateLocationList) { foreach (var robot in globalWorldMap.teammateLocationList) { robotToAvoidDictionary.Add(robot.Key, robot.Value); } } var opponentsList = globalWorldMap.opponentLocationList.ToList(); //On évite un lock couteux en perf en faisant une copie locale int i = 0; foreach (var robot in opponentsList) { i++; robotToAvoidDictionary.Add((int)TeamId.Opponents + i, robot); } //On veut éviter de taper les autres robots //lock (robotToAvoidList) var robotToAvoidList = robotToAvoidDictionary.ToList(); //On évite un lock couteux en perf en faisant une copie locale { foreach (var robot in robotToAvoidList) { int competitorId = robot.Key; Location competitorLocation = robot.Value; //On itère sur tous les robots sauf celui-ci if (competitorId != robotId && competitorLocation != null) { double angleRobotAdverse = Math.Atan2(competitorLocation.Y - robotLocation.Y, competitorLocation.X - robotLocation.X); double distanceRobotAdverse = Toolbox.Distance(competitorLocation.X, competitorLocation.Y, robotLocation.X, robotLocation.Y); //PointD ptCourant = GetFieldPosFromHeatMapCoordinates(x, y); double distancePt = Toolbox.Distance(ptCourant.X, ptCourant.Y, robotLocation.X, robotLocation.Y); double anglePtCourant = Math.Atan2(ptCourant.Y - robotLocation.Y, ptCourant.X - robotLocation.X); if (Math.Abs(distanceRobotAdverse * (anglePtCourant - angleRobotAdverse)) < 2.0 && distancePt > distanceRobotAdverse - 3) { penalisation += 1;// Math.Max(0, 1 - Math.Abs(anglePtCourant - angleRobotAdverse) *10.0); } } } } //} } } return(penalisation); }
// Use this for initialization void Awake() { Toolbox.RegisterComponent <TextViewManager>(); //curLang = Language.ZH_TW; //SceneManager.sceneLoaded += SetTextLocalize; }
private void Awake() { Toolbox.GetInstance().GetPlayerManager().SetAirTankController(this); }
public void Run(IrcMessage theMessage) { theMessage.Answer("http://lmgtfy.com/?q=" + Toolbox.UrlEncode(theMessage.CommandLine)); }
/// <summary> /// Gets the intersection between the sphere and the ray. /// </summary> /// <param name="ray">Ray to test against the sphere.</param> /// <param name="transform">Transform applied to the convex for the test.</param> /// <param name="maximumLength">Maximum distance to travel in units of the ray direction's length.</param> /// <param name="hit">Ray hit data, if any.</param> /// <returns>Whether or not the ray hit the target.</returns> public override bool RayTest(ref Ray ray, ref RigidTransform transform, Fix64 maximumLength, out RayHit hit) { return(Toolbox.RayCastSphere(ref ray, ref transform.Position, collisionMargin, maximumLength, out hit)); }
private void Awake() { eventManager = Toolbox.GetOrAddComponent <EventManager>(); }
public override void UpdateScene() { playTime += Time.deltaTime; Toolbox.GetInstance().GetManager <DisplayManager>().ShowHUD(playTime); }
public IEnumerator LateStart() { yield return(new WaitForSeconds(1f)); equip = Toolbox.GetInstance().GetEquip().GetComponent <EquipManager>(); }
private void PositionWordsHorizontally(float maxWidth, out float longestLineWidth) { fittedWords.Clear(); fittedWords.AddRange(words); longestLineWidth = 0; float x = 0; for (int i = 0; i < fittedWords.Count; i++) { var word = fittedWords[i]; word = word.Clone(); word.LineBreak = word.ForceLineBreak; if (word.LineBreak) { x = 0; } word.Width = CalcWordWidth(word); var isLongerThanWidth = x + word.Width > maxWidth; var t = texts[word.TextIndex]; var isTextOrBullet = (t.Length > 0 && t[word.Start] > ' ') || IsBullet(word); if (isLongerThanWidth && isTextOrBullet && (wordSplitAllowed || t.HasJapaneseSymbols(word.Start, word.Length))) { var fittedCharsCount = CalcFittedCharactersCount(word, maxWidth - x); if (fittedCharsCount > 0) { var wordEnd = word.Start + fittedCharsCount; Toolbox.AdjustLineBreakPosition(t, ref wordEnd); if (wordEnd > word.Start) { fittedCharsCount = wordEnd - word.Start; } var newWord = word.Clone(); newWord.IsTagBegin = false; newWord.Start = word.Start + fittedCharsCount; newWord.Length = word.Length - fittedCharsCount; newWord.Width = CalcWordWidth(newWord); newWord.ForceLineBreak = true; word.Length = fittedCharsCount; word.Width = CalcWordWidth(word); word.X = x; fittedWords.Insert(i + 1, newWord); goto skip_default_placement; } } if (isLongerThanWidth && isTextOrBullet && x > 0 && !fittedWords[i - 1].IsNbsp) { var isWordContinue = word.TextIndex > 0 && word.Start == 0 && t.Length > 0 && t[word.Start] > ' ' && (GetLastChar(texts[fittedWords[i - 1].TextIndex]) > ' ' || IsBullet(fittedWords[i - 1])); if (isWordContinue) { var prev = fittedWords[i - 1]; prev.X = 0; prev.LineBreak = true; word.X = prev.Width; x = word.X + word.Width; goto skip_default_placement; } word.X = 0; word.LineBreak = true; word.Width = CalcWordWidth(word); x = word.Width; } else { word.X = x; x += word.Width; } skip_default_placement: if (overflowMode == TextOverflowMode.Ellipsis) { if (word.X == 0 && word.Width > maxWidth) { ClipWordWithEllipsis(word, maxWidth); } } if (isTextOrBullet) // buz: при автопереносе на концах строк остаются пробелы, они не должны влиять на значение длины строки { longestLineWidth = Math.Max(longestLineWidth, word.X + word.Width); } fittedWords[i] = word; } }
// Use this for initialization protected virtual void Start() { //print ("Starting puzzle: " + this.puzzleName); toolbox = Toolbox.Instance; EnablePuzzle (false); }
internal void RaiseBlockRequestCancelled(BlockEventArgs args) { Toolbox.RaiseAsyncEvent <BlockEventArgs>(BlockRequestCancelled, args.TorrentManager, args); }
private void loadFunctionsToolbox(string functionsFile, Toolbox fToolbox) { //something should be done for templte repository if (System.IO.File.Exists(functionsFile)) { try { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(functionsFile, readerSettings)) { // SECTION 1. Create a DOM Document and load the XML data into it. fdom = new XmlDocument(); fdom.Load(reader); // SECTION 2. Initialize Elements XmlNodeList arfunctions = fdom.SelectNodes("Functions/Arithmetic/Function"); XmlNodeList reffunctions = fdom.SelectNodes("Functions/Reference/Condition"); //MessageBox.Show(customNodes.Count.ToString()); // SECTION 3. Populate Items with the DOM nodes. foreach (XmlNode func in arfunctions) { VisualFunction f = new VisualFunction(func); ToolboxItem item = new ToolboxItem(f); //item.Content = f; //item.loadFunctionToolBoxItem(func); fToolbox.Items.Add(item); } foreach (XmlNode func in reffunctions) { VisualCondition f = new VisualCondition(func); ToolboxItem item = new ToolboxItem(f); //item.Content = f; //item.loadFunctionToolBoxItem(func); fToolbox.Items.Add(item); } reader.Close(); } } catch (XmlException xmlEx) { reportMessage(xmlEx.Message, ReportIcon.Error); } catch (Exception ex) { reportMessage(ex.Message, ReportIcon.Error); } } else reportMessage("Could not load Function ToolboxItems file : " + functionsFile, ReportIcon.Error); }
/// <summary> /// Computes a bounding box for the shape and expands it. /// </summary> /// <param name="transform">Transform to use to position the shape.</param> /// <param name="sweep">Extra to add to the bounding box.</param> /// <param name="boundingBox">Expanded bounding box.</param> public void GetSweptBoundingBox(ref RigidTransform transform, ref Vector3 sweep, out BoundingBox boundingBox) { GetBoundingBox(ref transform, out boundingBox); Toolbox.ExpandBoundingBox(ref boundingBox, ref sweep); }
/// <summary> /// /// </summary> /// <param name="mission"></param> /// <param name="template"></param> /// <param name="playerCoalitionDB"></param> /// <param name="windDirection0">Wind direction at altitude 0, in degrees. Used by carrier groups to make sure carriers sail into the wind.</param> /// <returns></returns> public DBEntryUnit GenerateCarrier(DCSMission mission, MissionTemplate template, DBEntryCoalition playerCoalitionDB, int windDirection0) { if (string.IsNullOrEmpty(template.PlayerCarrier)) { return(null); } DBEntryTheaterSpawnPoint?spawnPoint = UnitMaker.SpawnPointSelector.GetRandomSpawnPoint( // If spawn point types are specified, use them. Else look for spawn points of any type new TheaterLocationSpawnPointType[] { TheaterLocationSpawnPointType.Sea }, // Select spawn points at a proper distance from last location (previous objective or home airbase) mission.InitialPosition, new MinMaxD(10, 50), // Make sure no objective is too close to the initial location null, null, GeneratorTools.GetAllySpawnPointCoalition(template)); if (!spawnPoint.HasValue) { throw new Exception($"Failed to find a spawn point for Carrier"); } Coordinates position = mission.InitialPosition; DCSMissionUnitGroup group; string[] ships = new string[] { template.PlayerCarrier }; foreach (var ship in new UnitFamily[] { UnitFamily.ShipFrigate, UnitFamily.ShipFrigate, UnitFamily.ShipCruiser, UnitFamily.ShipCruiser, UnitFamily.ShipTransport }) { ships = ships.Append(playerCoalitionDB.GetRandomUnits(ship, mission.DateTime.Decade, 1, template.OptionsUnitMods)[0]).ToArray(); } DebugLog.Instance.WriteLine($"Ships to be spawned {ships.Aggregate((acc, x) => $"{acc}, {x}")}", 1, DebugLogMessageErrorLevel.Warning); group = UnitMaker.AddUnitGroup( mission, ships, Side.Ally, spawnPoint.Value.Coordinates, "GroupCarrier", "UnitShip", Toolbox.BRSkillLevelToDCSSkillLevel(template.PlayerAISkillLevel)); if (group == null) { DebugLog.Instance.WriteLine($"Failed to create AI Carrier with ship of type \"{template.PlayerCarrier}\".", 1, DebugLogMessageErrorLevel.Warning); } else { //set all units against the wind double heading = Toolbox.ClampAngle((windDirection0 + 180) * Toolbox.DEGREES_TO_RADIANS); foreach (DCSMissionUnitGroupUnit unit in group.Units) { unit.Heading = heading; } } mission.Carrier = group.Units[0]; return((from DBEntryUnit unit in Database.Instance.GetAllEntries <DBEntryUnit>() where unit.ID == template.PlayerCarrier select unit).ToArray()[0]); }
//Relies on the triangle being located in the local space of the convex object. The convex transform is used to transform the //contact points back from the convex's local space into world space. ///<summary> /// Generates a contact between the triangle and convex. ///</summary> ///<param name="contactList">Contact between the shapes, if any.</param> ///<returns>Whether or not the shapes are colliding.</returns> public override bool GenerateContactCandidates(TriangleShape triangle, out TinyStructList <ContactData> contactList) { contactList = new TinyStructList <ContactData>(); Vector3f ab, ac; Vector3f.Subtract(ref triangle.vB, ref triangle.vA, out ab); Vector3f.Subtract(ref triangle.vC, ref triangle.vA, out ac); Vector3f triangleNormal; Vector3f.Cross(ref ab, ref ac, out triangleNormal); if (triangleNormal.LengthSquared < MathHelper.Epsilon * .01f) { //If the triangle is degenerate, use the offset between its center and the sphere. Vector3f.Add(ref triangle.vA, ref triangle.vB, out triangleNormal); Vector3f.Add(ref triangleNormal, ref triangle.vC, out triangleNormal); Vector3f.Multiply(ref triangleNormal, 1 / 3f, out triangleNormal); if (triangleNormal.LengthSquared < MathHelper.Epsilon * .01f) { triangleNormal = Toolbox.UpVector; //Alrighty then! Pick a random direction. } } float dot; Vector3f.Dot(ref triangleNormal, ref triangle.vA, out dot); switch (triangle.sidedness) { case TriangleSidedness.DoubleSided: if (dot < 0) { Vector3f.Negate(ref triangleNormal, out triangleNormal); //Normal must face outward. } break; case TriangleSidedness.Clockwise: if (dot > 0) { return(false); //Wrong side, can't have a contact pointing in a reasonable direction. } break; case TriangleSidedness.Counterclockwise: if (dot < 0) { return(false); //Wrong side, can't have a contact pointing in a reasonable direction. } break; } Vector3f closestPoint; //Could optimize this process a bit. The 'point' being compared is always zero. Additionally, since the triangle normal is available, //there is a little extra possible optimization. lastRegion = Toolbox.GetClosestPointOnTriangleToPoint(ref triangle.vA, ref triangle.vB, ref triangle.vC, ref Toolbox.ZeroVector, out closestPoint); float lengthSquared = closestPoint.LengthSquared; float marginSum = triangle.collisionMargin + sphere.collisionMargin; if (lengthSquared <= marginSum * marginSum) { var contact = new ContactData(); if (lengthSquared < MathHelper.Epsilon) { //Super close to the triangle. Normalizing would be dangerous. Vector3f.Negate(ref triangleNormal, out contact.Normal); contact.Normal.Normalize(); contact.PenetrationDepth = marginSum; contactList.Add(ref contact); return(true); } lengthSquared = (float)Math.Sqrt(lengthSquared); Vector3f.Divide(ref closestPoint, lengthSquared, out contact.Normal); contact.PenetrationDepth = marginSum - lengthSquared; contact.Position = closestPoint; contactList.Add(ref contact); return(true); } return(false); }
/// <summary> /// Attempts to load opencv modules from the specific location /// </summary> /// <param name="loadDirectory">The directory where the unmanaged modules will be loaded. If it is null, the default location will be used.</param> /// <param name="unmanagedModules">The names of opencv modules. e.g. "opencv_cxcore.dll" on windows.</param> /// <returns>True if all the modules has been loaded successfully</returns> /// <remarks>If <paramref name="loadDirectory"/> is null, the default location on windows is the dll's path appended by either "x64" or "x86", depends on the applications current mode.</remarks> public static bool LoadUnmanagedModules(String loadDirectory, params String[] unmanagedModules) { #if NETFX_CORE if (loadDirectory != null) { throw new NotImplementedException("Loading modules from a specific directory is not implemented in Windows Store App"); } String subfolder = String.Empty; if (Emgu.Util.Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows) //|| Platform.OperationSystem == Emgu.Util.TypeEnum.OS.WindowsPhone) { if (IntPtr.Size == 8) { //64bit process #if UNITY_METRO subfolder = "x86_64"; #else subfolder = String.Empty; #endif } else { subfolder = String.Empty; } } Windows.Storage.StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; #if UNITY_METRO loadDirectory = Path.Combine( Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(installFolder.Path)))) , "Plugins", "Metro", subfolder); #else loadDirectory = Path.Combine(installFolder.Path, subfolder); #endif var t = System.Threading.Tasks.Task.Run(async() => { List <string> files = new List <string>(); Windows.Storage.StorageFolder loadFolder = installFolder; try { if (!String.IsNullOrEmpty(subfolder)) { loadFolder = await installFolder.GetFolderAsync(subfolder); } foreach (var file in await loadFolder.GetFilesAsync()) { files.Add(file.Name); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(String.Format("Unable to retrieve files in folder '{0}':{1}", loadFolder.Path, e.StackTrace)); } return(files); }); t.Wait(); List <String> loadableFiles = t.Result; #else if (loadDirectory == null) { String subfolder = String.Empty; #if UNITY_EDITOR_WIN subfolder = IntPtr.Size == 8 ? "x86_64" : "x86"; #elif UNITY_STANDALONE_WIN #else if (Platform.OperationSystem == Emgu.Util.Platform.OS.Windows) { subfolder = IntPtr.Size == 8 ? "x64" : "x86"; } #endif /* * else if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.MacOS) * { * subfolder = ".."; * }*/ System.Reflection.Assembly asm = typeof(CvInvoke).Assembly; //System.Reflection.Assembly.GetExecutingAssembly(); if ((String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))) { if (String.IsNullOrEmpty(AppDomain.CurrentDomain.BaseDirectory)) { loadDirectory = String.Empty; } else { //we may be running in a debugger visualizer under a unit test in this case String visualStudioDir = AppDomain.CurrentDomain.BaseDirectory; DirectoryInfo visualStudioDirInfo = new DirectoryInfo(visualStudioDir); String debuggerVisualizerPath = Path.Combine(visualStudioDirInfo.Parent.FullName, "Packages", "Debugger", "Visualizers"); if (Directory.Exists(debuggerVisualizerPath)) { loadDirectory = debuggerVisualizerPath; } else { loadDirectory = String.Empty; } /* * loadDirectory = Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path); * * DirectoryInfo dir = new DirectoryInfo(loadDirectory); * string subdir = String.Join(";", Array.ConvertAll(dir.GetDirectories(), d => d.ToString())); * * throw new Exception(String.Format( * "The Emgu.CV.dll assembly path (typeof (CvInvoke).Assembly.Location) '{0}' is invalid." + * Environment.NewLine + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().Location): '{1}';" + + Environment.NewLine + " Other possible path (Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path): '{2}';" + + Environment.NewLine + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().CodeBase): '{3};'" + + Environment.NewLine + " Other possible path (typeof(CvInvoke).Assembly.CodeBase): '{4}'" + + Environment.NewLine + " Other possible path (AppDomain.CurrentDomain.BaseDirectory): '{5}'" + + Environment.NewLine + " subfolder name: '{6}'", + asm.Location, + Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path), + loadDirectory + ": subdir '" + subdir +"'", + System.Reflection.Assembly.GetExecutingAssembly().CodeBase, + typeof(CvInvoke).Assembly.Location, + AppDomain.CurrentDomain.BaseDirectory, + subfolder + )); */ } } else { loadDirectory = Path.GetDirectoryName(asm.Location); } /* * FileInfo file = new FileInfo(asm.Location); * //FileInfo file = new FileInfo(asm.CodeBase); * DirectoryInfo directory = file.Directory; * loadDirectory = directory.FullName; */ if (!String.IsNullOrEmpty(subfolder)) { var temp = Path.Combine(loadDirectory, subfolder); if (Directory.Exists(temp)) { loadDirectory = temp; } else { loadDirectory = Path.Combine(Path.GetFullPath("."), subfolder); } } #if (UNITY_STANDALONE_WIN && !UNITY_EDITOR_WIN) if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location)) { Debug.WriteLine(String.Format("UNITY_STANDALONE_WIN: asm.Location is invalid: '{0}'", asm.Location)); return(false); } FileInfo file = new FileInfo(asm.Location); DirectoryInfo directory = file.Directory; if (directory.Parent != null) { String unityAltFolder = Path.Combine(directory.Parent.FullName, "Plugins"); if (Directory.Exists(unityAltFolder)) { loadDirectory = unityAltFolder; } else { Debug.WriteLine("No suitable directory found to load unmanaged modules"); return(false); } } #elif UNITY_ANDROID #else if (!Directory.Exists(loadDirectory)) { //try to find an alternative loadDirectory path //The following code should handle finding the asp.NET BIN folder String altLoadDirectory = Path.GetDirectoryName(asm.CodeBase); if (!String.IsNullOrEmpty(altLoadDirectory) && altLoadDirectory.StartsWith(@"file:\")) { altLoadDirectory = altLoadDirectory.Substring(6); } if (!String.IsNullOrEmpty(subfolder)) { altLoadDirectory = Path.Combine(altLoadDirectory, subfolder); } if (!Directory.Exists(altLoadDirectory)) { if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location)) { Debug.WriteLine(String.Format("asm.Location is invalid: '{0}'", asm.Location)); return(false); } FileInfo file = new FileInfo(asm.Location); DirectoryInfo directory = file.Directory; #if UNITY_EDITOR_WIN if (directory.Parent != null && directory.Parent.Parent != null) { String unityAltFolder = Path.Combine( Path.Combine(Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Emgu.CV"), "Plugins"), subfolder); Debug.WriteLine("Trying unityAltFolder: " + unityAltFolder); if (Directory.Exists(unityAltFolder)) { loadDirectory = unityAltFolder; } else { Debug.WriteLine("No suitable directory found to load unmanaged modules"); return(false); } } else #elif (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX) if (directory.Parent != null && directory.Parent.Parent != null) { String unityAltFolder = Path.Combine(Path.Combine(Path.Combine( Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Plugins"), "emgucv.bundle"), "Contents"), "MacOS"); if (Directory.Exists(unityAltFolder)) { loadDirectory = unityAltFolder; } else { return(false); } } else #endif { Debug.WriteLine("No suitable directory found to load unmanaged modules"); return(false); } } else { loadDirectory = altLoadDirectory; } } #endif } String oldDir = Environment.CurrentDirectory; if (!String.IsNullOrEmpty(loadDirectory) && Directory.Exists(loadDirectory)) { Environment.CurrentDirectory = loadDirectory; } #endif System.Diagnostics.Debug.WriteLine(String.Format("Loading open cv binary from {0}", loadDirectory)); bool success = true; string prefix = string.Empty; foreach (String module in unmanagedModules) { string mName = module; //handle special case for universal build if ( mName.StartsWith("opencv_videoio_ffmpeg") && //opencv_ffmpegvvv(_64).dll (IntPtr.Size == 4) //32bit application ) { mName = module.Replace("_64", String.Empty); } String fullPath = Path.Combine(prefix, mName); //Use absolute path for Windows Desktop fullPath = Path.Combine(loadDirectory, fullPath); bool fileExist = File.Exists(fullPath); if (!fileExist) { System.Diagnostics.Trace.WriteLine(String.Format("File {0} do not exist.", fullPath)); } bool fileExistAndLoaded = fileExist && !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath)); if (fileExist && (!fileExistAndLoaded)) { System.Diagnostics.Trace.WriteLine(String.Format("File {0} cannot be loaded.", fullPath)); } success &= fileExistAndLoaded; } Environment.CurrentDirectory = oldDir; return(success); }
// LateUpdate is called once per frame after all Update was completed. // Camera should move after the player moves. void LateUpdate() { if (m_camState == CameraState.CameraOnDirector) { transform.position = Vector3.zero; } else { transform.position = slime.transform.position + 1.7f * Vector3.up; } //calc camera distance RaycastHit hitInfo = new RaycastHit(); if (Physics.Raycast(transform.position, transform.rotation * Vector3.back, out hitInfo, cameraDistanceMax, -1, QueryTriggerInteraction.Ignore) == true) { cameraDistance = hitInfo.distance - 0.2f; if (cameraDistance <= 0.5f) { cameraDistance = 0.5f; } } else { cameraDistance = cameraDistanceMax; } localPosTarget = cameraDistance * Vector3.back; localRotTarget = Quaternion.identity; switch (m_camState) { case CameraState.CameraOnDirector: case CameraState.CameraOnOther: slime.GetComponent <Slime>().FreezePlayer(); break; case CameraState.CameraMovingTowards: //Moving camera towards the target m_camera.transform.position = Vector3.MoveTowards( m_camera.transform.position, targetPos, speed * Time.deltaTime); m_camera.transform.rotation = Quaternion.RotateTowards( m_camera.transform.rotation, targetRot, speedDeg * Time.deltaTime); slime.GetComponent <Slime>().FreezePlayer(); //State change if (Toolbox.VectorEquals(m_camera.transform.position, targetPos) && Toolbox.QuaternionEquals(m_camera.transform.rotation, targetRot)) { m_camState = CameraState.CameraOnOther; } break; case CameraState.CameraMovingBack: //Moving camera back to player m_camera.transform.localPosition = Vector3.MoveTowards( m_camera.transform.localPosition, localPosTarget, speed * Time.deltaTime); m_camera.transform.localRotation = Quaternion.RotateTowards( m_camera.transform.localRotation, localRotTarget, speedDeg * Time.deltaTime); //State change if (Toolbox.VectorEquals(m_camera.transform.localPosition, localPosTarget) && Toolbox.QuaternionEquals(m_camera.transform.localRotation, localRotTarget)) { m_camState = CameraState.CameraOnPlayer; if (m_UIController.IsPlayerUnfreezeable()) { playerUnfreezed = true; slime.GetComponent <Slime>().UnfreezePlayer(); } } break; case CameraState.CameraOnPlayer: float mouseRotationX = 0, mouseRotationY = 0; if (Slime.controlMode == ControlMode.KeyboardMouse) { mouseRotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * mouseSensitivity; mouseRotationY = transform.localEulerAngles.x - Input.GetAxis("Mouse Y") * mouseSensitivity; } else { mouseRotationX = transform.localEulerAngles.y + Input.GetAxis("Horizontal") * 1.15f; } //Debug.Log(mouseRotationY); if ((mouseRotationY > 85) && (mouseRotationY < 180)) { mouseRotationY = 85; } else if ((mouseRotationY < 320) && (mouseRotationY > 180)) { mouseRotationY = 320; } transform.localEulerAngles = new Vector3(mouseRotationY, mouseRotationX, 0); m_camera.transform.localPosition = Vector3.MoveTowards( m_camera.transform.localPosition, localPosTarget, 10.0f * Time.deltaTime); m_camera.transform.localRotation = Quaternion.RotateTowards( m_camera.transform.localRotation, localRotTarget, 360.0f * Time.deltaTime); //if (playerUnfreezed == false && (m_UIController && m_UIController.IsPlayerUnfreezeable())) //{ // playerUnfreezed = true; // slime.GetComponent<Slime>().UnfreezePlayer(); //} if (Input.GetButtonDown("ResetCam")) { m_camState = CameraState.CameraReset; } break; case CameraState.CameraReset: transform.rotation = Quaternion.RotateTowards(transform.rotation, slime.transform.rotation, 720.0f * Time.deltaTime); if (Toolbox.QuaternionEquals(transform.rotation, slime.transform.rotation)) { m_camState = CameraState.CameraOnPlayer; } break; } }
protected override float GetDistance(Quaternion start, Quaternion end) { Quaternion.Conjugate(ref end, out end); Quaternion.Multiply(ref end, ref start, out end); return(Toolbox.GetAngleFromQuaternion(ref end)); }
/// <summary> /// Initializes the constraint for the current frame. /// </summary> /// <param name="dt">Time between frames.</param> public override void Update(float dt) { basis.rotationMatrix = connectionA.orientationMatrix; basis.ComputeWorldSpaceAxes(); if (settings.mode == MotorMode.Servomechanism) //Only need to do the bulk of this work if it's a servo. { //The error is computed using this equation: //GoalRelativeOrientation * ConnectionA.Orientation * Error = ConnectionB.Orientation //GoalRelativeOrientation is the original rotation from A to B in A's local space. //Multiplying by A's orientation gives us where B *should* be. //Of course, B won't be exactly where it should be after initialization. //The Error component holds the difference between what is and what should be. //Error = (GoalRelativeOrientation * ConnectionA.Orientation)^-1 * ConnectionB.Orientation //ConnectionA.Orientation is replaced in the above by the world space basis orientation. Quaternion worldBasis = Matrix3x3.CreateQuaternion(basis.WorldTransform); Quaternion bTarget; Quaternion.Concatenate(ref settings.servo.goal, ref worldBasis, out bTarget); Quaternion bTargetConjugate; Quaternion.Conjugate(ref bTarget, out bTargetConjugate); Quaternion error; Quaternion.Concatenate(ref bTargetConjugate, ref connectionB.orientation, out error); float errorReduction; settings.servo.springSettings.ComputeErrorReductionAndSoftness(dt, out errorReduction, out usedSoftness); //Turn this into an axis-angle representation. Toolbox.GetAxisAngleFromQuaternion(ref error, out axis, out angle); //Scale the axis by the desired velocity if the angle is sufficiently large (epsilon). if (angle > Toolbox.BigEpsilon) { float velocity = -(MathHelper.Min(settings.servo.baseCorrectiveSpeed, angle / dt) + angle * errorReduction); biasVelocity.X = axis.X * velocity; biasVelocity.Y = axis.Y * velocity; biasVelocity.Z = axis.Z * velocity; //Ensure that the corrective velocity doesn't exceed the max. float length = biasVelocity.LengthSquared(); if (length > settings.servo.maxCorrectiveVelocitySquared) { float multiplier = settings.servo.maxCorrectiveVelocity / (float)Math.Sqrt(length); biasVelocity.X *= multiplier; biasVelocity.Y *= multiplier; biasVelocity.Z *= multiplier; } } else { biasVelocity.X = 0; biasVelocity.Y = 0; biasVelocity.Z = 0; } } else { usedSoftness = settings.velocityMotor.softness / dt; angle = 0; //Zero out the error; Matrix3x3 transform = basis.WorldTransform; Matrix3x3.Transform(ref settings.velocityMotor.goalVelocity, ref transform, out biasVelocity); } //Compute effective mass Matrix3x3.Add(ref connectionA.inertiaTensorInverse, ref connectionB.inertiaTensorInverse, out effectiveMassMatrix); effectiveMassMatrix.M11 += usedSoftness; effectiveMassMatrix.M22 += usedSoftness; effectiveMassMatrix.M33 += usedSoftness; Matrix3x3.Invert(ref effectiveMassMatrix, out effectiveMassMatrix); //Update the maximum force ComputeMaxForces(settings.maximumForce, dt); }
public bool Equals(NodeId other) { return(other != null && Toolbox.ByteMatch(Bytes, other.Bytes)); }
public static void Init() { Gun gun = ETGMod.Databases.Items.NewGun("Super Bullat Launcher", "superbatlauncher"); Game.Items.Rename("outdated_gun_mods:super_bullat_launcher", "spapi:bullat_launcher+king_bullat_shooter"); GunExt.SetShortDescription(gun, "Fires Bullats"); GunExt.SetLongDescription(gun, "Shoots angry bullats.\n\nCatching Bullats is fairly easy and every good gundead hunter has to have a Bullat collection. Frifle through had an idea to weaponize his collection, and made this gun."); GunExt.SetupSprite(gun, null, "superbatlauncher_idle_001", 12); for (int i = 0; i < 12; i++) { GunExt.AddProjectileModuleFrom(gun, "klobb", true, false); } int j = 0; foreach (ProjectileModule mod in gun.Volley.projectiles) { mod.angleVariance = 0; mod.shootStyle = ProjectileModule.ShootStyle.Charged; mod.cooldownTime = 0.5f; mod.numberOfShotsInClip = 10; Projectile projectile = Instantiate(Toolbox.GetGunById(38).DefaultModule.projectiles[0]); projectile.gameObject.SetActive(false); FakePrefab.MarkAsFakePrefab(projectile.gameObject); DontDestroyOnLoad(projectile); projectile.transform.parent = gun.barrelOffset; projectile.baseData.damage = 15f; projectile.name = "SuperBullat_Projectile"; BounceProjModifier modifier = projectile.gameObject.GetOrAddComponent <BounceProjModifier>(); modifier.numberOfBounces = 1; mod.chargeProjectiles = new List <ProjectileModule.ChargeProjectile> { new ProjectileModule.ChargeProjectile { ChargeTime = 1.5f, Projectile = projectile } }; mod.ammoType = GameUIAmmoType.AmmoType.CUSTOM; mod.customAmmoType = "finished small"; mod.angleFromAim = j * 30; j++; } AdvancedGunBehaviour advancedGunBehaviour = gun.gameObject.AddComponent <AdvancedGunBehaviour>(); advancedGunBehaviour.preventNormalFireAudio = true; gun.muzzleFlashEffects.type = VFXPoolType.None; gun.reloadTime = 1.5f; gun.gunHandedness = GunHandedness.OneHanded; gun.SetBaseMaxAmmo(50); gun.InfiniteAmmo = true; gun.quality = PickupObject.ItemQuality.EXCLUDED; gun.barrelOffset.transform.localPosition = new Vector3(1.625f, 1.5625f, 0f); gun.encounterTrackable.EncounterGuid = "superbatlauncher"; gun.gunClass = GunClass.CHARGE; gun.GetComponent <tk2dSpriteAnimator>().GetClipByName(gun.shootAnimation).frames[0].eventAudio = "Play_ENM_bullat_tackle_01"; gun.GetComponent <tk2dSpriteAnimator>().GetClipByName(gun.shootAnimation).frames[0].triggerEvent = true; gun.GetComponent <tk2dSpriteAnimator>().GetClipByName(gun.chargeAnimation).frames[0].eventAudio = "Play_ENM_bullat_charge_01"; gun.GetComponent <tk2dSpriteAnimator>().GetClipByName(gun.chargeAnimation).frames[0].triggerEvent = true; gun.GetComponent <tk2dSpriteAnimator>().GetClipByName(gun.chargeAnimation).wrapMode = tk2dSpriteAnimationClip.WrapMode.LoopSection; gun.GetComponent <tk2dSpriteAnimator>().GetClipByName(gun.chargeAnimation).loopStart = 1; ETGMod.Databases.Items.Add(gun, null, "ANY"); gun.AddToTrorkShop(); gun.AddToBlacksmithShop(); gun.RemovePeskyQuestionmark(); gun.PlaceItemInAmmonomiconAfterItemById(22); }
internal Tuple <Coordinates, List <Waypoint> > GenerateObjective( DCSMission mission, MissionTemplateRecord template, DBEntrySituation situationDB, MissionTemplateObjectiveRecord objectiveTemplate, Coordinates lastCoordinates, DBEntryAirbase playerAirbase, bool useObjectivePreset, ref int objectiveIndex, ref List <Coordinates> objectiveCoordinatesList, ref List <Waypoint> waypoints, ref List <UnitFamily> objectiveTargetUnitFamilies) { var extraSettings = new List <KeyValuePair <string, object> >(); var waypointList = new List <Waypoint>(); string[] featuresID; DBEntryObjectiveTarget targetDB; DBEntryObjectiveTargetBehavior targetBehaviorDB; DBEntryObjectiveTask taskDB; ObjectiveOption[] objectiveOptions; GetObjectiveData(objectiveTemplate, useObjectivePreset, out featuresID, out targetDB, out targetBehaviorDB, out taskDB, out objectiveOptions); var luaUnit = targetBehaviorDB.UnitLua[(int)targetDB.UnitCategory]; Coordinates objectiveCoordinates = GetSpawnCoordinates(template, lastCoordinates, playerAirbase, targetDB); // Spawn target on airbase var unitCount = targetDB.UnitCount[(int)objectiveTemplate.TargetCount].GetValue(); var objectiveTargetUnitFamily = Toolbox.RandomFrom(targetDB.UnitFamilies); if (AIRBASE_LOCATIONS.Contains(targetBehaviorDB.Location) && targetDB.UnitCategory.IsAircraft()) { objectiveCoordinates = PlaceInAirbase(template, situationDB, playerAirbase, extraSettings, targetDB, targetBehaviorDB, ref luaUnit, objectiveCoordinates, unitCount, objectiveTargetUnitFamily); } UnitMakerGroupFlags groupFlags = 0; if (objectiveOptions.Contains(ObjectiveOption.ShowTarget)) { groupFlags = UnitMakerGroupFlags.NeverHidden; } else if (objectiveOptions.Contains(ObjectiveOption.HideTarget)) { groupFlags = UnitMakerGroupFlags.AlwaysHidden; } if (objectiveOptions.Contains(ObjectiveOption.EmbeddedAirDefense)) { groupFlags |= UnitMakerGroupFlags.EmbeddedAirDefense; } // Set destination point for moving unit groups Coordinates destinationPoint = objectiveCoordinates + ( (targetDB.UnitCategory == UnitCategory.Plane ? Coordinates.CreateRandom(30, 60) : Coordinates.CreateRandom(10, 20)) * Toolbox.NM_TO_METERS ); if (targetBehaviorDB.Location == DBEntryObjectiveTargetBehaviorLocation.GoToPlayerAirbase) { destinationPoint = playerAirbase.Coordinates; } var unitCoordinates = objectiveCoordinates; var objectiveName = Toolbox.RandomFrom(ObjectiveNames); if (TRANSPORT_TASKS.Contains(taskDB.ID)) { Coordinates?spawnPoint = UnitMaker.SpawnPointSelector.GetRandomSpawnPoint( targetDB.ValidSpawnPoints, playerAirbase.Coordinates, new MinMaxD(1, 5), coalition: GeneratorTools.GetSpawnPointCoalition(template, Side.Ally)); if (!spawnPoint.HasValue) // Failed to generate target group { throw new BriefingRoomException($"Failed to find Cargo SpawnPoint"); } unitCoordinates = spawnPoint.Value; var cargoWaypoint = GenerateObjectiveWaypoint(objectiveTemplate, unitCoordinates, $"{objectiveName} Pickup", template, true); waypoints.Add(cargoWaypoint); waypointList.Add(cargoWaypoint); if (taskDB.isEscort()) { extraSettings.Add("GroupX2".ToKeyValuePair(objectiveCoordinates.X)); extraSettings.Add("GroupY2".ToKeyValuePair(objectiveCoordinates.Y)); groupFlags |= UnitMakerGroupFlags.RadioAircraftSpawn; } } extraSettings.Add("GroupX2".ToKeyValuePair(destinationPoint.X)); extraSettings.Add("GroupY2".ToKeyValuePair(destinationPoint.Y)); UnitMakerGroupInfo?targetGroupInfo = UnitMaker.AddUnitGroup( objectiveTargetUnitFamily, unitCount, taskDB.TargetSide, targetBehaviorDB.GroupLua[(int)targetDB.UnitCategory], luaUnit, unitCoordinates, groupFlags, extraSettings.ToArray()); if (!targetGroupInfo.HasValue) // Failed to generate target group { throw new BriefingRoomException($"Failed to generate group for objective."); } if (objectiveOptions.Contains(ObjectiveOption.EmbeddedAirDefense) && (targetDB.UnitCategory == UnitCategory.Static)) { AddEmbeddedAirDefenseUnits(template, targetDB, targetBehaviorDB, taskDB, objectiveOptions, objectiveCoordinates, groupFlags, extraSettings); } var pluralIndex = targetGroupInfo.Value.UnitsID.Length == 1 ? 0 : 1; var taskString = GeneratorTools.ParseRandomString(taskDB.BriefingTask[pluralIndex], mission).Replace("\"", "''"); // Pick a name, then remove it from the list ObjectiveNames.Remove(objectiveName); CreateTaskString(mission, pluralIndex, ref taskString, objectiveName, objectiveTargetUnitFamily); CreateLua(mission, template, targetDB, taskDB, objectiveIndex, objectiveName, targetGroupInfo, taskString); // Add briefing remarks for this objective task if (taskDB.BriefingRemarks.Length > 0) { string remark = Toolbox.RandomFrom(taskDB.BriefingRemarks); GeneratorTools.ReplaceKey(ref remark, "ObjectiveName", objectiveName); GeneratorTools.ReplaceKey(ref remark, "UnitFamily", Database.Instance.Common.Names.UnitFamilies[(int)objectiveTargetUnitFamily][pluralIndex]); mission.Briefing.AddItem(DCSMissionBriefingItemType.Remark, remark); } // Add feature ogg files foreach (string oggFile in taskDB.IncludeOgg) { mission.AddMediaFile($"l10n/DEFAULT/{oggFile}", $"{BRPaths.INCLUDE_OGG}{oggFile}"); } // Add objective features Lua for this objective mission.AppendValue("ScriptObjectivesFeatures", ""); // Just in case there's no features foreach (string featureID in featuresID) { FeaturesGenerator.GenerateMissionFeature(mission, featureID, objectiveName, objectiveIndex, targetGroupInfo.Value.GroupID, objectiveCoordinates, taskDB.TargetSide, objectiveOptions.Contains(ObjectiveOption.HideTarget)); } objectiveCoordinatesList.Add(objectiveCoordinates); var waypoint = GenerateObjectiveWaypoint(objectiveTemplate, objectiveCoordinates, objectiveName, template); waypoints.Add(waypoint); waypointList.Add(waypoint); objectiveTargetUnitFamilies.Add(objectiveTargetUnitFamily); var preValidSpawns = targetDB.ValidSpawnPoints.ToList(); foreach (var subTasks in objectiveTemplate.SubTasks) { objectiveIndex++; GenerateSubTask(mission, template, situationDB, subTasks, objectiveCoordinates, playerAirbase, preValidSpawns, targetBehaviorDB.Location, featuresID, ref objectiveIndex, ref objectiveCoordinatesList, ref waypoints, ref waypointList, ref objectiveTargetUnitFamilies); } return(new (objectiveCoordinates, waypointList)); }
public ActionValPair(int myVal, Toolbox.BasicAction myAction, Toolbox.AttackType myAttackColour = Toolbox.AttackType.Summon) { val = myVal; action = myAction; attackColour = myAttackColour; }
internal void RaiseStatsUpdate(StatsUpdateEventArgs args) { Toolbox.RaiseAsyncEvent <StatsUpdateEventArgs>(StatsUpdate, this, args); }
public void AddEnergy(int val, Toolbox.EnergyColour colour) { switch (colour) { case Toolbox.EnergyColour.Dark: darkEnergy += val; break; case Toolbox.EnergyColour.Red: redEnergy += val; break; case Toolbox.EnergyColour.White: whiteEnergy += val; break; case Toolbox.EnergyColour.Green: greenEnergy += val; break; case Toolbox.EnergyColour.Blue: blueEnergy += val; break; default: break; } UpdateLabels(); }
/// <summary> /// Generate histograms for the image. One histogram is generated for each color channel. /// You will need to call the Refresh function to do the painting afterward. /// </summary> /// <param name="image">The image to generate histogram from</param> /// <param name="numberOfBins">The number of bins for each histogram</param> public void GenerateHistograms(IImage image, int numberOfBins) { Mat[] channels = new Mat[image.NumberOfChannels]; Type imageType; if ((imageType = Toolbox.GetBaseType(image.GetType(), "Image`2")) != null || (imageType = Toolbox.GetBaseType(image.GetType(), "Mat")) != null) { for (int i = 0; i < image.NumberOfChannels; i++) { Mat channel = new Mat(); CvInvoke.ExtractChannel(image, channel, i); channels[i] = channel; } } else if ((imageType = Toolbox.GetBaseType(image.GetType(), "CudaImage`2")) != null) { IImage img = imageType.GetMethod("ToImage").Invoke(image, null) as IImage; for (int i = 0; i < img.NumberOfChannels; i++) { Mat channel = new Mat(); CvInvoke.ExtractChannel(img, channel, i); channels[i] = channel; } } else { throw new ArgumentException(String.Format("The input image type of {0} is not supported", image.GetType().ToString())); } Type[] genericArguments = imageType.GetGenericArguments(); String[] channelNames; Color[] colors; Type typeOfDepth; if (genericArguments.Length > 0) { IColor typeOfColor = Activator.CreateInstance(genericArguments[0]) as IColor; channelNames = Reflection.ReflectColorType.GetNamesOfChannels(typeOfColor); colors = Reflection.ReflectColorType.GetDisplayColorOfChannels(typeOfColor); typeOfDepth = imageType.GetGenericArguments()[1]; } else { channelNames = new String[image.NumberOfChannels]; colors = new Color[image.NumberOfChannels]; for (int i = 0; i < image.NumberOfChannels; i++) { channelNames[i] = String.Format("Channel {0}", i); colors[i] = Color.Red; } if (image is Mat) { typeOfDepth = CvInvoke.GetDepthType(((Mat)image).Depth); } else { throw new ArgumentException(String.Format("Unable to get the type of depth from image of type {0}", image.GetType().ToString())); } } float minVal, maxVal; #region Get the maximum and minimum color intensity values if (typeOfDepth == typeof(Byte)) { minVal = 0.0f; maxVal = 256.0f; } else { #region obtain the maximum and minimum color value double[] minValues, maxValues; Point[] minLocations, maxLocations; image.MinMax(out minValues, out maxValues, out minLocations, out maxLocations); double min = minValues[0], max = maxValues[0]; for (int i = 1; i < minValues.Length; i++) { if (minValues[i] < min) { min = minValues[i]; } if (maxValues[i] > max) { max = maxValues[i]; } } #endregion minVal = (float)min; maxVal = (float)max; } #endregion for (int i = 0; i < channels.Length; i++) { //using (DenseHistogram hist = new DenseHistogram(numberOfBins, new RangeF(minVal, maxVal))) using (Mat hist = new Mat()) using (Util.VectorOfMat vm = new Util.VectorOfMat()) { vm.Push(channels[i]); float[] ranges = new float[] { minVal, maxVal }; CvInvoke.CalcHist(vm, new int[] { 0 }, null, hist, new int[] { numberOfBins }, ranges, false); //hist.Calculate(new IImage[1] { channels[i] }, true, null); AddHistogram(channelNames[i], colors[i], hist, numberOfBins, ranges); } } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.arToolbox = new DataDynamics.ActiveReports.Design.Toolbox.Toolbox(); this.pnlToolbox = new System.Windows.Forms.Panel(); this.splitterToolboxDesigner = new System.Windows.Forms.Splitter(); this.arDesigner = new DataDynamics.ActiveReports.Design.Designer(); this.arPropertyGrid = new System.Windows.Forms.PropertyGrid(); this.splitterDesignerProperties = new System.Windows.Forms.Splitter(); this.pnlProperties = new System.Windows.Forms.Panel(); this.splitterReportExplorerPropertyGrid = new System.Windows.Forms.Splitter(); this.arStatus = new System.Windows.Forms.StatusBar(); this.commandBarManager = new DataDynamics.ActiveReports.Design.CommandBarManager(); ((System.ComponentModel.ISupportInitialize)(this.arToolbox)).BeginInit(); this.pnlToolbox.SuspendLayout(); this.pnlProperties.SuspendLayout(); this.SuspendLayout(); // // arToolbox // this.arToolbox.Dock = System.Windows.Forms.DockStyle.Fill; this.arToolbox.LargeImages = null; this.arToolbox.Location = new System.Drawing.Point(0, 0); this.arToolbox.Name = "arToolbox"; this.arToolbox.Selected = null; this.arToolbox.Size = new System.Drawing.Size(200, 578); this.arToolbox.SmallImages = null; this.arToolbox.TabIndex = 0; // // pnlToolbox // this.pnlToolbox.Controls.Add(this.arToolbox); this.pnlToolbox.Dock = System.Windows.Forms.DockStyle.Left; this.pnlToolbox.Location = new System.Drawing.Point(0, 0); this.pnlToolbox.Name = "pnlToolbox"; this.pnlToolbox.Size = new System.Drawing.Size(200, 578); this.pnlToolbox.TabIndex = 0; // // splitterToolboxDesigner // this.splitterToolboxDesigner.BackColor = System.Drawing.SystemColors.Control; this.splitterToolboxDesigner.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitterToolboxDesigner.Location = new System.Drawing.Point(200, 0); this.splitterToolboxDesigner.Name = "splitterToolboxDesigner"; this.splitterToolboxDesigner.Size = new System.Drawing.Size(3, 578); this.splitterToolboxDesigner.TabIndex = 1; this.splitterToolboxDesigner.TabStop = false; // // arDesigner // this.arDesigner.Dock = System.Windows.Forms.DockStyle.Fill; this.arDesigner.IsDirty = false; this.arDesigner.Location = new System.Drawing.Point(203, 0); this.arDesigner.LockControls = false; this.arDesigner.Name = "arDesigner"; this.arDesigner.PropertyGrid = this.arPropertyGrid; this.arDesigner.ReportTabsVisible = true; this.arDesigner.ShowDataSourceIcon = true; this.arDesigner.Size = new System.Drawing.Size(397, 578); this.arDesigner.TabIndex = 2; this.arDesigner.Toolbox = null; this.arDesigner.ToolBoxItem = null; this.arDesigner.SelectionChanged += new DataDynamics.ActiveReports.Design.SelectionChangedEventHandler(this.arDesigner_SelectionChanged); // // arPropertyGrid // this.arPropertyGrid.CommandsVisibleIfAvailable = true; this.arPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.arPropertyGrid.LargeButtons = false; this.arPropertyGrid.LineColor = System.Drawing.SystemColors.ScrollBar; this.arPropertyGrid.Location = new System.Drawing.Point(0, 231); this.arPropertyGrid.Name = "arPropertyGrid"; this.arPropertyGrid.Size = new System.Drawing.Size(200, 347); this.arPropertyGrid.TabIndex = 2; this.arPropertyGrid.Text = "propertyGrid1"; this.arPropertyGrid.ViewBackColor = System.Drawing.SystemColors.Window; this.arPropertyGrid.ViewForeColor = System.Drawing.SystemColors.WindowText; // // splitterDesignerProperties // this.splitterDesignerProperties.BackColor = System.Drawing.SystemColors.Control; this.splitterDesignerProperties.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.splitterDesignerProperties.Dock = System.Windows.Forms.DockStyle.Right; this.splitterDesignerProperties.Location = new System.Drawing.Point(597, 0); this.splitterDesignerProperties.Name = "splitterDesignerProperties"; this.splitterDesignerProperties.Size = new System.Drawing.Size(3, 578); this.splitterDesignerProperties.TabIndex = 3; this.splitterDesignerProperties.TabStop = false; // // pnlProperties // this.pnlProperties.Controls.Add(this.arPropertyGrid); this.pnlProperties.Controls.Add(this.splitterReportExplorerPropertyGrid); this.pnlProperties.Dock = System.Windows.Forms.DockStyle.Right; this.pnlProperties.Location = new System.Drawing.Point(600, 0); this.pnlProperties.Name = "pnlProperties"; this.pnlProperties.Size = new System.Drawing.Size(200, 578); this.pnlProperties.TabIndex = 4; // // splitterReportExplorerPropertyGrid // this.splitterReportExplorerPropertyGrid.Dock = System.Windows.Forms.DockStyle.Top; this.splitterReportExplorerPropertyGrid.Location = new System.Drawing.Point(0, 228); this.splitterReportExplorerPropertyGrid.Name = "splitterReportExplorerPropertyGrid"; this.splitterReportExplorerPropertyGrid.Size = new System.Drawing.Size(200, 3); this.splitterReportExplorerPropertyGrid.TabIndex = 1; this.splitterReportExplorerPropertyGrid.TabStop = false; // // arStatus // this.arStatus.Location = new System.Drawing.Point(0, 578); this.arStatus.Name = "arStatus"; this.arStatus.Size = new System.Drawing.Size(800, 22); this.arStatus.TabIndex = 5; // // commandBarManager // this.commandBarManager.Dock = System.Windows.Forms.DockStyle.Top; this.commandBarManager.Location = new System.Drawing.Point(0, 0); this.commandBarManager.Name = "commandBarManager"; this.commandBarManager.Size = new System.Drawing.Size(800, 0); this.commandBarManager.TabIndex = 6; this.commandBarManager.TabStop = false; // // EndUserDesignerMainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(800, 600); this.Controls.Add(this.splitterDesignerProperties); this.Controls.Add(this.arDesigner); this.Controls.Add(this.splitterToolboxDesigner); this.Controls.Add(this.pnlToolbox); this.Controls.Add(this.pnlProperties); this.Controls.Add(this.arStatus); this.Controls.Add(this.commandBarManager); this.Name = "EndUserDesignerMainForm"; this.Text = (string)App.Current.FindResource("ActiveReportsTitle"); ((System.ComponentModel.ISupportInitialize)(this.arToolbox)).EndInit(); this.pnlToolbox.ResumeLayout(false); this.pnlProperties.ResumeLayout(false); this.ResumeLayout(false); }
public void loadToolboxes(string toolboxfile) { loadToolBoxItem(toolboxfile); //where customise items will be customToolbox = new Toolbox(); //load customtoolbox Items //string customElementsFile = "../../Resources/CustomToolBoxItems.xml"; string customElementsFile = DirectoryHelper.getFilePathExecutingAssembly("Resources\\CustomToolBoxItems.xml"); loadCutomToolbox(customElementsFile, customToolbox); CustomVisualisationExpander.Content = customToolbox; CustomVisualisationExpander.IsExpanded = false; //load functions toolbox functionsToolBox = new Toolbox(); //string functionsFile = "../../Resources/Functions.xml"; string functionsFile = DirectoryHelper.getFilePathExecutingAssembly("Resources\\Functions.xml"); loadFunctionsToolbox(functionsFile, functionsToolBox); FunctionsExpander.Content = functionsToolBox; FunctionsExpander.IsExpanded = false; }
// Use this for initialization void Start() { inventoryList = GameObject.Find("InventoryList"); inventory = inventoryList.GetComponent<Toolbox>(); //inventory = inventoryList.SendMessage("Instance"); }
private void loadCutomToolbox(string customElementsFile, Toolbox customToolbox) { //something should be done for templte repository if (System.IO.File.Exists(customElementsFile)) { try { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(customElementsFile, readerSettings)) { // SECTION 1. Create a DOM Document and load the XML data into it. dom = new XmlDocument(); dom.Load(reader); // SECTION 2. Initialize Elements XmlNodeList customNodes = dom.SelectNodes("CustomItems/CustomItem"); //MessageBox.Show(customNodes.Count.ToString()); // SECTION 3. Populate Items with the DOM nodes. foreach (XmlNode xnode in customNodes) { ToolboxItem item = new ToolboxItem(); item.loadCustomisedToolBoxItem(xnode); customToolbox.Items.Add(item); } reader.Close(); } } catch (XmlException xmlEx) { System.Windows.MessageBox.Show(xmlEx.Message); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); } } else reportMessage("Could not load Custom ToolboxItems file : " + customElementsFile, ReportIcon.Error); }
// Public methods. /// <summary> /// Initializes the control with the specified toolbox. /// </summary> /// <param name="toolbox">The toolbox.</param> /// <param name="triggers">The list of triggers.</param> public void Initialize(Toolbox toolbox, IEnumerable<ToolMethodTrigger> triggers) { // Check the list of triggers is not empty. if (triggers.Count() == 0) throw new ArgumentException("The list of triggers cannot be empty."); // Set the toolbox. this.toolbox = toolbox; // Update the list of triggers. this.comboBoxTrigger.Items.Clear(); foreach (ToolMethodTrigger trigger in triggers) { this.comboBoxTrigger.Items.Add(trigger); } // Select the first trigger. this.comboBoxTrigger.SelectedIndex = 0; // Update the list of tools. this.comboBoxTool.Items.Clear(); foreach (Tool tool in this.toolbox) { this.comboBoxTool.Items.Add(tool); } // Clear the list of methods. this.listViewMethods.Items.Clear(); // Call the trigger selection changed. this.OnTriggerSelectionChanged(this, EventArgs.Empty); // Call the method selection changed. this.OnMethodSelectionChanged(this, EventArgs.Empty); }
// Use this for initialization void Start() { Debug.Log("Starting tutorial level"); shownBoxAnimation = false; endingCenterAnimation = false; showingPortalAnimation = false; toolbox = Toolbox.Instance; toolbox.SetUpForLevelBegin (); GameObject tableObj = GameObject.Find ("Table"); GameObject rotateMiddleObj = GameObject.Find ("Middle_Rotate"); GameObject padlockObj = GameObject.Find ("Padlock"); GameObject zinlockObj = GameObject.Find ("Zinlock"); GameObject dominosaObj = GameObject.Find ("Dominosa"); GameObject pedestal = GameObject.Find ("Pedestal"); GameObject pedestalRotator = GameObject.Find ("Pedestal Rotator"); gemPuzzle = tableObj.GetComponent<GemPuzzle>(); rotateTablePuzzle = rotateMiddleObj.GetComponent<RotateObject> (); padlockPuzzle = padlockObj.GetComponent<PadlockPuzzle> (); dominosaPuzzle = dominosaObj.GetComponent<DominosaScript> (); zinlockPuzzle = zinlockObj.GetComponent<ZinlockScript> (); //pedestalPuzzle = pedestal.GetComponent<PedestalScript> (); //skullPuzzle = pedestalRotator.GetComponent<PedestalRotatorScript> (); openBox = false; padlockActivated = false; skullActivated = false; }
public Cost(int myVal, Toolbox.EnergyColour myColour, bool mySacrifice = false) { val = myVal; colour = myColour; sacrifice = mySacrifice; }
/// <summary> /// Creates a new crawer global object, based on a configuration from the specified root registry key. /// </summary> /// <param name="rootKey">The root registry key.</param> /// <param name="rootPath">The root registry path.</param> public Crawler(RegistryKey rootKey, string rootPath) { // Create the configuration. this.config = new CrawlerConfig(rootKey, rootPath); // Create the crawler events. this.events = new CrawlerEvents(); // Create the logger. this.log = new Logger(this.config.LogFileName); // Create the database servers. this.dbConfig = new DbConfig(this, rootKey, rootPath + @"\Database"); // Create the PlanetLab configuration. this.plConfig = new PlConfig(rootKey, rootPath + @"\PlanetLab"); // Create the YouTube configuration. this.ytConfig = new YtConfig(this.config); // Create the status. this.status = new ApplicationStatus(); // Create the comments. this.comments = new CrawlerComments(this.config); // Create the crawler spiders. this.spiders = new Spiders(this); // Create the crawler API. this.api = new CrawlerApi(this.config, this.dbConfig, this.log, this.status); // Create the toolbox. this.toolbox = new Toolbox(this, rootKey, rootPath + @"\Toolbox"); }
private void Start() { Toolbox.GetInstance().GetManager <GameManager>().ShowSummary(); }
void Check(UdpTrackerMessage message, MessageType type) { byte[] e = message.Encode(); Assert.AreEqual(e.Length, message.ByteLength, "#1"); Assert.IsTrue(Toolbox.ByteMatch(e, UdpTrackerMessage.DecodeMessage(e, 0, e.Length, type).Encode()), "#2"); }
public Interaction(int myVal, Toolbox.InteractionType myType) { val = myVal; type = myType; }
//Routine to update score for colored player //Inputs: Color of player to update, boolean determining action // False=Decrement score of inputted player, increment everyone else's (for Battle mode self-score) // True = Increment score of inputted player public static void UpdateScore(Toolbox.Color clr, bool action) { byte i=0; //Generic for loop counter //String arrays of GameOver music //Aligns with Toolbox.mode enum string[] music = { "GO2_trsi-borntro", "GO1_johnmadden-scoutreport", "GO_scout" }; Helper.light.enabled = true; //Set the score box light to on //If incrementing a score if (action == true) { //If score is NOT 10, then increment if (Score[(byte)clr]!=10) { Score[(byte)clr]++; } } else { //If decrementing self-score, incrementing everyone else's for (i = 1; i <= 4; i++) { if (i == (byte)clr) { //Decrement self-scorer, if score is not 0 if (Score[(byte)clr]!=0) { Score[(byte)clr]--; } } else { //Increment everybody else's score, if score is not 10 if (Score[i] != 10) { Score[i]++; } } } } //If gameover condition is met (somebody has score of 10) //then play appropriate gameover song for mode if (FindHiScore(true) >= 10) { SoundManager.StopAllSounds(); //Stop all songs SoundManager.Play(music[(int)Toolbox.Options.Mode]); //Play appropriate gameover song } SoundManager.Play("vGoal"); //"Goal!" SoundManager.Play("Siren"); //Siren ScoreTalk(); //Speak the game score }
public Mapper() { InitializeComponent(); //For interaction modes in Mapper. InteractModes = new List<string> { "Mouse", "Stylus", "Gesture", "Stylus and Gesture" }; InteractionModeCombobox.ItemsSource = InteractModes; InteractionModeCombobox.SelectedIndex = 0; //style for values list box -> rule designer Style valuesListboxStyle = new Style(); EventSetter esVSMouseDown = new EventSetter(ListBoxItem.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(ValueListBox_PreviewMouseDown)); EventSetter esVSMouseMove = new EventSetter(ListBoxItem.PreviewMouseMoveEvent, new MouseEventHandler(ValueListBox_PreviewMouseMove)); valuesListboxStyle.Setters.Add(esVSMouseDown); valuesListboxStyle.Setters.Add(esVSMouseMove); ValuesListBox.ItemContainerStyle = valuesListboxStyle; RulesListBox.ItemsSource = Matches; //style for defined rules list box //Style rulesListboxStyle = new Style(); //EventSetter esMouseDown = new EventSetter(ListBoxItem.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(ListBoxItem_PreviewMouseDown)); //EventSetter esMouseMove = new EventSetter(ListBoxItem.PreviewMouseMoveEvent, new MouseEventHandler(ListBoxItem_MouseMove)); //rulesListboxStyle.Setters.Add(esMouseDown); //rulesListboxStyle.Setters.Add(esMouseMove); //RulesListBox.ItemContainerStyle = rulesListboxStyle; suggestions = new ObservableCollection<Suggestion>(); SuggestionsListBox.ItemsSource = suggestions; //set them to true mapperSuggester = new Suggester(); //load functions toolbox functionsToolBox = new Toolbox(); string functionsFile = "../../Resources/Functions.xml"; loadFunctionsToolbox(functionsFile, functionsToolBox); FunctionsExpander.Content = functionsToolBox; FunctionsExpander.IsExpanded = true; //Logger logger = new Logger("MapperLogger"); logsTab.Content = logger; }
private void FixedUpdate() { Debug.Log(p.money); if (agent.isOnNavMesh && agent.isStopped && !mining && !emptying && currentCapacity < maxCapacity) { target = Toolbox.FindNearest(transform.position, Toolbox.GoldToGameObjects(FindObjectsOfType <Gold>())); agent.isStopped = false; agent.SetDestination(target.transform.position); } if (!agent.isStopped && !mining && !emptying && Vector3.Distance(transform.position, target.transform.position) <= 3) { agent.isStopped = true; mining = true; weld.SetActive(true); spin.GetComponent <Animator>().SetBool("Mines", true); } if (mining) { if (target.GetComponent <Gold>().value < miningSpeed * Time.fixedDeltaTime) { currentCapacity += target.GetComponent <Gold>().value; target.GetComponent <Gold>().value = 0; Destroy(target); weld.SetActive(false); spin.GetComponent <Animator>().SetBool("Mines", false); mining = false; } if ((maxCapacity - currentCapacity) < miningSpeed * Time.fixedDeltaTime) { target.GetComponent <Gold>().value -= (maxCapacity - currentCapacity); currentCapacity = maxCapacity; emptying = true; mining = false; List <GameObject> refineries = new List <GameObject>(); foreach (Building b in FindObjectsOfType <Building>()) { if (b.type == BuildingType.ResourceDepot) { refineries.Add(b.gameObject); } } agent.SetDestination(Toolbox.FindNearest(transform.position, refineries.ToArray()).GetComponent <Building>().rallyPoint.transform.position); agent.isStopped = false; weld.SetActive(false); carried.SetActive(true); spin.GetComponent <Animator>().SetBool("Mines", false); } if (currentCapacity < maxCapacity - miningSpeed * Time.fixedDeltaTime) { currentCapacity += miningSpeed * Time.fixedDeltaTime; target.GetComponent <Gold>().value -= miningSpeed * Time.fixedDeltaTime; } } if (emptying == true && Vector3.Distance(transform.position, agent.destination) < 0.5f) { if (!agent.isStopped) { agent.isStopped = true; } if (currentCapacity < miningSpeed * 2 * Time.deltaTime) { p.money += currentCapacity; currentCapacity = 0; carried.SetActive(false); emptying = false; } else { p.money += miningSpeed * 2 * Time.fixedDeltaTime; currentCapacity -= miningSpeed * 2 * Time.fixedDeltaTime; } } }
private void createToolbox() { this.toolbox = new Toolbox(); this.toolbox.DefaultItemSize = new Size(GRIDITEM_WIDTH, GRIDITEM_HEIGHT); // TODO Größe variabel?? this.toolbox.SnapsToDevicePixels = true; ExpanderShapes.Content = this.toolbox; }