CtrEditor/ObjetosSim/osBase.cs

985 lines
35 KiB
C#
Raw Normal View History

2024-05-31 14:25:24 -03:00

using System.Text.Json.Serialization;
using System.Windows;
2024-05-11 15:55:44 -03:00
using CtrEditor.Siemens;
using CtrEditor.Simulacion;
using System.Windows.Media;
2024-05-25 09:38:36 -03:00
using nkast.Aether.Physics2D.Common;
2024-05-16 13:45:14 -03:00
using Siemens.Simatic.Simulation.Runtime;
using System.Windows.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Windows.Media.Animation;
2024-05-30 13:48:37 -03:00
using System.Diagnostics;
2024-05-31 14:25:24 -03:00
using System.Windows.Shapes;
using System.Windows.Controls;
2024-06-02 04:13:01 -03:00
using System.ComponentModel;
2024-06-04 17:27:35 -03:00
using System.Configuration;
using System.Windows.Threading;
using System.IO;
using Tesseract;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
using Newtonsoft.Json;
using JsonIgnoreAttribute = Newtonsoft.Json.JsonIgnoreAttribute;
using System.Collections.ObjectModel;
using ItemCollection = Xceed.Wpf.Toolkit.PropertyGrid.Attributes.ItemCollection;
namespace CtrEditor.ObjetosSim
{
public interface IosBase
{
static abstract string NombreClase();
}
public interface IDataContainer
{
[JsonIgnore]
osBase? Datos { get; set; }
2024-05-06 12:31:45 -03:00
void Resize(float width, float height);
void Move(float Left, float Top);
void Rotate(float Angle);
2024-05-04 16:27:04 -03:00
void Highlight(bool State);
int ZIndex();
}
2024-05-20 09:05:34 -03:00
public class DataSaveToSerialize
{
private MainViewModel? _mainViewModel;
private UserControl? VisualRepresentation;
private SimulationManagerFP? simulationManager;
2024-05-27 05:34:20 -03:00
public DataSaveToSerialize(MainViewModel a, UserControl b, SimulationManagerFP c)
2024-05-20 09:05:34 -03:00
{
_mainViewModel = a;
VisualRepresentation = b;
simulationManager = c;
}
public void DataRestoreAfterSerialize(out MainViewModel a, out UserControl b, out SimulationManagerFP c)
{
a = _mainViewModel;
b = VisualRepresentation;
c = simulationManager;
}
}
public abstract partial class osBase : ObservableObject
{
public virtual string Nombre { get; set; } = "osBase";
[JsonIgnore]
private Storyboard _storyboard;
[JsonIgnore]
2024-06-04 17:27:35 -03:00
private System.Threading.Timer timer = null;
public UniqueId Id { get; set; }
[ObservableProperty]
[property: Description("X coordinate.")]
[property: Category("Layout:")]
private float left;
partial void OnLeftChanged(float value)
{
CanvasSetLeftinMeter(value);
LeftChanged(value);
}
2024-06-04 12:33:00 -03:00
partial void OnLeftChanging(float oldValue, float newValue)
{
LeftChanging(oldValue, newValue);
}
public virtual void LeftChanged(float value) { }
2024-06-04 12:33:00 -03:00
public virtual void LeftChanging(float oldValue, float newValue) { }
[ObservableProperty]
[property: Description("Y coordinate.")]
[property: Category("Layout:")]
private float top;
partial void OnTopChanged(float value)
{
CanvasSetTopinMeter(value);
TopChanged(value);
}
2024-06-04 12:33:00 -03:00
partial void OnTopChanging(float oldValue, float newValue)
{
TopChanging(oldValue, newValue);
}
public virtual void TopChanged(float value) { }
2024-06-04 12:33:00 -03:00
public virtual void TopChanging(float oldValue, float newValue) { }
public void InicializaNuevoObjeto()
{
Id = new UniqueId().ObtenerNuevaID();
}
// Group
[ObservableProperty]
[property: Description("This is a link to a faceplate. It works like an anchor.")]
[property: Category("Group:")]
[property: ItemsSource(typeof(osBaseItemsSource<osTextPlate>))]
private string group_Panel;
[JsonIgnore]
private osTextPlate TextPlate;
[JsonIgnore]
private bool isUpdatingFromTextPlate = false;
partial void OnGroup_PanelChanged(string value)
{
if (TextPlate != null)
TextPlate.PropertyChanged -= OnTextPlatePropertyChanged;
if (_mainViewModel != null && value != null && value.Length > 0)
{
TextPlate = (osTextPlate)_mainViewModel.ObjetosSimulables.FirstOrDefault(s => (s is osTextPlate && s.Nombre == value), null);
if (TextPlate != null)
TextPlate.PropertyChanged += OnTextPlatePropertyChanged;
}
}
private void OnTextPlatePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (!isUpdatingFromTextPlate)
{
isUpdatingFromTextPlate = true;
if (e.PropertyName == nameof(osTextPlate.Nombre))
Group_Panel = ((osTextPlate)sender).Nombre;
if (e.PropertyName == nameof(osTextPlate.Top))
Top += ((osTextPlate)sender).offsetY;
if (e.PropertyName == nameof(osTextPlate.Left))
Left += ((osTextPlate)sender).offsetX;
isUpdatingFromTextPlate = false;
}
}
private void ShowPreviewWindow(Stream imageStream)
{
// Create a new window for preview
Window previewWindow = new Window
{
Title = "Preview Captured Image",
Width = 500,
Height = 500,
Content = new Image
{
Source = BitmapFrame.Create(imageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad),
Stretch = Stretch.Uniform
}
};
previewWindow.ShowDialog();
}
2024-06-11 07:30:27 -03:00
public string CaptureImageAreaAndDoOCR(float Left, float Top, float Ancho, float Alto, float Angulo = 0, bool ShowPreview = false)
{
if (_mainViewModel?.MainCanvas.Children[0] is Image imagenDeFondo)
{
if (imagenDeFondo.Source is BitmapSource bitmapSource)
{
float originalDpiX = (float)bitmapSource.DpiX;
float originalDpiY = (float)bitmapSource.DpiY;
2024-06-11 07:30:27 -03:00
float canvasDpiX = 96;
float canvasDpiY = 96;
float scaleFactorX = originalDpiX / canvasDpiX;
float scaleFactorY = originalDpiY / canvasDpiY;
int x = (int)MeterToPixels(Left * scaleFactorX);
int y = (int)MeterToPixels(Top * scaleFactorY);
int width = (int)MeterToPixels(Ancho * scaleFactorX);
int height = (int)MeterToPixels(Alto * scaleFactorY);
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x + width > bitmapSource.PixelWidth) width = bitmapSource.PixelWidth - x;
if (y + height > bitmapSource.PixelHeight) height = bitmapSource.PixelHeight - y;
CroppedBitmap croppedBitmap = new CroppedBitmap(bitmapSource, new Int32Rect(x, y, width, height));
2024-06-11 07:30:27 -03:00
TransformedBitmap transformedBitmap = new TransformedBitmap();
transformedBitmap.BeginInit();
transformedBitmap.Source = croppedBitmap;
if (Angulo != 0)
{
RotateTransform rotateTransform = new RotateTransform(-Angulo);
transformedBitmap.Transform = rotateTransform;
}
transformedBitmap.EndInit();
PngBitmapEncoder encoder = new PngBitmapEncoder();
2024-06-11 07:30:27 -03:00
encoder.Frames.Add(BitmapFrame.Create(transformedBitmap));
using (MemoryStream memoryStream = new MemoryStream())
{
encoder.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
2024-06-11 07:30:27 -03:00
if (ShowPreview) ShowPreviewWindow(memoryStream);
2024-06-11 07:30:27 -03:00
using (var bmp = new System.Drawing.Bitmap(memoryStream))
{
2024-06-11 07:30:27 -03:00
int targetDpi = 400;
var resizedBmp = new System.Drawing.Bitmap(bmp, new System.Drawing.Size(bmp.Width * targetDpi / (int)originalDpiX, bmp.Height * targetDpi / (int)originalDpiY));
using (var msResized = new MemoryStream())
{
resizedBmp.Save(msResized, System.Drawing.Imaging.ImageFormat.Png);
msResized.Seek(0, SeekOrigin.Begin);
using (var img = Pix.LoadFromMemory(msResized.ToArray()))
using (var engine = new TesseractEngine(@"./Tesseract", "eng", EngineMode.Default))
{
// Configuraciones para mejorar el OCR de una sola letra
engine.SetVariable("tessedit_char_whitelist", " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-."); // Lista blanca de caracteres
var result = engine.Process(img);
return result.GetText();
}
}
}
}
}
}
return "";
}
2024-06-11 07:30:27 -03:00
// All Pages Objects
[NotifyPropertyChangedFor(nameof(Show_On_This_Page))]
[ObservableProperty]
[property: Description("Enable this object to be used in all pages.")]
[property: Category("Layout:")]
private bool enable_On_All_Pages;
partial void OnEnable_On_All_PagesChanged(bool value)
{
if (!value)
Show_On_This_Page = true;
}
[ObservableProperty]
[property: Hidden]
private List<string> showOnThisPagesList;
private bool show_On_This_Page;
[property: Category("Layout:")]
public bool Show_On_This_Page
{
get
{
if (!Enable_On_All_Pages)
{
showOnThisPagesList?.Clear();
showOnThisPagesList = null;
show_On_This_Page = true;
}
else
{
if (showOnThisPagesList == null)
{
showOnThisPagesList = new List<string> { _mainViewModel?.SelectedImage };
}
show_On_This_Page = _mainViewModel?.SelectedImage != null && showOnThisPagesList.Contains(_mainViewModel.SelectedImage);
}
return show_On_This_Page;
}
set
{
if (Enable_On_All_Pages)
{
if (showOnThisPagesList == null)
{
showOnThisPagesList = new List<string>();
}
if (_mainViewModel?.SelectedImage == null) return;
if (value)
{
if (!showOnThisPagesList.Contains(_mainViewModel.SelectedImage))
{
showOnThisPagesList.Add(_mainViewModel.SelectedImage);
}
}
else
{
showOnThisPagesList.Remove(_mainViewModel.SelectedImage);
}
}
SetProperty(ref show_On_This_Page, value);
}
}
2024-06-04 17:27:35 -03:00
private async void TimerCallback(object state)
{
await Task.Delay(500); // Esperar 0.5 segundos antes de ejecutar la función
Application.Current.Dispatcher.Invoke(() =>
{
// Realiza tus cambios en la interfaz de usuario aquí
OnTimerAfterMovement();
});
2024-06-04 17:27:35 -03:00
}
/// <summary>
/// Este timer se usa para llamar a OnTimerAfterMovement luego de que han pasado 500ms sin que se
/// llame a ResetTimer.
/// Esto es util para no actualizar las simulaciones o controles mientras se esta moviendo aun el control.
/// Se debe hacer overrride de OnTimerAfterMovement y dentro de esta funcion llamar a la actualizacion que se
/// requiere hacer una vez terminado el movimiento del control por parte del usuario.
/// </summary>
2024-06-04 17:27:35 -03:00
public void ResetTimer()
{
if (timer == null)
2024-06-04 17:27:35 -03:00
timer = new System.Threading.Timer(TimerCallback, null, Timeout.Infinite, Timeout.Infinite);
timer.Change(500, Timeout.Infinite);
}
public virtual void OnTimerAfterMovement() { }
2024-05-27 05:34:20 -03:00
/// <summary>
/// Usado para saber cuando un objeto fue creado manualmente o por algun generador
/// Mas adelante la idea es poder eliminar o tratar de manera diferente a estos objetos
/// </summary>
public bool AutoCreated = false;
2024-05-27 05:34:20 -03:00
/// <summary>
/// Son los objetos marcados para ser eliminados luego de se detectados por un sensor del mundo fisico
/// Se deben eliminar fuera de la simulacion
/// </summary>
public bool RemoverDesdeSimulacion = false; // La simulacion indica que se debe remover
2024-05-20 09:05:34 -03:00
[JsonIgnore]
private DataSaveToSerialize DataSave;
2024-05-27 05:34:20 -03:00
/// <summary>
/// Link al UserControl. Inicializado en el evento OnLoaded
/// </summary>
[JsonIgnore]
2024-05-06 12:31:45 -03:00
protected UserControl? _visualRepresentation = null;
2024-05-27 05:34:20 -03:00
/// <summary>
/// Link al control PLC.
/// Inicializado en el metodo SetPLC
/// </summary>
2024-05-23 14:56:14 -03:00
[JsonIgnore]
protected PLCModel? _plc = null;
/// <summary>
2024-05-27 05:34:20 -03:00
/// Se llama luego de cada Step. Esto permite actualziar las posiciones graficas de cada objeto que se esta dibujando
/// con las nuevas posiciones calculadas luego de la simulacion fisica.
/// </summary>
/// <param name="elapsedMilliseconds"></param>
public virtual void UpdateControl(int elapsedMilliseconds) { }
2024-05-27 05:34:20 -03:00
/// <summary>
/// Se llama antes de comenzar la simulacion con el boton de Iniciar simulacion.
/// La idea es actualizar los objetos en el motor fisico antes de comenzar la simulacion fisica.
/// </summary>
public virtual void UpdateGeometryStart() { }
/// <summary>
2024-05-27 05:34:20 -03:00
/// Se llama al terminar la simulacion con el boton de Detener simulacion.
/// Se puede utilizar para detener los storyboard o alguna otra simulacion independiente
/// </summary>
public virtual void SimulationStop() { }
/// <summary>
/// Se llama antes de cada Step al World de la simulacion fisica.
/// Permite actualizar el estado de los objetos de la simulacion fisica
/// </summary>
public virtual void UpdateGeometryStep() { }
/// <summary>
/// Es llamada en cada Tick del reloj establecido del PLC
2024-05-27 05:34:20 -03:00
/// cuando la conexion con el PLC esta establecida.
/// </summary>
/// <param name="plc"></param>
/// <param name="elapsedMilliseconds"></param>
public virtual void UpdatePLC(PLCModel plc, int elapsedMilliseconds) { }
/// <summary>
/// El UserControl ya se ha cargado y podemos obtener las coordenadas para
/// crear el objeto de simulacion
/// </summary>
public virtual void ucLoaded()
{
ActualizarLeftTop();
OnGroup_PanelChanged(Group_Panel); // Establece el link y se suscribe a los eventos
Show_On_This_Page = Show_On_This_Page; // Update data
}
/// <summary>
/// El UserControl se esta eliminando
/// eliminar el objeto de simulacion
/// </summary>
2024-05-27 05:34:20 -03:00
public virtual void ucUnLoaded() { }
[JsonIgnore]
public MainViewModel _mainViewModel;
2024-05-27 05:34:20 -03:00
/// <summary>
/// Link al UserControl. Inicializado en el evento OnLoaded
/// </summary>
[JsonIgnore]
public UserControl? VisualRepresentation
{
get => _visualRepresentation;
set => _visualRepresentation = value;
}
2024-05-27 05:34:20 -03:00
/// <summary>
/// Link al Simualdor fisico.
/// </summary>
[JsonIgnore]
public SimulationManagerFP simulationManager;
2024-05-27 05:34:20 -03:00
/// <summary>
/// Prepara la clase para ser serializable poniendo a null los objetos que tienen referencias circulares
/// Luego se debe llamar a RestaurarDatosNoSerializables para restaurar el estado original
/// </summary>
2024-05-20 09:05:34 -03:00
public void SalvarDatosNoSerializables()
{
2024-05-27 05:34:20 -03:00
DataSave = new DataSaveToSerialize(_mainViewModel, _visualRepresentation, simulationManager);
2024-05-20 09:05:34 -03:00
_mainViewModel = null;
_visualRepresentation = null;
simulationManager = null;
}
2024-05-27 05:34:20 -03:00
/// <summary>
/// Restaura los links de los objetos que se eliminaron temporalmente para serializar.
/// </summary>
2024-05-20 09:05:34 -03:00
public void RestaurarDatosNoSerializables()
{
if (DataSave == null) return;
2024-05-27 05:34:20 -03:00
DataSave.DataRestoreAfterSerialize(out _mainViewModel, out _visualRepresentation, out simulationManager);
2024-05-20 09:05:34 -03:00
}
2024-05-27 05:34:20 -03:00
/// <summary>
/// Se llama una unica vez al conectar con el PLC.
/// </summary>
/// <param name="plc"></param>
2024-05-23 14:56:14 -03:00
public void SetPLC(PLCModel plc)
{
_plc = plc;
2024-05-27 05:34:20 -03:00
UpdatePLCPrimerCiclo();
2024-05-23 14:56:14 -03:00
}
2024-05-27 05:34:20 -03:00
/// <summary>
/// Se llama una unica vez al conectar con el PLC
/// </summary>
public virtual void UpdatePLCPrimerCiclo() { }
2024-05-31 14:25:24 -03:00
protected Storyboard CrearAnimacionMultiStoryBoardTrasnporte(Rectangle transporte, bool invertirDireccion)
{
2024-05-31 10:06:49 -03:00
if (_visualRepresentation == null) return null;
if (transporte == null) return null;
2024-05-31 10:06:49 -03:00
Storyboard storyboard = new Storyboard();
var animation = new DoubleAnimation
{
From = invertirDireccion ? 20 : 0,
To = invertirDireccion ? 0 : 20, // Total Pixels Brush
Duration = TimeSpan.FromSeconds(PixelToMeter.Instance.calc.PixelsToMeters(20) * 60),
RepeatBehavior = RepeatBehavior.Forever
};
Storyboard.SetTarget(animation, transporte);
Storyboard.SetTargetProperty(animation, new PropertyPath("(Rectangle.Fill).(VisualBrush.Transform).(TransformGroup.Children)[0].(TranslateTransform.X)"));
2024-05-31 10:06:49 -03:00
storyboard.Children.Add(animation);
storyboard.Begin();
storyboard.SetSpeedRatio(0);
return storyboard;
}
2024-05-31 14:25:24 -03:00
protected Storyboard CrearAnimacionMultiStoryBoardTrasnporte(Storyboard storyboard, Rectangle transporte, bool invertirDireccion)
2024-05-31 10:06:49 -03:00
{
// Detener y eliminar el storyboard existente si hay uno
if (storyboard != null)
{
storyboard.Stop();
storyboard.Children.Clear();
}
return CrearAnimacionMultiStoryBoardTrasnporte(transporte, invertirDireccion);
}
protected void ActualizarAnimacionMultiStoryBoardTransporte(Storyboard storyboard, float velocidadActual)
{
if (_visualRepresentation == null) return;
2024-05-31 10:06:49 -03:00
if (storyboard == null) return;
if (!_mainViewModel.IsSimulationRunning)
2024-05-31 10:06:49 -03:00
storyboard.SetSpeedRatio(0);
else
2024-05-31 10:06:49 -03:00
storyboard.SetSpeedRatio(Math.Abs(velocidadActual));
}
2024-05-31 14:25:24 -03:00
protected void CrearAnimacionStoryBoardTrasnporte(Rectangle transporte, bool invertirDireccion)
2024-05-31 10:06:49 -03:00
{
_storyboard = CrearAnimacionMultiStoryBoardTrasnporte(_storyboard, transporte, invertirDireccion);
}
protected void ActualizarAnimacionStoryBoardTransporte(float velocidadActual)
{
ActualizarAnimacionMultiStoryBoardTransporte(_storyboard, velocidadActual);
}
2024-05-27 05:34:20 -03:00
/// <summary>
/// Actualiza Left Top del objeto respecto al Canvas padre.
/// </summary>
public void ActualizarLeftTop()
{
CanvasSetLeftinMeter(Left);
CanvasSetTopinMeter(Top);
}
2024-05-23 14:56:14 -03:00
public bool LeerBitTag(string Tag)
2024-05-16 13:45:14 -03:00
{
2024-05-23 14:56:14 -03:00
if (this._plc == null) return false;
2024-05-16 13:45:14 -03:00
if (!string.IsNullOrEmpty(Tag))
{
if (Tag == "1") return true;
else if (Tag == "0") return false;
2024-05-23 14:56:14 -03:00
if (_plc != null)
return _plc.LeerTagBool(Tag);
2024-05-16 13:45:14 -03:00
}
return false;
}
2024-05-27 05:34:20 -03:00
/// <summary>
/// Si la conexion con el plc esta activa y el Tag no es nulo escribe el bit en el PLC
/// </summary>
/// <param name="Tag"></param>
/// <param name="Value"></param>
2024-05-23 14:56:14 -03:00
public void EscribirBitTag(string Tag, bool Value)
2024-05-16 13:45:14 -03:00
{
2024-05-23 14:56:14 -03:00
if (_plc == null) return;
2024-05-16 13:45:14 -03:00
if (!string.IsNullOrEmpty(Tag))
2024-05-23 14:56:14 -03:00
if (_plc != null)
_plc.EscribirTagBool(Tag, Value);
2024-05-16 13:45:14 -03:00
}
2024-05-23 14:56:14 -03:00
public void EscribirWordTagScaled(string Tag, float Value, float IN_scale_Min, float IN_scale_Max, float OUT_scale_Min, float OUT_scale_Max)
2024-05-16 13:45:14 -03:00
{
2024-05-23 14:56:14 -03:00
if (_plc == null) return;
if (!string.IsNullOrEmpty(Tag))
{
SDataValue plcData = new SDataValue();
plcData.UInt16 = (ushort)((Value - IN_scale_Min) / (IN_scale_Max - IN_scale_Min) * (OUT_scale_Max - OUT_scale_Min) + OUT_scale_Min);
_plc.EscribirTag(Tag, plcData);
}
2024-05-16 13:45:14 -03:00
}
2024-05-30 13:48:37 -03:00
public float LeerWordTagScaled(string Tag, float IN_scale_Min = 0, float IN_scale_Max = 27648, float OUT_scale_Min = 0, float OUT_scale_Max = 100)
2024-05-16 13:45:14 -03:00
{
2024-05-23 14:56:14 -03:00
if (_plc == null) return 0;
2024-05-16 13:45:14 -03:00
if (!string.IsNullOrEmpty(Tag))
{
if (float.TryParse(Tag, out float v))
return v;
2024-05-23 14:56:14 -03:00
if (_plc != null)
2024-05-16 13:45:14 -03:00
{
2024-05-23 14:56:14 -03:00
SDataValue plcData = _plc.LeerTag(Tag);
2024-05-16 13:45:14 -03:00
float Value = plcData.UInt16; // WORD
2024-05-30 13:48:37 -03:00
return (Value - IN_scale_Min) / (IN_scale_Max - IN_scale_Min) * (OUT_scale_Max - OUT_scale_Min) + OUT_scale_Min;
}
}
return 0;
}
public float LeerWordTag(string Tag)
{
if (_plc == null) return 0;
if (!string.IsNullOrEmpty(Tag))
{
if (float.TryParse(Tag, out float v))
return v;
if (_plc != null)
{
SDataValue plcData = _plc.LeerTag(Tag);
float Value = plcData.UInt16; // WORD
return Value;
2024-05-16 13:45:14 -03:00
}
}
return 0;
}
2024-05-15 06:20:09 -03:00
2024-05-08 08:41:26 -03:00
public void CanvasSetLeftinMeter(float left)
{
if (_visualRepresentation != null)
Canvas.SetLeft(_visualRepresentation, PixelToMeter.Instance.calc.MetersToPixels(left));
2024-05-08 08:41:26 -03:00
}
public float CanvasGetLeftinMeter()
{
if (_visualRepresentation != null)
return PixelToMeter.Instance.calc.PixelsToMeters((float)Canvas.GetLeft(_visualRepresentation));
else return 0f;
}
2024-05-08 08:41:26 -03:00
public void CanvasSetTopinMeter(float top)
{
if (_visualRepresentation != null)
Canvas.SetTop(_visualRepresentation, PixelToMeter.Instance.calc.MetersToPixels(top));
}
public float CanvasGetTopinMeter()
{
if (_visualRepresentation != null)
2024-05-31 14:25:24 -03:00
return PixelToMeter.Instance.calc.PixelsToMeters((float)System.Windows.Controls.Canvas.GetTop(_visualRepresentation));
else return 0f;
}
2024-05-08 08:41:26 -03:00
2024-05-31 10:06:49 -03:00
public float PixelsToMeters(float pixel)
{
return PixelToMeter.Instance.calc.PixelsToMeters(pixel);
}
2024-05-31 14:25:24 -03:00
public Vector2 PixelsToMeters(Vector2 pixel)
{
return new Vector2(PixelsToMeters(pixel.X), PixelsToMeters(pixel.Y));
2024-05-31 14:25:24 -03:00
}
2024-05-31 10:06:49 -03:00
public float MeterToPixels(float meter)
{
return PixelToMeter.Instance.calc.MetersToPixels(meter);
}
2024-05-31 14:25:24 -03:00
public Vector2 MeterToPixels(Vector2 meter)
{
return new Vector2(MeterToPixels(meter.X), MeterToPixels(meter.Y));
}
private static GeneralTransform GetTransformToRoot(Visual visual)
{
// Crear una transformación acumulativa inicial
GeneralTransformGroup transformGroup = new GeneralTransformGroup();
// Recorrer hacia arriba el árbol visual, acumulando las transformaciones
while (visual != null)
{
GeneralTransform transform = visual.TransformToAncestor(visual);
transformGroup.Children.Insert(0, transform);
visual = VisualTreeHelper.GetParent(visual) as Visual;
}
return transformGroup;
}
2024-05-31 14:25:24 -03:00
public (Vector2 TopLeft, Vector2 BottomRight) GetRectangleCoordinatesInMeter(Rectangle rect)
{
if (rect != null)
{
var _canvasLeft = CanvasGetLeftinMeter();
var _canvasTop = CanvasGetTopinMeter();
// Obtiene la transformada del objeto visual
GeneralTransform transform = rect.TransformToAncestor(_visualRepresentation);
// Obtiene la posición absoluta
Point topLeft = transform.Transform(new Point(0, 0));
Point bottomRight = transform.Transform(new Point(rect.ActualWidth, rect.ActualHeight));
return (new Vector2(PixelToMeter.Instance.calc.PixelsToMeters((float)topLeft.X) + _canvasLeft, PixelToMeter.Instance.calc.PixelsToMeters((float)topLeft.Y) + _canvasTop),
new Vector2(PixelToMeter.Instance.calc.PixelsToMeters((float)bottomRight.X) + _canvasLeft, PixelToMeter.Instance.calc.PixelsToMeters((float)bottomRight.Y) + _canvasTop));
}
else return (new Vector2(0, 0), new Vector2(0, 0));
}
2024-05-31 14:25:24 -03:00
public (Vector2 Start, Vector2 End) GetCenterLineVectors(Rectangle rect)
{
if (rect == null)
return (new Vector2(0, 0), new Vector2(0, 0));
2024-05-31 14:25:24 -03:00
Vector2 start = new Vector2(0, 0);
Vector2 end = new Vector2(0, 0);
// Usar Dispatcher para asegurar la ejecución en el hilo correcto
_visualRepresentation?.Dispatcher.Invoke(() =>
{
// Asegúrate de que el control está en el árbol visual y actualizado
if (_visualRepresentation.IsLoaded && rect.IsLoaded)
{
_visualRepresentation.UpdateLayout();
var _canvasLeft = CanvasGetLeftinMeter();
var _canvasTop = CanvasGetTopinMeter();
2024-05-31 14:25:24 -03:00
var transform = rect.TransformToAncestor(_visualRepresentation);
2024-05-31 14:25:24 -03:00
// Puntos en coordenadas locales del rectángulo no rotado
Point startLocal = new Point(0, rect.ActualHeight / 2);
Point endLocal = new Point(rect.ActualWidth, rect.ActualHeight / 2);
2024-05-31 14:25:24 -03:00
// Transformar estos puntos al sistema de coordenadas del ancestro
Point transformedStart = transform.Transform(startLocal);
Point transformedEnd = transform.Transform(endLocal);
2024-05-31 14:25:24 -03:00
// Convierte a unidades de Farseer (metros en este caso)
start = new Vector2(PixelToMeter.Instance.calc.PixelsToMeters((float)transformedStart.X) + _canvasLeft, PixelToMeter.Instance.calc.PixelsToMeters((float)transformedStart.Y) + _canvasTop);
end = new Vector2(PixelToMeter.Instance.calc.PixelsToMeters((float)transformedEnd.X) + _canvasLeft, PixelToMeter.Instance.calc.PixelsToMeters((float)transformedEnd.Y) + _canvasTop);
}
});
return (start, end);
}
2024-05-31 14:25:24 -03:00
2024-05-22 06:19:31 -03:00
public Vector2 GetCurveCenterInMeter(float RadioExterno)
{
var _canvasLeft = CanvasGetLeftinMeter();
var _canvasTop = CanvasGetTopinMeter();
// El centro del Canvas
double centerX = RadioExterno + _canvasLeft;
double centerY = RadioExterno + _canvasTop;
// Convertir a Vector2
return new Vector2((float)centerX, (float)centerY);
}
2024-05-31 14:25:24 -03:00
public Vector2 GetRectangleCenter(Rectangle wpfRect)
{
var coords = GetRectangleCoordinatesInMeter(wpfRect);
Vector2 topLeft = coords.TopLeft;
Vector2 bottomRight = coords.BottomRight;
// Calcular el centro, ancho y alto en metros
return new Vector2((topLeft.X + bottomRight.X) / 2, (topLeft.Y + bottomRight.Y) / 2);
}
2024-05-22 06:19:31 -03:00
2024-05-31 14:25:24 -03:00
public void UpdateRectangle(simTransporte simRect, Rectangle wpfRect, float Alto, float Ancho, float Angulo)
{
if (simRect != null)
simRect.Create(Ancho, Alto, GetRectangleCenter(wpfRect), Angulo);
}
2024-05-31 14:25:24 -03:00
public void UpdateRectangle(simBarrera simRect, Rectangle wpfRect, float Alto, float Ancho, float Angulo)
{
if (simRect != null)
simRect.Create(Ancho, Alto, GetRectangleCenter(wpfRect), Angulo);
}
2024-05-27 05:34:20 -03:00
public void UpdateCurve(simCurve curva, float RadioInterno, float RadioExterno, float startAngle, float endAngle)
2024-05-22 06:19:31 -03:00
{
2024-05-27 05:34:20 -03:00
curva.Create(RadioInterno, RadioExterno, startAngle, endAngle, GetCurveCenterInMeter(RadioExterno));
2024-05-22 06:19:31 -03:00
}
public simCurve AddCurve(float RadioInterno, float RadioExterno, float startAngle, float endAngle)
{
return simulationManager.AddCurve(RadioInterno, RadioExterno, startAngle, endAngle, GetCurveCenterInMeter(RadioExterno));
}
2024-05-31 14:25:24 -03:00
public simTransporte AddRectangle(SimulationManagerFP simulationManager, Rectangle wpfRect, float Alto, float Ancho, float Angulo)
{
return simulationManager.AddRectangle(Ancho, Alto, GetRectangleCenter(wpfRect), Angulo);
}
2024-05-31 14:25:24 -03:00
public simBarrera AddBarrera(SimulationManagerFP simulationManager, Rectangle wpfRect, float Alto, float Ancho, float Angulo, bool detectarCuello)
{
2024-05-30 13:48:37 -03:00
return simulationManager.AddBarrera(Ancho, Alto, GetRectangleCenter(wpfRect), Angulo, detectarCuello);
}
2024-05-31 14:25:24 -03:00
public void UpdateOrCreateLine(simGuia simGuia, Rectangle wpfRect)
{
if (simGuia != null)
{
2024-05-31 14:25:24 -03:00
var coords = GetCenterLineVectors(wpfRect);
// Crear o actualizar simRectangle
simGuia.Create(coords.Start, coords.End); // asumiendo que el ángulo inicial es 0
}
}
2024-05-31 14:25:24 -03:00
public simGuia AddLine(SimulationManagerFP simulationManager, Rectangle wpfRect)
{
var coords = GetCenterLineVectors(wpfRect);
return simulationManager.AddLine(coords.Start, coords.End);
}
public ImageSource ImageFromPath(string value)
{
if (value is string stringValue)
{
return new BitmapImage(new Uri(stringValue, UriKind.RelativeOrAbsolute));
}
return null;
}
static protected T GetLastElement<T>(List<T> list) where T : class
{
if (list.Count > 0)
{
return list[list.Count - 1];
}
else
{
return null;
}
}
}
public class UniqueId
{
public int Value { get; set; }
2024-06-11 07:30:27 -03:00
public UniqueId ObtenerNuevaID()
{
Value = EstadoPersistente.Instance.newid;
if (Value == 0)
Value++;
return this;
}
2024-06-11 07:30:27 -03:00
public void NoId()
{
// No ID == NULL
Value = 0;
}
2024-06-11 07:30:27 -03:00
// Sobrecarga del operador ++
public static UniqueId operator ++(UniqueId id)
{
if (id == null)
{
id = new UniqueId();
}
id.Value = EstadoPersistente.Instance.newid;
if (id.Value == 0)
id.Value++;
return id;
}
// Sobrecarga del operador ==
public static bool operator ==(UniqueId id1, UniqueId id2)
{
if (ReferenceEquals(id1, null) || ReferenceEquals(id2, null))
return false;
return id1.Value == id2.Value;
}
// Sobrecarga del operador !=
public static bool operator !=(UniqueId id1, UniqueId id2)
{
if (ReferenceEquals(id1, null) || ReferenceEquals(id2, null))
return true;
return id1.Value != id2.Value;
}
// Sobrescribir Equals y GetHashCode también es una buena práctica
public override bool Equals(object obj)
{
if (obj is UniqueId id)
{
return Value == id.Value;
}
return false;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
2024-06-11 07:30:27 -03:00
public class osBaseItemsSource<T> : IItemsSource
{
public ItemCollection GetValues()
{
ItemCollection items = new ItemCollection();
var viewModel = (MainViewModel)App.Current.MainWindow.DataContext;
var objetosSimulables = viewModel.ObjetosSimulables;
items.Add("");
foreach (var obj in objetosSimulables)
{
if (obj.GetType() == typeof(T))
{
items.Add(obj.Nombre);
}
}
return items;
}
}
2024-05-30 13:48:37 -03:00
public class TimerTON_TOFF
{
Stopwatch _stopwatch_ON = new Stopwatch();
Stopwatch _stopwatch_OFF = new Stopwatch();
private bool _senalFiltrada;
public float Tiempo_ON_s { get; set; }
public float Tiempo_OFF_s { get; set; }
private bool senal;
public bool Senal
{
get => senal;
set
{
senal = value;
if (value)
{
ReiniciarTimer(_stopwatch_ON);
_stopwatch_OFF.Reset();
}
else
{
_stopwatch_ON.Reset();
ReiniciarTimer(_stopwatch_OFF);
}
}
}
public TimerTON_TOFF()
{
Senal = false;
Tiempo_ON_s = 1;
Tiempo_OFF_s = 1;
}
public bool SenalFiltrada()
{
if (_stopwatch_ON.ElapsedMilliseconds > (Tiempo_ON_s * 1000))
_senalFiltrada = true;
if (_stopwatch_OFF.ElapsedMilliseconds > (Tiempo_OFF_s * 1000))
_senalFiltrada = false;
return _senalFiltrada;
}
void ReiniciarTimer(Stopwatch timer)
{
timer.Reset();
timer.Start();
}
}
[AttributeUsage(AttributeTargets.Property)]
public class HiddenAttribute : Attribute
{
}
}