예제 #1
0
        [TestMethod] //заполнение с использованием Insert
        public void InsertTest()
        {
            int n = 3;
            ListArray<object> data = new ListArray<object>(n);
            data.Add(8);
            data.Add(6);
            data.Insert(4, 1);

        }
예제 #2
0
 [TestMethod] //Поиск не существующего элемента
 public void FindNotExistItemTest()
 {
     int n = 3;
     ListArray<object> data = new ListArray<object>(n);
     data.Add(8);
     data.Add(6);
     data.Add(10);
     data.Find(11);
 }
예제 #3
0
        [TestMethod] //заполнение списка 
        public void AppendTest()
        {
            int n = 3;
            ListArray<object> data = new ListArray<object>(n);
            data.Add(8);
            data.Add(6);
            data.Add(10);

        }
예제 #4
0
        [TestMethod] //Удаление элемента из списка 
        public void DeleteTest()
        {
            int n = 3;
            ListArray<object> data = new ListArray<object>(n);
            data.Add(8);
            data.Add(6);
            data.Add(10);
            data.Remove(2);

        }
예제 #5
0
        public void Initialize(int width, int height, bool rotations)
        {
            BinWidth      = width;
            BinHeight     = height;
            AllowRotation = rotations;

            _usedRects.Clear();
            _freeRects.Clear();

            _freeRects.Add(new Rect(0, 0, width, height));
        }
예제 #6
0
        public bool Insert(int width, int height, ChoiceHeuristic method, out Rect rect)
        {
            var newNode = new Rect(0, 0, 0, 0);
            int score1  = 0; // Unused in this function. We don't need to know the score after finding the position.
            int score2  = 0;

            switch (method)
            {
            case ChoiceHeuristic.BestShortSideFit:
                newNode = FindPositionForNewNodeBestShortSideFit(width, height, ref score1, ref score2);
                break;

            case ChoiceHeuristic.BottomLeftRule:
                newNode = FindPositionForNewNodeBottomLeft(width, height, ref score1, ref score2);
                break;

            case ChoiceHeuristic.ContactPointRule:
                newNode = FindPositionForNewNodeContactPoint(width, height, ref score1);
                break;

            case ChoiceHeuristic.BestLongSideFit:
                newNode = FindPositionForNewNodeBestLongSideFit(width, height, ref score2, ref score1);
                break;

            case ChoiceHeuristic.BestAreaFit:
                newNode = FindPositionForNewNodeBestAreaFit(width, height, ref score1, ref score2);
                break;
            }

            if (newNode.H == 0)
            {
                rect = Rect.Zero;
                return(false);
            }

            int numRectanglesToProcess = _freeRects.Count;

            for (int i = 0; i < numRectanglesToProcess; ++i)
            {
                if (SplitFreeNode(ref _freeRects.GetReferenceAt(i), ref newNode))
                {
                    _freeRects.RemoveAt(i);
                    --i;
                    --numRectanglesToProcess;
                }
            }

            PruneFreeList();
            _usedRects.Add(newNode);
            rect = newNode;
            return(true);
        }
