/// <summary>
        /// Creates and adds the root for all imported scene objects.
        /// </summary>
        public ScenePivotObject CreateAndAddRootObject()
        {
            // Append an object which transform the whole coordinate system
            ScenePivotObject rootObject = new ScenePivotObject();

            // Handle base transformation
            switch (m_importOptions.ResourceCoordinateSystem)
            {
            case CoordinateSystem.LeftHanded_UpY:
                rootObject.TransformationType = SpacialTransformationType.None;
                break;

            case CoordinateSystem.LeftHanded_UpZ:
                rootObject.Scaling            = new Vector3(1f, -1f, 1f);
                rootObject.RotationEuler      = new Vector3(-EngineMath.RAD_90DEG, 0f, 0f);
                rootObject.TransformationType = SpacialTransformationType.ScalingTranslationEulerAngles;
                break;

            case CoordinateSystem.RightHanded_UpY:
                rootObject.Scaling            = new Vector3(1f, 1f, -1f);
                rootObject.TransformationType = SpacialTransformationType.ScalingTranslation;
                break;

            case CoordinateSystem.RightHanded_UpZ:
                rootObject.Scaling            = new Vector3(-1f, 1f, -1f);
                rootObject.RotationEuler      = new Vector3(EngineMath.RAD_90DEG, 0f, 0f);
                rootObject.TransformationType = SpacialTransformationType.ScalingTranslationEulerAngles;
                break;
            }

            // Add the object finally
            this.Objects.Add(rootObject);

            return(rootObject);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Reads the model in ASCII format from the specified stream.
        /// </summary>
        private ImportedModelContainer TryReadAscii(Stream stream, StlImportOptions importOptions)
        {
            using (var reader = new StreamReader(stream, ENCODING, false, 128, true))
            {
                VertexStructure newStructure = new VertexStructure();
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (line == null)
                    {
                        continue;
                    }

                    line = line.Trim();
                    if (line.Length == 0 || line.StartsWith("\0") || line.StartsWith("#") || line.StartsWith("!") ||
                        line.StartsWith("$"))
                    {
                        continue;
                    }

                    string id, values;
                    ParseLine(line, out id, out values);
                    switch (id)
                    {
                    // Header.. not needed here
                    case "solid":
                        break;

                    // Geometry data
                    case "facet":
                        this.ReadFacet(reader, values, newStructure, importOptions);
                        break;

                    // End of file
                    case "endsolid":
                        break;
                    }
                }

                // Generate result container
                ImportedModelContainer result         = new ImportedModelContainer(importOptions);
                NamedOrGenericKey      geoResourceKey = result.GetResourceKey(
                    RES_KEY_GEO_CLASS, RES_KEY_GEO_NAME);
                result.ImportedResources.Add(new ImportedResourceInfo(
                                                 geoResourceKey,
                                                 () => new GeometryResource(newStructure)));
                GenericObject geoObject = new GenericObject(geoResourceKey);
                result.Objects.Add(geoObject);

                // Append an object which transform the whole coordinate system
                ScenePivotObject rootObject = result.CreateAndAddRootObject();
                result.ParentChildRelationships.Add(new Tuple <SceneObject, SceneObject>(rootObject, geoObject));

                return(result);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Reads the model from the specified binary stream.
        /// </summary>
        private ImportedModelContainer TryReadBinary(Stream stream, StlImportOptions importOptions)
        {
            // Check length
            long length = stream.Length;

            if (length < 84)
            {
                throw new SeeingSharpException("Incomplete file (smaller that 84 bytes)");
            }

            // Read number of triangles
            uint numberTriangles = 0;

            using (var reader = new BinaryReader(stream, Encoding.GetEncoding("us-ascii"), true))
            {
                // Read header (is not needed)
                //  (solid stands for Ascii format)
                string header = ENCODING.GetString(reader.ReadBytes(80), 0, 80).Trim();
                if (header.StartsWith("solid", StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                // Read and check number of triangles
                numberTriangles = ReadUInt32(reader);
                if (length - 84 != numberTriangles * 50)
                {
                    throw new SeeingSharpException("Incomplete file (smaller that expected byte count)");
                }

                // Read geometry data
                VertexStructure newStructure = new VertexStructure((int)numberTriangles * 3);
                newStructure.CreateSurface((int)numberTriangles);
                for (int loop = 0; loop < numberTriangles; loop++)
                {
                    this.ReadTriangle(reader, newStructure, importOptions);
                }

                // Generate result container
                ImportedModelContainer result         = new ImportedModelContainer(importOptions);
                NamedOrGenericKey      geoResourceKey = result.GetResourceKey(
                    RES_KEY_GEO_CLASS, RES_KEY_GEO_NAME);
                result.ImportedResources.Add(new ImportedResourceInfo(
                                                 geoResourceKey,
                                                 () => new GeometryResource(newStructure)));
                GenericObject geoObject = new GenericObject(geoResourceKey);
                result.Objects.Add(geoObject);

                // Append an object which transform the whole coordinate system
                ScenePivotObject rootObject = result.CreateAndAddRootObject();
                result.ParentChildRelationships.Add(new Tuple <SceneObject, SceneObject>(rootObject, geoObject));

                return(result);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates and adds the root for all imported scene objects.
        /// </summary>
        public void FinishLoading(BoundingBox boundingBox)
        {
            this.EnsureNotFinished();

            try
            {
                // Generic checks
                if (this.Objects.Count == 0)
                {
                    throw new SeeingSharpException("No objects imported");
                }
                if (EngineMath.EqualsWithTolerance(boundingBox.Width, 0) ||
                    EngineMath.EqualsWithTolerance(boundingBox.Height, 0) ||
                    EngineMath.EqualsWithTolerance(boundingBox.Depth, 0))
                {
                    throw new SeeingSharpException($"BoundingBox of the loaded model data seems to be empty (Width={boundingBox.Width}, Height={boundingBox.Height}, Depth={boundingBox.Height}");
                }

                // Create root for the imported object graph
                var rootObject = new ScenePivotObject();
                rootObject.TransformationType = SpacialTransformationType.ScalingTranslationEulerAngles;
                rootObject.Name = $"{IMPORT_ROOT_NODE_NAME_PREFIX} {_importId}";

                // Configure base transformation of the root object
                switch (_importOptions.ResourceCoordinateSystem)
                {
                case CoordinateSystem.LeftHanded_UpY:
                    break;

                case CoordinateSystem.LeftHanded_UpZ:
                    rootObject.Scaling       = new Vector3(1f, -1f, 1f);
                    rootObject.RotationEuler = new Vector3(-EngineMath.RAD_90DEG, 0f, 0f);
                    break;

                case CoordinateSystem.RightHanded_UpY:
                    rootObject.Scaling = new Vector3(1f, 1f, -1f);
                    break;

                case CoordinateSystem.RightHanded_UpZ:
                    rootObject.Scaling       = new Vector3(-1f, 1f, -1f);
                    rootObject.RotationEuler = new Vector3(EngineMath.RAD_90DEG, 0f, 0f);
                    break;
                }

                // Configure position and scaling of the root object
                if (_importOptions.FitToCube)
                {
                    var scaleFactor = Math.Min(
                        1f / boundingBox.Width,
                        Math.Min(1f / boundingBox.Height, 1f / boundingBox.Depth));
                    rootObject.Scaling *= scaleFactor;
                    rootObject.Position = new Vector3(
                        (0f - (boundingBox.Minimum.X + (boundingBox.Maximum.X - boundingBox.Minimum.X) / 2f)) *
                        scaleFactor,
                        (0f - (boundingBox.Minimum.Y + (boundingBox.Maximum.Y - boundingBox.Minimum.Y) / 2f)) *
                        scaleFactor,
                        (0f - (boundingBox.Minimum.Z + (boundingBox.Maximum.Z - boundingBox.Minimum.Z) / 2f)) *
                        scaleFactor);
                }

                // Find current root objects and assign them as child to the new root object
                foreach (var actRootObject in this.FindRootObjects())
                {
                    _parentChildRelationships.Add(
                        new ParentChildRelationship(rootObject, actRootObject));
                }

                // AddObject the object finally
                _objects.Add(rootObject);
                this.RootObject  = rootObject;
                this.BoundingBox = boundingBox;

                _isValid = true;
            }
            catch (Exception ex)
            {
                this.FinishLoading(ex);
            }
            finally
            {
                _isFinished = true;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Imports the texture node where the xml reader is currently located.
        /// </summary>
        private void ImportObject(XmlReader inStreamXml, ImportedModelContainer container, SceneObject parentObject, XglImportOptions xglImportOptions)
        {
            Vector3 upVector       = Vector3.UnitY;
            Vector3 forwardVector  = Vector3.UnitZ;
            Vector3 positionVector = Vector3.UnitX;
            string  meshID         = string.Empty;

            // Define a action which finally create the new object
            //  (may be called on two locations here.. so this action was defined
            SceneSpacialObject newObject            = null;
            Action             actionFinalizeObject = () =>
            {
                if (newObject != null)
                {
                    return;
                }

                if (string.IsNullOrEmpty(meshID))
                {
                    // Generate a Pivot on which other objects are orientated
                    newObject = new ScenePivotObject();
                }
                else
                {
                    // Generate an instance of a 3d mesh
                    newObject = new GenericObject(
                        container.GetResourceKey(RES_CLASS_MESH, meshID));
                }
                newObject.Position           = positionVector;
                newObject.TransformationType = SpacialTransformationType.TranslationDirection;
                newObject.RotationForward    = forwardVector;
                newObject.RotationUp         = upVector;
                container.Objects.Add(newObject);

                // Add dependency (parent => child)
                if (parentObject != null)
                {
                    container.ParentChildRelationships.Add(Tuple.Create <SceneObject, SceneObject>(
                                                               parentObject, newObject));
                }
            };

            // Read xml contents
            while (inStreamXml.Read())
            {
                // Ending condition
                if ((inStreamXml.NodeType == XmlNodeType.EndElement) &&
                    (inStreamXml.Name == NODE_NAME_OBJECT))
                {
                    break;
                }

                // Continue condition
                if (inStreamXml.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                switch (inStreamXml.Name)
                {
                case NODE_NAME_OBJECT:
                    actionFinalizeObject();
                    ImportObject(inStreamXml, container, newObject, xglImportOptions);
                    break;

                case NODE_NAME_TRANS_FORWARD:
                    inStreamXml.Read();
                    forwardVector = inStreamXml.ReadContentAsVector3();
                    break;

                case NODE_NAME_TRANS_UP:
                    inStreamXml.Read();
                    upVector = inStreamXml.ReadContentAsVector3();
                    break;

                case NODE_NAME_TRANS_POSITION:
                    inStreamXml.Read();
                    positionVector = inStreamXml.ReadContentAsVector3() * xglImportOptions.ResizeFactor;
                    break;

                case NODE_NAME_MESHREF:
                    inStreamXml.Read();
                    meshID = inStreamXml.ReadContentAsString();
                    break;

                case NODE_NAME_TRANSFORM:
                    break;

                default:
                    break;
                }
            }

            // finalize object here
            actionFinalizeObject();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Imports a model from the given file.
        /// </summary>
        /// <param name="sourceFile">The source file to be loaded.</param>
        /// <param name="importOptions">Some configuration for the importer.</param>
        public ImportedModelContainer ImportModel(ResourceLink sourceFile, ImportOptions importOptions)
        {
            // Get import options
            XglImportOptions xglImportOptions = importOptions as XglImportOptions;

            if (xglImportOptions == null)
            {
                throw new SeeingSharpException("Invalid import options for ACImporter!");
            }

            ImportedModelContainer result = new ImportedModelContainer(importOptions);

            // Append an object which transform the whole coordinate system
            ScenePivotObject rootObject = result.CreateAndAddRootObject();

            // Load current model by walking through xml nodes
            using (Stream inStream = sourceFile.OpenInputStream())
            {
                // Handle compressed xgl files (extension zgl)
                Stream nextStream = inStream;
                if (sourceFile.FileExtension.Equals("zgl", StringComparison.OrdinalIgnoreCase))
                {
                    // Skip the first bytes in case of compression
                    //  see https://github.com/assimp/assimp/blob/master/code/XGLLoader.cpp
                    inStream.ReadByte();
                    inStream.ReadByte();
                    nextStream = new System.IO.Compression.DeflateStream(inStream, CompressionMode.Decompress);
                }

                // Read all xml data
                try
                {
                    using (XmlReader inStreamXml = XmlReader.Create(nextStream, new XmlReaderSettings()
                    {
                        CloseInput = false
                    }))
                    {
                        while (inStreamXml.Read())
                        {
                            try
                            {
                                if (inStreamXml.NodeType != XmlNodeType.Element)
                                {
                                    continue;
                                }

                                switch (inStreamXml.Name)
                                {
                                case NODE_NAME_DATA:
                                    break;

                                case NODE_NAME_BACKGROUND:
                                    break;

                                case NODE_NAME_LIGHTING:
                                    break;

                                case NODE_NAME_TEXTURE:
                                    ImportTexture(inStreamXml, result);
                                    break;

                                case NODE_NAME_MESH:
                                    ImportMesh(inStreamXml, result, xglImportOptions);
                                    break;

                                case NODE_NAME_OBJECT:
                                    ImportObject(inStreamXml, result, rootObject, xglImportOptions);
                                    break;

                                default:
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                // Get current line and column
                                int          currentLine   = 0;
                                int          currentColumn = 0;
                                IXmlLineInfo lineInfo      = inStreamXml as IXmlLineInfo;
                                if (lineInfo != null)
                                {
                                    currentLine   = lineInfo.LineNumber;
                                    currentColumn = lineInfo.LinePosition;
                                }

                                // Throw an exception with more detail where the error was raised originally
                                throw new SeeingSharpGraphicsException(string.Format(
                                                                           "Unable to read file {0} because of an error while reading xml at {1}",
                                                                           sourceFile,
                                                                           currentLine + ", " + currentColumn), ex);
                            }
                        }
                    }
                }
                finally
                {
                    if (inStream != nextStream)
                    {
                        nextStream.Dispose();
                    }
                }
            }

            return(result);
        }