public WorkflowEngine() { Reader reader = new ModelReader(ConfigurationSettings.AppSettings["DryConfiguration"]); Persister persister = new XMLStore(ConfigurationSettings.AppSettings["DryConfiguration"]); this.tm = new TransactionManager(reader, persister);
public reading_model_synchronously_by_content_type() { theReader = new ModelReader(new IMessageDeserializer[] { new FakeReader("blue"), new FakeReader("red"), new FakeReader("green") }); }
public void When_GivenNonExistentModelPath_Then_ShouldThrowFileNotFoundException() { // Arrange var testTarget = new ModelReader( _testModelPath + "some nonexistant garbage"); // Act testTarget.LoadModel(); }
public CounterExampleResults LoadCounterModel() { if (!File.Exists(ModelBvd)) { return(new CounterExampleResults()); } List <ILanguageSpecificModel> specificModels = new ModelReader(ModelBvd).ReadModelFile(); return(new CounterExampleExtractor(PhysicalFile, specificModels).ExtractCounterExamples()); }
VrmLib.Model ReadModel(string path) { var bytes = MigrationVrm.Migrate(File.ReadAllBytes(path)); var data = new GlbLowLevelParser(path, bytes).Parse(); var model = ModelReader.Read(data); return(model); }
public void setUp() { if (model == null) { reader = getReader(); Assert.IsNotNull(model = reader.getModel()); OclTypesFactory.setEnvironment(model); } environment = model.getEnvironmentWithoutParents(); }
public WorkflowEngine () { Reader reader = new ModelReader(ConfigurationSettings.AppSettings["DryConfiguration"]); Persister persister = new XMLStore(ConfigurationSettings.AppSettings["DryConfiguration"]); this.tm = new TransactionManager(reader, persister); ... }
public void When_GivenValidModelPath_Then_ShouldLoadModel() { // Arrange var testTarget = new ModelReader(_testModelPath); int expectedFeatureSize = 470517; // figured out based on model metadata // Act testTarget.LoadModel(); // Assert Assert.AreEqual(testTarget.feature_size(), expectedFeatureSize); }
VrmLib.Model ReadModel(string path) { var bytes = MigrationVrm.Migrate(File.ReadAllBytes(path)); var parser = new GltfParser(); parser.Parse("migrated", bytes); var model = ModelReader.Read(parser); return(model); }
/// <summary> /// Displays a list of the models in the system. /// </summary> private static void ListModels() { Console.WriteLine("Models:"); ModelReader reader = new ModelReader(); Collection <Identifier> models = reader.GetModels(); foreach (Identifier modelId in models) { Console.WriteLine(modelId.Name); } }
private void DoLoadModel(string filePath) { Debug.LogFormat("start load model {0}", filePath); _model = ModelReader.LoadMmdModel(filePath, _modelReadConfig); Release(); var directoryInfo = new FileInfo(filePath).Directory; if (directoryInfo == null) { throw new MmdFileParseException(filePath + " does not belong to any directory."); } var relativePath = directoryInfo.FullName; _materialLoader = new MaterialLoader(new TextureLoader(relativePath, DefaultMaxTextureSize)); var vertCount = _model.Vertices.Length; if (vertCount <= 65535) { var mesh = new Mesh { vertices = new Vector3[vertCount], normals = new Vector3[vertCount] }; var triangleCount = _model.TriangleIndexes.Length / 3; var triangles = _model.TriangleIndexes; FillSubMesh(mesh, triangleCount, triangles); var uv = ExtratUv(_model.Vertices); var uvVec = new Vector2[vertCount]; Utils.MmdUvToUnityUv(uv, uvVec); mesh.uv = uvVec; mesh.boneWeights = _model.Vertices.Select(x => ConvertBoneWeight(x.SkinningOperator)).ToArray(); ReleasePreviousMeshes(); Mesh = mesh; mesh.RecalculateBounds(); _partIndexes = null; } else { var triangleCount = _model.TriangleIndexes.Length / 3; var triangles = _model.TriangleIndexes; var uv = ExtratUv(_model.Vertices); ; var uvVec = new Vector2[vertCount]; Utils.MmdUvToUnityUv(uv, uvVec); FillPartMeshes(triangleCount, triangles, uv); } _poser = new Poser(_model); _physicsReactor = new BulletPyhsicsReactor(); _physicsReactor.AddPoser(_poser); InitMesh(); Debug.LogFormat("load model finished {0}", filePath); }
public static CartesianModel LoadModel(string path) { var xdoc = XDocument.Load(path); var xresults = xdoc.Element("ProfilingResults"); if (xresults == null) { throw new FileLoadException("wrong format"); } return(ModelReader.CartesianModelFromX(xresults)); }
public override bool Run(FeatureContext context) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "STL File (*.stl)|*.stl||"; if(DialogResult.OK != dlg.ShowDialog()) return true; ModelReader reader = new ModelReader(); GroupSceneNode node = reader.LoadFile(new Path(dlg.FileName)); context.ShowSceneNode(node); return true; }
public static Model Load(DirectXDevice graphicsDevice, Stream stream, string assetName) { using (var serializer = new ModelReader(graphicsDevice, stream)) { Model model = serializer.ReadModel(); if (string.IsNullOrEmpty(model.Name)) { model.Name = assetName; } model.RegisterResources(); return(model); } }
public void When_GivenValidModelLoader_Then_ShouldLoadModel() { // Arrange Func <string, Stream> fakeLoader = modelName => new MemoryStream(File.ReadAllBytes(modelName)); var testTarget = new ModelReader(fakeLoader, _testModelPath); int expectedFeatureSize = 470517; // figured out based on model metadata // Act testTarget.LoadModel(); // Assert Assert.AreEqual(testTarget.feature_size(), expectedFeatureSize); }
public void Generate() { var mapper = Substitute.For <IMapper <IModelGenerator> >(); mapper.ContainsKey("NPN", false).Returns(true); IModelGenerator value; mapper.TryGetValue("NPN", false, out value).Returns( x => { x[2] = null; return(true); }); var readingContext = Substitute.For <ICircuitContext>(); readingContext.NameGenerator.GenerateObjectName(Arg.Any <string>()).Returns(x => x[0].ToString()); readingContext.CaseSensitivity.Returns(new SpiceNetlistCaseSensitivitySettings()); var resultService = Substitute.For <IResultService>(); readingContext.Result.Returns(resultService); var modelsGenerator = Substitute.For <IModelsGenerator>(); modelsGenerator.GenerateModel( Arg.Any <IModelGenerator>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <ParameterCollection>(), Arg.Any <ICircuitContext>()).Returns(x => new BipolarJunctionTransistorModel((string)x[1])); // act ModelReader reader = new ModelReader(mapper, modelsGenerator); var model = new Models.Netlist.Spice.Objects.Model("2Na2222", new ParameterCollection(new List <Parameter>() { new BracketParameter() { Name = "NPN" } }), null); reader.Read(model, readingContext); // assert modelsGenerator.Received().GenerateModel(Arg.Any <IModelGenerator>(), Arg.Any <string>(), "2Na2222", "NPN", Arg.Any <ParameterCollection>(), Arg.Any <ICircuitContext>()); resultService.Received().AddEntity(Arg.Is <Entity>((Entity e) => e.Name == "2Na2222")); }
/// <summary> /// Load a persisted <see cref="IModel"/> instance from disk. /// </summary> /// <typeparam name="T"> The type of the model. </typeparam> /// <param name="path"> The path to the persisted model file on disk. </param> /// <param name="ignoreCache"> /// True if the internal cache should be ignored, forcing a reload of the model from disk, false otherwise. /// </param> /// <returns> The persisted <see cref="IModel"/> instance. </returns> public async Task <T> LoadAsync <T>(string path, bool ignoreCache = false) where T : IModel { if (ignoreCache) { var(id, data) = await ModelReader.LoadFromAsync(path); if (ModelFactories.TryGetValue(id, out var modelFactory)) { var model = await modelFactory.CreateAsnyc(data); return((T)model); } } else { if (Cache.TryGetValue(path, out var model)) { return((T)model); } await SyncLock.WaitAsync(); try { if (Cache.TryGetValue(path, out model)) { return((T)model); } var(id, data) = await ModelReader.LoadFromAsync(path); if (ModelFactories.TryGetValue(id, out var modelFactory)) { model = await modelFactory.CreateAsnyc(data); Cache.Add(path, model); return((T)model); } } finally { SyncLock.Release(); } } // ToDo: ExceptionHandling return(default(T)); }
private void ReadFile(AlgorythmSettings settings) { if (settings.IsModel) { ModelReader reader = new ModelReader(settings.InputFileName); SignalRoutes signals = new SignalRoutes(reader.ReadData()); matrix = new ProjectionsData(reader.CellSize, signals, 0, reader.MaxX1, 0, reader.MaxY1); } else { RealDataReader reader = new RealDataReader(settings.InputFileName); SignalRoutes signals = new SignalRoutes(reader.ReadData()); matrix = new ProjectionsData(10, signals, 0, 150, 0, 100); } }
/// <summary> /// Get the Identifier object for the version with the given name. /// NOTE: ModelId property must be set on the reader first /// </summary> /// <param name="reader">The model reader object to use for the request.</param> /// <param name="versionName">Name of version to look for,</param> /// <returns>The identifier if it exists, otherwise an empty Identifier</returns> public static Identifier GetVersionIdentifier(ModelReader reader, string versionName) { Identifier versionId = new Identifier(); Collection<Identifier> versionIdentifiers; versionIdentifiers = reader.GetVersions(VersionStatusFlags.All); foreach (Identifier id in versionIdentifiers) { if (id.Name.Equals(versionName, StringComparison.OrdinalIgnoreCase)) { versionId = id; break; } } return versionId; }
/// <summary> /// Get the Identifier object for the model with the given name. /// </summary> /// <param name="reader">The <see cref="ModelReader"/> to use to retrieve the model information.</param> /// <param name="modelName">Name of model to look for</param> /// <returns>The identifier if it exists, otherwise an empty Identifier</returns> public static Identifier GetModelIdentifier(ModelReader reader, string modelName) { Identifier modelId = new Identifier(); Collection<Identifier> modelIdentifiers; modelIdentifiers = reader.GetModels(); foreach (Identifier id in modelIdentifiers) { if (id.Name.Equals(modelName)) { modelId = id; break; } } return modelId; }
public SpiceStatementsReader( IMapper <BaseControl> controlMapper, IMapper <IModelGenerator> modelMapper, IMapper <IComponentGenerator> entityMapper) { var modelReader = new ModelReader(modelMapper, new StochasticModelsGenerator()); var componentReader = new ComponentReader(entityMapper); var controlReader = new ControlReader(controlMapper); var subcircuitDefinitionReader = new SubcircuitDefinitionReader(); var commentReader = new CommentReader(); Readers[typeof(Component)] = componentReader; Readers[typeof(Model)] = modelReader; Readers[typeof(Control)] = controlReader; Readers[typeof(SubCircuit)] = subcircuitDefinitionReader; Readers[typeof(CommentLine)] = commentReader; }
/// <summary> /// Get the Identifier object for the model with the given name. /// </summary> /// <param name="reader">The <see cref="ModelReader"/> to use to retrieve the model information.</param> /// <param name="modelName">Name of model to look for</param> /// <returns>The identifier if it exists, otherwise an empty Identifier</returns> public static Identifier GetModelIdentifier(ModelReader reader, string modelName) { Identifier modelId = new Identifier(); Collection <Identifier> modelIdentifiers; modelIdentifiers = reader.GetModels(); foreach (Identifier id in modelIdentifiers) { if (id.Name.Equals(modelName)) { modelId = id; break; } } return(modelId); }
/// <summary> /// Get the Identifier object for the version with the given name. /// NOTE: ModelId property must be set on the reader first /// </summary> /// <param name="reader">The model reader object to use for the request.</param> /// <param name="versionName">Name of version to look for,</param> /// <returns>The identifier if it exists, otherwise an empty Identifier</returns> public static Identifier GetVersionIdentifier(ModelReader reader, string versionName) { Identifier versionId = new Identifier(); Collection <Identifier> versionIdentifiers; versionIdentifiers = reader.GetVersions(VersionStatusFlags.All); foreach (Identifier id in versionIdentifiers) { if (id.Name.Equals(versionName, StringComparison.OrdinalIgnoreCase)) { versionId = id; break; } } return(versionId); }
static void Main(string[] args) { string file = File.ReadAllText("1hho.cif"); // downloaded from http://www.rcsb.org/pdb/explore.do?structureId=1HHO (PDBx/mmCIF Format9 using (var reader = new ModelReader()) { var entry = reader.ReadEntry(file); foreach (var atomSite in entry.AtomSites) { Console.WriteLine( atomSite.Symbol + " Position: " + atomSite.X + "/" + atomSite.Y + "/" + atomSite.Z ); } } Console.ReadKey(); }
public static OneBlockModelSettings LoadOneBlockFromXml(string path) { var xdoc = XDocument.Load(path); var xsettings = xdoc.Element("ModelSettings"); var mesh = ReadMeshParameters(xsettings); var mb = ReadManualBoundaries(xsettings); var model = new OneBlockModelSettings(mesh, mb) .WithConductivity(xsettings.ElementAsDoubleOrNull("Conductivity") ?? -1) .WithAnomalyStartDepth(xsettings.ElementAsDecimal("AnomalyStartDepth")) .WithAnomalySizeX(xsettings.ElementAsDecimal("AnomalySizeX")) .WithAnomalySizeY(xsettings.ElementAsDecimal("AnomalySizeY")) .WithAnomalySizeZ(xsettings.ElementAsDecimal("AnomalySizeZ")); model.Section1D = ModelReader.LoadBackground(xsettings); return(model); }
/// <summary> /// Displays a list of the versions for a given model in the system. /// </summary> /// <param name="modelName">Name of model for which to list versions.</param> private static void ListVersions(string modelName) { Console.WriteLine("Versions for model {0}:", modelName); ModelReader reader = new ModelReader(); // Set the model ID on the reader to the passed-in model name. Identifier modelId = new Identifier(); modelId.Name = modelName; reader.ModelId = modelId; // Get the versions (all status types) for the specified model. Collection <Identifier> versions = reader.GetVersions(VersionStatusFlags.All); foreach (Identifier versionId in versions) { Console.WriteLine(versionId.Name); } }
private static void readAnalyzeInformationContainer(BinaryReader br, ref MotionPack pack) { string value = ModelReader.ReadString(br); IDanceMotionLeaf danceMotionLeaf = null; foreach (IDanceMotionLeaf current in pack.Motions) { if (current.Name.Equals(value)) { danceMotionLeaf = current; break; } } DanceMotionInformation danceMotionInformation = new DanceMotionInformation(br, danceMotionLeaf); if (danceMotionLeaf != null) { danceMotionLeaf.SetDanceMotionInformation(danceMotionInformation); } }
protected override void LoadFile(HpiArchive archive, HpiArchive.FileInfo file) { var records = this.objectMap[HpiPath.GetFileNameWithoutExtension(file.Name)]; var fileBuffer = new byte[file.Size]; archive.Extract(file, fileBuffer); using (var b = new MemoryStream(fileBuffer)) { var adapter = new ModelEdgeReaderAdapter(); var reader = new ModelReader(b, adapter); reader.Read(); var wire = Util.RenderWireframe(adapter.Edges); foreach (var record in records) { this.Records.Add(new KeyValuePair <string, OffsetBitmap>(record.Name, wire)); } } }
public static ResultsContainer Load(XDocument xdoc, LateralDimensions lateral = default(LateralDimensions)) { var xresult = xdoc.Element("ResultsMT"); if (xresult == null) { throw new ArgumentOutOfRangeException("xdoc"); } if (lateral == default(LateralDimensions)) { lateral = ModelReader.LateralDimensionsFromXElement(xresult); } if (lateral == default(LateralDimensions)) { throw new InvalidOperationException("no lateral dimensions"); } var xfreq = xresult.Element("Frequencies"); var xobs = xresult.Element("Observations"); var xvals = xresult.Element("Values"); if (xfreq == null) { throw new InvalidDataException("Frequencies"); } if (xobs == null) { throw new InvalidDataException("Observations"); } if (xvals == null) { throw new InvalidDataException("Values"); } var result = new ResultsContainer(lateral); return(result); }
private Model3DGroup LoadModel(Stream model, ModelDataType type, string textureFilePath = null, bool freeze = false) { ModelReader reader = null; switch (type) { case ModelDataType.OBJ: reader = new ObjReader(); break; case ModelDataType.STL: reader = new StLReader(); break; case ModelDataType.ThreeDS: reader = new StudioReader(); break; } if (reader == null) { throw new NotSupportedException("Given model type is not supported"); } reader.TexturePath = textureFilePath != null ? textureFilePath : ""; reader.Freeze = freeze; //using (model) return(reader.Read(model)); }
private void LoadModelData(string modelFile) { _Model = ModelReader.Read(modelFile); if (_Model != null) { _Model.Name = Path.GetFileNameWithoutExtension(Model.FileNames.First()); textBoxModelName.Text = _Model.Name; labelModelType.Text = Model.Type.ToString(); labelModelNumberOfModels.Text = Model.NumberOfModels.ToString(); labelModelDateMin.Text = Model.MinDate.ToDateTime().ToShortDateString(); labelModelDateMax.Text = Model.MaxDate.ToDateTime().ToShortDateString(); } else { MessageBox.Show(this, "", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static CartesianModel LoadCartesianModelWithoutAnomalyData(string modelFile) { try { if (ModelSettingsSerializer.IsModelCommemi(modelFile)) { var settings = ModelSettingsSerializer.LoadCommemiFromXml(modelFile); return(CreateModelWithoutAnomalyData(settings)); } if (ModelSettingsSerializer.IsModelCommemi3D3(modelFile)) { var settings = ModelSettingsSerializer.LoadCommemi3D3FromXml(modelFile); return(CreateModelWithoutAnomalyData(settings)); } if (ModelSettingsSerializer.IsModelOneBlock(modelFile)) { var settings = ModelSettingsSerializer.LoadOneBlockFromXml(modelFile); return(CreateModelWithoutAnomalyData(settings)); } if (ModelSettingsSerializer.IsModelNaser(modelFile)) { var settings = ModelSettingsSerializer.LoadNaserFromXml(modelFile); return(CreateModelWithoutAnomalyData(settings)); } return(ModelReader.LoadWithoutAnomalyData(modelFile)); } catch (Exception e) { throw new InvalidOperationException($"Can't load model {modelFile}", e); } }
public ModelReader GetSchema() { var connector = new DBConnector(_connection); int siteId = connector.GetSiteId(_siteName); bool replaceUrls; using (var cmd = new SqlCommand("SELECT TOP 1 REPLACE_URLS FROM SITE WHERE SITE_ID = @siteId")) { cmd.Parameters.AddWithValue("@siteId", siteId); replaceUrls = (bool)connector.GetRealScalarData(cmd); } var attributes = GetAttributes(connector, siteId); var contents = GetContents(connector, siteId, attributes); var model = new ModelReader(); model.Schema.ReplaceUrls = replaceUrls; model.Schema.SiteName = _siteName; model.Attributes.AddRange(attributes); model.Contents.AddRange(contents); return(model); }
public static Model Load(GraphicsDevice graphicsDevice, Stream stream, ModelMaterialTextureLoaderDelegate textureLoader) { using (var serializer = new ModelReader(graphicsDevice, stream, textureLoader)) { return serializer.ReadModel(); } }
internal ContentTypeReader[] LoadAssetReaders(ContentReader reader) { #pragma warning disable 0219, 0649 /* Trick to prevent the linker removing the code, but not actually execute the code * FIXME: Do we really need this in FNA? */ if (falseflag) { /* Dummy variables required for it to work on iDevices ** DO NOT DELETE ** * This forces the classes not to be optimized out when deploying to iDevices */ ByteReader hByteReader = new ByteReader(); SByteReader hSByteReader = new SByteReader(); DateTimeReader hDateTimeReader = new DateTimeReader(); DecimalReader hDecimalReader = new DecimalReader(); BoundingSphereReader hBoundingSphereReader = new BoundingSphereReader(); BoundingFrustumReader hBoundingFrustumReader = new BoundingFrustumReader(); RayReader hRayReader = new RayReader(); ListReader<char> hCharListReader = new ListReader<Char>(); ListReader<Rectangle> hRectangleListReader = new ListReader<Rectangle>(); ArrayReader<Rectangle> hRectangleArrayReader = new ArrayReader<Rectangle>(); ListReader<Vector3> hVector3ListReader = new ListReader<Vector3>(); ListReader<StringReader> hStringListReader = new ListReader<StringReader>(); ListReader<int> hIntListReader = new ListReader<Int32>(); SpriteFontReader hSpriteFontReader = new SpriteFontReader(); Texture2DReader hTexture2DReader = new Texture2DReader(); CharReader hCharReader = new CharReader(); RectangleReader hRectangleReader = new RectangleReader(); StringReader hStringReader = new StringReader(); Vector2Reader hVector2Reader = new Vector2Reader(); Vector3Reader hVector3Reader = new Vector3Reader(); Vector4Reader hVector4Reader = new Vector4Reader(); CurveReader hCurveReader = new CurveReader(); IndexBufferReader hIndexBufferReader = new IndexBufferReader(); BoundingBoxReader hBoundingBoxReader = new BoundingBoxReader(); MatrixReader hMatrixReader = new MatrixReader(); BasicEffectReader hBasicEffectReader = new BasicEffectReader(); VertexBufferReader hVertexBufferReader = new VertexBufferReader(); AlphaTestEffectReader hAlphaTestEffectReader = new AlphaTestEffectReader(); EnumReader<Microsoft.Xna.Framework.Graphics.SpriteEffects> hEnumSpriteEffectsReader = new EnumReader<Graphics.SpriteEffects>(); ArrayReader<float> hArrayFloatReader = new ArrayReader<float>(); ArrayReader<Vector2> hArrayVector2Reader = new ArrayReader<Vector2>(); ListReader<Vector2> hListVector2Reader = new ListReader<Vector2>(); ArrayReader<Matrix> hArrayMatrixReader = new ArrayReader<Matrix>(); EnumReader<Microsoft.Xna.Framework.Graphics.Blend> hEnumBlendReader = new EnumReader<Graphics.Blend>(); NullableReader<Rectangle> hNullableRectReader = new NullableReader<Rectangle>(); EffectMaterialReader hEffectMaterialReader = new EffectMaterialReader(); ExternalReferenceReader hExternalReferenceReader = new ExternalReferenceReader(); SoundEffectReader hSoundEffectReader = new SoundEffectReader(); SongReader hSongReader = new SongReader(); ModelReader hModelReader = new ModelReader(); Int32Reader hInt32Reader = new Int32Reader(); } #pragma warning restore 0219, 0649 /* The first content byte i read tells me the number of * content readers in this XNB file. */ int numberOfReaders = reader.Read7BitEncodedInt(); ContentTypeReader[] newReaders = new ContentTypeReader[numberOfReaders]; BitArray needsInitialize = new BitArray(numberOfReaders); contentReaders = new Dictionary<Type, ContentTypeReader>(numberOfReaders); /* Lock until we're done allocating and initializing any new * content type readers... this ensures we can load content * from multiple threads and still cache the readers. */ lock (locker) { /* For each reader in the file, we read out the * length of the string which contains the type * of the reader, then we read out the string. * Finally we instantiate an instance of that * reader using reflection. */ for (int i = 0; i < numberOfReaders; i += 1) { /* This string tells us what reader we * need to decode the following data. */ string originalReaderTypeString = reader.ReadString(); Func<ContentTypeReader> readerFunc; if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc)) { newReaders[i] = readerFunc(); needsInitialize[i] = true; } else { // Need to resolve namespace differences string readerTypeString = originalReaderTypeString; readerTypeString = PrepareType(readerTypeString); Type l_readerType = Type.GetType(readerTypeString); if (l_readerType != null) { ContentTypeReader typeReader; if (!contentReadersCache.TryGetValue(l_readerType, out typeReader)) { try { typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader; } catch (TargetInvocationException ex) { /* If you are getting here, the Mono runtime * is most likely not able to JIT the type. * In particular, MonoTouch needs help * instantiating types that are only defined * in strings in Xnb files. */ throw new InvalidOperationException( "Failed to get default constructor for ContentTypeReader. " + "To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " + "with the following failed type string: " + originalReaderTypeString, ex ); } needsInitialize[i] = true; contentReadersCache.Add(l_readerType, typeReader); } newReaders[i] = typeReader; } else { throw new ContentLoadException( "Could not find ContentTypeReader Type. " + "Please ensure the name of the Assembly that " + "contains the Type matches the assembly in the full type name: " + originalReaderTypeString + " (" + readerTypeString + ")" ); } } contentReaders.Add(newReaders[i].TargetType, newReaders[i]); /* I think the next 4 bytes refer to the "Version" of the type reader, * although it always seems to be zero. */ reader.ReadInt32(); } // Initialize any new readers. for (int i = 0; i < newReaders.Length; i += 1) { if (needsInitialize.Get(i)) { newReaders[i].Initialize(this); } } } // lock (locker) return newReaders; }
private void importToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openDlg = new OpenFileDialog(); openDlg.Filter = "STL (*.stl)|*.stl|3ds (*.3ds)|*.3ds|obj (*.obj)|*.obj|Skp (*.skp)|*.skp"; if (openDlg.ShowDialog() == DialogResult.OK) { ModelReader reader = new ModelReader(); GroupSceneNode node = reader.LoadFile(new AnyCAD.Platform.Path(openDlg.FileName)); if (node != null) { node.SetName(openDlg.SafeFileName); renderView.ShowSceneNode(node); renderView.RequestDraw(); } } }
/// <summary> /// Creates a model deployment package file for a specified model. /// </summary> /// <param name="packageFile">File name for the output package.</param> /// <param name="modelName">Name of the model to export to package.</param> /// <param name="versionName">Name of the version of master data to include in the package.</param> private static void CreatePackage(string packageFile, string modelName, string versionName) { Console.WriteLine("Creating a package for model {0}", modelName); ModelReader reader = new ModelReader(); // Set the model ID on the reader to the passed-in model name. Identifier modelId = new Identifier(); modelId.Name = modelName; reader.ModelId = modelId; // Set the version ID on the reader to the passed-in version name. Identifier versionId = new Identifier(); versionId.Name = versionName; reader.VersionId = versionId; // Create a package that contains metadata, business rules, and master data. List<Package> packages = reader.CreatePackage(true).ToList(); // Save the package Console.WriteLine("Saving package to file {0}", packageFile); using (var stream = new FileStream(packageFile, FileMode.CreateNew)) { var firstPackage = packages.FirstOrDefault(); if (firstPackage != null) firstPackage.Serialize(stream); } }
internal ContentTypeReader[] LoadAssetReaders(ContentReader reader) { #pragma warning disable 0219, 0649 // Trick to prevent the linker removing the code, but not actually execute the code if (falseflag) { // Dummy variables required for it to work on iDevices ** DO NOT DELETE ** // This forces the classes not to be optimized out when deploying to iDevices var hByteReader = new ByteReader(); var hSByteReader = new SByteReader(); var hDateTimeReader = new DateTimeReader(); var hDecimalReader = new DecimalReader(); var hBoundingSphereReader = new BoundingSphereReader(); var hBoundingFrustumReader = new BoundingFrustumReader(); var hRayReader = new RayReader(); var hCharListReader = new ListReader<Char>(); var hRectangleListReader = new ListReader<Rectangle>(); var hRectangleArrayReader = new ArrayReader<Rectangle>(); var hVector3ListReader = new ListReader<Vector3>(); var hStringListReader = new ListReader<StringReader>(); var hIntListReader = new ListReader<Int32>(); var hSpriteFontReader = new SpriteFontReader(); var hTexture2DReader = new Texture2DReader(); var hCharReader = new CharReader(); var hRectangleReader = new RectangleReader(); var hStringReader = new StringReader(); var hVector2Reader = new Vector2Reader(); var hVector3Reader = new Vector3Reader(); var hVector4Reader = new Vector4Reader(); var hCurveReader = new CurveReader(); var hIndexBufferReader = new IndexBufferReader(); var hBoundingBoxReader = new BoundingBoxReader(); var hMatrixReader = new MatrixReader(); var hBasicEffectReader = new BasicEffectReader(); var hVertexBufferReader = new VertexBufferReader(); var hAlphaTestEffectReader = new AlphaTestEffectReader(); var hEnumSpriteEffectsReader = new EnumReader<Graphics.SpriteEffects>(); var hArrayFloatReader = new ArrayReader<float>(); var hArrayVector2Reader = new ArrayReader<Vector2>(); var hListVector2Reader = new ListReader<Vector2>(); var hArrayMatrixReader = new ArrayReader<Matrix>(); var hEnumBlendReader = new EnumReader<Graphics.Blend>(); var hNullableRectReader = new NullableReader<Rectangle>(); var hEffectMaterialReader = new EffectMaterialReader(); var hExternalReferenceReader = new ExternalReferenceReader(); var hSoundEffectReader = new SoundEffectReader(); var hSongReader = new SongReader(); var hModelReader = new ModelReader(); var hInt32Reader = new Int32Reader(); // At the moment the Video class doesn't exist // on all platforms... Allow it to compile anyway. #if ANDROID || IOS || MONOMAC || (WINDOWS && !OPENGL) || (WINRT && !WINDOWS_PHONE) var hVideoReader = new VideoReader(); #endif } #pragma warning restore 0219, 0649 // The first content byte i read tells me the number of content readers in this XNB file var numberOfReaders = reader.Read7BitEncodedInt(); var contentReaders = new ContentTypeReader[numberOfReaders]; var needsInitialize = new BitArray(numberOfReaders); _contentReaders = new Dictionary<Type, ContentTypeReader>(numberOfReaders); // Lock until we're done allocating and initializing any new // content type readers... this ensures we can load content // from multiple threads and still cache the readers. lock (_locker) { // For each reader in the file, we read out the length of the string which contains the type of the reader, // then we read out the string. Finally we instantiate an instance of that reader using reflection for (var i = 0; i < numberOfReaders; i++) { // This string tells us what reader we need to decode the following data // string readerTypeString = reader.ReadString(); string originalReaderTypeString = reader.ReadString(); Func<ContentTypeReader> readerFunc; if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc)) { contentReaders[i] = readerFunc(); needsInitialize[i] = true; } else { //System.Diagnostics.Debug.WriteLine(originalReaderTypeString); // Need to resolve namespace differences string readerTypeString = originalReaderTypeString; readerTypeString = PrepareType(readerTypeString); var l_readerType = Type.GetType(readerTypeString); if (l_readerType != null) { ContentTypeReader typeReader; if (!_contentReadersCache.TryGetValue(l_readerType, out typeReader)) { try { typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader; } catch (TargetInvocationException ex) { // If you are getting here, the Mono runtime is most likely not able to JIT the type. // In particular, MonoTouch needs help instantiating types that are only defined in strings in Xnb files. throw new InvalidOperationException( "Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " + "with the following failed type string: " + originalReaderTypeString, ex); } needsInitialize[i] = true; _contentReadersCache.Add(l_readerType, typeReader); } contentReaders[i] = typeReader; } else throw new ContentLoadException( "Could not find ContentTypeReader Type. Please ensure the name of the Assembly that contains the Type matches the assembly in the full type name: " + originalReaderTypeString + " (" + readerTypeString + ")"); } var targetType = contentReaders[i].TargetType; if (targetType != null) _contentReaders.Add(targetType, contentReaders[i]); // I think the next 4 bytes refer to the "Version" of the type reader, // although it always seems to be zero reader.ReadInt32(); } // Initialize any new readers. for (var i = 0; i < contentReaders.Length; i++) { if (needsInitialize.Get(i)) contentReaders[i].Initialize(this); } } // lock (_locker) return contentReaders; }
/// <summary> /// Deploys an update to an existing model from a specified package. /// </summary> /// <param name="packageFile">File name of the input package.</param> /// <param name="versionName">Name of the version of master data to update.</param> private static void DeployUpdate(string packageFile, string versionName) { Console.WriteLine("Deploying package {0}, updating version {1} of the master data", packageFile, versionName); ModelDeployer deployer = new ModelDeployer(); ModelReader reader = new ModelReader(); // Deploy it. Warnings errorsAsWarnings = null; using (var package = new PackageReader(packageFile)) { // Get the ID for the model named in the package var firstPackage = package.FirstOrDefault(); if (firstPackage != null) { Identifier modelId = GetModelIdentifier(reader, firstPackage.ModelId.Name); // Now get the version Id for that model and the given version name. reader.ModelId = modelId; } Identifier versionId = GetVersionIdentifier(reader, versionName); errorsAsWarnings = deployer.DeployUpdate(package.GetEnumerator(), true, versionId); } Console.WriteLine("Package was deployed with {0} warnings", errorsAsWarnings.Count); }
/// <summary> /// Displays a list of the versions for a given model in the system. /// </summary> /// <param name="modelName">Name of model for which to list versions.</param> private static void ListVersions(string modelName) { Console.WriteLine("Versions for model {0}:", modelName); ModelReader reader = new ModelReader(); // Set the model ID on the reader to the passed-in model name. Identifier modelId = new Identifier(); modelId.Name = modelName; reader.ModelId = modelId; // Get the versions (all status types) for the specified model. Collection<Identifier> versions = reader.GetVersions(VersionStatusFlags.All); foreach (Identifier versionId in versions) { Console.WriteLine(versionId.Name); } }
/// <summary> /// Displays a list of the models in the system. /// </summary> private static void ListModels() { Console.WriteLine("Models:"); ModelReader reader = new ModelReader(); Collection<Identifier> models = reader.GetModels(); foreach (Identifier modelId in models) { Console.WriteLine(modelId.Name); } }