예제 #7
0
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="cacheValue">缓存数据</param>
        /// <param name="value">更新后的数据</param>
        /// <param name="oldValue">更新前的数据</param>
        /// <param name="memberMap"></param>
        private void onUpdated(valueType cacheValue, valueType value, valueType oldValue, MemberMap <modelType> memberMap)
        {
            keyType key = getKey(value);

            if (cacheValue == null)
            {
                ListArray <valueType> values;
                if (queueCache.Remove(ref key, out values))
                {
                    foreach (valueType removeValue in values)
                    {
                        counter.Remove(removeValue);
                    }
                }
            }
            else
            {
                keyType oldKey = getKey(oldValue);
                if (!key.Equals(oldKey))
                {
                    ListArray <valueType> values = queueCache.Get(ref key, null), oldValues = queueCache.Get(ref oldKey, null);
                    if (values != null)
                    {
                        if (oldValues != null)
                        {
                            values.Add(cacheValue);
                            if (!oldValues.Remove(cacheValue))
                            {
                                counter.SqlTable.Log.Add(AutoCSer.Log.LogType.Fatal, typeof(valueType).FullName + " 缓存同步错误");
                            }
                        }
                        else
                        {
                            values.Add(counter.Add(cacheValue));
                        }
                    }
                    else if (oldValues != null)
                    {
                        if (oldValues.Remove(cacheValue))
                        {
                            counter.Remove(cacheValue);
                        }
                        else
                        {
                            counter.SqlTable.Log.Add(AutoCSer.Log.LogType.Fatal, typeof(valueType).FullName + " 缓存同步错误");
                        }
                    }
                }
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            // Data Set Generation
            Random random = new Random(7);
            List <Vector <double> > vectors = new ListArray <Vector <double> >();
            int test_size = 100000;

            for (int i = 0; i < test_size; i++)
            {
                vectors.Add(new Vector <double>(i - (test_size / 2), random.Next(10000) - (test_size / 2) + i));
            }

            // Simple Linear Regression
            double slope, y_intercept;

            Compute <double> .LinearRegression2D(vectors.Stepper(), out slope, out y_intercept);

            Console.WriteLine("Slope: " + slope);
            Console.WriteLine("Y-Intercept: " + y_intercept);

            Console.WriteLine(Compute <float> .Pi);
            Console.WriteLine(Compute <double> .Pi);
            Console.WriteLine(Compute <Fraction64> .Pi);
            Console.WriteLine(Compute <Fraction128> .Pi);


            TestOmnitree1();
            Console.WriteLine();
            TestOmnitree2();
            Console.WriteLine();

            Console.WriteLine("Press Enter To Exit...");
            Console.ReadLine();
        }
예제 #9
0
        public override IValue Eval(IValue[] parameters)
        {
            this.Validate(parameters);

            var set       = parameters[0].AsSet;
            var res       = new ListArray();
            var i         = new Variable(parameters[1].AsString, new DoubleValue(0));
            var evaluator = default(PostFixEvaluator);

            this.Context.VariableManager.Define(i);

            try
            {
                var tokenizer = new Tokenizer(parameters[2].AsString, this.Context.Config);
                tokenizer.Run();
                var parser = new Parser(tokenizer.Tokens, this.Context.Config);
                evaluator = new PostFixEvaluator(parser.CreatePostFixExpression(), this.Context);
            }
            catch (System.Exception)
            {
                throw new OperandEvaluationException();
            }

            foreach (var item in set)
            {
                i.Value = item;
                if (evaluator.Run().AsDouble != 0)
                {
                    res.Add(item);
                }
            }

            return(new ArrayValue(res));
        }
예제 #10
0
 public void Add(UITransform transform)
 {
     _transforms.Add(transform);
     transform.Container      = this;
     transform.OnMarkedDirty += Transform_MarkedDirty;
     _boundsNeedUpdate        = true;
 }
예제 #11
0
        public void AddTest(int[] arr, int val, int[] expected)
        {
            ListArray la = new ListArray(arr);

            la.Add(val);

            Assert.AreEqual(expected, la.GetValues());
        }
예제 #12
0
        // ListArray

        [Benchmark] public void ListArray_Add()
        {
            IList <Person> list = new ListArray <Person>();

            foreach (Person person in RandomTestData)
            {
                list.Add(person);
            }
        }
예제 #13
0
 private void AddInternal(UITransform transform)
 {
     _transforms.Add(transform);
     lock (transform.SyncRoot)
     {
         transform.SetContainer(this);
         transform.MarkedDirty += Transform_MarkedDirty;
     }
 }
예제 #14
0
        [Benchmark] public void ListArray_AddWithCapacity()
        {
            IList <Person> list = new ListArray <Person>(RandomTestData.Length);

            foreach (Person person in RandomTestData)
            {
                list.Add(person);
            }
        }
예제 #15
0
        /// <summary>
        /// 增加数据
        /// </summary>
        /// <param name="value">新增的数据</param>
        private void onInserted(valueType value)
        {
            keyType key = getKey(value);
            ListArray <valueType> values = queueCache.Get(ref key, null);

            if (values != null)
            {
                values.Add(counter.Add(value));
            }
        }
예제 #16
0
        /// <summary>
        /// Creates a result value set of the size specified
        /// </summary>
        /// <returns>A Value set of the correct size.</returns>
        public static TimeSpaceValueSet <double> CreateResultValueSet(int numtimes, int numElements)
        {
            ListArray <double> outValues = new ListArray <double>(numtimes);

            for (int i = 0; i < numtimes; i++)
            {
                outValues.Add(new double[numElements]);
            }
            return(new TimeSpaceValueSet <double>(outValues));
        }
예제 #17
0
파일: Measurement.cs 프로젝트: inktan/Towel
        internal static void BuildParsingLibrary()
        {
            // make a regex pattern with all the currently supported unit types and
            // build the unit string to unit type string map
            IList <string>        strings = new ListArray <string>();
            IMap <string, string> unitStringToUnitTypeString = new MapHashLinked <string, string>();

            foreach (Type type in Assembly.GetExecutingAssembly().GetTypesWithAttribute <ParseableUnitAttribute>())
            {
                if (!type.IsEnum)
                {
                    throw new Exception("There is a bug in Towel. " + nameof(ParseableUnitAttribute) + " is on a non enum type.");
                }
                if (!type.Name.Equals("Units") || type.DeclaringType is null)
                {
                    throw new Exception("There is a bug in Towel. A unit type definition does not follow the required structure.");
                }
                string unitTypeString = type.DeclaringType.Name;
                foreach (Enum @enum in Enum.GetValues(type).Cast <Enum>())
                {
                    strings.Add(@enum.ToString());
                    unitStringToUnitTypeString.Add(@enum.ToString(), unitTypeString);
                }
            }
            strings.Add(@"\*");
            strings.Add(@"\/");
            AllUnitsRegexPattern       = string.Join("|", strings);
            UnitStringToUnitTypeString = unitStringToUnitTypeString;

            // make the Enum arrays to units map
            IMap <Enum, string> unitStringToEnumMap = new MapHashLinked <Enum, string>();

            foreach (Type type in Assembly.GetExecutingAssembly().GetTypesWithAttribute <ParseableUnitAttribute>())
            {
                foreach (Enum @enum in Enum.GetValues(type))
                {
                    unitStringToEnumMap.Add(@enum.ToString(), @enum);
                }
            }
            UnitStringToEnumMap = unitStringToEnumMap;

            ParsingLibraryBuilt = true;
        }
예제 #18
0
        public void AddTests(int[] array, int value, int[] expArray)

        {
            ListArray expected = new ListArray(expArray);
            ListArray actual   = new ListArray(array);

            actual.Add(value);

            Assert.AreEqual(expected, actual);
        }
예제 #19
0
        public void AddWithCapacity()
        {
            IList <int> addable  = new ListArray <int>(AddCount);
            int         addCount = AddCount;

            for (int i = 0; i < addCount; i++)
            {
                addable.Add(i);
            }
        }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Группирование контрактов по указанному свойству
            /// </summary>
            /// <param name="property_name">Имя свойства для группировки</param>
            //---------------------------------------------------------------------------------------------------------
            public void GroupContractBy(String property_name)
            {
                // 1) Превращаем в плоский список
                ListArray <CContract> flat_contracts = new ListArray <CContract>();

                for (Int32 i = 0; i < mModels.Count; i++)
                {
                    if (mModels[i] is CContract)
                    {
                        flat_contracts.Add(mModels[i] as CContract);
                    }
                    else
                    {
                        if (mModels[i] is CContractSet)
                        {
                            //CContractSet contract_set = mModels[i] as CContractSet;
                            //for (Int32 j = 0; j < contract_set.mModels.Count; j++)
                            //{
                            //	if (contract_set.mModels[j] is CContract)
                            //	{
                            //		flat_contracts.Add(contract_set.mModels[j] as CContract);
                            //	}
                            //}
                        }
                    }
                }

                // 2) Формируем группы
                ListArray <CContractSet> groups = new ListArray <CContractSet>();

                for (Int32 i = 0; i < flat_contracts.Count; i++)
                {
                    // 3) Ищем группу
                    Int32 find_index = groups.Find((CContractSet contract_set) =>
                    {
                        return(contract_set.Name == flat_contracts[i].CustomerName);
                    });
                    if (find_index != -1)
                    {
                        // Такую группу нашли добавляем туда контракт
                        groups[find_index].AddExistingModel(flat_contracts[i]);
                    }
                    else
                    {
                        // Группу не нашли, создаем с указанным именем и добавляем туда контракт
                        CContractSet contract_set = new CContractSet(flat_contracts[i].CustomerName);
                        contract_set.AddExistingModel(flat_contracts[i]);
                        groups.Add(contract_set);
                    }
                }

                // Обновляем список
                this.ClearModels();
                this.AddExistingModels(groups);
            }
예제 #21
0
        public override IValue Eval(IValue[] parameters)
        {
            this.Validate(parameters);

            var res = new ListArray();

            for (double i = parameters[0].AsDouble, end = parameters[2].AsDouble; i <= end; i += parameters[1].AsDouble)
            {
                res.Add(new DoubleValue(i));
            }

            return(new ArrayValue(res));
        }
예제 #22
0
        ///// <summary>
        ///// 创建随机数组函数信息
        ///// </summary>
        //internal static readonly MethodInfo CreateLeftArrayMethod = typeof(MethodCache).GetMethod("createLeftArray", BindingFlags.Static | BindingFlags.NonPublic);
        /// <summary>
        /// 创建随机数组
        /// </summary>
        /// <typeparam name="valueType"></typeparam>
        /// <param name="config"></param>
        /// <returns></returns>
        //[AutoCSer.IOS.Preserve(Conditional = true)]
        internal static ListArray <valueType> createListArray <valueType>(Config config)
        {
            object historyValue = config.TryGetValue(typeof(ListArray <valueType>));

            if (historyValue != null)
            {
                return((ListArray <valueType>)historyValue);
            }
            ListArray <valueType> value = config.SaveHistory(new ListArray <valueType>());

            value.Add(createArray <valueType>(config));
            return(value);
        }
예제 #23
0
        private void onInserted(valueType value)
        {
            memberCacheType node = getTarget(getKey(value));

            if (node != null)
            {
                ListArray <valueType> list = get(node);
                if (list != null)
                {
                    list.Add(value);
                }
            }
        }
예제 #24
0
파일: List.cs 프로젝트: Thaina/Towel
        [TestMethod] public void Add_Testing()
        {
            const int   count = 100000;
            IList <int> list  = new ListArray <int>();

            Stepper.Iterate(count, i => list.Add(i));

            // check count
            Assert.IsTrue(list.Count == count);

            // check for all values
            bool[] values = new bool[count];
            list.Stepper(i => values[i] = true);
            values.Stepper(b => Assert.IsTrue(b));
        }
예제 #25
0
        private IValue Extract(IArray set, IArray selection)
        {
            var res = new ListArray();

            foreach (var item in selection)
            {
                if (item.Type != ValueType.Number)
                {
                    throw new WrongOperandTypeException();
                }

                res.Add(set.At((int)item.AsDouble));
            }

            return(new ArrayValue(res));
        }
예제 #26
0
파일: List.cs 프로젝트: Thaina/Towel
        [TestMethod] public void Remove_Testing()
        {
            const int   count = 1000;
            IList <int> list  = new ListArray <int>();

            Stepper.Iterate(count, i => list.Add(i));

            // check count
            Assert.IsTrue(list.Count == count);

            // check for all values
            bool[] values = new bool[count];
            list.Stepper(i => values[i] = true);
            values.Stepper(b => Assert.IsTrue(b));

            // remove every 3rd value
            Stepper.Iterate(count / 3 + 1, i => list.RemoveFirst(i * 3));
            Array.Fill(values, false);
            list.Stepper(i => values[i] = true);
            for (int i = 0; i < count; i++)
            {
                Assert.IsTrue(i % 3 == 0 ? !values[i] : values[i]);
            }

            // check count
            Assert.IsTrue(list.Count == count / 3 * 2);

            // remove the remaining values
            for (int i = 0; i < count; i++)
            {
                if (values[i])
                {
                    list.RemoveFirst(i);
                }
            }
            Array.Fill(values, false);
            list.Stepper(i => values[i] = true);
            values.Stepper(b => Assert.IsFalse(b));

            // check count
            Assert.IsTrue(list.Count == 0);

            // exception
            Assert.ThrowsException <ArgumentException>(() => list.RemoveFirst(0));
        }
예제 #27
0
        public override IValue Eval(IValue[] parameters)
        {
            this.Validate(parameters);

            var set = parameters[0].AsSet;
            var res = new ListArray();
            var i   = new Variable(parameters[1].AsString, new DoubleValue(0));

            this.Context.VariableManager.Define(i);

            foreach (var item in set)
            {
                i.Value = item;
                res.Add(ValueHelper.Copy(parameters[2]));
            }

            return(new ArrayValue(res));
        }
예제 #28
0
        /// <summary>
        /// Multiply all element values in the value set with the matching factors in the factors array.
        /// <para>Assuming the value set contains doubles, and the number of elements in the value
        /// set matches the number of factors</para>
        /// </summary>
        /// <param name="sourceValueset">Valueset to multiply</param>
        /// <param name="factors">Factors to multiply element values with</param>
        /// <returns>A new value set where values have been multiplied</returns>
        public static ITimeSpaceValueSet MultiplyElementValues(this ITimeSpaceValueSet sourceValueset, double[] factors)
        {
            IList <IList>          sourceValues   = sourceValueset.Values2D;
            ValueSetArray <double> targetValueSet = new ValueSetArray <double>();
            ListArray <double>     targetValues   = targetValueSet.Values2DArray;

            // Loop over time
            for (int i = 0; i < sourceValues.Count; i++)
            {
                // Multiply every element value with the corresponding factor
                IList <double> sourceElmtValues = (IList <double>)sourceValues[i];
                double[]       targetElmtValues = new double[sourceElmtValues.Count];
                for (int j = 0; j < sourceElmtValues.Count; j++)
                {
                    targetElmtValues[j] = sourceElmtValues[j] * factors[j];
                }
                targetValues.Add(targetElmtValues);
            }
            return(targetValueSet);
        }
예제 #29
0
        public override IValue Eval(IValue[] parameters)
        {
            this.Validate(parameters);

            if (parameters.Length == 1)
            {
                return(new StringValue(parameters[0].Type.ToString()));
            }
            else
            {
                var res = new ListArray();

                foreach (var parameter in parameters)
                {
                    res.Add(new StringValue(parameter.Type.ToString()));
                }

                return(new ArrayValue(res));
            }
        }
예제 #30
0
        /// <summary>
        /// 根据表格名称获取表格信息
        /// </summary>
        /// <param name="connection">SQL连接</param>
        /// <param name="tableName">表格名称</param>
        /// <returns>表格信息</returns>
        internal override TableColumnCollection GetTable(DbConnection connection, string tableName)
        {
            if (isTable(connection, tableName))
            {
                using (DbCommand command = getCommand(connection, @"describe `" + tableName + @"`;
show index from `" + tableName + @"`;", CommandType.Text))
                    using (DbDataReader reader = command.ExecuteReader(CommandBehavior.Default))
                    {
                        Column identity = null;
                        Dictionary <HashString, Column> columns = DictionaryCreator.CreateHashString <Column>();
                        LeftArray <Column> primaryKeys          = default(LeftArray <Column>);
                        Dictionary <HashString, ListArray <IndexColumn> > indexs = null;
                        while (reader.Read())
                        {
                            string key          = (string)reader["Key"];
                            object defaultValue = reader["Default"];
                            Column column       = new Column
                            {
                                Name         = (string)reader["Field"],
                                DefaultValue = defaultValue == DBNull.Value ? null : (string)defaultValue,
                                IsNull       = (string)reader["Null"] == "YES",
                            };
                            column.DbType = DbType.FormatDbType((string)reader["Type"], out column.Size);
                            columns.Add(column.Name, column);
                            if (key == "PRI")
                            {
                                primaryKeys.Add(column);
                            }
                        }
                        if (reader.NextResult())
                        {
                            indexs = DictionaryCreator.CreateHashString <ListArray <IndexColumn> >();
                            ListArray <IndexColumn> indexColumns;
                            while (reader.Read())
                            {
                                string      name        = (string)reader["Key_name"];
                                IndexColumn indexColumn = new IndexColumn
                                {
                                    Column = columns[(string)reader["Column_name"]],
                                    Index  = (int)(long)reader["Seq_in_index"],
                                    IsNull = (string)reader["Null"] == "YES"
                                };
                                HashString nameKey = name;
                                if (!indexs.TryGetValue(nameKey, out indexColumns))
                                {
                                    indexs.Add(nameKey, indexColumns = new ListArray <IndexColumn>());
                                    indexColumns.Add(indexColumn);
                                    indexColumn.Type = (long)reader["Non_unique"] == 0 ? ColumnCollectionType.UniqueIndex : ColumnCollectionType.Index;
                                }
                                else
                                {
                                    indexColumns.Add(indexColumn);
                                }
                            }
                        }
                        return(new TableColumnCollection
                        {
                            Columns = new ColumnCollection
                            {
                                Name = tableName,
                                Columns = columns.Values.getArray(),
                                Type = ColumnCollectionType.None
                            },
                            Identity = identity,
                            PrimaryKey = primaryKeys.Length == 0 ? null : new ColumnCollection {
                                Type = ColumnCollectionType.PrimaryKey, Columns = primaryKeys.ToArray()
                            },
                            Indexs = indexs.getArray(index => new ColumnCollection
                            {
                                Name = index.Key.ToString(),
                                Type = index.Value[0].Type,
                                Columns = index.Value.ToLeftArray().GetSort(value => value.Index).getArray(column => column.Column)
                            })
                        });
                    }
            }
            return(null);
        }
예제 #31
0
        public static void LoadFontFile(string id, string filePath, string textureLocations)
        {
            ListArray<CharacterSprite> characters = new ListArray<CharacterSprite>(255);
              ListArray<string> textures = new ListArray<string>(1);
              int lineHeight = -1, fontBase = int.MinValue;
              using (StreamReader reader = new StreamReader(filePath))
              {
            int lineNumber = 1;
            while (!reader.EndOfStream)
            {
              string line = reader.ReadLine();
              string[] parameters = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
              switch (parameters[0].ToLower())
              {
            case "common":
              for (int i = 1; i < parameters.Length; i++)
              {
                string[] attributes = parameters[i].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                switch (attributes[0].ToLower())
                {
                  case "lineheight":
                    if (!int.TryParse(attributes[1], out lineHeight))
                      throw new TextManagerException("The line height value of the font file is corrupt on line " + lineNumber + ".");
                    break;

                  case "base":
                    if (!int.TryParse(attributes[1], out fontBase))
                      throw new TextManagerException("The base value of the font file is corrupt on line " + lineNumber + ".");
                    break;
                }
              }
              break;

            case "page":
              string[] textureFile = parameters[2].Split("\"".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
              try { TextureManager.LoadTexture(textureFile[1], textureLocations + textureFile[1]); }
              catch { throw new TextManagerException("The font file is using a non-supported image file on line " + lineNumber + "."); }
              textures.Add(textureFile[1]);
              break;

            case "char":
              int charId = -1,
                x = -1, y = -1,
                width = -1, height = -1,
                xOffset = int.MinValue, yOffset = int.MinValue,
                xAdvance = -1,
                page = -1;
              // channel=-1;

              // Lets get all the attributes of the character
              for (int i = 1; i < parameters.Length; i++)
              {
                string[] attribute = parameters[i].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (attribute.Length < 2)
                  throw new TextManagerException("Font file has a corrupted character attribute on line " + lineNumber + ".");
                switch (attribute[0].ToLower())
                {
                  case "id":
                    if (!int.TryParse(attribute[1], out charId))
                      throw new TextManagerException("An id value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "x":
                    if (!int.TryParse(attribute[1], out x))
                      throw new TextManagerException("A x value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "y":
                    if (!int.TryParse(attribute[1], out y))
                      throw new TextManagerException("A y value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "width":
                    if (!int.TryParse(attribute[1], out width))
                      throw new TextManagerException("A width value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "height":
                    if (!int.TryParse(attribute[1], out height))
                      throw new TextManagerException("A height value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "xoffset":
                    if (!int.TryParse(attribute[1], out xOffset))
                      throw new TextManagerException("A xoffset value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "yoffset":
                    if (!int.TryParse(attribute[1], out yOffset))
                      throw new TextManagerException("A yoffset value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "xadvance":
                    if (!int.TryParse(attribute[1], out xAdvance))
                      throw new TextManagerException("A xadvance value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  case "page":
                    if (!int.TryParse(attribute[1], out page))
                      throw new TextManagerException("A page value in font file is corrupted on line " + lineNumber + ".");
                    break;
                  //// This check is most likely unnecessary, an error will be thrown during image loading attempt.
                  //case "chnl":
                  //  if (!int.TryParse(attribute[1], out channel))
                  //    throw new TextManagerException("A chnl value in font file is corrupted on line " + lineNumber + ".");
                  //  if (channel != 15)
                  //    throw new TextManagerException("The font file is using a non-supported image file.");
                }
              }

              // Make sure all the necessary values were imported and are valid
              if (charId == -1)
                throw new TextManagerException("Font file is corrupt/missing on a char id on line " + lineNumber + ".");
              if (x < 0)
                throw new TextManagerException("Font file has corrupt/missing on x value on line " + lineNumber + ".");
              if (y < 0)
                throw new TextManagerException("Font file has a corrupt/missing y value on line " + lineNumber + ".");
              if (width < 0)
                throw new TextManagerException("Font file has a corrupt/missing width value on line " + lineNumber + ".");
              if (height == -1)
                throw new TextManagerException("Font file has a corrupt/missing height value on line " + lineNumber + ".");
              if (xOffset == int.MinValue)
                throw new TextManagerException("Font file is missing a xoffset value on line " + lineNumber + ".");
              if (yOffset == int.MinValue)
                throw new TextManagerException("Font file is missing a yoffset value on line " + lineNumber + ".");
              if (xAdvance < 0)
                throw new TextManagerException("Font file has a corrupt/missing xadvance value on line " + lineNumber + ".");
              if (page < 0 || page > textures.Count)
                throw new TextManagerException("Font file has a corrupt/missing page value on line " + lineNumber + ".");
              //// This check is most likely unnecessary, an error will be thrown during image loading attempt.
              //if (channel == -1)
              //  throw new TextManagerException("Font file is missing a channel value on line " + lineNumber + ".");

              characters.Add(
                new CharacterSprite(
                  TextureManager.Get(textures[page]),
                  charId,
                  xAdvance,
                  x, y,
                  width, height,
                  xOffset, yOffset));
              break;

            #region OLD CODE (I'll delete this when I'm done debugging the newer version)
            // THIS WAS MY INITIAL PARSER JUST TO GET THINGS WORKING
            //  characters.Add(new CharacterSprite(
            //    // Texture
            //    TextureManager.Get(textures[int.Parse(parameters[9].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture)]),
            //    // Id
            //    int.Parse(parameters[1].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //    // X Advance
            //    int.Parse(parameters[8].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //    // X
            //    int.Parse(parameters[2].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //    // Y
            //    int.Parse(parameters[3].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //    // Width
            //    int.Parse(parameters[4].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //    // Height
            //    int.Parse(parameters[5].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //    // X Offset
            //    int.Parse(parameters[6].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //    // Y Offset
            //    int.Parse(parameters[7].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture)));
            //  break;
            //case "kerning":
            //  int first = int.Parse(parameters[1].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture);
            //  for (int i = 0; i < characters.Count; i++)
            //    if (characters[i].Id == first)
            //      characters[i].AddKearning(
            //        int.Parse(parameters[2].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture),
            //        int.Parse(parameters[3].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture));
            //    break;
            #endregion
              }
              lineNumber++;
            }
              }
              if (lineHeight < 0)
            throw new TextManagerException("Font file has a corrupt/missing line height value.");
              _fontDatabase.Add(new Font(id, lineHeight, fontBase, characters));
              string[] pathSplit = filePath.Split('\\');
              Output.WriteLine("Font file loaded: \"" + pathSplit[pathSplit.Length - 1] + "\".");
        }
예제 #32
0
        [TestMethod] //ICloneable
        public void CloneTest()
        {
            int n = 3;
            ListArray<object> data = new ListArray<object>(n);
            data.Add(8);
            data.Add(6);
            data.Add(10);
            data.Clone();

        }
예제 #33
0
        /// <summary>Deserializes a static delegate from XML.</summary>
        /// <typeparam name="Delegate">The type of the delegate to deserialize.</typeparam>
        /// <param name="textReader">The text reader providing the XML to deserialize.</param>
        /// <returns>The deserialized delegate.</returns>
        /// <exception cref="NotSupportedException">
        /// Thrown when the delegate is pointing to a non-static method.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// Thrown when the delegate is pointing to a local function.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when deserialization fails due to a return type mis-match.
        /// </exception>
        /// <exception cref="Exception">
        /// Thrown when deserialization fails. See the inner exception for more information.
        /// </exception>
        public static Delegate StaticDelegateFromXml <Delegate>(TextReader textReader) where Delegate : System.Delegate
        {
            try
            {
                string         declaringTypeString  = null;
                string         methodNameString     = null;
                IList <string> parameterTypeStrings = new ListArray <string>();
                string         returnTypeString     = null;
                using (XmlReader xmlReader = XmlReader.Create(textReader))
                {
                    while (xmlReader.Read())
                    {
CONTINUE:
                        if (xmlReader.NodeType == XmlNodeType.Element)
                        {
                            switch (xmlReader.Name)
                            {
                            case StaticDelegateConstants.DeclaringType:
                                declaringTypeString = xmlReader.ReadInnerXml();
                                goto CONTINUE;

                            case StaticDelegateConstants.MethodName:
                                methodNameString = xmlReader.ReadInnerXml();
                                goto CONTINUE;

                            case StaticDelegateConstants.ParameterType:
                                parameterTypeStrings.Add(xmlReader.ReadInnerXml());
                                goto CONTINUE;

                            case StaticDelegateConstants.ReturnType:
                                returnTypeString = xmlReader.ReadInnerXml();
                                goto CONTINUE;
                            }
                        }
                    }
                }
                Type       declaringType = Type.GetType(declaringTypeString);
                Type       returnType    = Type.GetType(returnTypeString);
                MethodInfo methodInfo    = null;
                if (parameterTypeStrings.Count > 0)
                {
                    Type[] parameterTypes = parameterTypeStrings.Select(x => Type.GetType(x)).ToArray();
                    methodInfo = declaringType.GetMethod(methodNameString, parameterTypes);
                }
                else
                {
                    methodInfo = declaringType.GetMethod(methodNameString);
                }
                if (methodInfo.IsLocalFunction())
                {
                    goto ThrowLocalFunctionException;
                }
                if (!methodInfo.IsStatic)
                {
                    goto ThrowNonStaticException;
                }
                if (methodInfo.ReturnType != returnType)
                {
                    goto ThrowReturnTypeMisMatchException;
                }
                return(methodInfo.CreateDelegate <Delegate>());
            }
            catch (Exception exception)
            {
                throw new Exception("Deserialization failed.", exception);
            }
ThrowNonStaticException:
            throw new NotSupportedException("Delegates assigned to non-static methods are not supported.");
ThrowLocalFunctionException:
            throw new NotSupportedException("Delegates assigned to local functions are not supported.");
ThrowReturnTypeMisMatchException:
            throw new InvalidOperationException("Deserialization failed due to a return type mis-match.");
        }
예제 #34
0
파일: Obj.cs 프로젝트: lanicon/Theta
        /// <summary>Parses an OBJ file into a model instance.</summary>
        /// <param name="objFileContents">The contents of the obj file.</param>
        /// <returns>The parsed model.</returns>
        private static Model Parse(string objFileContents)
        {
            // These are temporarily needed lists for storing the parsed data as you read it.
            // Its better to use "ListArrays" vs "Lists" because they will be accessed by indeces
            // by the faces of the obj file.
            ListArray <float> filePositions          = new ListArray <float>();
            ListArray <float> fileNormals            = new ListArray <float>();
            ListArray <float> fileTextureCoordinates = new ListArray <float>();
            ListArray <int>   fileIndeces            = new ListArray <int>();

            // Obj files are not required to include texture coordinates or normals
            bool hasTextureCoordinates = true;
            bool hasNormals            = true;

            // Lets read the file and handle each line separately for ".obj" files
            using (StringReader reader = new StringReader(objFileContents))
            {
                int    lineNumber = 1;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    try
                    {
                        string[] parameters = line.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        switch (parameters[0])
                        {
                        // Vertex
                        case "v":
                            filePositions.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
                            filePositions.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
                            filePositions.Add(float.Parse(parameters[3], CultureInfo.InvariantCulture));
                            break;

                        // Texture Coordinate
                        case "vt":
                            fileTextureCoordinates.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
                            fileTextureCoordinates.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
                            break;

                        // Normal
                        case "vn":
                            fileNormals.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
                            fileNormals.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
                            fileNormals.Add(float.Parse(parameters[3], CultureInfo.InvariantCulture));
                            break;

                        // Face
                        case "f":
                            //if (parameters.Length < 4)
                            //  throw new StaticModelManagerException("obj file corrupt.");
                            int first = fileIndeces.Count;
                            for (int i = 1; i < parameters.Length; i++)
                            {
                                if (i > 3)
                                {
                                    // Triangulate using the previous two verteces
                                    // NOTE: THIS MAY BE INCORRECT! I COULD NOT YET FIND DOCUMENTATION
                                    // ON THE TRIANGULATION DONE BY BLENDER (WORKS FOR QUADS AT LEAST)

                                    //// Last two (triangle strip)
                                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);

                                    // First then previous (triangle fan)
                                    fileIndeces.Add(fileIndeces[first]);
                                    fileIndeces.Add(fileIndeces[first + 1]);
                                    fileIndeces.Add(fileIndeces[first + 2]);
                                    fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                    fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                    fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                                }

                                // Now include the new vertex
                                string[] indexReferences = parameters[i].Split('/');
                                //if (indexReferences[0] == "")
                                //  throw new StaticModelManagerException("ERROR: obj file corrupted (missing vertex possition):" + filePath);
                                fileIndeces.Add(int.Parse(indexReferences[0], CultureInfo.InvariantCulture));

                                if (hasNormals && indexReferences.Length < 3)
                                {
                                    hasNormals = false;
                                }
                                if (hasTextureCoordinates && (indexReferences.Length < 2 || indexReferences[1] == ""))
                                {
                                    hasTextureCoordinates = false;
                                }

                                if (hasTextureCoordinates && indexReferences[1] != "")
                                {
                                    fileIndeces.Add(int.Parse(indexReferences[1], CultureInfo.InvariantCulture));
                                }
                                else
                                {
                                    fileIndeces.Add(0);
                                }

                                if (hasNormals && indexReferences[2] != "")
                                {
                                    fileIndeces.Add(int.Parse(indexReferences[2], CultureInfo.InvariantCulture));
                                }
                                else
                                {
                                    fileIndeces.Add(0);
                                }
                            }
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new System.FormatException("Could not parse OBJ file.", ex);
                    }
                    lineNumber++;
                }
            }

            // Pull the final vertex order out of the indexed references
            // Note, arrays start at 0 but the index references start at 1
            float[] positions = new float[fileIndeces.Count];
            for (int i = 0; i < fileIndeces.Count; i += 3)
            {
                int index = (fileIndeces[i] - 1) * 3;
                positions[i]     = filePositions[index];
                positions[i + 1] = filePositions[index + 1];
                positions[i + 2] = filePositions[index + 2];
            }

            float[] textureCoordinates = null;
            if (hasTextureCoordinates)
            {
                // Pull the final texture coordinates order out of the indexed references
                // Note, arrays start at 0 but the index references start at 1
                // Note, every other value needs to be inversed (not sure why but it works :P)
                textureCoordinates = new float[fileIndeces.Count / 3 * 2];
                for (int i = 1; i < fileIndeces.Count; i += 3)
                {
                    int index  = (fileIndeces[i] - 1) * 2;
                    int offset = (i - 1) / 3;
                    textureCoordinates[i - 1 - offset] = fileTextureCoordinates[index];
                    textureCoordinates[i - offset]     = 1 - fileTextureCoordinates[(index + 1)];
                }
            }

            float[] normals = null;
            if (hasNormals)
            {
                // Pull the final normal order out of the indexed references
                // Note, arrays start at 0 but the index references start at 1
                normals = new float[fileIndeces.Count];
                for (int i = 2; i < fileIndeces.Count; i += 3)
                {
                    int index = (fileIndeces[i] - 1) * 3;
                    normals[i - 2] = fileNormals[index];
                    normals[i - 1] = fileNormals[(index + 1)];
                    normals[i]     = fileNormals[(index + 2)];
                }
            }

            int[] indeces = new int[positions.Length / 3];
            for (int i = 0; i < indeces.Length; i++)
            {
                indeces[i] = i;
            }

            return(new Model()
            {
                _positions = positions,
                _normals = normals,
                _textureCoordinates = textureCoordinates,
                _indices = indeces,
                _indexListFormat = Model.IndexListFormat.Triangles,
            });
        }
예제 #35
0
        /// <summary>DONT USE THIS FUNCTION!!! This is an experimental file type I may use in the future.</summary>
        public static StaticModel LoadSevenModelFromDisk(string staticModelId, string filePath)
        {
            // These are temporarily needed lists for storing the parsed data as you read it.
              ListArray<float> fileVerteces = new ListArray<float>(1000);
              ListArray<float> fileNormals = new ListArray<float>(1000);
              ListArray<float> fileTextureCoordinates = new ListArray<float>(1000);
              ListArray<int> fileIndeces = new ListArray<int>(1000);
              Texture texture = null;
              string meshName = "defaultMeshName";

              AvlTreeLinked<StaticMesh, string> meshes = new AvlTreeLinked<StaticMesh, string>
              (
            (StaticMesh left, StaticMesh right) => { return left.Id.CompareTo(right.Id); },
            (StaticMesh left, string right) => { return left.Id.CompareTo(right); }
              );

              // Lets read the file and handle each line separately for ".obj" files
              using (StreamReader reader = new StreamReader(filePath))
              {
            while (!reader.EndOfStream)
            {
              string[] parameters = reader.ReadLine().Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
              switch (parameters[0])
              {
            // MeshName
            case "m":
              meshName = parameters[1];
              break;

            // Texture
            case "t":
              if (!TextureManager.TextureExists(parameters[1]))
                TextureManager.LoadTexture(parameters[1], parameters[2]);
              texture = TextureManager.Get(parameters[1]);
              break;

            // Vertex
            case "v":
              fileVerteces.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
              fileVerteces.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
              fileVerteces.Add(float.Parse(parameters[3], CultureInfo.InvariantCulture));
              break;

            // Texture Coordinate
            case "vt":
              fileTextureCoordinates.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
              fileTextureCoordinates.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
              break;

            // Normal
            case "vn":
              fileNormals.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
              fileNormals.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
              fileNormals.Add(float.Parse(parameters[3], CultureInfo.InvariantCulture));
              break;

            // Face
            case "f":
              // DEVELOPMENT NOTE: The following triangulation algorithm works, but it
              // could be optimized beyond its current state.

              // The following variables are used for triangulation of a polygon
              // with greater than three verteces.
              int firstPosition, firstTextureCoordinates, firstNormal,
                secondPosition, secondTextureCoordinates, secondNormal;
              if (parameters.Length > 3)
              {
                // First Vertex (we have to store it this way for possible triangulation)
                string[] indexReferences = parameters[1].Split('/');
                if (indexReferences[0] == "")
                  throw new StaticModelManagerException("ERROR: obj file corrupted (missing vertex possition): " + filePath);
                firstPosition = int.Parse(indexReferences[0], CultureInfo.InvariantCulture);
                if (indexReferences[1] != "")
                  firstTextureCoordinates = int.Parse(indexReferences[1], CultureInfo.InvariantCulture);
                else
                  firstTextureCoordinates = 0;
                if (indexReferences[2] != "")
                  firstNormal = int.Parse(indexReferences[2], CultureInfo.InvariantCulture);
                else
                  firstNormal = 0;

                // Second Vertex (we have to store it this way for possible triangulation)
                indexReferences = parameters[2].Split('/');
                if (indexReferences[0] == "")
                  throw new StaticModelManagerException("ERROR: obj file corrupted (missing vertex possition): " + filePath);
                secondPosition = int.Parse(indexReferences[0], CultureInfo.InvariantCulture);
                if (indexReferences[1] != "")
                  secondTextureCoordinates = int.Parse(indexReferences[1], CultureInfo.InvariantCulture);
                else
                  secondTextureCoordinates = 0;
                if (indexReferences[2] != "")
                  secondNormal = int.Parse(indexReferences[2], CultureInfo.InvariantCulture);
                else
                  secondNormal = 0;
              }
              else
                throw new StaticModelManagerException("ERROR: obj file corrupted:" + filePath);

              // Verteces past the first two
              for (int i = 3; i < parameters.Length; i++)
              {
                // Triangulate using the first two verteces
                fileIndeces.Add(firstPosition);
                fileIndeces.Add(firstTextureCoordinates);
                fileIndeces.Add(firstNormal);
                fileIndeces.Add(secondPosition);
                fileIndeces.Add(secondTextureCoordinates);
                fileIndeces.Add(secondNormal);
                // Now include the new vertex
                string[] indexReferences = parameters[i].Split('/');
                if (indexReferences[0] == "")
                  throw new StaticModelManagerException("ERROR: obj file corrupted (missing vertex possition): " + filePath);
                fileIndeces.Add(int.Parse(indexReferences[0], CultureInfo.InvariantCulture));
                if (indexReferences[1] != "")
                  fileIndeces.Add(int.Parse(indexReferences[1], CultureInfo.InvariantCulture));
                else
                  fileIndeces.Add(0);
                if (indexReferences[2] != "")
                  fileIndeces.Add(int.Parse(indexReferences[2], CultureInfo.InvariantCulture));
                else
                  fileIndeces.Add(0);
              }
              break;

              //// OLD VERSION OF THE FACE PARSING
              //// NOTE! This does not yet triangulate faces
              //// NOTE! This needs all possible values (position, texture mapping, and normal).
              //for (int i = 1; i < parameters.Length; i++)
              //{
              //  string[] indexReferences = parameters[i].Split('/');
              //  fileIndeces.Add(int.Parse(indexReferences[0], CultureInfo.InvariantCulture));
              //  if (indexReferences[1] != "")
              //    fileIndeces.Add(int.Parse(indexReferences[1], CultureInfo.InvariantCulture));
              //  else
              //    fileIndeces.Add(0);
              //  if (indexReferences[2] != "")
              //    fileIndeces.Add(int.Parse(indexReferences[2], CultureInfo.InvariantCulture));
              //  else
              //    fileIndeces.Add(0);
              //}
              //break;

            // End Current Mesh
            case "7":
              // Pull the final vertex order out of the indexed references
              // Note, arrays start at 0 but the index references start at 1
              float[] verteces = new float[fileIndeces.Count];
              for (int i = 0; i < fileIndeces.Count; i += 3)
              {
                int index = (fileIndeces[i] - 1) * 3;
                verteces[i] = fileVerteces[index];
                verteces[i + 1] = fileVerteces[index + 1];
                verteces[i + 2] = fileVerteces[index + 2];
              }

              // Pull the final texture coordinates order out of the indexed references
              // Note, arrays start at 0 but the index references start at 1
              // Note, every other value needs to be inverse (not sure why but it works :P)
              float[] textureCoordinates = new float[fileIndeces.Count / 3 * 2];
              for (int i = 1; i < fileIndeces.Count; i += 3)
              {
                int index = (fileIndeces[i] - 1) * 2;
                int offset = (i - 1) / 3;
                textureCoordinates[i - 1 - offset] = fileTextureCoordinates[index];
                textureCoordinates[i - offset] = 1 - fileTextureCoordinates[(index + 1)];
              }

              // Pull the final normal order out of the indexed references
              // Note, arrays start at 0 but the index references start at 1
              float[] normals = new float[fileIndeces.Count];
              for (int i = 2; i < fileIndeces.Count; i += 3)
              {
                int index = (fileIndeces[i] - 1) * 3;
                normals[i - 2] = fileNormals[index];
                normals[i - 1] = fileNormals[(index + 1)];
                normals[i] = fileNormals[(index + 2)];
              }

              int vertexBufferId;
              if (verteces != null)
              {
                // Declare the buffer
                GL.GenBuffers(1, out vertexBufferId);
                // Select the new buffer
                GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
                // Initialize the buffer values
                GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(verteces.Length * sizeof(float)), verteces, BufferUsageHint.StaticDraw);
                // Quick error checking
                int bufferSize;
                GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
                if (verteces.Length * sizeof(float) != bufferSize)
                  throw new StaticModelManagerException("Vertex array not uploaded correctly");
                // Deselect the new buffer
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { vertexBufferId = 0; }

              int textureCoordinateBufferId;
              if (textureCoordinates != null)
              {
                // Declare the buffer
                GL.GenBuffers(1, out textureCoordinateBufferId);
                // Select the new buffer
                GL.BindBuffer(BufferTarget.ArrayBuffer, textureCoordinateBufferId);
                // Initialize the buffer values
                GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(textureCoordinates.Length * sizeof(float)), textureCoordinates, BufferUsageHint.StaticDraw);
                // Quick error checking
                int bufferSize;
                GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
                if (textureCoordinates.Length * sizeof(float) != bufferSize)
                  throw new StaticModelManagerException("TexCoord array not uploaded correctly");
                // Deselect the new buffer
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { textureCoordinateBufferId = 0; }

              int normalBufferId;
              if (normals != null)
              {
                // Declare the buffer
                GL.GenBuffers(1, out normalBufferId);
                // Select the new buffer
                GL.BindBuffer(BufferTarget.ArrayBuffer, normalBufferId);
                // Initialize the buffer values
                GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(normals.Length * sizeof(float)), normals, BufferUsageHint.StaticDraw);
                // Quick error checking
                int bufferSize;
                GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
                if (normals.Length * sizeof(float) != bufferSize)
                  throw new StaticModelManagerException("Normal array not uploaded correctly");
                // Deselect the new buffer
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { normalBufferId = 0; }

              meshes.Add(
                new StaticMesh(
                  meshName,
                  texture,
                  new StaticMeshInstance(
                  filePath,
                  staticModelId + "sub" + meshes.Count,
                  vertexBufferId,
                  0, // Obj files don't support vertex colors
                  textureCoordinateBufferId,
                  normalBufferId,
                  0, // I don't support an index buffer at this time
                  verteces.Length)));
              fileVerteces.Clear();
              fileNormals.Clear();
              fileTextureCoordinates.Clear();
              fileIndeces.Clear();
              texture = null;
              break;
              }
            }
              }
              return new StaticModel(staticModelId, meshes);
        }
예제 #36
0
파일: Program.cs 프로젝트: inktan/Towel
        static void Main()
        {
            Random random = new Random();
            int    test   = 10;

            Console.WriteLine("You are runnning the Data Structures example.");
            Console.WriteLine("======================================================");
            Console.WriteLine();

            #region Link (aka Tuple)

            Console.WriteLine("  Link------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    A \"Link\" is like a System.Tuple that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. A Link/Tuple is");
            Console.WriteLine("    used when you have a small, known-sized set of objects");
            Console.WriteLine("    that you want to bundle together without making a custom");
            Console.WriteLine("    custom class.");
            Console.WriteLine();

            Link link = new Link <int, int, int, int, int, int>(0, 1, 2, 3, 4, 5);
            Console.Write("    Traversal: ");
            link.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    Size: {link.Size}");
            Console.WriteLine();

            #endregion

            #region Array

            Console.WriteLine("  Array---------------------------------");
            Console.WriteLine();
            Console.WriteLine("    An Array<T> is just a wrapper for arrays that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. An array is used when");
            Console.WriteLine("    dealing with static-sized, known-sized sets of data. Arrays");
            Console.WriteLine("    can be sorted along 1 dimensions for binary searching algorithms.");
            Console.WriteLine();

            IArray <int> array = new Array <int>(test);

            Console.Write($"    Filling in (0-{test - 1})...");
            for (int i = 0; i < test; i++)
            {
                array[i] = i;
            }
            Console.WriteLine();

            Console.Write("    Traversal: ");
            array.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    Length: {array.Length}");

            Console.WriteLine();

            #endregion

            #region List

            Console.WriteLine("  List---------------------------------");
            Console.WriteLine();
            Console.WriteLine("    An List is like an IList that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. \"ListArray\" is");
            Console.WriteLine("    the array implementation while \"ListLinked\" is the");
            Console.WriteLine("    the linked-list implementation. An List is used");
            Console.WriteLine("    when dealing with an unknown quantity of data that you");
            Console.WriteLine("    will likely have to enumerate/step through everything. The");
            Console.WriteLine("    ListArray shares the properties of an Array in");
            Console.WriteLine("    that it can be relateively quickly sorted along 1 dimensions");
            Console.WriteLine("    for binary search algorithms.");
            Console.WriteLine();

            // ListArray ---------------------------------------
            IList <int> listArray = new ListArray <int>(test);

            Console.Write($"    [ListArray] Adding (0-{test - 1})...");
            for (int i = 0; i < test; i++)
            {
                listArray.Add(i);
            }
            Console.WriteLine();

            Console.Write("    [ListArray] Traversal: ");
            listArray.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    [ListArray] Count: {listArray.Count}");

            listArray.Clear();

            Console.WriteLine();

            // ListLinked ---------------------------------------
            IList <int> listLinked = new ListLinked <int>();

            Console.Write($"    [ListLinked] Adding (0-{test - 1})...");
            for (int i = 0; i < test; i++)
            {
                listLinked.Add(i);
            }
            Console.WriteLine();

            Console.Write("    [ListLinked] Traversal: ");
            listLinked.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    [ListLinked] Count: {listLinked.Count}");

            listLinked.Clear();

            Console.WriteLine();

            #endregion

            #region Stack
            {
                Console.WriteLine("  Stack---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Stack\" is a Stack that implements");
                Console.WriteLine("    Towel.DataStructures.DataStructure. \"StackArray\" is");
                Console.WriteLine("    the array implementation while \"StackLinked\" is the");
                Console.WriteLine("    the linked-list implementation. A Stack is used");
                Console.WriteLine("    specifically when you need the algorithm provided by the Push");
                Console.WriteLine("    and Pop functions.");
                Console.WriteLine();

                IStack <int> stackArray = new StackArray <int>();

                Console.Write($"    [StackArray] Pushing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    stackArray.Push(i);
                }
                Console.WriteLine();

                Console.Write("    [StackArray] Traversal: ");
                stackArray.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [StackArray] Pop: {stackArray.Pop()}");
                Console.WriteLine($"    [StackArray] Pop: {stackArray.Pop()}");
                Console.WriteLine($"    [StackArray] Peek: {stackArray.Peek()}");
                Console.WriteLine($"    [StackArray] Pop: {stackArray.Pop()}");
                Console.WriteLine($"    [StackArray] Count: {stackArray.Count}");

                stackArray.Clear();

                Console.WriteLine();

                IStack <int> stackLinked = new StackLinked <int>();

                Console.Write($"    [StackLinked] Pushing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    stackLinked.Push(i);
                }
                Console.WriteLine();

                Console.Write("    [StackLinked] Traversal: ");
                stackLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [StackLinked] Pop: {stackLinked.Pop()}");
                Console.WriteLine($"    [StackLinked] Pop: {stackLinked.Pop()}");
                Console.WriteLine($"    [StackLinked] Peek: {stackLinked.Peek()}");
                Console.WriteLine($"    [StackLinked] Pop: {stackLinked.Pop()}");
                Console.WriteLine($"    [StackLinked] Count: {stackLinked.Count}");

                stackLinked.Clear();

                Console.WriteLine();
            }
            #endregion

            #region Queue
            {
                Console.WriteLine("  Queue---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Queue\" is a Queue that implements");
                Console.WriteLine("    Towel.DataStructures.DataStructure. \"QueueArray\" is");
                Console.WriteLine("    the array implementation while \"QueueLinked\" is the");
                Console.WriteLine("    the linked-list implementation. A Queue/Stack is used");
                Console.WriteLine("    specifically when you need the algorithm provided by the Queue");
                Console.WriteLine("    and Dequeue functions.");
                Console.WriteLine();

                IQueue <int> queueArray = new QueueArray <int>();

                Console.Write($"    [QueueArray] Enqueuing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    queueArray.Enqueue(i);
                }
                Console.WriteLine();

                Console.Write("    [QueueArray] Traversal: ");
                queueArray.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [QueueArray] Dequeue: {queueArray.Dequeue()}");
                Console.WriteLine($"    [QueueArray] Dequeue: {queueArray.Dequeue()}");
                Console.WriteLine($"    [QueueArray] Peek: {queueArray.Peek()}");
                Console.WriteLine($"    [QueueArray] Dequeue: {queueArray.Dequeue()}");
                Console.WriteLine($"    [QueueArray] Count: {queueArray.Count}");

                queueArray.Clear();

                Console.WriteLine();

                IQueue <int> queueLinked = new QueueLinked <int>();

                Console.Write($"    [QueueLinked] Enqueuing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    queueLinked.Enqueue(i);
                }
                Console.WriteLine();

                Console.Write("    [QueueLinked] Traversal: ");
                queueLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [QueueLinked] Pop: {queueLinked.Dequeue()}");
                Console.WriteLine($"    [QueueLinked] Pop: {queueLinked.Dequeue()}");
                Console.WriteLine($"    [QueueLinked] Peek: {queueLinked.Peek()}");
                Console.WriteLine($"    [QueueLinked] Pop: {queueLinked.Dequeue()}");
                Console.WriteLine($"    [QueueLinked] Count: {queueLinked.Count}");

                queueLinked.Clear();

                Console.WriteLine();
            }
            #endregion

            #region Heap
            {
                Console.WriteLine("  Heap---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Heap\" is a binary tree that stores items based on priorities.");
                Console.WriteLine("    It implements Towel.DataStructures.DataStructure like the others.");
                Console.WriteLine("    It uses sifting algorithms to move nodes vertically through itself.");
                Console.WriteLine("    It is often the best data structure for standard priority queues.");
                Console.WriteLine("    \"HeapArray\" is an implementation where the tree has been flattened");
                Console.WriteLine("    into an array.");
                Console.WriteLine();

                Console.WriteLine("    Let's say the priority is how close a number is to \"5\".");
                Console.WriteLine("    So \"Dequeue\" will give us the next closest value to \"5\".");
예제 #37
0
 //---------------------------------------------------------------------------------------------------------
 /// <summary>
 /// Добавление сообщения
 /// </summary>
 /// <param name="text">Имя сообщения</param>
 /// <param name="type">Тип сообщения</param>
 //---------------------------------------------------------------------------------------------------------
 public void Log(String text, TLogType type)
 {
     mMessages.Add(new TLogMessage(text, type));
     outputData.ScrollIntoView(mMessages[mMessages.Count - 1]);
 }
예제 #38
0
        private static StaticMeshInstance LoadObj(string staticMeshId, string filePath)
        {
            // These are temporarily needed lists for storing the parsed data as you read it.
              // Its better to use "ListArrays" vs "Lists" because they will be accessed by indeces
              // by the faces of the obj file.
              ListArray<float> fileVerteces = new ListArray<float>(10000);
              ListArray<float> fileNormals = new ListArray<float>(10000);
              ListArray<float> fileTextureCoordinates = new ListArray<float>(10000);
              ListArray<int> fileIndeces = new ListArray<int>(10000);

              // Obj files are not required to include texture coordinates or normals
              bool hasTextureCoordinates = true;
              bool hasNormals = true;

              // Lets read the file and handle each line separately for ".obj" files
              using (StreamReader reader = new StreamReader(filePath))
              {
            int lineNumber = 1;
            while (!reader.EndOfStream)
            {
              try
              {
            string[] parameters = reader.ReadLine().Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            switch (parameters[0])
            {
              // Vertex
              case "v":
                fileVerteces.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
                fileVerteces.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
                fileVerteces.Add(float.Parse(parameters[3], CultureInfo.InvariantCulture));
                break;

              // Texture Coordinate
              case "vt":
                fileTextureCoordinates.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
                fileTextureCoordinates.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
                break;

              // Normal
              case "vn":
                fileNormals.Add(float.Parse(parameters[1], CultureInfo.InvariantCulture));
                fileNormals.Add(float.Parse(parameters[2], CultureInfo.InvariantCulture));
                fileNormals.Add(float.Parse(parameters[3], CultureInfo.InvariantCulture));
                break;

              // Face
              case "f":
                //if (parameters.Length < 4)
                //  throw new StaticModelManagerException("obj file corrupt.");
                int first = fileIndeces.Count;
                for (int i = 1; i < parameters.Length; i++)
                {
                  if (i > 3)
                  {
                    // Triangulate using the previous two verteces
                    // NOTE: THIS MAY BE INCORRECT! I COULD NOT YET FIND DOCUMENTATION
                    // ON THE TRIANGULATION DONE BY BLENDER (WORKS FOR QUADS AT LEAST)

                    //// Last two (triangle strip)
                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                    //fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);

                    // First then previous (triangle fan)
                    fileIndeces.Add(fileIndeces[first]);
                    fileIndeces.Add(fileIndeces[first + 1]);
                    fileIndeces.Add(fileIndeces[first + 2]);
                    fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                    fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                    fileIndeces.Add(fileIndeces[fileIndeces.Count - 6]);
                  }

                  // Now include the new vertex
                  string[] indexReferences = parameters[i].Split('/');
                  //if (indexReferences[0] == "")
                  //  throw new StaticModelManagerException("ERROR: obj file corrupted (missing vertex possition):" + filePath);
                  fileIndeces.Add(int.Parse(indexReferences[0], CultureInfo.InvariantCulture));

                  if (hasNormals && indexReferences.Length < 3)
                    hasNormals = false;
                  if (hasTextureCoordinates && (indexReferences.Length < 2 || indexReferences[1] == ""))
                    hasTextureCoordinates = false;

                  if (hasTextureCoordinates && indexReferences[1] != "")
                    fileIndeces.Add(int.Parse(indexReferences[1], CultureInfo.InvariantCulture));
                  else
                    fileIndeces.Add(0);

                  if (hasNormals && indexReferences[2] != "")
                    fileIndeces.Add(int.Parse(indexReferences[2], CultureInfo.InvariantCulture));
                  else
                    fileIndeces.Add(0);
                }
                break;
            }
              }
              catch
              {
            string[] pathSplit = filePath.Split('\\');
            throw new StaticModelManagerException("Could not load model " + pathSplit[pathSplit.Length - 1] +
              ". There is a corruption on line " + lineNumber +".");
              }
              lineNumber++;
            }
              }

              // Pull the final vertex order out of the indexed references
              // Note, arrays start at 0 but the index references start at 1
              float[] verteces = new float[fileIndeces.Count];
              for (int i = 0; i < fileIndeces.Count; i += 3)
              {
            int index = (fileIndeces[i] - 1) * 3;
            verteces[i] = fileVerteces[index];
            verteces[i + 1] = fileVerteces[index + 1];
            verteces[i + 2] = fileVerteces[index + 2];
              }

              float[] textureCoordinates = null;
              if (hasTextureCoordinates)
              {
            // Pull the final texture coordinates order out of the indexed references
            // Note, arrays start at 0 but the index references start at 1
            // Note, every other value needs to be inverse (not sure why but it works :P)
            textureCoordinates = new float[fileIndeces.Count / 3 * 2];
            for (int i = 1; i < fileIndeces.Count; i += 3)
            {
              int index = (fileIndeces[i] - 1) * 2;
              int offset = (i - 1) / 3;
              textureCoordinates[i - 1 - offset] = fileTextureCoordinates[index];
              textureCoordinates[i - offset] = 1 - fileTextureCoordinates[(index + 1)];
            }
              }

              float[] normals = null;
              if (hasNormals)
              {
            // Pull the final normal order out of the indexed references
            // Note, arrays start at 0 but the index references start at 1
            normals = new float[fileIndeces.Count];
            for (int i = 2; i < fileIndeces.Count; i += 3)
            {
              int index = (fileIndeces[i] - 1) * 3;
              normals[i - 2] = fileNormals[index];
              normals[i - 1] = fileNormals[(index + 1)];
              normals[i] = fileNormals[(index + 2)];
            }
              }

              int vertexBufferId;
              if (verteces != null)
              {
            // Make the vertex buffer on the GPU
            GL.GenBuffers(1, out vertexBufferId);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
            GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(verteces.Length * sizeof(float)), verteces, BufferUsageHint.StaticDraw);
            int bufferSize;
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
            if (verteces.Length * sizeof(float) != bufferSize)
              throw new StaticModelManagerException("Vertex array not uploaded correctly");
            // Deselect the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { vertexBufferId = 0; }

              int textureCoordinateBufferId;
              if (hasTextureCoordinates && textureCoordinates != null)
              {
            // Make the texture coordinate buffer on the GPU
            GL.GenBuffers(1, out textureCoordinateBufferId);
            GL.BindBuffer(BufferTarget.ArrayBuffer, textureCoordinateBufferId);
            GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(textureCoordinates.Length * sizeof(float)), textureCoordinates, BufferUsageHint.StaticDraw);
            int bufferSize;
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
            if (textureCoordinates.Length * sizeof(float) != bufferSize)
              throw new StaticModelManagerException("TexCoord array not uploaded correctly");
            // Deselect the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { textureCoordinateBufferId = 0; }

              int normalBufferId;
              if (hasNormals && normals != null)
              {
            // Make the normal buffer on the GPU
            GL.GenBuffers(1, out normalBufferId);
            GL.BindBuffer(BufferTarget.ArrayBuffer, normalBufferId);
            GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(normals.Length * sizeof(float)), normals, BufferUsageHint.StaticDraw);
            int bufferSize;
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
            if (normals.Length * sizeof(float) != bufferSize)
              throw new StaticModelManagerException("Normal array not uploaded correctly");
            // Deselect the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { normalBufferId = 0; }

              return new StaticMeshInstance(
            filePath,
            staticMeshId,
            vertexBufferId,
            0, // Obj files don't support vertex colors
            textureCoordinateBufferId,
            normalBufferId,
            0, // I don't support an index buffer at this time
            verteces.Length);
        }
예제 #39
0
        [TestMethod] //Удаление несуществующего элемента 
        public void DeleteNotExistItemTest()
        {
            int n = 3;
            ListArray<object> data = new ListArray<object>(n);
            data.Add(8);
            data.Add(6);
            data.Add(10);
            data.Remove(5);

        }
예제 #40
0
        [TestMethod] //IDisposable
        public void DisposeTest()
        {
            int n = 3;
            ListArray<object> data = new ListArray<object>(n);
            data.Add(8);
            data.Add(6);
            data.Add(10);
            data.Dispose();

        }
예제 #41
0
 /// <summary>
 /// Creates a result value set of the size specified
 /// </summary>
 /// <returns>A Value set of the correct size.</returns>
 public static TimeSpaceValueSet<double> CreateResultValueSet(int numtimes, int numElements)
 {
     ListArray<double> outValues = new ListArray<double>(numtimes);
     for (int i = 0; i < numtimes; i++)
     {
         outValues.Add(new double[numElements]);
     }
     return new TimeSpaceValueSet<double>(outValues);
 }
예제 #42
0
        private static StaticMesh LoadObj(string staticMeshId, string filePath)
        {
            // These are temporarily needed lists for storing the parsed data as you read it.
              // Its better to use "ListArrays" vs "Lists" because they will be accessed by indeces
              // by the faces of the obj file.
              ListArray<float> fileVerteces = new ListArray<float>(10000);
              ListArray<float> fileNormals = new ListArray<float>(10000);
              ListArray<float> fileTextureCoordinates = new ListArray<float>(10000);
              ListArray<int> fileIndeces = new ListArray<int>(10000);

              // Lets read the file and handle each line separately for ".obj" files
              using (StreamReader reader = new StreamReader(filePath))
              {
            while (!reader.EndOfStream)
            {
              string[] parameters = reader.ReadLine().Trim().Split(' ');
              switch (parameters[0])
              {
            // Vertex
            case "v":
              fileVerteces.Add(float.Parse(parameters[1]));
              fileVerteces.Add(float.Parse(parameters[2]));
              fileVerteces.Add(float.Parse(parameters[3]));
              break;

            // Texture Coordinate
            case "vt":
              fileTextureCoordinates.Add(float.Parse(parameters[1]));
              fileTextureCoordinates.Add(float.Parse(parameters[2]));
              break;

            // Normal
            case "vn":
              fileNormals.Add(float.Parse(parameters[1]));
              fileNormals.Add(float.Parse(parameters[2]));
              fileNormals.Add(float.Parse(parameters[3]));
              break;

            // Face
            case "f":
              // NOTE! This does not yet triangulate faces
              // NOTE! This needs all possible values (position, texture mapping, and normal).
              for (int i = 1; i < parameters.Length; i++)
              {
                string[] indexReferences = parameters[i].Split('/');
                fileIndeces.Add(int.Parse(indexReferences[0]));
                if (indexReferences[1] != "")
                  fileIndeces.Add(int.Parse(indexReferences[1]));
                else
                  fileIndeces.Add(0);
                if (indexReferences[2] != "")
                  fileIndeces.Add(int.Parse(indexReferences[2]));
                else
                  fileIndeces.Add(0);
              }
              break;
              }
            }
              }

              // Pull the final vertex order out of the indexed references
              // Note, arrays start at 0 but the index references start at 1
              float[] verteces = new float[fileIndeces.Count];
              for (int i = 0; i < fileIndeces.Count; i += 3)
              {
            int index = (fileIndeces[i] - 1) * 3;
            verteces[i] = fileVerteces[index];
            verteces[i + 1] = fileVerteces[index + 1];
            verteces[i + 2] = fileVerteces[index + 2];
              }

              // Pull the final texture coordinates order out of the indexed references
              // Note, arrays start at 0 but the index references start at 1
              // Note, every other value needs to be inverse (not sure why but it works :P)
              float[] textureCoordinates = new float[fileIndeces.Count / 3 * 2];
              for (int i = 1; i < fileIndeces.Count; i += 3)
              {
            int index = (fileIndeces[i] - 1) * 2;
            int offset = (i - 1) / 3;
            textureCoordinates[i - 1 - offset] = fileTextureCoordinates[index];
            textureCoordinates[i - offset] = 1 - fileTextureCoordinates[(index + 1)];
              }

              // Pull the final normal order out of the indexed references
              // Note, arrays start at 0 but the index references start at 1
              float[] normals = new float[fileIndeces.Count];
              for (int i = 2; i < fileIndeces.Count; i += 3)
              {
            int index = (fileIndeces[i] - 1) * 3;
            normals[i - 2] = fileNormals[index];
            normals[i - 1] = fileNormals[(index + 1)];
            normals[i] = fileNormals[(index + 2)];
              }

              int vertexBufferId;
              if (verteces != null)
              {
            // Declare the buffer
            GL.GenBuffers(1, out vertexBufferId);
            // Select the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
            // Initialize the buffer values
            GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(verteces.Length * sizeof(float)), verteces, BufferUsageHint.StaticDraw);
            // Quick error checking
            int bufferSize;
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
            if (verteces.Length * sizeof(float) != bufferSize)
              throw new ApplicationException("Vertex array not uploaded correctly");
            // Deselect the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { vertexBufferId = 0; }

              int textureCoordinateBufferId;
              if (textureCoordinates != null)
              {
            // Declare the buffer
            GL.GenBuffers(1, out textureCoordinateBufferId);
            // Select the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, textureCoordinateBufferId);
            // Initialize the buffer values
            GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(textureCoordinates.Length * sizeof(float)), textureCoordinates, BufferUsageHint.StaticDraw);
            // Quick error checking
            int bufferSize;
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
            if (textureCoordinates.Length * sizeof(float) != bufferSize)
              throw new ApplicationException("TexCoord array not uploaded correctly");
            // Deselect the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { textureCoordinateBufferId = 0; }

              int normalBufferId;
              if (normals != null)
              {
            // Declare the buffer
            GL.GenBuffers(1, out normalBufferId);
            // Select the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, normalBufferId);
            // Initialize the buffer values
            GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(normals.Length * sizeof(float)), normals, BufferUsageHint.StaticDraw);
            // Quick error checking
            int bufferSize;
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
            if (normals.Length * sizeof(float) != bufferSize)
              throw new ApplicationException("Normal array not uploaded correctly");
            // Deselect the new buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
              }
              else { normalBufferId = 0; }

              return new StaticMesh(
            filePath,
            staticMeshId,
            vertexBufferId,
            0, // Obj files don't support vertex colors
            textureCoordinateBufferId,
            normalBufferId,
            0, // I don't support an index buffer at this time
            verteces.Length);
        }
예제 #43
0
        [TestMethod] //IEnumerable
        public void EnumerableTest()
        {
            int n = 3;
            ListArray<object> data = new ListArray<object>(n);
            data.Add(8);
            data.Add(6);
            data.Add(10);
            data.GetEnumerator();

        }